More than a question
A question is one of four things a Plugin may declare. It may also be told to do something, with a command; say that something happened, with an occurrence; and publish live data, with a stream. Each is declared, each is governed by a capability, and each reaches the Plugin only if the operator granted it (the families).
| A Plugin | Declares | Does | Governed by a capability such as |
|---|---|---|---|
| is asked | a question | answers it, with bytes of its own | query.hello.answer |
| is told | a command | acknowledges it: accepted, done or failed, with a line | command.set.accept |
| reports | an occurrence | reports it with a severity it states, a line and bytes of its own | event.changed.report |
| publishes | a stream | sends data on it, once the Core has activated it | stream.<name>.publish |
Told, and saying so
The greeter now also accepts the command greeter.set, whose payload is the greeting to use, and
reports the occurrence greeter.changed when the greeting changes. The question answers with the
greeting in force. The whole program, in each language:
- Go
- Rust
- Python
- C
- C++
// Command greeter is a Plugin that answers who it is greeting, and is told how to greet.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/yoke-project/yoke-sdk-go/plugin"
)
func declaration() plugin.Declaration {
return plugin.Declaration{
ID: "com.example.greeter",
Commands: []string{"greeter.set"},
Queries: []string{"greeter.hello"},
Occurrences: []string{"greeter.changed"},
Capabilities: []plugin.Capability{
{Name: "command.set.accept", Governs: plugin.Object{Command: "greeter.set"}},
{Name: "query.hello.answer", Governs: plugin.Object{Query: "greeter.hello"}},
{Name: "event.changed.report", Governs: plugin.Object{Occurrence: "greeter.changed"}},
},
}
}
// A change of greeting is routine: the author states its severity, since the library chooses none.
var changed = plugin.SeverityOf(10)
// greeter is the Plugin's own state: the word it greets with.
type greeter struct{ greeting string }
func (g *greeter) handle(u *plugin.Unit, event any) error {
switch e := event.(type) {
case plugin.Question:
if e.Type == "greeter.hello" {
return u.Answer(e, []byte(g.greeting+", "+string(e.Payload)))
}
case plugin.Command:
if e.Type == "greeter.set" {
if len(e.Payload) == 0 {
return u.Ack(e, plugin.Failed, "a greeting cannot be empty")
}
g.greeting = string(e.Payload)
line := "greeting with " + g.greeting
if err := u.Ack(e, plugin.Done, line); err != nil {
return err
}
return u.Report("greeter.changed", changed, line, nil)
}
}
return nil
}
func main() {
if len(os.Args) == 2 && os.Args[1] == "--manifest" {
os.Stdout.Write(declaration().Manifest())
return
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
u, err := plugin.Start(ctx, declaration())
if err != nil {
fmt.Fprintln(os.Stderr, "greeter:", err)
os.Exit(1)
}
u.Health(0, "ready to greet")
g := &greeter{greeting: "hello"}
for {
select {
case event, open := <-u.Events():
if !open {
return
}
if err := g.handle(u, event); err != nil {
fmt.Fprintln(os.Stderr, "greeter:", err)
}
case <-ctx.Done():
u.Close()
<-u.Done()
return
}
}
}
//! greeter: a Plugin that answers who it is greeting, and is told how to greet.
use tokio::signal::unix::{SignalKind, signal};
use yoke_sdk::base::Error;
use yoke_sdk::plugin::{Capability, Declaration, Event, Object, Outcome, Severity, Unit, start};
fn declaration() -> Declaration {
Declaration {
id: "com.example.greeter".into(),
commands: vec!["greeter.set".into()],
queries: vec!["greeter.hello".into()],
occurrences: vec!["greeter.changed".into()],
capabilities: vec![
Capability {
name: "command.set.accept".into(),
governs: Object::Command("greeter.set".into()),
},
Capability {
name: "query.hello.answer".into(),
governs: Object::Query("greeter.hello".into()),
},
Capability {
name: "event.changed.report".into(),
governs: Object::Occurrence("greeter.changed".into()),
},
],
..Default::default()
}
}
/// A change of greeting is routine: the author states its severity, since the library chooses none.
const CHANGED: u8 = 10;
async fn handle(unit: &Unit, greeting: &mut String, event: &Event) -> Result<(), Error> {
match event {
Event::Question(q) if q.r#type == "greeter.hello" => {
let answer = format!("{greeting}, {}", String::from_utf8_lossy(&q.payload));
unit.answer(q, answer.into_bytes()).await
}
Event::Command(c) if c.r#type == "greeter.set" => {
if c.payload.is_empty() {
return unit.ack(c, Outcome::Failed, "a greeting cannot be empty").await;
}
*greeting = String::from_utf8_lossy(&c.payload).into_owned();
let line = format!("greeting with {greeting}");
unit.ack(c, Outcome::Done, &line).await?;
unit.report("greeter.changed", Some(Severity::of(CHANGED)), &line, Vec::new())
.await
}
_ => Ok(()),
}
}
#[tokio::main]
async fn main() {
if std::env::args().nth(1).as_deref() == Some("--manifest") {
print!("{}", declaration().manifest());
return;
}
let unit = match start(&declaration()).await {
Ok(unit) => unit,
Err(err) => {
eprintln!("greeter: {err}");
std::process::exit(1);
}
};
let _ = unit.health(0, "ready to greet").await;
let mut greeting = String::from("hello");
let mut term = signal(SignalKind::terminate()).expect("greeter listens for SIGTERM");
loop {
tokio::select! {
event = unit.next() => match event {
None | Some(Event::Ended(_)) => return,
Some(event) => {
if let Err(err) = handle(&unit, &mut greeting, &event).await {
eprintln!("greeter: {err}");
}
}
},
_ = term.recv() => {
let _ = unit.close().await;
while let Some(event) = unit.next().await {
if matches!(event, Event::Ended(_)) {
break;
}
}
return;
}
}
}
}
"""greeter: a Plugin that answers who it is greeting, and is told how to greet."""
import asyncio
import signal
import sys
from yoke_sdk import base, plugin
def declaration():
return plugin.Declaration(
id="com.example.greeter",
commands=["greeter.set"],
queries=["greeter.hello"],
occurrences=["greeter.changed"],
capabilities=[
plugin.Capability("command.set.accept", plugin.Object(command="greeter.set")),
plugin.Capability("query.hello.answer", plugin.Object(query="greeter.hello")),
plugin.Capability("event.changed.report", plugin.Object(occurrence="greeter.changed")),
],
)
# A change of greeting is routine: the author states its severity, since the library chooses none.
CHANGED = plugin.Severity.of(10)
class Greeter:
def __init__(self):
self.greeting = "hello"
async def handle(self, unit, event):
if isinstance(event, plugin.Question) and event.type == "greeter.hello":
await unit.answer(event, f"{self.greeting}, {event.payload.decode()}".encode())
elif isinstance(event, plugin.Command) and event.type == "greeter.set":
if not event.payload:
await unit.ack(event, plugin.Outcome.FAILED, "a greeting cannot be empty")
return
self.greeting = event.payload.decode()
line = "greeting with " + self.greeting
await unit.ack(event, plugin.Outcome.DONE, line)
await unit.report("greeter.changed", CHANGED, line)
async def run():
unit = await plugin.start(declaration())
await unit.health(0, "ready to greet")
greeter = Greeter()
stopping = asyncio.Event()
asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, stopping.set)
asked = asyncio.create_task(stopping.wait())
while True:
following = asyncio.create_task(unit.next())
done, _ = await asyncio.wait({following, asked}, return_when=asyncio.FIRST_COMPLETED)
if following in done:
event = following.result()
if event is None or isinstance(event, plugin.Ended):
return
try:
await greeter.handle(unit, event)
except base.Error as err:
print("greeter:", err, file=sys.stderr)
continue
following.cancel()
await unit.close()
while (event := await unit.next()) is not None and not isinstance(event, plugin.Ended):
pass
return
def main():
if sys.argv[1:] == ["--manifest"]:
sys.stdout.write(declaration().manifest())
return
try:
asyncio.run(run())
except base.Error as err:
print("greeter:", err, file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
/* greeter: a Plugin that answers who it is greeting, and is told how to greet. */
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <yoke/plugin.h>
static const char *const commands[] = {"greeter.set", NULL};
static const char *const queries[] = {"greeter.hello", NULL};
static const char *const occurrences[] = {"greeter.changed", NULL};
static const yoke_capability capabilities[] = {
{.name = "command.set.accept", .governs = {YOKE_GOVERNS_COMMAND, "greeter.set"}},
{.name = "query.hello.answer", .governs = {YOKE_GOVERNS_QUERY, "greeter.hello"}},
{.name = "event.changed.report", .governs = {YOKE_GOVERNS_OCCURRENCE, "greeter.changed"}},
{0},
};
static const yoke_declaration declaration = {
.id = "com.example.greeter",
.commands = commands,
.queries = queries,
.occurrences = occurrences,
.capabilities = capabilities,
};
/* A change of greeting is routine: the author states its severity, since the library chooses none. */
#define CHANGED YOKE_SEVERITY(10)
static char greeting[64] = "hello";
static volatile sig_atomic_t stopping;
static void on_term(int sig) { (void)sig; stopping = 1; }
static int handle(yoke_unit *unit, const yoke_event *e, yoke_error *err) {
if (e->kind == YOKE_QUESTION && strcmp(e->type, "greeter.hello") == 0) {
char answer[192];
int len = snprintf(answer, sizeof answer, "%s, %.*s", greeting, (int)e->payload_len,
(const char *)e->payload);
return yoke_answer(unit, e, answer, (size_t)len, err);
}
if (e->kind == YOKE_COMMAND && strcmp(e->type, "greeter.set") == 0) {
if (e->payload_len == 0)
return yoke_ack(unit, e, YOKE_FAILED, "a greeting cannot be empty", err);
if (e->payload_len >= sizeof greeting)
return yoke_ack(unit, e, YOKE_FAILED, "a greeting is at most 63 bytes", err);
memcpy(greeting, e->payload, e->payload_len);
greeting[e->payload_len] = '\0';
char line[96];
snprintf(line, sizeof line, "greeting with %s", greeting);
if (yoke_ack(unit, e, YOKE_DONE, line, err) != 0)
return -1;
return yoke_report(unit, "greeter.changed", CHANGED, line, NULL, 0, err);
}
return 0;
}
int main(int argc, char **argv) {
if (argc == 2 && strcmp(argv[1], "--manifest") == 0) {
char *manifest = yoke_manifest(&declaration);
fputs(manifest, stdout);
free(manifest);
return 0;
}
signal(SIGTERM, on_term);
yoke_error err = {0};
yoke_unit *unit = yoke_start(&declaration, &err);
if (unit == NULL) {
fprintf(stderr, "greeter: %s\n", err.message);
yoke_error_clear(&err);
return 1;
}
yoke_health(unit, 0, "ready to greet", &err);
yoke_event event = {0};
while (!stopping) {
int got = yoke_next_within(unit, &event, 200);
if (got == 0)
break; /* the Session has ended */
if (got == 1) {
if (handle(unit, &event, &err) != 0) {
fprintf(stderr, "greeter: %s\n", err.message);
yoke_error_clear(&err);
}
yoke_event_clear(&event);
}
}
if (stopping) {
yoke_close(unit, &err);
while (yoke_next(unit, &event) == 1)
yoke_event_clear(&event);
}
yoke_free(unit);
return 0;
}
// greeter: a Plugin that answers who it is greeting, and is told how to greet.
#include <atomic>
#include <chrono>
#include <csignal>
#include <iostream>
#include <string>
#include <string_view>
#include <variant>
#include <yoke/base.hpp>
#include <yoke/plugin.hpp>
using namespace yoke::plugin;
Declaration declaration() {
return {
.id = "com.example.greeter",
.commands = {"greeter.set"},
.queries = {"greeter.hello"},
.occurrences = {"greeter.changed"},
.capabilities = {{"command.set.accept", {Governs::command, "greeter.set"}},
{"query.hello.answer", {Governs::query, "greeter.hello"}},
{"event.changed.report", {Governs::occurrence, "greeter.changed"}}},
};
}
// A change of greeting is routine: the author states its severity, since the library chooses none.
const Severity changed = Severity::of(10);
class Greeter {
public:
void handle(Unit &unit, const Event &event) {
if (auto *q = std::get_if<Question>(&event); q && q->type == "greeter.hello") {
unit.answer(*q, greeting_ + ", " + q->payload);
} else if (auto *c = std::get_if<Command>(&event); c && c->type == "greeter.set") {
if (c->payload.empty()) {
unit.ack(*c, Outcome::failed, "a greeting cannot be empty");
return;
}
greeting_ = c->payload;
std::string line = "greeting with " + greeting_;
unit.ack(*c, Outcome::done, line);
unit.report("greeter.changed", changed, line);
}
}
private:
std::string greeting_ = "hello";
};
static std::atomic<bool> stopping;
int main(int argc, char **argv) {
if (argc == 2 && std::string_view(argv[1]) == "--manifest") {
std::cout << declaration().manifest();
return 0;
}
std::signal(SIGTERM, [](int) { stopping = true; });
try {
auto unit = Unit::start(declaration());
unit->health(0, "ready to greet");
Greeter greeter;
while (!stopping && !unit->done()) {
if (auto event = unit->next(std::chrono::milliseconds(200)))
greeter.handle(*unit, *event);
}
if (stopping) {
unit->close();
while (unit->next()) {
}
}
} catch (const std::exception &err) {
std::cerr << "greeter: " << err.what() << '\n';
return 1;
}
}
What is new is the declaration and the handling of each event:
- A command is acknowledged once, at least.
donewhen it is carried out,failedwhen it cannot be, each with a line for a person;acceptedfirst when the work outlasts the wait a caller is given, followed by onedoneorfailed. An acknowledgement carries no result: a result is an answer. - An occurrence carries the severity its author states, from 0 to 99, higher being more serious. The library chooses none, and an occurrence reported without one is refused (severity).
- The state is the Plugin's own. The greeting lives in the program; the Core neither reads nor keeps
it, and a Plugin that is restarted starts from
helloagain.
Build it and print its Manifest again, as on the program. It now declares three capabilities:
manifest: 1
id: com.example.greeter
protocol: 1
commands:
- id: greeter.set
queries:
- id: greeter.hello
occurrences:
- id: greeter.changed
capabilities:
- name: command.set.accept
governs:
command: greeter.set
- name: query.hello.answer
governs:
query: greeter.hello
- name: event.changed.report
governs:
occurrence: greeter.changed
Try it
Write the Manifest again and take the Plugin into try/ again, as in
after a change, and declare a channel there: a command reaches a Plugin
from an interface, and an interface attaches to a channel. From greeter/:
build/x86_64/greeter --manifest > plugin/com.example.greeter.yaml
yoke-compose add channel cli --dir try --transport local --clients multiple
yoke app run --from try
By hand, the same is done to greeter-try/, with the digest written again
(after a change).
Grant the three capabilities, and restart the unit so that it is admitted with them:
yoke plugin grant com.example.greeter command.set.accept
yoke plugin grant com.example.greeter query.hello.answer
yoke plugin grant com.example.greeter event.changed.report
yoke unit restart greeter
A command is sent by an interface client attached to the channel, with its library's Command call:
in Go, a.Command(ctx, "greeter", "greeter.set", []byte("ciao"))
(an interface client). Told ciao, the greeter acknowledges
done with the line greeting with ciao; told an empty greeting, it acknowledges failed with
a greeting cannot be empty. The question then answers with the new greeting:
echo -n world | yoke unit ask greeter greeter.hello --input -
ciao, world
And the occurrence is in the instance's log, under the unit, its incarnation and the severity the greeter stated:
yoke log query --unit greeter
…
2026-11-02T20:37:10.786896563Z greeter/2 [10] greeting with ciao
A report the Plugin was not granted is refused by the Core, and the Session goes on. The library
hands the refusal to the Plugin as an event, correlated to the message it refused; the greeter above
ignores it. Granted everything but event.changed.report, a greeter that wrote each refusal to its
standard error would leave this in the log:
2026-11-02T20:48:35.562801791Z greeter/2 [10] greeter: refused: u-5 scope.withheld: the unit's grant does not cover the occurrence greeter.changed
What a Plugin does about what it was not granted is its own to decide: carry on without it, run reduced, or exit (admission).
Streams
A stream is live data a Plugin publishes: samples, frames, a measurement as it happens. It is
declared with what its data tolerates — loss, reordering — and the Plugin sends on it only once the Core
has activated it, which the library hands over as an event naming the stream, its transport and its
address. Before that there is nowhere to send, and the library refuses rather than make a transport of
its own. An operator starts and stops a stream with yoke stream start and yoke stream stop, and an
interface subscribes to it through a channel (streams and transports,
streams to clients).
Needs
What a Plugin must reach on the host is declared as a need, by class and never by a particular
thing: device:instrument, storage:datasets, secret:token, display. That this program opens a
serial device is true of it wherever it runs; which device a copy of it opens is a fact about one
deployment, supplied by the application that runs it. A Plugin declares the class, and the application
binds the thing (the Manifest,
how a unit gets a secret).