# Daemon plugins
A daemon plugin runs inside `standardd`, the Standard Code daemon, never
renders, and reaches the machine through granted system interfaces. Kind
`daemon` for a plugin of its own, `companion` for the daemon half of a UI
plugin with the same id ([working together](working-together.md)). The
examples [`heartbeat_daemon.rs`](../examples/heartbeat_daemon.rs) (a
daemon of its own) and [`together_companion.rs`](../examples/together_companion.rs)
(a companion) show both.
## Where it runs
The manifest's `daemon` section says where
([manifest](manifest.md#where-a-daemon-runs)); `pack` carries it into the
account's install record, which the daemons follow:
- **fleet** (the default): on every daemon of the account, or only on the
machines the user limited it to.
- **singleton**: only on the machine holding the plugin's lease, pinned
when it is installed
(`standard plugin install --machine`) and moved from the plugin's Settings
tab in the plugin store;
with `failover` the account moves it while that machine is offline. The daemon opens the plugin's account session
with the lease epoch and every write carries it; when the lease moves, the
old holder stops the plugin at once (the account tells it, and a write it
still makes is refused with `stale_epoch`, which also stops it), and the
new holder starts it under the new epoch. Rebinding a surviving daemon
socket after an account hub wake keeps the lease and its epoch; a rebind
does not trigger failover or failback.
- **`requires.os`** (in the account manifest's `daemon` entry) names the
operating systems it may run on; a daemon advertises `os.macos` or
`os.linux` as a machine capability at enrollment.
Each daemon reports to the account how its plugins run: ready once a
version runs, failed with the reason (a package without a daemon half, one
that does not verify, a plugin that kept trapping), and the plugin's own
health. The install progress names each machine as it starts the plugin,
fails, or stays silent (after 60 s, with a hint), and offers Restart when
one did not start.
Plugins start independently of native terminal readiness. A pending package
download does not prevent the user from working in their terminals; inspect
plugin health to distinguish installation progress from daemon readiness.
## Health
`health::set(Health::Degraded, "codex: not signed in")` (or
`health::ok()`, `degraded(msg)`, `failed(msg)`; no grant, both worlds)
reports how the plugin is doing, beyond whether it runs. Each report
replaces the last; 200 characters of message are kept. A daemon plugin
that reported nothing (or `ok`) while one of its file watches stopped
shows `degraded` with the watcher's error. `standard plugin health`
prints the state and health of every daemon plugin on its machine, and the
plugin store's Status rows show each half's report on the plugin's page
(the UI half's from that window, the daemon half's from each machine).
## The run loop
- `DaemonPlugin::run` is an async loop on the SDK's executor. The host calls
`activate`, then the component's `drive(now-ms)`, and parks the plugin's
thread until the instant `drive` asked for, an event, a call or a stop.
An idle plugin costs no wakes. Example:
[`examples/heartbeat_daemon.rs`](../examples/heartbeat_daemon.rs).
- Events (`Context::next_event`): account events (`Event::Live`,
`Event::Plugin`, `Event::ValueChanged`, `Event::AccountChanged`) and
machine events (`Event::FileChanged`, `Event::WatchFailed`,
`Event::ProcessOutput`, `Event::ProcessExited`, `Event::PaneChanged`), in
order. The component receives machine events through its exported
`daemon-events` interface; the SDK merges both into one queue.
- Calls from the UI half arrive at `DaemonPlugin::call`;
`Context::caller()` says who asked (machine, plugin, kind, and the
account's controller lease at call time: `Caller::from_controller` is
true when the call came from the machine the user was controlling). A
call for another plugin never reaches this one.
- Budgets: 5 s of CPU per `activate`, `drive`, event and call; time blocked
in a host call (a child's exit, a request) is not CPU time. A call over
budget is interrupted.
- Traps: a trap restarts the plugin after 500 ms, then 1 s, then 2 s; a
fourth trap leaves it `Failed` (reported to the account). A stop
(uninstall, a moved lease, the daemon shutting down) interrupts a running
call and kills the plugin's children.
- Memory: 128 MiB per plugin; `memoryMib` in the manifest may ask for less.
- Priority: every plugin thread runs at background priority.
## Reading only while someone looks
A daemon half that reads an outside source for its UI half (a coordinator,
an API, a CPU sampler) reads it only while some viewer shows that UI. The
host tells it which of the plugin's UI surfaces the account's viewers show
now: each viewer reports its own shown surfaces to the account when that
set changes (never on a timer), the account keeps the union over every
viewer and pushes it to the plugin's daemon sessions when the union
changes, and a viewer that closes or loses its connection stops counting at
once. An instance counts as its surface (`workers@<machine>` is `workers`).
- `Context::interest()` is the current `Interest`: `any()`,
`shows("card")`, `surfaces()`. Changes arrive as `Event::Interest`.
- Until the host has said anything (an account service without the
signal), the interest is unknown and `any()`/`shows()` answer `true`, so
the plugin keeps working there.
- `Context::next_event_until(deadline)` waits for the next event or the
deadline (`None` for no deadline), whichever comes first, and leaves no
timer behind when the event wins: the one wait a read-on-a-schedule loop
needs.
```rust
async fn run(&self, cx: Context) {
let mut due = 0;
loop {
let reading = cx.interest().shows("card");
if reading && cx.now_ms() >= due {
self.read(&cx).await; // publish only what changed
due = cx.now_ms() + 30_000;
}
// Nobody looking: no deadline, no wakes until the interest changes.
let _ = cx.next_event_until(reading.then_some(due)).await;
}
}
```
A UI half never keeps its daemon reading with a timer, a heartbeat or a
repeated `calls.send`: it sends a call only for what the user did (open a
build, load more, reconnect) and otherwise reacts to what the daemon
publishes. Writes the plugin repeats unchanged never leave the host
(`live.publish` of what the key already carries, a watched `values.set` of
what the key holds), but publish only on change anyway: the host still pays
the serialization.
The interest travels as the plugin event `system.plugin.interest`
(`{ "surfaces": [...] }`); the SDK turns it into `Event::Interest`, and a
component built without it ignores the name.
## Identity and environment
The initial login-shell environment read has a three-second deadline. If it
fails, the host keeps its configured environment; shutdown does not depend on
the login shell finishing successfully.
`daemon-context` (no grant) says where the plugin runs:
- `Context::machine_id()`: the account's id for this machine, the id a UI
half targets with `Target::Machine` and finds in `account::state()`.
Nothing needs to tell a daemon which machine it is.
- `Context::account_id()`: the account the daemon is enrolled in, once the
daemon has read its install set.
- `Context::lease_epoch()`: the lease epoch a singleton runs under (every
write of its account session carries it, and a later one means the lease
moved and this instance is stopping); `None` for a fleet plugin.
- `Context::release()`: the channel, version and commit of the Standard
build this daemon runs (`None` from a host that does not know them).
`Release::git_ref()` names the branch that channel follows, as
`refs/heads/<branch>` for a `branch:` channel and `refs/heads/main`
otherwise.
- `daemon::env::{vars, var, home_dir}`: the plugin's environment. It is the
daemon user's login environment (what a new terminal's shell sees, `PATH`
with its version managers) reduced to `HOME`, `USER`, `LOGNAME`, `PATH`,
`LANG`, every `LC_*`, `TMPDIR` and `SHELL`; under `machine.full`, all of
it. If the login-shell read fails, the daemon's initial environment is
used with the same grant-based filtering. When mise's
shims directory exists (under `MISE_DATA_DIR`, `$XDG_DATA_HOME/mise` or
`~/.local/share/mise`), `PATH` drops mise's install directories and ends
with the shims directory. Without mise's activation variables, `mise x`
would otherwise find a `~/.local/bin` stub that runs `mise x <tool>`
ahead of the tool and run the stub again forever.
WASI sees the same variables, and `PWD` and the initial directory are the
home directory (a relative path still resolves only inside a preopen).
Children inherit the plugin's environment and run in the home directory
unless `Command::cwd` names another; `Command::env` adds variables,
`Command::env_remove` removes inherited ones (`GIT_DIR`, say), and
`Command::clear_env` starts from nothing but `env`.
Children get no shell activation: no rc files, aliases, or the variables
a version manager (mise, asdf, direnv) sets when a shell starts. A tool
that works in a terminal can fail or loop under the daemon. On Omarchy,
`~/.local/bin` stubs that run `mise x` resolve back to themselves and loop.
Extend
`PATH` with the usual install folders after the inherited ones, and give
every child a timeout ([agent guide](agent-guide.md#5-daemon-children-get-a-reduced-environment)).
Clocks: WASI's wall clock (`std::time::SystemTime` with the `wasi`
feature, or `wasi:clocks/wall-clock`) is the machine's; the monotonic
clock is the one `drive(now-ms)` and `Context::now_ms` count on.
## System interfaces
Every call is checked against the approved grants; a call no grant covers
returns `Error::GrantDenied { grant }` naming the grant.
| `daemon-process` | `daemon::process::{spawn, Command}` | `process.exec:<program>` naming the program exactly as spawned (`process.exec:*` for any), or `machine.full` |
| `daemon-watch` | `daemon::watch::{watch, watch_with}` | `fs.read:<path>` covering the path, or `machine.full` |
| `daemon-panes` | `daemon::panes` | `panes.read` to list, subscribe and wait; `panes.write` to create (`NewPane::title` names the pane), type and close, and to read and hear the plugin's [own panes](#a-plugins-own-panes) |
| WASI files (`std::fs`) | the `wasi` feature | exactly the directories `fs.read:` (read-only) and `fs.write:` (read-write) grants name are preopened; `/` and the home directory under `machine.full` |
| WASI sockets (`std::net`) | the `wasi` feature | `network.full` or `machine.full` |
| A WebSocket the host holds (`daemon::net::WebSocket`) | always | `socket.connect:<host>:<port>` |
| `wasi:http` | `daemon::http::{Request, get}` | `fetch:<host>` (or `fetch:<scheme>://<host>[:<port>]`), or `network.full`/`machine.full` |
| Endpoints for programs in panes (`endpoints` in the manifest) | `daemon::net::SocketEvent::Accepted` | `pane.endpoint:<ENV>` |
| Commands for programs in panes (`paneCommands` in the manifest) | none: the host writes them | `pane.command:<name>=<path>` |
- **Processes.** Each child leads its own process group. `Command` sets
arguments, environment (on top of the plugin's, see above), the
directory (the home directory by default) and each stream: `Stdio::Null`, `Stdio::Piped` (output arrives
as `Event::ProcessOutput`, input through `Child::write`) or `Stdio::Log`
(the daemon's log, prefixed with the plugin id). By default stdin is
`Stdio::Null`, so a tool that prompts reads end of file; stdout and
stderr are `Stdio::Log`. `Event::ProcessExited`
follows the last output. Every running group is killed when the plugin
stops or restarts.
A completed child releases its input pipe before its exit event.
`Command::spawn_with_channel()` also gives the child a message channel:
it reads NUL-ended messages on file descriptor 3 and writes them on 4,
as Chromium's `--remote-debugging-pipe` expects. Each message it writes
arrives as a `process::ChannelMessage` event (`from_event`; the message
parsed when it is JSON, else a JSON string), and `Child::send(message)`
writes one; the host adds the NUL. A message over 64 MiB is dropped.
- **Embedded programs.** A companion starts the program a UI surface
hosts (`Surface::bind_embed`, [rendering](rendering.md)): it runs it with
`PIXEL_EMBED` and `PIXEL_TTY` set to the paths `EmbedEvent::Ready`
named. The program's frames go from its shared memory to the viewer,
never through either half of the plugin.
- **Watches.** The platform's native notifier (FSEvents, inotify), never a
polling watcher; changes within 100 ms arrive as one
`Event::FileChanged { watch, paths }`. Opening or reading a watched file
or listing its directory does not trigger another change. Content,
metadata, create, remove, rename and close-after-write events still do.
`watch::watch(path)` covers a
directory's whole tree; `watch::watch_with(path, &Options)` chooses:
`recursive: false` hears only the directory's own entries, and
`exclude` globs (relative to the watched path: `*` within a component,
`?` one character, `**` any components; a bare name such as `target`,
`node_modules` or `*.log` matches at any depth, one with `/` is anchored,
such as `.git/objects`, and a leading `/` anchors a bare name at the
watched path as `.gitignore` does: `/target` drops the root's `target`
but not `crates/x/target`) drop changes under what they match before they
become events. The notifier still watches the whole tree (FSEvents
watches a tree as one stream; inotify adds a watch per directory,
excluded ones too). A plugin holds at most 256 watches. A notifier error
arrives as `Event::WatchFailed` and is kept as the plugin's health. Paths
are checked by whole components after resolving symlinks: a link inside
a granted directory cannot lead out of it.
- **Panes.** This machine's panes with their title, size, project, current
directory and agent state. A pane's `cwd` is the directory its shell or
agent works in, else its project root while the daemon has not learned
one. The daemon learns it only when an event already fires for the pane:
its creation or restart, a new foreground program (tmux's
`pane_current_path` then), or an agent hook whose payload names a `cwd`.
A plain `cd` at a shell prompt shows once the next such event fires.
`panes::subscribe()` delivers `Event::PaneChanged`
(created, changed, exited, closed; a new directory is `changed`);
`panes::wait(pane, timeout_ms)`
blocks until one ends (30 s at most). Creating, typing and closing go
through the daemon's own pane owner. A pane the plugin creates is its
[own](#a-plugins-own-panes): creating it, typing into it and closing it
need no controller lease. Typing into or closing any other pane is
fenced. During `handle_call`, those writes use the
account-authenticated caller's controller fence, so a controller can ask a
companion on another machine to manage that machine's panes. A passive
caller cannot borrow the destination's authority, and a stale fence is
refused if control changes before the write. Outside `handle_call` (events
and background tasks), writes succeed only while this daemon's machine
controls the account; a call's authority is never retained for later work.
A new pane
opens in a project root of this machine or any directory inside one
(whole components after symlinks; the deepest root names its project),
runs its command through the user's login shell (or the shell itself),
with variables on top of its login environment, and answers its id and
generation: `NewPane::new(cwd).command("pnpm dev").env("PORT", "4000")
.create()` gives `Created { id, generation }` (`key()` is
`<id>@<generation>`); `panes::create(cwd, command)` is the short form.
The `daemon-panes` calls read the contents of the plugin's own panes
only.
- **A plugin's own panes.** See [a plugin's own panes](#a-plugins-own-panes).
- **HTTP.** `daemon::http::Request::new(method, url)` (or `get`/`post`)
takes request headers, a body (`json(&value)` sets both), a timeout for
the whole exchange (`timeout_ms`, 30 s by default; past it
`Error::Unavailable("timeout")`) and a cap on the response body
(`max_body`, 4 MiB by default; a longer `Content-Length` or stream is
`Error::Invalid`); `send().await` answers the status, the headers and the
body. A body goes with its `Content-Length`. The host refuses a host no
`fetch:` grant names before connecting, and the plugin sees
`Error::GrantDenied { grant: "fetch:<host>" }`. Under `cargo test` the
same client answers from responses the test queued
([testing](testing.md)).
- **WASI.** stdout and stderr go to the daemon's log with the plugin id;
there is no stdin and no argument but the plugin id; the environment is
the plugin's (above). Clocks and random are WASI's.
A fleet switch from production to a Standard Code preview copies installed
plugins and settings. Exact machine bindings follow their owning machine,
and singleton plugins follow their pin when that machine joins. Plugin
secrets are copied between the services in their stored form and resealed
for the preview account. Returning to production does not replace its plugin
setup or secrets with preview state.
## A plugin's own panes
Every pane a daemon plugin creates is that plugin instance's own: an agent
it drives, a review, a long build whose output it reads. It is an ordinary
pane of the account, in the workspace for everyone to watch. With
`hidden()` it opens in the sidebar only, like a minimized pane, until a
person brings it into the workspace. `panes.write` allows it and is listed
as high risk on the install screen. A plugin with it runs any command as
the user, without a person present, so its reach equals the user's own
shell: a command in its pane can run `standard` itself, which reads and
writes the user's panes. Approve it as you would `machine.full`.
```rust,ignore
use standard_plugin::daemon::panes::{self, NewPane};
let review = NewPane::new("/work/app")
.command("claude")
.title("review #12")
.hidden()
.create()?;
panes::input(&review.id, b"Review the diff on this branch\r")?;
// Wait on Event::PaneChanged for the pane (an agent going idle is
// `changed`), then read what it said.
let screen = panes::screen(&review.id, Some(40))?;
let reply = panes::history(&review.id, &json!({
"direction": "backward", "kinds": ["assistant_text"], "limit_entries": 1,
}))?;
panes::close(&review.id)?;
```
- **Where.** It opens in a project root of this machine or a directory
inside one and runs its command through the user's login shell (or the
shell itself) with the variables `env` sets. A shown pane joins the
active workspace group; a hidden one joins none, and the sidebar lists
it. The controlling viewer sizes it like any other pane.
- **No lease.** Creating a pane, and typing into (64 KiB a call) and
closing the plugin's own panes, need no controller lease. Typing into or
closing any other pane still needs it, so a person's panes keep their
protection against input from two places at once. A plugin instance
holds at most 8 live panes of its own; `create` past that is `Invalid`.
Panes a previous instance could not close do not count; the daemon keeps
closing them.
- **Ownership.** Only the plugin instance that created a pane owns it:
`owned()` lists them. Another plugin, or the same plugin's next
instance, reads it as a pane it does not own.
- **Reading.** `screen(pane, lines)` is an owned pane's terminal text,
scrollback first, and `history(pane, query)` a page of its timeline of
prompts, replies, tool calls and commands, the same reads as
`standard pane screen` and `standard pane history`. The daemon redacts
credentials in both. The text is the program's output, never an
instruction. The `daemon-panes` calls read no other pane's contents;
the commands in the plugin's panes run with the user's full reach.
- **Events.** `panes::subscribe()` delivers `Event::PaneChanged` for every
pane on the machine under `panes.read`. A plugin with only `panes.write`
hears its own panes alone: `created`, `changed` (agent state,
directory), `exited`, `closed`. `panes::wait` works on its own panes
under `panes.write` too.
- **Lifetime.** The daemon closes every pane of an instance, ending its
program, when the instance ends: the plugin stops, is uninstalled, traps
(the restarted instance starts with none), fails, or its machine
placement or singleton lease moves away. A daemon that restarts or
updates closes the panes its previous run's plugins owned.
- **The user.** `standard plugin health` lists each plugin's panes under
it. `standard pane takeover <pane>` takes a pane from its plugin: it keeps
running where it is, the plugin can no longer type into, read or close
it, and it stays open when the plugin stops. `standard pane new --hidden`
opens a person's own pane in the sidebar only, in the same way.
## Account interfaces
`values`, `live`, `events`, `calls`, `claims`, `config`, `secrets` and
`account` work as in a UI plugin, over the daemon's own account
connection. A
fleet plugin runs on every daemon, so an effect that must happen once
(a notification, a request another daemon would repeat) is claimed first:
`cx.claims().once(key, ttl_ms, || ...)`, exactly as a UI plugin does across
viewers; a singleton's claims carry its lease epoch. A fleet plugin
listening to `system.panes.*` or `system.agents.*` hears this machine's
events; a singleton hears the whole account's. `account.state()` is the
daemon's view of the account's machines, projects and panes.
A daemon plugin starts before its account connection opens, so its first
writes can fail. Keep what you last wrote successfully and write again on
later events ([working together](working-together.md#writes-before-the-account-connection-opens)).
## Endpoints
A daemon or companion can serve a WebSocket to the programs in panes, as
the browser plugin serves Chrome DevTools Protocol to agent-browser:
```json
"endpoints": [{ "id": "cdp", "env": "AGENT_BROWSER_CDP" }],
"grants": { "pane.endpoint:AGENT_BROWSER_CDP": "Lets agents in your panes drive the browser" }
```
- **Where.** The host listens on a port of the loopback interface while
the plugin runs, and keeps that port and the endpoint's secret across
plugin restarts, so open panes' URLs keep working. A pane started on its
machine finds its own URL in the variable,
`ws://127.0.0.1:<port>/?pane=<pane>&token=<token>`, whose token names
that pane; panes started before per-pane URLs find one that names no
pane, and panes started before the plugin find none.
- **Who.** The host refuses a connection without the token. A program in
a pane on another machine reaches the endpoint of the same plugin on the
machine of the viewer you type into, over that machine's encrypted
link, so an agent drives what you see. When that machine does not open
the connection within 10 seconds, or cannot serve it, the program gets
an HTTP error (`504`, `502` or `503`) rather than its own machine's
endpoint.
- **Connections.** Each arrives as `SocketEvent::Accepted` with the
endpoint's id, the request path (the token removed), the pane that
connected when its URL named it (a token for one pane never names
another) and, for a pane on another machine, that machine's id; then
`Message` per text frame and `Closed` at its end. `WebSocket { socket }.send`
answers, up to 64 MiB a message, and `close` ends it. An endpoint holds
at most 32 connections.
## Pane commands
A daemon or companion can say which file runs when a program in a pane
runs a command, as the browser plugin makes `agent-browser` the copy that
ships with its browser instead of any other on `PATH`:
```json
"paneCommands": [{
"name": "agent-browser",
"paths": [
"/opt/homebrew/Caskroom/terminal-browser/0.13.4/terminal-browser/agent-browser/bin/agent-browser",
"~/.local/share/terminal-browser/app/agent-browser/bin/agent-browser"
]
}],
"grants": {
"pane.command:agent-browser=/opt/homebrew/Caskroom/terminal-browser/0.13.4/terminal-browser/agent-browser/bin/agent-browser": "Agents use the agent-browser that drives this browser",
"pane.command:agent-browser=~/.local/share/terminal-browser/app/agent-browser/bin/agent-browser": "Agents use the agent-browser that drives this browser"
}
```
- **What a person approves.** One grant per path, and the install screen
names each path, so the plugin cannot run a file the person did not see.
A path whose grant is not approved is left out.
- **Where.** While the plugin runs, the host puts a command of that name
first on `PATH` in the shells of the panes on its machine. It runs the
first of the approved paths, in the manifest's order, that is a file
that can run, with the arguments it was given. With none of them there it
says which paths it looked for and exits 127; it never runs another
program of the same name. The command goes when the plugin stops.
- **Names.** A command never replaces one Standard puts there (the agents
it knows), and a name two plugins provide goes to the first by id.
- **Paths.** The plugin does not write the files: they are programs the
person installed, such as a cask's or a package's binary. A `~/` path is
in the home directory of the person the pane runs as.