Skip to content
Docs0.9GitHubInstall

Building on itWrite a plugin

Write a plugin

Build a working Vendetta plugin in Python that registers, serves a method, adds a page with a button, and reacts to events, then the same in outline for Rust.

This page builds a plugin from an empty file, for anyone who wants Vendetta to do something it doesn’t ship with. You need Python 3 and a running vendetta install.

A plugin is a separate program the workerWorker. The background process everything talks to, one per user. Start it with vendetta notify start. starts, keeps running, and stops with itself. It talks to Vendetta only through the worker’s control socketControl socket. The worker's private Unix socket. The chooser, plugins, and vendetta commands reach the worker through it.: one JSON object per line. Before writing one, check whether something smaller will do.

The plugin is called notes. It keeps a list of one-line notes in memory.

  • Agents, scripts, and you add a note with vendetta service call notes add.
  • The apps get a Notes entry beside Chats, with a count, that opens a page listing the notes.
  • A Clear button on that page empties the list.
  • The page’s subtitle says how many agents are waiting for you, and follows them as they change.

Save this as notes.py:

#!/usr/bin/env python3
"""A Vendetta plugin that keeps notes: a service to add them, a page to read them."""
import json, os, socket, sys, threading

NAME = "notes"


# The worker holds the other end of stdin. End of file means it is gone.
def exit_with_worker():
    sys.stdin.read()
    os._exit(0)


threading.Thread(target=exit_with_worker, daemon=True).start()

control = socket.socket(socket.AF_UNIX)
control.connect(os.environ["VENDETTA_CONTROL_SOCKET"])
stream = control.makefile(encoding="utf-8")
last_request = 0
events = []  # Events that arrived while waiting for a response.


def read_frame():
    line = stream.readline()
    if not line:
        sys.exit("The worker closed the connection")
    return json.loads(line)


def call(method, params=None):
    global last_request
    last_request += 1
    request = {"type": "request", "id": last_request, "method": method, "params": params or {}}
    control.sendall(json.dumps(request).encode() + b"\n")
    while True:
        frame = read_frame()
        if frame["type"] == "event":
            events.append(frame["event"])
        elif "error" in frame:
            raise RuntimeError(f"{method}: {frame['error']}")
        else:
            return frame.get("result")


notes = []  # (key, text), kept in memory: a restart starts empty.
added = 0
waiting = 0  # Agents with a question or an approval open.


def publish():
    rows = {key: {"kind": "row", "title": text} for key, text in notes}
    call("ui_set_page", {"page": "notes", "title": "Notes", "root": "top", "nodes": {
        "top": {"kind": "stack", "children": ["head", "list"]},
        "head": {"kind": "header", "title": "Notes", "trailing": ["clear"],
                 "subtitle": f"{len(notes)} notes · {waiting} agents waiting"},
        "clear": {"kind": "button", "label": "Clear", "style": "secondary",
                  "confirm": "Remove every note?", "on": {"action": "clear"}},
        "list": {"kind": "list", "empty": "No notes yet", "children": list(rows)},
        **rows}})
    call("ui_set_contributions", {"contributions": [
        {"id": "notes", "slot": "nav", "label": "Notes", "icon": {"symbol": "list"},
         "badge": len(notes), "on": {"page": "notes"}}]})


def count_waiting():
    global waiting
    agents = call("list_agents")["agents"]
    waiting = sum(agent["state"] in ("input", "approval") for agent in agents)


def serve(event):
    global added
    taken = call("service_take", {"call": event["call"]})
    if taken["method"] == "add":
        text = str(taken["args"].get("text", "")).strip()
        if not text or len(text) > 200 or "\n" in text:
            call("service_reply", {"call": event["call"], "error": "text: one line, 1 to 200 characters"})
            return
        added += 1
        notes.append((f"note:{added}", text))
        publish()
    call("service_reply", {"call": event["call"], "result": {"notes": [text for _, text in notes]}})


def act(event):
    taken = call("ui_take", {"call": event["call"]})
    if taken["action"] == "clear":
        notes.clear()
        publish()
    call("ui_reply", {"call": event["call"], "result": {"notice": "Notes cleared"}})


call("hello", {"plugin": NAME, "protocol": 1})
call("subscribe", {"topics": ["agents", "ui_calls", "service_calls"]})  # Before the first read.
call("set_services", {"services": [{"name": NAME, "methods": [
    {"name": "add", "callers": ["any"], "max_args": 4096},
    {"name": "list", "callers": ["any"]}]}]})
count_waiting()
publish()
call("report_health", {"state": "running"})

while True:
    if not events:
        events.append(read_frame()["event"])  # Blocks until the next event.
    event = events.pop(0)
    try:
        if event["kind"] == "service_call" and event["service"] == NAME:
            serve(event)
        elif event["kind"] == "ui_call" and event["plugin"] == NAME:
            act(event)
        elif event["kind"] in ("agents", "resync"):
            count_waiting()
            publish()
    except RuntimeError as error:  # Such as a reply after the caller's deadline.
        print(error, file=sys.stderr)

A worker is named by its state directory, so a second one with its own folders runs beside yours and leaves your setup alone. In a new shell, from the file’s folder:

root=$(mktemp -d)
mkdir -p "$root/config/vendetta" "$root/state" "$root/run"
chmod 700 "$root/state" "$root/run"
cat > "$root/config/vendetta/config.toml" <<EOF
[plugins.notes]
command = ["python3", "$PWD/notes.py"]
EOF
export XDG_CONFIG_HOME="$root/config" XDG_STATE_HOME="$root/state" XDG_RUNTIME_DIR="$root/run"

vendetta notify start
until vendetta notify status | grep -q notes=running; do sleep 0.2; done
vendetta service list
vendetta service call notes add '{"text": "Ship it"}'
vendetta service call notes list
vendetta notify stop

While you work on the file, the worker restarts the plugin when its process exits, a second later, so stop it to load an edit: pkill -f notes.py. The plugin’s stderr, a Python traceback included, goes to the worker’s log, $XDG_STATE_HOME/vendetta/notifications/worker.log. A plugin that exited or could not start shows as notes=unavailable; Plugins lists the causes.

vendetta notify status reports plugins: notes=running, service list shows notes with its two methods, and each call prints the plugin’s answer:

{
  "notes": [
    "Ship it"
  ]
}

An empty text exits 1 with the plugin’s error, text: one line, 1 to 200 characters.

The worker starts the plugin with the command from its table, as an argument list with no shell. It passes the socket’s path in VENDETTA_CONTROL_SOCKET, the config file’s path in VENDETTA_CONFIG, and a pipe on stdin that stays open while the worker lives.

The first request on a connection is hello:

{"type":"request","id":1,"method":"hello","params":{"plugin":"notes","protocol":1}}
{"type":"response","id":1,"result":{"protocol":1,"tmux_socket":"/tmp/tmux-1000/default"}}

plugin is a label. The worker knows the plugin by its process: the PID and start time of the exact program it started. A wrapper script must exec the plugin, or the worker supervises the wrapper and refuses the calls only a supervised plugin may make, report_health among them.

report_health {"state": "running"} tells the worker the plugin is ready. Until then notify status shows it as starting.

The stdin thread matters. When the worker stops a plugin it closes stdin and sends SIGTERM; if the worker dies, only stdin and the connection close. A plugin that exits on end of file never outlives its worker.

set_services declares what the plugin serves and who may call each method:

{"services": [{"name": "notes", "methods": [
  {"name": "add", "callers": ["any"], "max_args": 4096},
  {"name": "list", "callers": ["any"]}]}]}

callers is a list of plugin, owner, master, and any; the worker checks it against the calling process, and may always call itself. owner is you at a terminal you can see, never an agent; Who may call has the exact rule. any includes agents, so an agent can add a note with the same vendetta service call.

A call arrives as a service_call {call, service} event on the service_calls topic. The plugin reads it once with service_take, which gives {call, service, method, args, caller, deadline_ms}, and answers with service_reply, carrying a result or an error. The default deadline is 10 seconds. A call is never resent.

Plugins put UI into the apps as data. The apps and the chooser draw it with their own pieces, so the same page works in a browser, on an iPhone, and in a terminal.

ui_set_contributions puts an entry in a slot. Here the slot is nav, beside Chats, with a badge count and an on that opens the page:

{"id": "notes", "slot": "nav", "label": "Notes", "icon": {"symbol": "list"},
 "badge": 2, "on": {"page": "notes"}}

ui_set_page publishes a page: a flat map of keyed nodes and the key of its root. Send the whole page every time. The worker compares it with the last one and sends the apps only what changed, and a node that keeps its key is the same node, which is why each note gets a key that never repeats.

The Clear button’s on is {"action": "clear"}. A press reaches the plugin as a ui_call {call, plugin} event on the ui_calls topic. ui_take gives {call, page, node, action, args, context, caller}, with action and args exactly as the plugin published them, so a device can name a node and nothing more. ui_reply answers, here with a notice the app shows. confirm is a sentence the app asks before it calls.

Plugin UI lists every slot, layout, and element.

subscribe takes the topics the plugin wants, once per connection. An event says that something changed and never carries the new data, so the plugin rereads: on agents it calls list_agents again and republishes.

What keeps this correct:

  • Subscribe before the first read, so nothing changes between the read and the subscription.
  • Treat resync as “events were lost” and reread everything.
  • Events can arrive between a request and its response. call above queues them for the main loop.

list_agents entries carry state: running, input (a question is open), approval, idle, or unknown.

To act when an agent finishes, asks, needs approval, or fails, subscribe to notifications and call the notifications method on each event; it returns the alerts newest first. Plugins has a plugin that writes each one to a file.

Every plugin sends "protocol": 1 in hello. The worker refuses any other number, and the number changes only when the protocol breaks older plugins.

Add the table to your own ~/.config/vendetta/config.toml, with the path to the file. The worker applies a saved config by itself and starts the plugin:

[plugins.notes]
command = ["python3", "/path/to/notes.py"]

Every other key in the table is the plugin’s own to read from the file VENDETTA_CONFIG names. A plugin runs as you, with your permissions.

  • Never repeat an uncertain request. If the connection ends or times out after a request was written, the worker may have acted. An error response is a definite answer; a lost connection is not.
  • Start from a baseline. A plugin restarts whenever the worker does. Treat what exists at start as already handled.
  • Handles belong to their connection. An id from list_agents works only on the connection that listed it. To recognise an agent across restarts, use its conversation_key.
  • Give slow calls their own connection. A connection answers one request at a time.
  • Treat agent text as untrusted. Never run it or render it as markup.
  • Leave decisions to the person. No method answers a provider’s permission dialog.

Plugins has the full list, what the worker does for a plugin, the manifest keys, commands a plugin can add to vendetta, and troubleshooting. Plugin protocol has every method and event.

vendetta-protocol has the client and the wire types, and vendetta-ui-common has what a plugin’s main loop needs. Neither is on crates.io, so depend on a checkout:

[dependencies]
anyhow = "1"
serde_json = "1"
vendetta-protocol = { path = "../vendetta/crates/protocol" }
vendetta-ui-common = { path = "../vendetta/crates/ui-common" }

The same plugin in outline, with one method and the page:

use anyhow::{Result, ensure};
use serde_json::{Value, json};
use std::time::Duration;
use vendetta_protocol::{Client, Event, Heartbeat, Topic, exit_on_panic};
use vendetta_ui_common::plugin::{terminating, watch_termination};

const NAME: &str = "notes";

fn publish(client: &Client, notes: &[String]) -> Result<()> {
    let mut nodes = json!({
        "top": {"kind": "list", "empty": "No notes yet", "children": []},
    });
    for (index, text) in notes.iter().enumerate() {
        let key = format!("note:{index}");
        nodes[&key] = json!({"kind": "row", "title": text});
        nodes["top"]["children"].as_array_mut().unwrap().push(json!(key));
    }
    client.call(
        "ui_set_page",
        json!({"page": "notes", "title": "Notes", "root": "top", "nodes": nodes}),
    )?;
    client.call(
        "ui_set_contributions",
        json!({"contributions": [{"id": "notes", "slot": "nav", "label": "Notes",
            "icon": {"symbol": "list"}, "badge": notes.len(), "on": {"page": "notes"}}]}),
    )?;
    Ok(())
}

fn main() -> Result<()> {
    exit_on_panic();
    watch_termination()?;
    let client = Client::from_env(NAME)?;
    client.subscribe(&[Topic::ServiceCalls, Topic::Resync])?;
    client.call(
        "set_services",
        json!({"services": [{"name": NAME, "methods": [{"name": "add", "callers": ["any"]}]}]}),
    )?;
    let mut notes: Vec<String> = Vec::new();
    publish(&client, &notes)?;
    client.call("report_health", json!({"state": "running"}))?;
    // Exits the process if the loop stops beating, so the worker restarts it.
    let heartbeat = Heartbeat::new(NAME, Duration::from_secs(120));
    while !terminating() {
        heartbeat.beat();
        ensure!(!client.closed(), "The worker closed the connection");
        let Some(event) = client.next_event(Duration::from_millis(250))? else {
            continue;
        };
        if let Event::ServiceCall { call, service } = event {
            if service != NAME {
                continue;
            }
            let taken: Value = client.call("service_take", json!({"call": call}))?;
            if let Some(text) = taken["args"]["text"].as_str() {
                notes.push(text.to_owned());
                publish(&client, &notes)?;
            }
            client.call("service_reply", json!({"call": call, "result": {"notes": notes}}))?;
        }
    }
    Ok(())
}

What the crates add over the raw socket:

Piece Does
Client::from_env Connects to VENDETTA_CONTROL_SOCKET and sends hello
Client::call, call_timeout One request and its response; events that arrive meanwhile are kept for next_event
uncertain(&error) Says when a failed request may still have happened and must not be repeated
exit_on_panic Exits on a panic in any thread, so the worker restarts the plugin
Heartbeat Exits when the main loop stops beating
watch_termination, terminating A flag set on the worker’s SIGTERM or when stdin closes
plugin::Feed Connects, subscribes to agent changes, reports running, and rereads agents when they change
plugin::load_config Parses the config file the worker named

plugins/ntfy is a small shipped plugin to read, and plugins/dashboard is a whole page built from the worker’s overview.