API Commands
Source: ExaBGP reactor/api/command/, reactor/api/dispatch/
Purpose: Document all API commands for compatibility
Design decisions
| Decision | It forbids | Source | Date |
|---|---|---|---|
| The pipe wins: a command path names the subject and stops; scope, presentation and format are pipe operations after it, selector words included | Rewriting the command line to carry a pipe as an argument; refusing a pipe a command declares; a subcommand for scope or presentation | plan/records/audit-command-pipe-vs-subcommand.md, plan/records/audit-presentation-pipes.md | 2026-08-21 |
A command may override any generic pipe operation that acts on its data, as long as the answer keeps the generic's data format: every data operator of the catalog is overridable, each held to its generic's answer shape; a format, paging, save and log are the data format or its display, and stay the generic's. In Thomas's words: "I believe it should be possible to overwrite more command as long as their data format is not changed." |
Limiting overrides to a fixed list of names (count, first, last, match); an override that answers another shape than its generic; a command declaring a format's, paging's, save's or log's name |
plan/release/fixes/spec-pipe-chain-honored-on-every-command-surface.md, 69944ce197 | 2026-11-20 |
Overview
Ze uses verb-first command paths with JSON or text encoding.
Transport Request Metadata
REST and gRPC remain thin adapters over the shared API engine. Execute and
Stream pass the caller's context.Context together with trusted auth
metadata (Username, RemoteAddr) into the engine; hub wiring then builds
pluginserver.CommandContext for dispatcher/accounting use.
Request bodies and plugin RPC payloads do not carry identity fields. Caller identity is injected only by trusted transport wiring.
ExaBGP Differences
| Aspect | ExaBGP | Ze |
|---|---|---|
| Syntax styles | v4 (action-first) and v6 (target-first) | Verb-first only |
| Encoder | json or text (v4), json only (v6) | json or text |
| Peer selectors | *, IP, filters ([local-as ...]) |
*, IP, negated (!IP) |
| Multi-session filters | Supported (draft) | Not supported |
| Forward command | Not available | send bgp <selector> cached <id> for route reflection |
Command Verb Taxonomy
Commands follow a verb-first convention: <action> <module> [args...].
The verb identifies the action, and the module implements it.
command.Verbs is the vocabulary, and it gives each verb one of three roles:
RoleRead for show, monitor and resolve, RoleMutation for set and
delete, and RoleAction for every other verb. A token the map does not hold
answers RoleUnspecified, which is what IsVerb reads.
The command verb reference describes each verb's behavior, its selectors, and the requirements for commands that use it.
IsReadOnlyPath selects the authorization section for a command. It uses
command.IsReadOnlyVerb to identify read verbs and also accepts five legacy
noun-first roots as read-only commands.
Internal dispatch: <action> <module> is dispatched as the module implementing the action.
For example, monitor bgp is handled by the BGP module's monitor implementation.
Legacy noun-first RPCs (peer list, bgp summary) remain for internal dispatch but
user-facing commands use verb-first syntax.
Streaming vs polling: monitor commands keep the display active and auto-refresh.
monitor event streams live events line-by-line. monitor bgp polls summary data
every second and renders a dashboard. Both use the monitor verb because they
produce continuously-updating output.
Command Categories
| Category | Commands |
|---|---|
| Daemon | shutdown, reload, restart, status |
| Session | ack, sync, reset, ping, bye |
| System | help, version, api version |
| Peer | list, detail, capabilities, statistics, set (add/save), delete, teardown, notify, flush |
| Announce | route, flow, vpls, eor, operational |
| Withdraw | route, flow, vpls, watchdog |
| RIB | routes, best, status, clear |
| Log | levels, set (runtime log levels) |
| Metrics | values, list (Prometheus metrics) |
| Group | start, end (batching) |
| Monitor | monitor bgp (TUI dashboard), monitor event (live event streaming), monitor system netlink (kernel events) |
| Subscribe | request subscribe, request unsubscribe (event filtering) |
| OSPF | show ospf neighbor, interface, database, route, border-routers, spf; for OSPFv3, show ospf ipv6 neighbor, interface, database, route, spf, graceful-restart, segment-routing, each answering every running address family and taking address-family <af> to narrow |
| Reports | show warnings, show errors (cross-subsystem operational report bus) |
Dispatch keys are YANG paths
The daemon registers each built-in handler under its YANG command path, derived
from the tree (LoadBuiltins: d.RegisterWithOptions(wireToPath[wireMethod], ...)).
The loader receives the command tree alongside the maps derived from that same
schema. It carries hidden ancestors into builtin and local-data metadata, and
binds that tree before plugins declare commands.
Because dispatch uses that path, moving a ze:command container renames the
command. Callers that still send the old path will fail, including plugins using
dispatch-command or an interactive plugin CLI session. Before migrating a
noun-first command to verb-first syntax, search for its senders and update them
too. See ai/rules/cli.md, "Migrating a Built-in Command's Path".
A dispatch key has one holder. Dispatcher.RegisterWithOptions refuses a name
already registered, compared case-insensitively, with ErrCommandHeld naming the
holder (a builtin's holder is its wire method), and the holder keeps the name.
The builtin loader also refuses a wire method that two linked builtins carry
(ErrWireMethodHeld). NewServer returns either refusal, and a refused
registration in the socket wire-method dispatcher, so a collision stops the
daemon at startup. The order in which init() runs across packages is not
controlled, so a later registration never replaces an earlier one.
Private artifact imports and selected-configuration restores are declared in the artifact YANG model and registered with ordinary mutation audit metadata. Import consumes an account-owned completed byte transfer and delegates to the standalone data import producer inside complete artifact staging. Selected restore finishes the native checked source read before entering the installed runtime owner's shared restore publication. Source selection and live reload therefore do not hold the artifact owner lock together. Transport adapters use the same modeled command paths and authenticated account; they do not implement another import, selection or publication algorithm.
A native artifact refusal retains its complete operator error and HTTP category through the command answer, including a singleton join created when cleanup succeeds. If the operation and an independent cleanup both fail, the answer keeps both causes and reports HTTP 500. Selecting the first refusal from that aggregate would hide the cleanup failure.
A parent command never swallows a registered child
The daemon serves the LONGEST registered key that prefixes the input and hands the
rest to that handler as arguments. A parent registered at a short path would
therefore own the whole subtree below it, children another owner registered
included. show bgp is a builtin key; show bgp rpki status is a PLUGIN name that
Dispatch reaches only after the builtin match fails, so an unguarded match sends
the rpki subtree to the summary handler, which reads its first argument as an
address family.
matchBuiltinTokens refuses its match when a LONGER prefix of the input is itself a
registered command. It asks all three registries the dispatcher resolves from: the
builtin keys, the plugin registry, and the subsystem handlers. The test is a
registered PATH, never the presence of leftover tokens, because leftovers are how
every argument-taking command works: show bgp ipv4 still reaches its
handler with the family.
The client-side lookup carries the same rule, and the two are separate because they read different registries. Neither is derived from the other.
A command that starts work outliving its request
A builtin handler can start work that keeps running after it answers: update serve start opens a listener and serves it from a goroutine. No config
transaction and no plugin process owns that work, so the handler binds it to
the daemon's plugin server with CommandContext.Server.OnStop(fn) before it
starts the goroutine. The server's Stop, which the daemon's ordered shutdown
calls, cancels the server context and then runs every registered fn, and
returns only once each has ended its work, goroutines included. OnStop
answers a withdrawal the owner calls when the work ends first (an operator's
update serve stop), and it refuses once Stop has started, so a command that
arrives while the daemon stops starts nothing.
Each fn returns an error when its cleanup fails. StopFailure retains every
hook error alongside any fatal plugin error, so the daemon exits with failure
after it has joined all cleanup work.
Offline fallback (read-only commands without a daemon)
Some read-only show commands are useful when the daemon is unreachable:
show crashes helps investigate a stopped daemon, and show host provides
hardware inventory before startup. Their owner registers an in-process handler with
command.MustRegisterOfflineFallback(path, handler) from its init(). The CLI serves the command from the
daemon when it is reachable and calls the fallback only after a connection failure,
so the fallback never shadows the daemon. A daemon that answers and refuses the login is
not a connection failure: its SSH server presented a host key the client accepted, so the
dial answers sshclient.LoginRefused, and ze cli prints that the daemon refused the
login, with the login fix, and never calls the fallback, whose answer would claim no
daemon ran. cmdutil.RunCommand sends a path that has a
registered fallback down the daemon path even when the CLI binary's tree does not hold it,
so the fallback is reachable with no daemon; any other path the tree does not hold takes
the route of the next section. Output is identical to the daemon RPC (both read the same detection library
/ crash files), so online and offline results match. show crashes holds that
identity to one call on each side: both build their rows from
crashlog.CrashListFields and their readiness block from crashes.Readiness, so
the answer cannot vary with the health of the box being diagnosed.
A path the ze binary does not hold (an external plugin's command)
ze <verb> <path> resolves the path against the command tree compiled into the
binary. An external plugin brings its commands in its own YANG, which the
daemon joins when ze start runs the plugin, so ze show acme-monitor status
names a path that tree does not hold even while the running ze serves it.
Before such a path is refused, cmdutil.RunCommand asks the running ze:
| What answers | What the operator gets |
|---|---|
| A running ze that holds the command | Its answer, as for a compiled-in command: the line goes through the same one-shot route as ze cli -c (cli.RunReached), so the output, the exit code, a refusal of a value, and the format keyword (ze show acme-monitor status json) are the daemon's |
| A running ze that holds no such command either | error: unknown command: <path>, the nearest compiled-in command, and ze <verb> help, as with no daemon; the daemon's own text follows as a hint when it says more than "unknown command" |
| ✕ | An operator error: the path is not available, may belong to an external plugin, which only a running ze holds, why no ze answered, and one fix: ze start when nothing listens, ze status when the address cannot be read, ze cli --user <name> -c "<path>" when a ze listens and this account cannot log in |
| ✕ | error: unknown command: <path> with its hints, unchanged |
The walk to the daemon is sshclient.ReachDaemon, and the wording of each step
it stops at is sshclient.Unreached.Explain, shared with the daemon route of
ze config validate, fmt, dump, diff and graph. Which plugins the
stored config declares is the step every command that parses a config with no
daemon takes (config.PublishDeclaredSchemas): no plugin program is started
(owner ruling of 2026-11-16). A stored config that cannot be read leaves the
unknown-command refusal in place, with a hint that says the config was not
checked.
ze <verb> <path> help still renders from the compiled-in tree, so for an
external plugin's path it prints only the navigation usage line, and shell
completion of ze <verb> offers no external plugin's command: both need the
running ze's tree, and ze cli (?, Tab) has it.
Local-data commands (answered in the caller's own process, and by the daemon)
A local-data command needs no daemon. Its handler reads a registry that
init() filled in the process running it, so the answer exists before
main() does, and the daemon runs the same handler for a remote caller
(below). It registers with command.MustRegisterLocalData(path, handler, meta, command.RenderLocalAnswer) and returns DATA, which is what lets | json,
| yaml and | table be three renderings of one payload. The handler
(command.LocalDataHandler) takes the command.ValidatedArgs the validator
returned, never a token slice, and reads Tokens(), Positional(leaf), or
Value(leaf). The
data-handler and local-handler registries live in package command rather than
in command/registry, because that package cannot import command and so
cannot name the value.
The handler returns a command.LocalAnswer: a payload, an exit code and a
diagnostic, and the three are independent. The code carries the verdict, the
payload carries the evidence, and show config validation is the command that
needs both: it answers the diagnostics of a configuration it rejects and exits
- The answer therefore goes to stdout whatever the code is, because a payload on stderr is a payload no pipe operator can reach.
A completed check can return its verdict in the diagnostic with no structured
payload. ze config fmt --check successfully reads and compares the source,
then exits 1 with exactly <path> needs formatting on stderr if it needs
changes; stdout stays empty. The nonzero code expresses that negative verdict,
and does not mean Ze was unable to perform the check. It uses LocalAnswer
directly because LocalRefusal would misstate a completed check as an inability
to answer. A nil payload and a nonzero code alone do not define a refusal.
A handler writes nothing to the process's stdout or stderr, and neither does
any helper it calls. A handler that cannot answer returns a nil payload and
its operator error in the diagnostic (command.LocalRefusal): what went wrong,
why it prevented an answer, and the recovery action. A check that cannot run
still takes that refusal path, rather than reporting a negative verdict.
Diagnostics are whole lines that each end in a newline.
A diagnostic beside a payload is a warning about the answer, such
as the parse warnings show config dump reports for a config it still
resolved. The route that ran the handler decides where the diagnostic goes: the
local routes (ServeLocal, the plain ze <verb> handler, and le's Run)
print it verbatim on stderr before the payload. A handler that wrote its own
refusal put it on whatever stderr the running process had, which for a daemon
route is the daemon's, and the caller got an empty failure. The one local
result stdout never sees is a pipe error, which is a diagnostic about the
operator's own chain rather than an answer to their question.
Before the handler runs, ServeLocal judges the arguments against the leaves
the command's YANG declares, with command.ValidateArgs, the same validator the
daemon dispatcher calls. A refused argument becomes a refusal value printed on
stderr like a handler's own, the route exits 1, and the handler is never
called. The definitions come from the YANG package, which
registers itself as the source (command.RegisterArgDefSource); a process with
no source registered refuses every local command rather than skipping the check.
The handler runs on the value ValidateArgs returned, never on the raw words.
ze <verb> does not pass through ServeLocal: it runs the plain local handler
that command.RegisterLocalData builds from the same data handler and registers
in the local-handler registry. The judgment happens before that handler runs:
command.InvokeLocal, which every ze <verb> route calls with the path it
matched, runs command.ValidateModelArgs and hands the plain handler the value
it got, which passes it to the data handler, so ze show env get <key> and
ze cli -c "show env get <key>" refuse the same values with the same message.
A pipe chain reaches a local-data command on the routes that read a line:
ServeLocal (ze cli -c) and, for every daemon surface, Dispatch through
the handler loadLocalData registers. Both partition the line the same way, so
an operation the command declares reaches its handler in the same declared
list (ValidatedArgs.PipeOperations) and the two answers are equal. ze <verb> reads no chain: its argv holds the command and an output-format keyword
at most, and RenderLocalAnswer is handed the command path, never a line, so
it renders the default format alone. A declared operation therefore reaches a
local-data handler through ServeLocal or Dispatch, never through ze <verb>. le <tool> reads its chain through command.ReadLocalLine, the same
partition (docs/architecture/core-design.md).
An le tool registers through the same call (leroot.Register), and le's
own dispatcher (leroot.Run) is a route too: an le tool declares no
argument definitions, since its words are its own grammar, so Run judges them
against none with command.ValidateArgs and runs the registered handler on that
value. The tool's own leroot.Answer keeps the token slice and reads the judged
tokens.
Text and bytes answers
A command whose answer IS text or bytes (a stored file, a formatted config, a
page of documentation) answers a command.Blob and declares the blob shape
(command.ShapeBlob). show config cat, show config fmt, show config graph,
show data cat and show yang doc answer this way. The bytes are what the
operator asked for, so the plain ze <verb> route prints them unchanged, with
no format applied and no newline added (RenderLocalAnswer), and the root
spellings (ze config cat, ze data cat, ze yang doc) print the same answer
through command.PrintLocalAnswer. A help page, a refusal, a password warning,
fmt --check's verdict and fmt --diff's hunks travel in the diagnostic and
reach stderr, where they always went.
A route that carries the answer as JSON receives
{"blob":{"encoding":"utf-8","content":"..."}}. Content that is not valid
UTF-8 travels as "encoding":"base64", because json.Marshal would replace each
invalid byte and the caller could not recover the file; command.DecodeBlob
reverses either form and refuses an encoding it does not know. The text
renderer registered under blob prints the content, and a chain naming no
format renders a blob command as text whatever the configured default is, so
ze cli -c "show data cat <key>" prints the file and | json prints the
envelope. The global operators act on a blob as on any answer. Every data
operator is refused by name before the command runs, because bytes have no
rows or fields: match cannot apply here: this command answers text or bytes, which hold no rows or fields, and match acts on rows; read it whole with | text, or as JSON with | json.
Served by the daemon too
The daemon dispatcher serves every local-data command whose exact path a YANG
ze:command node declares, under that path, through the same handler, so MCP,
REST, gRPC, SSH and the web reach it like any builtin. LoadBuiltins and the
alias loader the server calls end with loadLocalData, which reads the local
registry and the YANG maps and lists no command: a new local-data command with
a node is served with no further edit, and one with no node is not. A plain
local command (one that prints rather than answering a value) is not served
this way. A path a builtin RPC already holds is refused (ErrCommandHeld), as
two builtins on one path are.
A local command at an offline root (ze doctor, ze help command, ze help ai) cannot have a node at its own path: the root is not a verb, and every
command path in the model starts with one (ai/rules/cli.md, R1). Its
registration names the path that answers it on the daemon instead,
registry.Meta.DaemonPath, and four readers follow that one field. The local
route validates its arguments against the leaves of the daemon path
(command.ModelPath). loadLocalData serves the handler under the daemon
path, or leaves it to the builtin that holds it, and refuses to start when no
node declares the path. command.AnswerSurface offers the root on shell
completion and ze cli, and the daemon path on every daemon surface. The
command-contract gate counts the local handler as served by the daemon
path, reading the field from the registration's source, so its value is a
string literal.
| Offline root | Daemon path | Daemon handler |
|---|---|---|
doctor |
show doctor |
the builtin HandleDoctor, which adds the plugin checks |
help command |
show command catalog |
the same local-data handler, through the bridge |
help ai |
show command reference |
the same local-data handler, through the bridge |
thanks |
show thanks list |
the same local-data handler, through the bridge |
thanks licence |
show thanks licence |
the same local-data handler, through the bridge; the declared name operation reaches it in the declared list on both routes |
show command list is not the daemon form of help command: it answers the
commands the running daemon's dispatcher serves, a name and a summary each,
while the catalog walks the YANG tree, the local registry and the plugin
declarations of this binary and gives each command its grammar, arguments,
pipes and mode.
The catalog's mode retains a live command's daemon or read-only
classification and appends offline when an exact-path local handler also
serves it. Each command path has one row, even when both routes serve it.
A call passes authorization and accounting first, then the dispatcher's
validator over the node's leaves, then the handler, exactly as a builtin
does. A token that starts with - is refused before the handler, because a
--flag is offline tooling the daemon never reads. The answer maps onto the
response the way the local route maps it onto the terminal: the payload is
the response data, under the shape the path declares; a non-zero code is a
failed status, and the payload, if any, still beside it. The error is a
plugin.RefusalError holding the diagnostic: the response's error field
and the error's text are the reason without its final newline and without
the error: it may open with, for a program to read, and a surface that
prints for a person asks plugin.RefusalLine and prints the diagnostic as it
stands (SSH exec, the SSH session, the web terminal, the web admin card and an
MCP result), so a usage refusal reads usage: ... there as it does locally,
never error: usage: ..., and an error: refusal carries its prefix once.
Every other error keeps the surface's own rendering (error: <text>, MCP
Error: <text>). A refusal with no diagnostic is a plain error naming the
exit code. Nothing is written to the daemon's stdout or stderr.
A required argument missing from an exact local-data command produces the same
help hint on local and daemon routes. command.ArgumentRefusal preserves the
typed validation cause; authorization and flag checks still run first on the
daemon. A different child command beneath that path keeps its own refusal.
The SSH exec channel writes a payload that stands beside a refusal on the
session's stdout, before the refusal line on stderr, as the local route does
(writeExecRefusedAnswer). The frame's terminator then counts that one
document under the refusal's message, so a client reads the document as real
(rpc.Verdict answers aborted, not error). ze config validate reads the
daemon's diagnostics of a config it rejects this way.
A diagnostic beside a zero code is a warning about an answer the command still
gave, such as the parse warnings of show config dump. It travels in the
response's warnings field, one line each, under the warning status, and
every surface shows it where the local route prints it, on stderr before the
answer:
| Surface | Where the warning appears |
|---|---|
SSH exec, and ze cli -c reading it |
On the session's stderr before the answer frame (writeExecWarnings); sshclient.ExecCommandStream returns it as Answer.Warnings, which ze cli prints on stderr |
| SSH interactive session | Above the rendered answer (cli.CommandOutput.Warning) |
MCP tools/call |
A second text item, Warning: <lines>, after the answer item |
| REST | The warnings array of the JSON body |
| gRPC | CommandResponse.warnings |
| Web admin | The warnings key of a JSON result; above the output in the result card |
| Web CLI terminal | Above the rendered answer |
A plugin that sends a command through the engine (dispatch-command) receives
the status, the data and the warning lines: the lines ride the wrn
terminator of the answer (docs/architecture/api/ipc_protocol.md, "Answer
Protocol").
Authorization reads the verb (IsReadOnlyPath), unless the registration
declares its daemon form does more than read with registry.Meta.NotReadOnly.
show plugin declarations config declares it, because the daemon answers it
by starting each external plugin's run line from the file (the local route,
with no daemon, starts none), so it is judged in the edit
section and the read-only profile, whose edit section denies by default,
refuses it before any process starts. show data cat and show config cat
declare it too: either reads any store key, the HTTPS private key
(meta/web/key) and the bcrypt hashes under meta/auth and meta/ssh
included, so a secret reaches only a caller the edit section allows.
The daemon-host file forms show config dump, fmt, migrate, set,
activate, deactivate and replace also declare NotReadOnly. Their
complete answers can carry usable credentials, including reversible $9$
values, even though they do not change the source file. The dispatcher requires
edit authorization before resolving or reading the filename. Selecting a
preview or stripped form does not change that command's authorization.
Caller-supplied forms still inspect the caller's own bytes under read
authorization. show config source remains a read-authorized view with parsed
secrets masked; it refuses an unparseable host file instead of returning raw
private bytes.
The handler learns which route called it from ValidatedArgs.Route():
command.RouteLocal on ServeLocal and the plain ze <verb> handler,
command.RouteRemote when the daemon runs it (command.AnswerRemote).
Only the command package marks a route. Route.CallerLocal() is true for
RouteLocal alone, so the zero value, RouteUnspecified, is refused the
caller-only forms the same way the remote route is. show bgp decode and
show bgp encode refuse a standard-input form and a decoder program named by
path unless the route is local, and a help page is drawn with colors only on
the local route.
A handler whose work takes time reads ValidatedArgs.Context() and stops when
it is done. The dispatcher hands each daemon-route call the request's context
(ValidatedArgs.WithContext, set in localDataHandler), so a caller that goes
away stops the work. A local route sets none, and Context() then answers
context.Background(): the work lives as long as the operator's own process.
request support archive checks it before each module.
A blob answer to a caller in another process is bounded by
command.BlobRemoteOctetsMax (8 MiB), because the daemon route carries the
whole answer in one response. A command that would answer more refuses with
the size and the local command that reads the bytes on the host holding them:
show data cat does so for a large store value, and request support archive
refuses to store an archive it could not hand back.
A command that produces a file names it differently on each route, by design:
the local route writes it under a directory its caller names, and the daemon
keeps it in its store under a key show data cat reads. Its registration says
so with registry.Meta.Artifact: the words that give the local route a
directory (LocalArgs), the answer field naming the path locally
(LocalField) and the key on the daemon (DaemonField), and the fields that
differ between any two runs (Volatile). request support archive declares
it, and TestLocalCommandDaemonMatchesLocal (cmd/ze/hub) reads it to
compare the two routes' documents field by field, with no command named in
the test. Both routes answer the same typed manifest (support.SupportManifest),
so a pipe reads its fields on either one; the ze request support archive
spelling draws it through its registered renderer (support.Render) as the
archive's path on one line, or under --json as the indented manifest.
A path argument on the daemon route names a file on the daemon's host, read
with the daemon's identity, and the authorizer judges command text with no
notion of a filesystem location. So every handler that reads a file its
caller names asks command.CallerPath for the path to read: on the local
route the path comes back unchanged, - included, and on every other route
- is refused, and a named path is read only when, made absolute and with
every symbolic link resolved, it lies inside one of the directories the daemon
already reads configuration from: the user's ze directory under
XDG_CONFIG_HOME, else ~/.config/ze, and the store's directory, which
internal/component/config/cli registers with
command.RegisterCallerPathDirs. The working directory, which show config list also scans, is not one of them on the daemon route: the daemon's is
wherever it was started, a place no configuration rule names and a remote
caller cannot see, so a file there is refused remotely and read locally,
where the working directory is the operator's own. A relative path is still
made absolute against the daemon's working directory before it is judged.
The filesystem root never counts as one. A path
outside them, a .. that climbs out, a link that points out and a missing
file are refused alike, so the refusal says nothing about files outside the
directories, and it names the local ze command that reads any file. A file
inside them that is one of the configuration store's own entries (the live
tree under database/, its lock, a replaced tree or blob, a stage) is refused
too, with the reason: those files carry every stored value, the HTTPS private
key and the password hashes included, and a remote caller reads a stored value
only with show data cat <key>, which is edit-authorized. The registration
names that test (callerPathWithheld, which asks
storage.StoreOwnedPath), so the command layer still knows no location. The
commands that read through it are show config dump, validation, diff,
history (whose store is opened beside the resolved file, so a link placed
outside the directories cannot choose the store), graph and fmt,
show plugin declarations config and show bgp decode pcap.
CallerPath owns a complete operator refusal for every rejected path. Its
final fix is the local invocation, with each word quoted and private credential
or content operands masked before presentation; adapters retain that refusal.
show config fmt -w rewrites its file, so it is refused on the daemon route
whatever the path.
The dispatcher refuses a flag-shaped token before any handler runs, because a
flag is read only by the client. When the command also has a local-data
handler, the refusal names the local ze command to run instead. A flag that
selects what is answered is declared as a YANG leaf so every surface can send
it: show config dump strip-private asks for what --strip-private asks for.
The same holds for show config fmt check and diff (--check, --diff),
show yang tree commands and config, show yang completion min-prefix,
and show yang doc list and command (--list, and the command words). A
keyword given beside the flag that makes the same choice is refused rather
than resolved by a silent winner.
A daemon-served command that parses a caller's config file reads it with
config.ReadConfig or the bare parser, never config.LoadConfig, because
LoadConfig publishes the file's environment { } block into the process
that runs it: on the daemon route a read would change the daemon's log and env
settings. show plugin declarations config, ze doctor, the support report
and the crash-capture readiness check read through ReadConfig, and the
config commands above go through the parser alone. Ze's config grammar has no
include statement, so the confined file is the only file a parse reads.
This differs from the offline fallback above: a fallback is a second answer for
a command the daemon normally serves, tried only after the connection fails. A
local-data command is one handler behind both routes. It registers no RPC on
the wire-method dispatcher, and therefore owes no wire-methods.snapshot row.
internal/component/plugin/register.go serves one of them, and it is the
template: show plugin list answers which plugins this binary carries and what
each plugin's own init() recorded about its setup. It is owned by the package
that owns the registry it reads, so removing the plugin host removes the
command with it.
show fleet status (internal/component/managed) is one handler behind both
routes that still asks the daemon first, as ze doctor does. Its answer is
where a managed device stands with its hub. Most of that is in the store, which
any ze process reads: the managed flag, the hub the configuration declares,
the baseline (meta/managed/base-version) and the hash of the active
configuration. The state of the hub client lives only in a running daemon. So
on the local route (ValidatedArgs.Route().CallerLocal()) the handler sends
show fleet status to the daemon over SSH and answers the document the daemon
gave. When no daemon answers, it reads the store and marks the answer
daemon-answered false, with no-daemon in the client fields. On the daemon
route the same handler reads the store, fills the client fields from the owner
of the daemon's hub client (managed.FleetTarget, which the hub installs on a
managed start; with none the client is not-started), among them held-by-hub
and revert-offered, which the client reports from each fetch answer its hub
gave (managed.ClientConfig.OnHubAnswer, not-fetched before the first), marks the answer
daemon-answered true, and asks nobody. That mark is also how the local route recognizes a
daemon's document: a reply of another shape, or one a store alone produced, is
no answer. It registers no RPC, so it holds no wire-methods.snapshot row.
show fleet divergence list and show fleet divergence name <client>
(internal/component/managed) answer the same way, for the copies a hub keeps
of the configurations its holding clients run
(meta/config/client-<name>.conf/held, pluginserver.ReadHeldRecord). Every
fact but one is in the store. The one is whether a server block declares the
client, which the running managed server knows (DivergenceTarget.ServesClient).
So the local route sends the line to the daemon over SSH and answers the
daemon's document, decoded strictly; when none answers, it reads the store and
the server blocks of the hub's stored configuration (servedClientNames, the
rule the hub's doctor-managed-client-diverged check uses). The show of one
client answers the whole-tree diff of infra.DiffConfigs, secret-masked, and
no configuration text; a configuration the hub cannot parse leaves the diff
unavailable with the reason, and the rest of the answer holds. The list is a
plain local-data command and registers no RPC. The show is also registered as
the builtin ze-managed:fleet-divergence-show over the same handler
(pluginserver.AnswerLocalData), as show doctor is, so that it declares the
completer of its client name (completeDivergenceClients); that RPC holds a
wire-methods.snapshot row.
update fleet divergence name <client> adopt version <hash> changes what the
hub serves, so its daemon form is the RPC ze-managed:fleet-divergence-adopt
with the audit action fleet-divergence-adopt. It acts on the store handle
the daemon owns, reached through the DivergenceTarget the hub installs once
its managed server serves; a daemon with none refuses. The local route opens
the store as its writer: while a daemon owns it (storage.ErrBusy) the line
goes to that daemon through daemonroute, and the answer is decoded and
checked to name the client; with the store free it refuses with ze start as
the fix, because the audit action is recorded only by the running hub's
dispatcher. The daemon runs one producer, adoptHeld, which holds the writer lock of client-<name>.conf across the
hash check, storage.CommitConfigWithGuard and the removal of the record.
request fleet divergence name <client> revert version <hash> hub-version <hash> changes what the hub offers a holding client, so its daemon form is the RPC
ze-managed:fleet-divergence-revert with the audit action
fleet-divergence-revert, over the same DivergenceTarget. revertHeld
holds the writer lock of client-<name>.conf across the device hash check,
the check that the configuration the hub serves the client still hashes to
the hub-version given, and the write of the record carrying the decision (HeldRecord.WithRevert,
WriteHeldRecordWithGuard); the handler then calls
DivergenceTarget.NotifyConfigChanged, because the decision writes no
configuration the store's write observer would report. The local route sends
the line to the daemon that owns the store as adopt does; with the store free
it refuses with ze start as the fix, because the audit action is recorded
only by the running hub's dispatcher.
Local commands already served by the daemon under the same path
A few local registrations share their path with a daemon RPC the owner registered itself. The two routes call one producer, so they cannot drift:
| Command | Producer | Local route | Daemon route |
|---|---|---|---|
doctor (daemon path show doctor) |
doctor.Answer |
the local-data handler ze doctor runs: it asks the running daemon's show doctor over SSH and draws that answer, and only when no daemon answers runs the checks in the caller's process, with no plugin check, plus a doctor-runtime-not-checked warning. docs/architecture/doctor-and-health-checks.md |
HandleDoctor, the RPC for ze-doctor:show-doctor, adding the runtime-phase checks and the doctor checks of the plugins the daemon runs |
show ping |
pingResults |
showPingLocal prints it |
handleShowPing |
show traceroute |
tracerouteResults |
showTracerouteLocal prints it |
handleTraceroute |
show interface |
iface.ListInterfaces, iface.GetInterface |
cmdShow renders the list or one interface (--json prints the payload) |
handleShowInterface, handleShowInterfaceDetail answer it as data |
show version |
zeversion.Answer |
printVersion prints it (ze show version, ze version, ze --version) |
handleShowVersion; --extended reaches both routes as a token, since the model declares no leaf |
create agent skill, show agent skill, delete agent skill |
agentPlan, the skills plugin's plan producer: per harness, the stub and, in its local form, the hook item, at the default paths relative to the home directory |
createAgentSkillLocal, showAgentSkillLocal, deleteAgentSkillLocal (localAnswer): they resolve the caller's own harness directories and write, inspect or remove each item of the local form |
handleCreateAgentSkill, handleShowAgentSkill, handleDeleteAgentSkill (remoteAnswer), the RPCs for ze-skills:create-agent-skill and its siblings: they call no file or environment function and answer the remote form, every row not-inspected, with the stub a remote agent places |
request fleet disable, request fleet enable |
storeManagedFlag, the one writer of the managed flag for both commands, and for a rejoin requireDeclaredHub, which refuses a configuration that names no hub |
requestFleetDisableLocal, requestFleetEnableLocal (changeFleetLocal): with the store free they open it as its writer and store the flag (disableStopped, enableStopped); while a daemon owns the store they send the same line to that daemon (daemonroute.Send) and print its answer |
handleFleetDisable, handleFleetEnable, the RPCs for ze-managed:fleet-disable and ze-managed:fleet-enable, each recording the data-key-change audit action: they store the flag through the daemon's own store handle, then stop or start the daemon's hub client through managed.FleetTarget (disableOnDaemon, enableOnDaemon). A daemon that started unmanaged installs no target and changes the flag alone |
show agent context |
sharedContextFacts, the skills plugin's context producer |
showAgentContextLocal adds the bounded dial and the config directory |
handleShowAgentContext, the RPC for ze-skills:show-agent-context, answers the shared facts with no path and no dial |
monitor ping, monitor traceroute |
NewPingSession, NewTracerouteSession |
the local loop prints each result | the ze cli view and the hub's SSH session factory inject the producer itself as the view factory; SSH exec and ze cli -c stream from the same producer (streamMonitorPing, streamMonitorTraceroute), and the one-shot RPC answers a sample of it: handleMonitorPing the rows of a bounded run, handleMonitorTraceroute one probe round |
The bridge leaves such a path to its builtin: when the YANG node's own RPC is
registered as a builtin, the local-data handler on that path is the command's
no-daemon route (loadLocalData). doctor is local-data because its answer
is about the host it runs on, whichever host that is. show ping and show traceroute stay plain local commands, because ze cli -c answers a
local-data command in its own process before it asks the daemon, and a ping
asked through ze cli is sent from the router; show interface and show version stay plain local for the same reason, since each describes the
daemon's host or binary. An interactive ze cli session never answers in the
client's process: it is a shell on the daemon (sshclient.RunInteractive),
where every typed line is dispatched. The agent setup commands are plain local
because a person sets their agent up at a shell, where the handler reaches
their home; ze cli is the router's CLI, so every form of it gets the
daemon's answer. The two fleet commands are plain local for the same reason:
ze cli asks the daemon, which owns the hub client, and only ze request fleet ... at a shell writes the store itself, when no daemon holds it.
doctor config <file> is confined on the
daemon route like every other caller path (command.CallerPath).
Which surfaces offer a command
One predicate, command.AnswerSurface, answers for a command and a surface
whether the surface must offer it, must not, or offers it with a qualifier,
and why. It reads only the registration: its kind, and the hidden, streaming,
streaming-only, TUI-only, daemon-path and modeled declarations. Each surface producer asks it, and
TestEveryCommandOnEverySurface (cmd/ze/hub) asks each producer and fails a
gap or an offer the predicate refuses, naming the command, the surface, the
kind and the expected answer.
| Registration | SSH, browser CLI completion, ze cli |
Shell completion (ze <verb>) |
Web admin, MCP, REST, gRPC |
|---|---|---|---|
Hidden (ze:hidden true on the command or an ancestor, or a plugin command declared Hidden) |
Not offered | Not offered | Not offered. It still runs when typed in full |
| Builtin RPC, local, local-data | Offered | Offered | Offered: the daemon serves each through its handler |
| Local or local-data at an offline root, with a declared daemon path | ze cli offers a local-data one, which ze cli -c answers in its own process; SSH, and the interactive ze cli shell it carries, does not, and offers the daemon path |
Offered | Not offered: the daemon path is, as its own registration |
| Plugin command (Stage 1 declaration) | Offered | Not offered: no plugin runs in the shell's process | Offered |
Plugin command whose path is a schema node with no ze:command of its own (Modeled, as show vrrp interface, whose command node is name below it) |
Offered | Offered: shell completion walks the shipped schema, which holds the node | Offered |
Streaming (RegisterStreamingHandler) |
Offered as a stream | Offered as a stream | By its one-shot declaration: OneShotSample offered, OneShotStreamingOnly not ("One-shot answer of a streaming command") |
| A live view with no RPC | Offered as TUI-only, when cli.RegisterView declares it |
Not offered | Not offered. An undeclared one fails the check. No view is TUI-only today |
The producers that ask it: the SSH and web admin trees, the web terminal
completer, buildCommandMeta (the MCP, REST and gRPC list) and the ze cli
tree. command-completion.md names each one.
Operational Report Bus (ze-cmd:show-warnings, ze-cmd:show-errors)
The report bus is a single in-process place for Ze subsystems to push
operator-visible issues. Any subsystem (BGP, config, interface, plugins)
can call report.RaiseWarning / report.RaiseError / report.ClearWarning,
and operators query the aggregate via two RPCs.
Severity contract
| Severity | Lifecycle | Storage | Cleared by |
|---|---|---|---|
warning |
State-based. Condition is currently problematic. | Deduped map on (Source, Code, Subject). Bounded by warningCap (default 1024, max 10000). Oldest-by-Updated evicted at cap. |
ClearWarning(source, code, subject), ClearSource(source), or implicit eviction. |
error |
Event-based. Something already happened. | Ring buffer of errorCap events (default 256, max 10000). Oldest evicted on overflow. |
Never; ring buffer aging only. |
Producers MUST pick the right severity. The bus does not auto-promote. "Did anything actually fail or behave unexpectedly?" Yes -> error. No, but it might soon -> warning.
Push API (for subsystems)
Subsystems import internal/core/report and call:
| Function | Purpose |
|---|---|
RaiseWarning(source, code, subject, message string, detail ...map[string]any) |
Add or refresh an active warning. Deduplicated. |
ClearWarning(source, code, subject string) |
Remove an active warning. No-op if missing. |
ClearSource(source string) |
Remove all active warnings for one source (shutdown cleanup). |
RaiseError(source, code, subject, message string, detail ...map[string]any) |
Append an error event to the ring buffer. No dedup. |
RaiseWarningFix(source, code, subject, message, fix string, detail ...map[string]any), RaiseErrorFix(...) |
The same, carrying the command that fixes the subject in Issue.Fix; a re-raised warning refreshes it. show doctor shows it as the event's fix line. |
Warnings() []Issue |
Snapshot of all active warnings, most-recently-updated first. Consumed by ze-cmd:show-warnings handler. |
Errors(limit int) []Issue |
Recent N error events, newest first. limit 0 or negative returns all retained. Consumed by ze-cmd:show-errors handler. |
Empty or oversized fields (Source/Code > 64 bytes, Subject > 256, Message > 1024, Detail > 16 keys, Fix > 256 bytes) are rejected at the boundary with a debug log, protecting the bus from buggy or malicious producers.
Query RPCs
For ze-bgp:show-policy-test, action describes the external per-peer policy
stage and its final, not the full protocol pipeline. A named in-process check
has a trace entry with action: "not-evaluated" and empty text-after; no
filter-update RPC was made for it. Selecting such a check as a single-filter
override is refused with instructions to test it on the peer session. A
plugin filter on a policy that compiled no library chain is never called: its
trace entry has action: "reject" and an error saying the chain is not
compiled, and the route is rejected, as the session fails it closed.
text-before, text-after and each entry's text-after are read from the
wire UPDATE (the pasted one, or the one the chain built) by a display-only
renderer that no filter is sent, and changed-attrs names the attributes
whose shown value differs between the two.
A chain with a library member (an in-process filter instance) runs in the
dry-run as it runs live, through the same chain, display only: no failure is
counted or logged. Its plugin members are reached through the chain, and no
filter-update is sent for a library member. Each member's trace entry has
action accept, modify, reject or withdraw, delta the sets a passing member asked as
text (local-preference 200), error why a failed member failed (its
on-error decided the action), and text-after the UPDATE as the chain
rewrote it up to that member (after a failed-open member, the earlier
members' changes only), built the way the result's is; a rejecting or
withdrawing member's entry carries none. A plugin member that rewrote the
whole UPDATE body (a raw answer) is a modify with no delta, and its
text-after is the body it answered, though the policy's final still
decides whether the route keeps it. The result's text-after
is the rewritten UPDATE. A single-filter override on such a chain runs that one
member through the chain, display only, under the policy's final; a name
the chain does not hold is
refused as not in the peer's chain. The reported policy stays the whole
chain the live session runs.
An unresolved remote AS returns action: "undetermined" with a reason telling
the operator to wait for establishment and repeat show policy test. No filter
executes, including a single-filter override. Trace, input and resulting text
are empty, and no changed attributes or wire changes are returned. Known-session
results omit reason unless an explicit role's absent-policy default applies.
An absent EBGP direction uses the RFC 8212 rejecting final.
Every result carries policy, the simulated class's effective policy in the shape
show policy chain uses for one direction (canonical filter strings, final,
final-source), so the verdict for this UPDATE stays distinct from the final the
session applies. policy is omitted only when that simulated class has no
final on IBGP and there are no automatic filters.
The export-only route-kind learned|local keyword selects a read-only
simulation; omission means learned. Import refuses it, and unknown values
are refused. The result names simulated-route-kind; this choice never
authorizes live output. An absent internal ordinary export policy reports
final: reject with final-source: learned-export-policy for a learned
simulation. A resolved explicit dissemination role retains its existing
default for either class, reported with role-default: true when the policy
is absent. Configured policies retain their configured final. External
sessions retain RFC 8212 for both classes.
After resolving one peer, the handler passes its nonzero stable peer owner to the dry-run interface. The adapter captures that peer's policy, role and facts under its lock. A removed owner is refused, even if another peer has the same address; neither zero nor an address lookup substitutes a different peer.
| WireMethod | Handler | Response shape |
|---|---|---|
ze-cmd:show-warnings |
handleShowWarnings in. internal/component/cmd/show/show.go |
{"warnings": [Issue, ...], "count": N} |
ze-cmd:show-errors |
handleShowErrors in. internal/component/cmd/show/show.go |
{"errors": [Issue, ...], "count": N} |
ze-traffic:show-traffic |
handleShowTraffic in. internal/component/traffic/cmd/traffic.go |
{"interfaces": [...], "count": N} or single interface detail |
ze-mtu:show-mtu |
handleShowMTU in. internal/component/mtu/cmd/mtu.go |
one document: status, measurements (rows of target, label, outcome, path-mtu, method, probes, lossy, prober, exchanges, ike-confirmed, ike-declined, caveats, cached-path-mtu), tunnels (rows of peer, remote, interface, mode, encapsulation, transform, path-mtu, assumed, current-mtu, ceiling, recommended, mss, verdict, octets, sized, reason), commands, notes, caveats; inventory, verdict, reference on a run over the peers; underlay once read; tcp-mtu-probing once read. Keys and presence rules. docs/architecture/diagnostics/path-mtu.md |
ze-static:show-static |
forwardShowStatic in. internal/plugins/static/cmd_show.go |
JSON array of configured static routes (proxy to static plugin) |
ze-policyroute:show-policy-routes |
forwardShowPolicyRoutes in. internal/plugins/policyroute/cmd_show.go |
JSON array of PBR policy routes (proxy to policyroute plugin) |
ze-bgp:show-policy-chain |
handleShowPolicyChain in. internal/component/bgp/plugins/cmd/policy/handler.go |
{"chains": [{"peer": "...", "name": "...", "import": {"filters": [{"name": "...", "canonical": "..."}], "final": "accept"}, "export": {"filters": null, "final": "reject"}}]} shows effective policies with the direction's effective final: the configured final; reject with "final-source": "rfc8212" for an EBGP direction with no policy (RFC 8212 Section 3); undetermined for an absent direction on a dynamic peer not yet established. An IBGP direction with no policy has no final, and is omitted when it has no automatic filters. |
ze-bgp:show-policy-test |
handleShowPolicyTest in. internal/component/bgp/plugins/cmd/policy/handler.go |
{"direction": "...", "peer": "...", "action": "accept|reject|modify|undetermined", "trace": [PolicyTraceEntry], "text-before": "...", "text-after": "...", "changed-attrs": [...], "wire-changes": ["AS_PATH set", ...], "policy": {"filters": [...], "final": "reject", "final-source": "rfc8212"}} reports a read-only policy dry-run. The action includes the effective final decision, including after a raw rewrite. reason is present for an unresolved remote AS. |
ze-bgp:show-bmp-sessions |
forwardShowBMPSessions in. internal/component/bgp/plugins/bmp/cmd_show.go |
JSON array of BMP receiver sessions (proxy to BMP plugin) |
ze-bgp:show-bmp-peers |
forwardShowBMPPeers in. internal/component/bgp/plugins/bmp/cmd_show.go |
JSON array of BMP monitored peers (proxy to BMP plugin) |
ze-bgp:show-bmp-collectors |
forwardShowBMPCollectors in. internal/component/bgp/plugins/bmp/cmd_show.go |
JSON array of BMP sender collectors (proxy to BMP plugin) |
ze-bgp:show-bmp-rib |
forwardShowBMPRib in. internal/component/bgp/plugins/bmp/cmd_show.go |
BMP-monitored routes (proxy to BMP plugin, dispatches to RIB) |
ze-bgp:show-rr-status |
forwardShowRRStatus in. internal/component/bgp/plugins/rr/cmd_show.go |
{"running": true} (proxy to RR plugin) |
ze-bgp:show-rr-peers |
forwardShowRRPeers in. internal/component/bgp/plugins/rr/cmd_show.go |
JSON array of RR peer states (proxy to RR plugin) |
ze-bgp:show-reject-asn |
forwardShowRejectASN in. internal/component/bgp/plugins/filter_path_asn/register_command.go |
{"lists": [{"name": "...", "import-peers": N, "export-peers": N, "entries": [{"asn": N, "positions": ["transit", "origin"], "network": "..."}], "patterns": ["..."]}]} (proxy to the reject-asn filter plugin). network is written for every ASN and is EMPTY for one the curated table does not hold |
ze-bgp:show-reject-asn-name (selector: name) |
forwardShowRejectASNName in the same file |
One list record, the same shape as a row of lists. The value after the name keyword arrives as a SELECTOR rather than a positional, because name is both the last token of the path and the leaf under it, so the forwarder reads ctx.Selector("name") |
ze-bgp:show-reject-asn-known-transit-free |
forwardShowRejectASNTransitFree in the same file |
{"curated": "YYYY-MM-DD", "sources": [...], "networks": [{"asn": N, "name": "...", "contested": bool}], "block": ["# ...", "indirect [ ... ];"]}. block is an array of config LINES an operator pastes |
ze-cmd:show-system-sockets |
handleShowSystemSockets in sockets_linux.go |
{"sockets": [...], "count": N} (Linux only) |
ze-host:show-system-kernel-log |
handleShowSystemKernelLog in kernel_log_linux.go |
{"entries": [...], "count": N} (Linux only) |
ze-cmd:show-system-goroutines |
handleShowSystemGoroutines in goroutines.go |
{"total": N, "by-state": {...}, "mode": "..."} |
ze-diag:show-tcp-check |
HandleTCPCheck in. internal/plugins/diag/cmd/tcp_check.go |
{"host": "...", "port": N, "result": "...", "latency-ms": N} |
ze-traceroute:show-traceroute |
handleTraceroute in traceroute.go |
{"target": ". ", "hops": [{"hop": N, "addr": ". ", "rtt-ms": N, "ttl": N}. ]}. Under do-not-fragment a hop that refused the probe's size also carries "next-hop-mtu-reported": bool and, when true, "next-hop-mtu": N, and ends the trace. docs/architecture/diagnostics/active-probes.md |
ze-diag:show-capture-interface |
handleCaptureInterface in capture_interface_linux.go |
pcap: {"format": "pcap", "packets": N, "pcap": "base64...", "snap-len": N}; text: {"format": "text", "packets": N, "lines": [...]} (Linux only) |
ze-cmd:show-system-file-descriptors |
handleShowSystemFD in fd_linux.go |
{"total": N, "by-type": {...}, "soft-limit": N, "hard-limit": N} (Linux only) |
ze-resolve:show-dns-lookup |
handleDNSLookup in. internal/component/resolve/cmd/show_dns.go |
{"name": "...", "type": "...", "records": [...], "query-time-ms": N} |
ze-resolve:show-dns-cache-stats |
handleDNSCacheStats in. internal/component/resolve/cmd/show_dns.go |
{"entries": N, "capacity": N, "hits": N, "misses": N, "hit-rate": N, "miss-rate": N, "evictions": N, "expired": N} |
ze-resolve:show-dns-cache-list |
handleDNSCacheList in. internal/component/resolve/cmd/show_dns.go |
{"entries": [...], "count": N} |
ze-resolve:show-dns-cache-record |
handleDNSCacheRecord in. internal/component/resolve/cmd/show_dns.go |
{"entries": [...], "count": N, "filter": "name"} |
ze-resolve:clear-dns-cache |
handleClearDNSCache in. internal/component/resolve/cmd/dns.go |
{"action": "clear-all"} |
ze-resolve:clear-dns-cache-stats |
handleClearDNSCacheStats in. internal/component/resolve/cmd/dns.go |
{"action": "reset-stats"} |
ze-resolve:clear-dns-cache-record |
handleClearDNSCacheRecord in. internal/component/resolve/cmd/dns.go |
{"action": "delete-entry", "name": "...", "removed": N} or {"action": "delete-entry", "name": "...", "type": "...", "found": bool} |
ze-dnsresolver:show-dns-resolver |
handleShowDNSResolver in. internal/plugins/dnsresolver/show.go |
{"running": true, "enabled": bool, "mode": "forward", "listeners": [{"name": "...", "ip": "...", "port": N}], "allow-from": N, "upstreams": ["ip:port", ...], "timeout-seconds": N, "limit-outstanding": N, "limit-per-client-rate": N, "outstanding": N, "cache-max-ttl": N, "cache-max-negative-ttl": N, "cache-answer-entries": N, "cache-negative-entries": N, "cache-hits": N, "cache-misses": N, "cache-hit-rate": N, "queries": N, "coalesced": N, "refused-acl": N, "refused-rd-clear": N, "rate-limited": N, "dropped": N, "upstream-queries": {"answered": N, "timeout": N, "error": N, "failure": N, "truncated": N}}. {"running": false} while the plugin is not running, and {"running": true, "enabled": false} before its first config apply |
ze-system-dns:show-system-dns |
showSystemDNS in. internal/plugins/system-dns-cmd/cmd/show_dns.go |
{"records": [. ], "consumers": [{"consumer": "system", "selections": [. ]}. ]}: every learned resolver record, then the router's selection under consumer system, then each consumer's published selections. docs/features/dns-resolver.md |
ze-dnsresolver:clear-dns-resolver-cache |
handleClearDNSResolverCache in. internal/plugins/dnsresolver/show.go |
{"cleared-answer": N, "cleared-negative": N}: the entries removed from each cache; the counters are kept. An error naming the config to commit while the plugin is not running. The CLI words are clear dns resolver cache all; the bare clear dns resolver cache has no handler |
ze-resolve:show-rir (args: <asn>) |
handleRIRASN in. internal/component/resolve/cmd/rir.go |
{"asn": N, "registry": "ARIN", "whois": "whois.arin.net", "range-start": N, "range-end": N}. Two distinct errors: AS<n> is in no delegated range for a table that was read, RIR delegation table unreadable: ... for one that was not |
ze-resolve:update-rir (no args) |
handleRIRRefresh in. internal/component/resolve/cmd/rir.go |
{"key": "meta/rir/delegation", "ranges": N, "generated": "YYYY-MM-DD"}. ranges is how many ranges the stored table holds and generated is the date it stored. All or nothing: a fetch that failed, a parse that refused, a run that read no ASN record, and a write that stored nothing each answer an error and change no stored table |
ze-cmd:show-system-profile |
handleShowSystemProfile in profile.go |
{"type": "...", "format": "pprof-base64", "data": "..."} |
ze-cmd:show-system-memory-map |
handleShowSystemMemoryMap in memory_map_linux.go |
{"vm-rss-kb": N, "vm-size-kb": N, ...} (Linux only) |
ze-update:show-system-update |
handleShowSystemUpdate in. internal/plugins/update-cmd/cmd/show.go |
{"backend": "ze-self-update"|"gokrazy-ab", "running-version": "...", "remote-version": "...", "update-available": bool, "status": "...", "download-status": "...", "staged-version": "...", "gokrazy-reachable": bool, "gokrazy-features": [...]} |
ze-update:show-system-update-history |
handleShowSystemUpdateHistory in. internal/plugins/update-cmd/cmd/show.go |
{"history": [{"timestamp": "...", "from": "...", "to": "...", "result": "..."}], "count": N} |
ze-update:system-firmware-check |
handleFirmwareCheck in firmware.go |
{"running-version": "...", "update-available": bool, ...} or on gokrazy {"backend":"gokrazy-ab", "status":"unsupported", "message":"updates managed by gokrazy"} |
ze-update:system-firmware-download |
handleFirmwareDownload in firmware.go |
{"downloaded-version": "...", "status": "complete"} |
ze-update:system-firmware-apply |
handleFirmwareApply in firmware.go |
{"applied-version": "...", "status": "restarting"} |
ze-update:system-firmware-restart |
handleFirmwareRestart in firmware.go |
{"status": "restarting"} |
ze-update:system-firmware-rollback |
handleFirmwareRollback in firmware.go |
{"status": "rolling back"} |
ze-iface:show-interface (no args) |
handleShowInterface in. internal/component/iface/cmd/show_interface.go |
JSON array of InterfaceInfo. A stray token is refused with the usage text: every subcommand below has its own wire method |
ze-iface:show-interface-brief |
handleShowInterfaceBrief in. internal/component/iface/cmd/show_interface.go |
{"interfaces": [{name, state, mtu, address?}], "count": N} |
ze-iface:show-interface-type (args: <type>) |
handleShowInterfaceType in. internal/component/iface/cmd/show_interface.go |
{"interfaces": [InterfaceInfo]} for that type. An unmatched type is refused, and the refusal lists the types the running set has |
ze-iface:show-interface-errors |
handleShowInterfaceErrors in. internal/component/iface/cmd/show_interface.go |
{"interfaces": [{name, rx-errors, rx-dropped, tx-errors, tx-dropped}]}, only the links with a non-zero counter |
ze-iface:show-interface-rate (args: [<name>]) |
handleShowInterfaceRateCmd in. internal/component/iface/cmd/show_interface.go |
JSON array of InterfaceRate (all) or single object (named); fields: name, rx-bps, tx-bps, rx-pps, tx-pps, stats |
ze-iface:show-interface-pppoe-client |
handleShowInterfacePPPoEClient in, forwarded to the iface plugin's show interface pppoe-client. internal/component/iface/cmd/show_pppoe_client.go |
JSON array of PPPoEClientStatus sorted by name: name, state, source-interface, ppp-interface, session-id, local-ip, peer-ip, uptime, dns-servers, delegated-prefixes ([{prefix, valid-lifetime, preferred-lifetime}], seconds remaining, 4294967295 infinite, [] when none) |
ze-iface:show-interface-delegated-prefix |
handleShowInterfaceDelegatedPrefix in, forwarded to the iface plugin's show interface delegated-prefix. internal/component/iface/cmd/show_delegated_prefix.go |
JSON array of DelegatedUnitStatus, one per delegated-prefix entry of an enabled unit: interface, unit, source, subnet-id, state (installed, waiting, too-small, not-installed); installed adds device, address, prefix, delegated, valid-lifetime, preferred-lifetime; the others add reason, and too-small and not-installed add delegated |
ze-iface:monitor-interface-rate |
streamInterfaceRate in. internal/component/iface/cmd/interface_rate.go |
Streaming JSON lines (1/s); optional <name> filter |
ze-storage:show-smart |
handleShowStorageSmart in. internal/component/storage/show.go |
JSON array of per-device objects: name, transport, healthy, temp-celsius, power-on-hours, error-count, percent-used (NVMe), available-spare (NVMe), smart-enabled, last-checked, last-short-test, last-long-test. Returns error if SMART management not configured. |
ze-flowexport:show-flow-export (args: [<collector>]) |
handleShowFlowExport in. internal/plugins/flowexport/cmd_show.go |
✕ |
ze-trafficstat:show-traffic-stat (args: [name <interface>]) |
handleShowTraffic in. internal/component/trafficstat/cmd/traffic.go |
One-shot aggregated snapshot: {"at": "RFC3339", "severity": "normal|caution|danger", "degraded": bool, "interfaces": [{name, rx-bps, tx-bps, rx-pps, tx-pps}], "top-source-ips": [{address, bps}], "top-dest-ips": [{address, bps}], "top-ports": [{port, service, proto, bps, amplification?}], "protocol-mix": [{proto, name, bps, percent}], "history": [float64]}. Optional name <interface> filters the interfaces array. When no collector data: "degraded": true with interface rates only. |
ze-trafficstat:monitor-traffic-stat (args: [name <interface>]) |
streamTraffic in. internal/component/trafficstat/cmd/traffic.go |
Streaming JSON lines (1/s) with the same shape as ze-trafficstat:show-traffic-stat. Attaches as a consumer on connect, detaches on disconnect (lazy lifecycle). Also registered as a MonitorProvider for full-screen TUI rendering via createTrafficMonitorSession in. cmd/render.go |
ze-trafficfeature:show-traffic-feature (args: [name <address>]) |
handleShowTrafficFeature in. internal/component/trafficfeature/cmd/traffic_feature.go |
Neutral per-source feature snapshot: {"degraded": bool, "top-source-ips": [{address, fan-out, out-in-ratio, port-entropy, new-peer, rare-port, beaconing}]}. out-in-ratio is the string "inf" when a source has no inbound bytes (else a float). Optional name <address> filters to one source. Facts only (no verdict); the anomaly detection family applies judgment. |
ze-anomaly:show-anomaly (no args) |
handleShowAnomaly in. internal/plugins/anomaly/detect/show.go |
Recent behavioral anomaly incidents (report-only): {"enabled": bool, "incidents": [{entity, entity-kind, cohort, score, severity, at, fired-features: [{name, z}]}]}. entity-kind is source, dest or port. A source or dest row names its subject in entity as a prefix; a port row carries port and proto as two more fields and renders entity as proto/port, because a port is not an address. Bounded recent-incident ring; empty until an entity's correlated deviation confirms. enabled is false when the detector is not running. The anomaly/shape responder consumes the underlying anomaly-detect events; this command is the read-only view. |
ze-anomaly:show-observe (no args) |
handleShowAnomalyObserve in. internal/plugins/anomaly/observe/show.go |
Behavioral anomaly incident LIFECYCLE, newest first: {"enabled": bool, "active-count": N, "incidents": [{id, interface, entity, cohort, fired-features: [{name, z}], score, severity, start-time, end-time, active}]}. end-time is omitted while active is true. It is set when the incident clears, or when the stale timeout finalizes it. A finished incident's duration is readable here and nowhere else. enabled is false when the plugin is not running. |
ze-anomaly:show-shape (no args) |
handleShowAnomalyShape in. internal/plugins/anomaly/shape/show.go |
Shadow-first responder status: {"enabled": bool, "mode": "shadow"|"armed", "action": "limit"|"drop", "kill-switch": bool, "armed-count": N, "armed": [source, ...]}. enabled is false before configuration. In shadow mode (default) nothing is installed; armed sources carry a live per-source firewall action with a timed auto-revert. |
ze-trafficusage:show-traffic-usage (args: [name <interface>]) |
handleShowTrafficUsage in. internal/plugins/trafficusage/show.go |
✕ |
ze-pki:show-certificates |
handleShowPKICertificates in. internal/component/pki/show.go |
{"certificates": [CertSummary, ...], "count": N} |
ze-pki:show-certificate (args: <name> [pem | bundle pem | fingerprint [algo]]) |
handleShowPKICertificate in. internal/component/pki/show.go |
✕ |
Both warnings/errors handlers accept optional source <name> filter and
errors accepts count <N> limit. Return a non-nil empty slice when empty.
Issue JSON shape
| Field | JSON type | Notes |
|---|---|---|
source |
string | Subsystem name (lowercase, short: bgp, config, iface, ...) |
code |
string | Kebab-case identifier (prefix-threshold, notification-sent, ...) |
severity |
string | "warning" or "error" (MarshalJSON converts the internal uint8 enum to the label) |
subject |
string | What the issue is about (peer address, transaction id, file path) |
message |
string | Human-readable one-liner |
detail |
object | Optional. Omitted via omitempty when nil or empty. Keys and values are producer-defined. |
fix |
string | Optional. The command that fixes the subject, set by RaiseWarningFix / RaiseErrorFix. Omitted via omitempty when empty. |
raised |
RFC 3339 time | First appearance |
updated |
RFC 3339 time | Most recent raise (warnings advance; errors equal raised) |
Day-one BGP producers
| Severity | Code | Subject | Detail keys | Source function |
|---|---|---|---|---|
| warning | prefix-threshold |
<peerAddr>/<afi>/<safi> |
family, count, warning, maximum |
raisePrefixThreshold in applyPrefixCheck. reactor/session_prefix.go |
| warning | prefix-stale |
peer address | updated |
RaisePrefixStale in at peer add (and clear at remove). reactor/session_prefix.go, reactor_peers.go |
| error | notification-sent |
peer address | code, subcode, direction=sent |
raiseNotificationError("sent". ) in Peer.IncrNotificationSent. reactor/session_prefix.go |
| error | notification-received |
peer address | code, subcode, direction=received |
raiseNotificationError("received". ) in Peer.IncrNotificationReceived. reactor/session_prefix.go |
| error | session-dropped |
peer address | reason |
raiseSessionDropped in FSM Established->Idle branch when no notification was exchanged. reactor/session_prefix.go, peer_run.go |
| error | doctor-bgp-peer-not-reading |
peer address | budget |
Session.reportWriteBudgetExpiry in retireWrite when a write waited out its budget and that expiry is the session's close reason. Raised with a fix (report.RaiseErrorFix). reactor/session_write_budget.go |
| error | doctor-bgp-write-path-held |
peer address | notification or waited |
Session.reportWritePathHeld in, called from the close routine (closeConnWithin) when the write path stayed held for the close's wait, or when the NOTIFICATION before it found the path held. Raised with a fix (report.RaiseErrorFix). reactor/session_connection.go |
The session-dropped producer is suppressed when a NOTIFICATION was sent
or received during the same session lifecycle: the operator already sees
that event in show errors so a duplicate session-dropped would be noise.
Tracking is via Peer.notificationExchanged atomic.Bool, reset at the
start of each runOnce iteration. It is suppressed the same way when the
session's recorded close reason is a write budget expiry, which the session
raised as doctor-bgp-peer-not-reading when it happened, and when a close
of the session met a held write path, which the close routine raised as
doctor-bgp-write-path-held (sessionDroppedOwed and leaveCause in
reactor/peer_close.go).
Login banner integration
The Ze CLI login banner reads from the same report bus (filtered by
source bgp). One active warning displays the detail line; multiple
warnings collapse to a count line pointing at show warnings. This
is the single source of truth for "what's wrong right now" across
the connect path and the show command.
Capacity limits and env vars
| Env var | Default | Maximum | Registered by |
|---|---|---|---|
ze.report.warnings.max |
1024 | 10000 | env.MustRegister in. internal/core/report/report.go |
ze.report.errors.max |
256 | 10000 | same |
Operator values exceeding the maximum are clamped and logged at warn level. Zero or negative values fall back to the default. This prevents an env-var typo from causing memory exhaustion.
Target-First Syntax
For value arguments, omission differs from an explicit empty string. The shared
invocation writer quotes an empty value as ""; the command's model decides
whether that value is valid. REST, gRPC and generated MCP arguments preserve
that distinction, including empty encoded byte content. Optional blank HTML
controls remain omitted at the form boundary, while a required supplied-byte
input can contain zero bytes when its shared argument validator permits an
empty value. A blank required HTML control whose model rejects empty, such as
an integer, remains omitted for the dispatcher's missing-argument check.
Empty flag controls leave the flag unset.
Structured API and MCP boolean flags use true for presence and false for
omission; ordinary nonflag booleans remain values. REST and gRPC keep command
and parameters separate until one engine metadata generation supplies typed
placement and the original definitions for the shared invocation matcher.
An already supplied raw invocation retains its text and selector values while
extra parameters follow as keywords, written before the first pipe of a line
that holds a chain. Malformed flag values refuse before a
handler runs and name the command's help.
Process Lifecycle Commands
request shutdown # Graceful shutdown
request restart # Graceful daemon restart; host stays running
request reboot # Graceful shutdown + OS reboot (requires root on Linux)
request reload # Reload configuration
request halt # Goroutine dump, then graceful shutdown (stop drain included)
show status # Get process status
request restart uses the shared dispatcher, authorization and accounting on
every command surface. It answers restart initiated before the transport
releases the daemon's restart action. With BGP, the action writes the existing
graceful-restart marker and stops sessions without a shutdown notification.
After teardown the daemon exits 75. The generated systemd unit classifies this
as successful and forces a new start; gokrazy's normal supervision loop also
retries this exit. A foreground invocation exits 75 and its caller must start
the next process. A daemon without BGP uses the same stop notification, with no
BGP marker. The host stays running.
Bare interactive stop and restart require confirmation and dispatch the
canonical request shutdown or request restart through the session executor.
SSH exec also maps its bare reboot to request reboot. A missing authenticated
SSH policy refuses the command rather than using a daemon fallback policy.
A request canceled before acceptance is refused. Once accepted, restart runs
after the response write attempt even if the connection closes during delivery.
Separate accepted requests share one restart action. Restart takes no arguments;
an extra argument is refused before any action is accepted.
gRPC releases an accepted action on its payload write or terminal RPC End,
whichever first completes it, so an accepted call that loses its response still
runs the action once. A rejected call installs no lifecycle action.
Session Commands
plugin session ready # Signal plugin init complete
plugin session ping # Health check
plugin session bye # Disconnect
Peer-specific replay completion is a different command:
request peer <addr> plugin session ready session <captured-token>
<captured-token> is the nonzero decimal initial-replay value from the peer-UP
event that started this replay. Empty replays must report it too. The peer
atomically validates the current, non-retired Session and credits only the
sending process. Missing/stale receipts fail without releasing live forwards;
looking up a fresh token to finish old work is forbidden. Explicit operator
readiness is a no-op, not authority to release a named process's replay fence.
Ze's own End-of-RIB does not wait for these reports.
SDK producers send this complete YANG command with DispatchCommand, not
DispatchCommandArgs: the latter accepts an exact plugin command registration,
whereas this builtin is registered by its ze-bgp:plugin-session-peer-ready wire
method. Completion means that the producer finished its replay attempts, not
that every history entry was delivered. A rejected entry cannot strand the
live-forward fence; independent entries are still attempted, and completion
always retains the original token.
BGP Plugin Configuration
bgp plugin encoding json # Set event encoding to JSON (default)
bgp plugin encoding text # Set event encoding to human-readable text
bgp plugin format hex # Wire bytes as hex string
bgp plugin format base64 # Wire bytes as base64
bgp plugin format parsed # Decoded fields only (default)
bgp plugin format full # Both parsed AND wire bytes
bgp plugin ack sync # Wait for wire transmission
bgp plugin ack async # Return immediately (default)
Event Subscription Commands
A plugin declares what it CAN handle. The peer's configuration decides what it
GETS. A peer-scoped event is delivered to a process when both halves name it:
the process subscribed to the event, and the peer's attach process <name>
block grants that type in that direction. A peer that attaches no block for a
process feeds it nothing.
request subscribe <namespace> event <type> [direction received|sent|both]
request subscribe peer <selector> event <type> [direction ...]
request subscribe plugin <name> <namespace> event <type> [direction ...]
request unsubscribe <namespace> event <type> [direction received|sent|both]
Precedence. The configuration is durable receive authorization and is
rebuilt on every config apply. A request subscribe typed at a running daemon
is a live capability override: it can add a type the process did not declare at
startup only where the peer's block grants that type. It cannot widen the
configured grant, and the next config apply discards it.
At plugin ready, and again after every apply, ze reports each peer, process and event type the two halves disagree about. Two lines an operator sees:
event delivery: the config grants an event the plugin never declared peer=... process=... granted=update-received
event delivery: the plugin declared an event the peer does not grant it peer=... process=... declared=state
Namespaces:
bgp- BGP protocol eventsrib- RIB events (cache, route changes)
BGP event types:
| Event | Has Direction | Description |
|---|---|---|
update |
✅ | UPDATE message |
open |
✅ | OPEN message |
notification |
✅ | NOTIFICATION message |
keepalive |
✅ | KEEPALIVE message |
refresh |
✅ | ROUTE-REFRESH message |
state |
❌ | Peer state change (up/down) |
negotiated |
❌ | Capability negotiation complete |
rpki |
❌ | RPKI validation result (from bgp-rpki plugin) |
update-rpki |
✅ | UPDATE merged with RPKI validation (from bgp-rpki-decorator) |
Plugins may register additional event types via Registration.EventTypes. These are validated at runtime against the dynamic registry.
RIB event types:
| Event | Description |
|---|---|
cache |
Cache entry events |
route |
Route change events |
Examples:
request subscribe bgp event update # All peers, both directions
request subscribe bgp event update direction received # Received only
request subscribe peer upstream1 event update # Specific peer
request subscribe peer * event state # All peers, state changes
request subscribe peer !upstream1 event update direction sent # Exclude one peer
request subscribe rib event route # RIB route events
Monitor Commands
Stream live events or display live dashboards. All monitor commands follow verb-first syntax: monitor <module> [args...].
monitor event # All events, all peers
monitor event peer <addr> # Filter by peer address
monitor event peer * # Explicit all peers
monitor event include <type>,<type> # Only listed event types
monitor event exclude <type>,<type> # All types except listed
monitor event direction received # Received events only
monitor event direction sent # Sent events only
monitor event include update peer <addr> direction received # Combined filters
monitor bgp # Live peer dashboard (TUI)
| Keyword | Values | Default |
|---|---|---|
peer |
IP address, peer name, !exclusion, or * |
* (all peers) |
include |
Comma-separated event types | All types (mutually exclusive with exclude) |
exclude |
Comma-separated event types | None (mutually exclusive with include) |
direction |
received, sent |
Both directions |
Keywords may appear in any order. include and exclude are mutually exclusive.
Event types span all namespaces: BGP (update, open, notification, keepalive, refresh, state, negotiated, eor, congested, resumed, rpki) and RIB (cache, route). Types are validated at parse time.
Wire method: ze-meta:event-monitor. Supports pipe operators: | json, | table, | match.
Compact BGP event lines show AS<number> when the peer's AS is known and
AS unknown before negotiation. An event with an invalid AS value stays in
its original JSON form.
One-shot answer of a streaming command
A streaming command registers with RegisterStreamingHandler(prefix, oneShot, handler), and oneShot declares what the command answers where no stream can
be shown: MCP, REST, gRPC and the web admin console run a command once.
| Declaration | One-shot surfaces | Commands |
|---|---|---|
OneShotSample |
Offered. The one-shot RPC answers one sample from the producer the stream reads | monitor interface rate (the rate tracker, as show interface rate), monitor traffic stat (the trafficstat snapshot, as show traffic stat), monitor ping (a bounded run of probes), monitor traceroute (one probe round) |
OneShotStreamingOnly |
Not offered: the stream is a sequence of events, so no single answer holds its data. Typed in full, the command is refused with StreamingOnlyError, which names ze <command> and SSH, the places it streams |
monitor bgp, monitor event, monitor system netlink, monitor vpn ipsec |
A stream whose data lives in a plugin process registers with
RegisterPluginStreamingHandler(prefix, oneShot, pluginCommand, handler)
instead, naming the plugin command its handler forwards to
(Dispatcher.ForwardToPlugin), the way RPCRegistration.PluginCommand names
it for a builtin. StreamingPluginCommand(prefix) answers it, so a reader of
the registry knows which plugin must run for the stream and its sample to
answer. monitor interface rate declares show interface rate, which the
iface plugin serves from its own rate tracker. With that plugin absent the
sample is refused (ratesOf, iface.ErrRatePluginAbsent): the refusal says
the interface plugin is not running, that Ze starts it only for a
configuration holding an interface section, and the command that adds one.
The surface parity check starts the plugin that declares the command before it
asks.
The surface predicate (command.AnswerSurface) reads the declaration, so the
MCP, REST and gRPC command list and the web admin tree leave a streaming-only
command out. The browser terminal completer offers it because that terminal
has a streaming transport. The surface parity check fails a sample command
whose one-shot answer carries no data.
The refusal is decided once, from the declaration, on both one-shot routes: the
dispatcher (Dispatcher.Dispatch, which MCP, REST, gRPC, the web console and a
plugin's dispatch-command use) and the wire-method route (wrapHandler).
The command's RPC handler is StreamingOnlyRPC, which answers an error if a
route ever skipped the refusal, never a reply.
Where a monitor command streams
Every monitor command streams live on the terminal surfaces below. Each surface branches on a registry, never on a command name:
Registered rich views also expose an internal request-scoped headless driver,
cli.RunBrowserView. The caller supplies an authenticated factory binding and
bounded action/frame channels; view owners declare the controls and retain the
same model state, key handlers and data producers as the terminal. This driver
is a rendering/interaction seam; the browser transport still determines which
route opens it. It does not authorize commands or replace the dispatcher.
Dashboard detail failures appear in the shared view error zone, including a
denied detail request.
| Surface | Route |
|---|---|
SSH exec (ssh router monitor ...) |
pluginserver.IsStreamingCommand judges the command part, and execMiddleware hands the streaming executor (sshStreamingExecutorFactory) the line as typed, chain included, with the session's rendering. The executor accounts and authorizes the typed line, then runs the handler the one lookup answers. cmd/ze/hub/service_ssh.go |
ze cli -c "monitor ..." |
The client streams when pluginserver.IsStreamingCommand holds: it sends the typed line with the rendering key set and presents only the presentation suffix (below). internal/component/cli/client/main.go |
SSH interactive and the ze cli TUI |
The model opens a registered live view first (the monitor bgp dashboard, the monitor ping and monitor traceroute views), then a streaming session for any other streaming command. internal/component/cli/model_keys.go |
ze monitor ... |
A registered local handler runs its live loop in-process (monitor ping, monitor traceroute), and any other command goes through ze cli -c |
| Browser CLI | /cli/stream checks the same streaming registry, then runs the judged raw handler through serverStreamDispatcher. A consumer negotiating application/x-ze-cli-view+ndjson can instead drive the registered shared view. Both use serverStreamCommand admission with the browser identity, accepted authorization policy and command accounting; other commands keep the normal terminal response |
The stream route partitions in one lookup
Every caller of a streaming handler (the browser's serverStreamCommand, the
REST and gRPC streams' apiStreamSource, the SSH exec executor and the
daemon-hosted model's extractMonitorCmdArgs) hands the typed line, chain
included, to pluginserver.GetStreamingHandlerRendered, which
GetStreamingHandlerForCommand calls with the engine's rendering. It reads
the line once (command.ReadStreamLine): one scan under the chain grammar,
the alias expansion and the partition the one-shot route runs. The handler
receives the operations the monitor declares in ValidatedArgs
(PipeOperations), never a chain word among its arguments, and the handler
it answers writes every event through the residual chain (RunStreamPipes):
each newline event is formatted once, a final unterminated event is flushed
after producer success, and pending event bytes are limited to 4 MiB. A
larger event is refused without truncation. | save is refused before a
producer starts, because the daemon never writes a caller's file. Each caller
accounts and authorizes the typed line, chain tokens included.
TestEveryPipeSplitGoesThroughThePartition refuses a reader of the streaming
registry that goes around the lookup.
The same handler holds a monitor's override to its generic's answer shape, event by event. When the last operation the monitor declares on the line is an override, each event the producer writes is judged before the residual chain runs. A stream's rows are its events, so one event is one row:
| Override | Each event is |
|---|---|
count |
one object holding an integer count |
| every other data operator | one JSON document, which is the row |
The events of first N and last N are not counted, because the engine
holds no stream whole. An event of another shape is not written: its refusal
stops the stream, names the monitor and the operation, and ends in show command help "<the monitor>". A blank line is no event and is not judged.
An override followed by another declared operation, and a line that ends in
the monitor's own operation, are not judged. The check runs inside
StreamLine.Run, so no stream site carries a copy of it.
Rendering (command.StreamRendering) |
Stated by | The daemon applies |
|---|---|---|
StreamRenderingEngine |
the browser, REST, gRPC, the daemon-hosted model | the whole residual chain, in the default format when the chain names none; a line with no chain passes the events unchanged |
StreamRenderingTerminal |
SSH exec without the rendering key | as above, and a line with no chain is rendered in the default format too |
StreamRenderingClientPresentation |
SSH exec with the rendering key | every operation before the presentation suffix; the events stay data for the client |
Each event is one row of the stream. The daemon runs the chain over one
event at a time (applyStreamEventPipes), so | match keeps or removes a
JSON event whole, by its values, as it judges one row, and never searches
the event for rows of its own: a BGP OPEN event's body is a map of objects
that the one-shot row finder would take for rows keyed by identity. The same
document answered by a one-shot command is the whole answer, matched row by
row, or refused by name when it holds no rows. A rendered event is matched
line by line, as text (applyEventMatch).
The rendering key. A client in another process holds no
CallerIdentity, so it states that it presents a stream through the SSH
session environment: ZE_CLI_RENDER=client (sshclient.EnvCLIRender,
CLIRenderClient), set by sshclient.StreamPresentedCommand, which the
ze cli monitor uses. parseSessionRequest reads it beside
ZE_CONFIG_NAME and ZE_CLI_MODE, on the exec channel and the interactive
one, and refuses any other value by name before a command runs. It is
honoured on the exec stream route only: a one-shot exec and the interactive
session render as without it. The key is untrusted input and hands over
presentation, never selection. The daemon applies every operation before the
PRESENTATION SUFFIX, the longest trailing run of operators the catalog marks
Presentation (the formats, no-more, save), found on the names as typed
before any alias is expanded, so an alias ends the suffix and the daemon
applies its whole expansion. The client applies the suffix alone
(command.PresentStreamSuffix): its format, or the monitor event formatter
when the chain names no format, and | save, which writes the operator's own
file. Both sides find the suffix with one function
(presentationSuffixLength), and the client reads the catalog alone, so it
never refuses an operation it has not heard of.
| Line, with the key set | The daemon applies | The client applies |
|---|---|---|
monitor x | match up | save f |
match |
the default format, save |
monitor x | match up | table | save f |
match |
table, save |
monitor x | json | match up |
json, then match |
nothing |
monitor x | top-talkers | save f (the monitor's own operation) |
top-talkers, in the handler |
the default format, save |
monitor x | brief | save f (brief an alias) |
the whole expansion of brief |
the default format, save |
Raw browser consumers can request
Accept: application/x-ze-cli-output+ndjson on the same route and dispatch.
Data frames carry base64 producer bytes in data with done: false; dispatch
completion carries done: true and an optional actionable error. A complete
result requires that final frame without an error, so producer text beginning
with error: stays ordinary output and a disconnected or canceled stream stays
incomplete. The producer budget is 4 MiB, chunks are at most 32 KiB, encoded
frames are at most 64 KiB and socket writes have a five-second deadline. A
pre-output authorization refusal remains HTTP 403; unhandled finite commands
keep their JSON response. Unnegotiated raw consumers retain flushed text.
The streaming handlers of the three commands that also own a live view:
| Command | Streaming handler | Producer | One-shot answer |
|---|---|---|---|
monitor bgp |
streamBGPMonitor. internal/component/bgp/plugins/cmd/monitor/register.go |
StreamMonitor over the daemon's monitor set: a header, then one line per BGP event |
OneShotStreamingOnly |
monitor ping |
streamMonitorPing. internal/component/ping/cmd/monitor.go |
NewPingSession: one line per probe, the text ze monitor ping prints |
OneShotSample: the rows of a bounded run (the requested count, else 5) |
monitor traceroute |
streamMonitorTraceroute. internal/component/traceroute/cmd/monitor.go |
NewTracerouteSession: one block per probe round, a round each second |
OneShotSample: one probe round, as show probe-round |
TestEveryMonitorCommandStreams reads every monitor command from the streaming
prefixes, the live views and the YANG paths under monitor, and fails any one
a surface would answer once instead of streaming.
Netlink Monitor
Stream kernel route, link, and address change events as one JSON line per event. Replaces ip monitor on gokrazy appliances.
monitor system netlink # All netlink groups (route + link + address)
monitor system netlink route # Route changes only
monitor system netlink link # Link state changes only
monitor system netlink address # Address changes only
monitor system netlink all # Explicit all (same as no argument)
Wire method: ze-iface:monitor-system-netlink. Linux only; returns "not available on this platform" on other OSes.
System Commands
system help # Show help (uses dispatcher, includes plugin commands)
system version software # Show Ze version
system version api # Show IPC protocol version
system subsystem list # List available subsystems
system command list # List all commands (builtin + plugin)
system command list verbose # List with source (builtin/process name)
system command help name "<name>" # Show command details; the bare "<name>" is accepted too
system command complete partial "<partial>" # Complete command names; the bare "<partial>" is accepted too
system command complete args "<cmd>" [<completed>...] ["<partial>"] # Arg completion; no partial lists every candidate
A builtin whose argument names runtime state declares an ArgCompleter in its
RPCRegistration; system command complete args answers it from the daemon,
and system command list marks the command completable, so the ze cli
tree asks the daemon at Tab while an SSH session's tree calls the completer in
the daemon's own process (docs/architecture/cli/command-completion.md). A
plugin command that declared itself completable is answered by its plugin.
A builtin that changes state an operator must be able to trace declares an
AuditAction (an audit.Action* value) in its RPCRegistration. After a
successful run the dispatcher records one audit entry under that action, with
the command line through config.DisplayCommand as its detail, so a credential
value and the value after content read as the placeholder. A refusal or a
handler error records nothing, and a registration that declares no action is
not audited: the dispatcher never picks the audited commands by their text.
request reload declares daemon-reload, delete data key and
update data key declare data-key-change, and update data config declares
data-config-import (docs/guide/audit.md). A plugin command has no such
declaration: pkg/plugin/sdk carries none, so the audit log records no plugin
command.
A command that needs bytes held on the caller's side takes them base64-encoded
in an argument named content, as update data key <key> content <base64>,
update data config name <name> content <base64> and the
show config supplied commands below do. The two update data leaves
declare ze:keyword-only, so the bytes are read after the word content and
never from a stray word: update data key <key> <word> is told content is
missing. show config supplied validation content <base64> name <label> is how
the local ze config validate <file> has the running daemon judge a config
that declares an external plugin: the daemon reads a named file only from its
own config directories (command.CallerPath), so the local command sends the
file's bytes, name carries the file's base name as a label for the daemon's
messages, and nothing is read on the daemon's host. Its larger-value route is
show config validation file <path>, for a file inside those directories
(docs/architecture/config/yang-config-design.md,
"ze config validate asks the running Ze first"). The local ze config fmt,
dump, diff and graph send their own supplied form the same way, and draw
the answer with their local renderer (the same page, "ze config fmt, dump,
diff and graph take the same route"). No surface has a
second input channel, so the argument is the same on SSH, REST, gRPC, MCP and
the web. Each leaf declares the bound, 261,120 base64 characters (195,840 bytes
of content), which is what one SSH packet carries with the rest of the
command: an SSH exec request is a single packet of at most 256 KiB, and the
local ze data write and ze data import reach the daemon that way. Each
leaf's own error message says what to do with a larger value: the offline
ze data write for a key, request data restore path <file> config for a
config. The value after
content is never recorded and never echoed in a refusal
(redact.Command, redact.IsCredentialKeyword).
Caller-supplied configuration inspection
The config CLI owner registers show config supplied dump, validation,
fmt, graph, diff, migrate, fix-plan and source. Each takes a required content argument through
the same dispatcher as its file-based counterpart. A single-source command
receives padded base64 of native configuration bytes. Its optional name
is a basename used only in diagnostics; the default is supplied.conf.
migrate returns the set form by default, or nested blocks with format hierarchical, through the converter ze config migrate uses. fix-plan
returns the diagnostic repair plan ze config fix --plan produces, including
the plan of an invalid configuration. source returns the unexpanded source
tree with parsed secrets masked; optional path contains quoted configuration
path words. A missing subtree refuses rather than returning the whole source.
The exact bytes a caller supplied remain readable when they cannot parse, so
the caller can repair them. The corresponding file forms, show config migrate, fix-plan and source, take file and confine remote host filenames
through CallerPath. A remotely read source that cannot parse is refused
because its secret leaves cannot be masked.
Detached editing uses show config supplied set, activate, deactivate and
replace. These operations return configuration text; they do not publish it
into a source file, store or live candidate. Each takes one encoded JSON object
with before and after strings. For the three editing verbs, before is the
source configuration and after is exactly one matching editing command, such
as set bgp router-id 192.0.2.1. Multiple lines, pipes and a different leading verb
are refused before the operation runs. Assigned values remain inside masked
content, rather than a separate value argument that command records might
disclose. For replace, both strings are complete configuration sources and
the shared transition validator checks the replacement before serialization.
Its warnings remain in the diagnostics for both serialized output and the
masked diff returned by dry-run; serialization warnings follow them. The
file counterparts take a confined
file and content containing the encoded editing command or replacement
bytes. Both routes use the same Editor operations and Save serializer as the
local file/stdin tools. Only the local adapters choose file publication.
The shared validator's complete value refusal keeps its original problem,
explanation and correction on both routes. The editor's schema mask applies to
each part before it is returned; adapters add no second explanation or fix.
Parse and activation failures are complete operator errors at their owning
Editor calls. Parser line numbers and load: context, or the activation verb,
remain in the problem; a native correction remains the final fix. Plain or
joined failures retain their whole cause and receive the operation's recovery
step before either route renders them.
An activation refusal also retains a rejected key's typed schema facts, so an
editor in a context can frame the same correction with its relative invocation.
Dump and graph refusals retain the parsing or resolution error and name a
validation command as the next step. Formatting a file that cannot be written
retains any earlier password warnings before the actionable write error.
Formatting check still answers its completed check with exit 1 and the
existing needs formatting diagnostic when the source needs changes.
The existing file commands retain their confined daemon paths, local stdin
and revision grammar.
For diff, decoded content is one JSON object with required before and
after string fields, each containing native configuration text. Missing,
duplicate, unknown and nonstring fields, invalid UTF-8 and trailing data are
refused. The combined envelope has the same 195,840-byte limit as a single
input. Both sources remain under the masked content keyword in history,
transcripts and accounting. command.DecodeContent enforces the common
261,120-character bound before decoding; the existing store-update handlers
use this codec too.
show config supplied completion takes the same bounded JSON envelope with
configuration and input string fields. The source and editing text stay
together inside masked content; editing text can itself contain a secret.
Optional context is a slash-separated configuration path. Without ghost,
the document contains completions, preserving each native candidate's text,
type, short help and description. With ghost, the blob contains the native
ghost text followed by a newline. The local file/stdin command and supplied
command share schema selection, parsing and the completion producer. Declared
external programs are never started to answer a completion request.
show secret encode and show secret decode take padded base64 content
containing the caller's literal operand. Their optional trim-line-ending
flag applies the standalone stdin rule; the default preserves every operand
byte. Both return a blob with the standalone final newline and use the same
codec and refusals as ze secret. These commands disclose the requested
conversion result to the caller, including decoded plaintext, but never read
host secrets. Their modeled sensitive content is masked in history and
accounting, and refusals do not echo the private operand.
Comparison has the same scope as the local file command: every root of the
two configurations, the bgp block as resolved values and every other root as
written, such as a changed system host, plus schema-declared ordered-list
ordering, with every secret masked.
File and supplied inputs share their parsing, resolution, validation,
formatting, inactive pruning, comparison and secret-display producers. Dump
retains strip-private; fmt retains check and diff and has no write option.
The supplied route opens no file, store or candidate, applies no environment
block and checks the original caller's cancellation. Shared authorization,
accounting and answer-shape pipe rules remain in force.
Input bounds do not bound generated output: conversion to set form can repeat
long source paths. The shared byte-answer boundary refuses a remote Blob larger
than BlobRemoteOctetsMax (8 MiB), with no oversized payload and a local command
as recovery. The local converter retains its file/stdout behavior. The same
boundary checks cancellation before and after production for both supplied
bytes and the file counterparts.
show config environment-validation answers a typed validation verdict over
the answering process's registered environment types and recorded range
failures. ze config validate --limit environment shares that authority and
returns exit 1 for invalid values; -q keeps the local invocation silent.
Secret values never enter the diagnostics. Configuration list and history
adapters share configListRows and configHistoryRows; their root text
presentations no longer repeat storage traversal. A configuration list is
returned only after every required store listing and selected loose-file
directory can be read. An absent optional search directory is allowed;
storage failures, an unreadable search directory or an unavailable working
directory refuse the list with its cause and ze doctor as the next check.
No partial configuration list is printed or published on those failures.
show config validation file <file> pending checks the saved <file>.draft
source. The local ze config validate --pending <file> shares that source
reader. The daemon confines the actual draft path, including symbolic links,
before reading it; permission to read the committed file does not admit an
outside draft. Standard input has no saved draft. show config history file <file> declares its source explicitly and retains the positional file form.
request data config rename old <name> new <name> renames a complete inactive
stored configuration, including versions, pointers and saved editor records.
The storage owner refuses destination collisions and unfinished publication
intents. The daemon also refuses its running configuration identity and a
configured managed client's serving identity. ze config rename <old-name> <new-name> calls the same transaction offline; a busy store sends the request
to its owning daemon and requires an acknowledgment of both requested names.
That route preserves the daemon's refusal and never removes the store lock.
request data config rollback name <name> revision <N> selects the same
one-based history revision as ze config history. The storage owner verifies
the selected bytes and publishes a new active version, retaining the previous
active version as rollback. The daemon stages and reloads its running source.
Other stored configurations use the guarded storage transaction. Pending
confirmation, file publication and another staged candidate refuse the write.
The local stored adapter uses that transaction offline and routes a busy store through its owning daemon. It prints success only after the response matches the requested name and revision and supplies both version identities and the selected source time.
Loose-file rollback retains its direct file behavior.
The primary graphical editor projects these registrations into native
file/paste inspection forms. It joins registry.Meta.SuppliedInput to the
actual command-tree argument definitions, composes the input once and dispatches
with the original authenticated identity, policy and cancellation. It does not
add another command list, open a daemon filename, create an editor or write
history. Failed validation retains its diagnostic data beside the original
error through the same operational formatter the browser CLI uses; the failure
remains incomplete.
An input control discovers these capabilities through
registry.Meta.SuppliedInput, joined to the command's YANG arguments. The
descriptor names the content argument, optional label argument and ordered
JSON source fields; an empty field list means one raw input. Bounds, help and
label constraints come from the real argument definitions. A surface keeps no
separate command list, and the generic metadata imports no config domain.
The owner spells registration paths and summaries as literals, so the
source-based command and help contracts read the same declarations as runtime.
Process Lifecycle Commands
request shutdown # Gracefully shutdown
request restart # Restart the daemon in place; keep the host running
request reboot # Gracefully shutdown then reboot the system
show status # Show process status
request reload # Reload the configuration
request plugin restart <name> # Restart a configured plugin, stopping it first if it runs (lifts a respawn-limit disable)
request data backup path <file> [spare <n>] [force] # Back up the store to a file on the daemon host
request config artifact system snapshot # Create a private full-store download transfer
request data restore path <file> config [name <n>] # Restore the config from a backup through the reload
request data restore path <file> full # Accept full recovery after clean shutdown and store close
delete data key <key> # Remove one runtime-state key (meta/ outside meta/config/) through the daemon's store
update data key <key> content <base64> # Write one runtime-state key from base64 bytes (at most 195,840 bytes) through the daemon's store
update data config name <name> content <base64> # Import one config as a new version (at most 195,840 bytes), through the reload for the daemon's own config
show reload-status # Show how many config reloads have been processed
show config running # Show the configuration the daemon applied
Standalone web mode binds the same store and full-recovery lifecycle without a configuration reload owner. Full-store restore can be accepted there, but applying a running configuration through restore, import or indexed rollback is refused before a candidate is staged. The accepted full source is applied only after web requests, command-owned resources and the original store finish cleanly; a cleanup failure prevents replacement.
request config artifact system snapshot requires edit access because its
complete .zefs includes credentials and private keys. Its result is the
existing private transfer document (transfer, total, next, complete).
Read it with show config artifact transfer read transfer <id> offset <n> and
finish with request config artifact upload abort transfer <id>, including
after a failed read. A different account cannot read the transfer. Source
history, drafts and pending changes are preserved as raw keys; creation invokes
neither commit nor reload. The daemon must serve a store, and bounded snapshot
admission may refuse before creating output. The browser creation form uses
this command and downloads the resulting bytes directly.
show reload-status (the reload fence)
Returns the reload generation counter as JSON:
{"generation": 3, "last-outcome": "applied", "last-reload-at": "2026-07-16T09:12:44Z"}
| Field | Meaning |
|---|---|
generation |
Reloads PROCESSED since daemon start. Starts at 0. |
last-outcome |
applied, failed, or none before the first reload. |
last-reload-at |
RFC3339 UTC completion time; empty string before the first reload. |
generation advances on every processed reload, including one that rejected
a change or changed nothing. That is what makes it a fence rather than a
statistic: a reload that rejects a change (l2tp refusing a listener rebind, for
example) leaves no other observable trace, so an observer wanting to assert "the
reload ran and correctly left this alone" has nothing else to wait on. It reads
generation, triggers the reload, polls until the value advances, then asserts.
Waiting on a timer instead makes the assertion pass vacuously against a reload
that had not started.
A reload refused with ErrReloadInProgress does not advance the counter: it was
queued, not processed, and the replay advances it.
The counter is observational only; nothing reads it to make a decision, so it cannot change what a reload accepts or rejects.
show config running (the applied configuration)
show config running answers the configuration the daemon is running, as a
tree. The daemon reads it from its running tree, not from the config file. Only
a reload whose transaction committed replaces that tree, so after a refused
reload this command still shows the configuration in force, while the file
already holds the text the daemon refused.
Every secret leaf (ze:sensitive or ze:bcrypt) is replaced with
/* SECRET-DATA */. The answer leaves the daemon over SSH, REST and gRPC, so it
never carries the reversible $9$ form that show config dump writes. A daemon
that holds no running tree yet refuses the command and says so. It never
answers an empty tree.
show config dump is a different command. It is a local-data command: it parses
the file it is given in the caller's own process, so it cannot say what a daemon
applied. Given no file, it refuses and names show config running. REST
GET /api/v1/config/running and gRPC GetRunningConfig dispatch
show config running.
Peer Commands
show bgp peer list # List all peers
show bgp peer <selector> detail # Show specific peer detail
show bgp peer <selector> capabilities # Show specific peer capabilities
show bgp peer <selector> statistics # Show specific peer statistics
show bgp peer <selector> history # Show FSM transition history
request peer <selector> teardown [<cease-subcode>] # Disconnect peer
request peer <selector> notify <code> <subcode> [<text>] # Disconnect one peer with any NOTIFICATION
request peer <selector> notify <code> <subcode> hex <octets> # The same, the Data field verbatim in hex
create bgp peer <address> asn <asn> [...] # Add a peer to the running daemon
delete bgp peer <name> # Stop a peer, configured or created, and remove it from the running set
update bgp config # Write the running peer set to the config file
request peer <sel> flush # Wait for forward pool to drain (barrier)
show bgp answers one row per peer. Two of its keys carry what the operator
configured to identify the peer, and each has one source:
| Key | Source | Empty when |
|---|---|---|
description |
The peer's description leaf, after the bgp, group and peer levels are merged (PeerSettings.Description, then plugin.PeerInfo.Description) |
The configuration states no description. Nothing is derived from the name or the group |
group |
The group the peer is declared in (PeerSettings.GroupName, then plugin.PeerInfo.GroupName) |
The peer stands outside any group |
Both keys are present on every row. The description is delivered to a running
peer by a configuration reload without a session restart, and the handler reads
it from the peer snapshot on each call. Only that snapshot carries it: the peer
object of a BGP event has group and no description.
show bgp peer <selector> history reads the peer's retained FSM transitions
through the registered BGP adapter. Each row carries the source and destination
states, plus the timestamp and reason when recorded.
create bgp peer (ze-bgp:peer-create) and delete bgp peer
(ze-bgp:peer-delete) change the running peer set and never write the
configuration file. A commit or a reload whose configuration does not declare a
created peer keeps it running: the reload leaves the created peers the
candidate does not name out of the running tree it compares against, so the
diff plans no removal, and carries them into the tree that replaces it.
update bgp config (ze-bgp:peer-save) takes no selector and makes the file state the whole running set: a created peer is
written in, and a configured peer that was deleted is taken out.
Cache Commands (Ze)
Design history: summary 148 was retired on 2026-08-01 and was not carried into
plan/learned/DESIGN-HISTORY.md. That file's header gives the git-recovery route. What survives of the cache pattern is in its "BGP engine: wire encoding and RIB" > Load-bearing invariants: cacheAckandRetainare independent refcount axes, and engine cache ack is cumulative.
send bgp <sel> cached <id> # Forward cached UPDATE to peers
request cache retain <id> # Prevent eviction
request cache release <id> # Allow eviction (reset TTL)
request cache expire <id> # Remove immediately
show cache # List cached message IDs
# Batch variants (comma-separated IDs, max 1000):
send bgp <sel> cached <id1>,<id2>,...,<idN> # Batch forward
request cache release <id1>,<id2>,...,<idN> # Batch release
The cache commands enable route reflection via API:
- Received UPDATEs are assigned a unique msg-id (per-UPDATE, not per-NLRI)
- API outputs UPDATE info with msg-id
- External process decides routing
- The
send bgp <sel> cached <id>command references msg-id (zero-copy when contexts match) - Cache entries expire after configurable TTL (default 60s) unless retained
Fast-path typed SDK (rs-fastpath-3)
The text-RPC send bgp <sel> cached <id> path tokenises, parses, and walks the command registry on every call. Plugins that forward many cached UPDATEs per second (route server, future route reflector) use a typed SDK pair instead:
Plugin.ForwardCached(ctx, input rpc.ForwardCachedInput) error
Plugin.ReleaseCached(ctx, ids []uint64) error
Both methods round-trip via DirectBridge when the plugin is in-process (zero socket I/O, no tokenisation, no command-registry lookup) and fall back to the ze-plugin-engine:forward-cached / :release-cached methods over the newline-framed plugin RPC connection when the plugin is out-of-process. The engine handler is reactorAPIAdapter.ForwardUpdatesDirect / ReleaseUpdates.
An intentional unbound call uses ForwardCachedInput.Destinations. A bound
call instead supplies the complete Targets set of original destination address,
Peer owner and UP session, with a bounded deadline. The two forms are exclusive.
The bound server joins every admitted target writer before acknowledging the
unique cached IDs once. An exact positive completion receipt proves settlement;
a transport error or generic cancellation receipt leaves the output unknown.
Use ReleaseCached to acknowledge an UPDATE without forwarding it.
Per-source ordering, egress filter chains, AS-PATH prepend, next-hop policy, replay-on-new-peer, and every other forwarding invariant are preserved. Only the transport differs from the text-RPC path.
Log Commands (Ze)
show log levels # Show all subsystem log levels (JSON map)
request log level <logger> <level> # Change subsystem log level at runtime
Levels: debug, info, warn, err. Changes take effect immediately via slog.LevelVar atomic swap. Only loggers created via slogutil.Logger() or slogutil.LazyLogger() (non-disabled) are shown and modifiable.
Metrics Commands (Ze)
show metrics values # Dump Prometheus text format output
show metrics list # List metric names only (no values)
show metrics pool # Per-attribute pool occupancy and dedup rates
Requires telemetry to be enabled in config (telemetry { prometheus { ... } }). Returns error if metrics registry is not available.
show metrics pool returns 13 per-attribute pools (Origin, AS-Path, LocalPref, MED, NextHop,
Communities, LargeCommunities, ExtCommunities, ClusterList, OriginatorID, AtomicAggregate,
Aggregator, OtherAttrs) with live/dead slots, bytes, intern count, dedup hit rate.
Peer Selectors
peer * # All peers
peer upstream1 # Specific peer by name
peer !upstream1 # All peers EXCEPT this one (for route reflection)
The !<ip> negated selector is useful for route reflection:
# Forward update to all peers except the source
send bgp !upstream1 cached 12345
Note: Filter selectors (
[local-as ...],[peer-as ...]) from the ExaBGP multi-session draft are unsupported. The draft never became an RFC.
Not every command takes every selector. A command whose handler resolves its
selector through ResolveSinglePeer acts on one peer: the selector must resolve
to exactly one, and *, an exclusion or a selector matching several peers is
refused. The handlers that call it are the list, so grep for the function rather
than trusting a copy here; the source anchors below name each caller (among them
teardown, notify, disable, enable, pause, resume, clear soft,
delete bgp peer and raw). The YANG selector leaf of ze-peer-cmd.yang says
which commands act on every peer it matches.
Route Commands (update text)
All route operations use unified update text syntax with flat attribute declarations
(no set keyword) and keyword aliases (short forms accepted, see Keyword Aliases below):
# Announce IPv4 unicast routes (flat attributes, no 'set')
send bgp <selector> update text next <ip> [attributes...] nlri add prefix <prefix>...
# Announce routes of any other family
send bgp <selector> update text next <ip> [attributes...] mp <family> add prefix <prefix>...
# Withdraw routes
send bgp <selector> update text nlri del prefix <prefix>...
send bgp <selector> update text mp <family> del prefix <prefix>...
# End-of-RIB marker (RFC 4724)
send bgp <selector> update text nlri eor
send bgp <selector> update text mp <family> eor
# VPLS (L2VPN/VPLS)
send bgp <selector> update text mp l2vpn/vpls add rd <rd> ve-id <n> ve-block-offset <n> ve-block-size <n> label-base <n>
# EVPN (L2VPN/EVPN)
send bgp <selector> update text mp l2vpn/evpn add mac-ip rd <rd> mac <mac> [ip <ip>] label <n>
send bgp <selector> update text mp l2vpn/evpn add ip-prefix rd <rd> prefix <prefix> label <n>
send bgp <selector> update text mp l2vpn/evpn add multicast rd <rd> ip <ip>
The section keyword names the UPDATE section the routes travel in. nlri
takes no family: it is IPv4
unicast in the NLRI and Withdrawn Routes fields (RFC 4271 Section 4.3). mp <family> is MP_REACH_NLRI and MP_UNREACH_NLRI (RFC 4760). IPv4 unicast takes
mp ipv4/unicast add only with an explicit IPv6 next hop (RFC 8950 Section 3);
its del, its eor and any other next hop are refused with the nlri form to
write. The removed form nlri <family> is refused by name, with the form to
write instead:
nlri ipv6/unicast is no longer accepted: nlri means IPv4 unicast in the NLRI and Withdrawn Routes fields, and ipv6/unicast travels in MP_REACH_NLRI and MP_UNREACH_NLRI, so write: mp ipv6/unicast add|del ..., or mp ipv6/unicast eor
A withdrawal can be answered with the peers it was withheld from
send bgp <selector> update text ... mp <family> del ... (or nlri del) names no route to a
peer whose session has advertised nothing, because RFC 4271 Section 4.3
identifies a withdrawn route in the context of the connection it was previously
advertised on. Nothing is written to such a peer
(docs/architecture/update-building.md, "A Withdrawal Names a Route This
Connection Advertised"). The command still answers done,
and the peers it withheld the routes from are named in the response's
warnings:
withdraw ipv4/unicast: withdrawal withheld: this session has advertised no route to the peer: ipv4/unicast, peers 192.0.2.10
Once the session has carried one UPDATE that makes any destination reachable, every later withdrawal is written, whether or not the peer holds the route named.
Route Commands (update cursor)
An announcement can name an explicit next hop, next-hop self, or
next-hop default <gateway>. The default form selects the address per peer;
the UPDATE syntax defines its internal and
external defaults and configured overrides. Cursor mode retains that policy
alongside the candidate gateway until it is replaced or cleared. The candidate
can be an IGP IPv6 link-local gateway; default selection then uses the session's
local address unless a configured next-hop setting overrides it.
Stateful cursor mode for efficient replay of stored routes on reconnect. The engine maintains attribute state per (plugin, peer) pair. Subsequent commands send only changed attributes (delta encoding), reducing per-call overhead.
# First command: establish full attribute state + announce NLRIs
send bgp <selector> update cursor origin igp as-path [65001] med 100 \
next-hop 10.0.0.1 nlri add 10.0.0.0/24 10.0.1.0/24
# Delta: only changed attributes, rest inherited from cursor
send bgp <selector> update cursor as-path [65001 65003] \
nlri add 10.1.0.0/24
# NLRIs only (all attributes inherited)
send bgp <selector> update cursor nlri add 10.2.0.0/24
# Remove an attribute from cursor
send bgp <selector> update cursor del med nlri add 10.3.0.0/24
# Clear cursor state (call after replay completes)
send bgp <selector> update cursor done
Cursor mode supports announce-only (nlri add, mp <family> add). Withdrawals are not
supported because replay re-sends stored routes, never withdrawals.
Removed Commands (use update text instead)
The following legacy commands have been removed:
| Old Command | Replacement |
|---|---|
announce ipv4/unicast <p> next-hop <nh> |
update text next <nh> nlri add prefix <p> |
announce ipv6/unicast <p> next-hop <nh> |
update text next <nh> mp ipv6/unicast add prefix <p> |
announce eor <afi> <safi> |
update text mp <family> eor (update text nlri eor for IPv4 unicast). A bare announce eor is IPv4 unicast, as in ExaBGP. The marker goes out each time it is asked for; a replaying plugin's replay-eor marker goes out once per session (update-syntax.md, "End-of-RIB") |
announce vpls ... |
update text mp l2vpn/vpls add rd <rd> ve-id <n> ve-block-offset <n> ve-block-size <n> label-base <n> |
announce l2vpn ... |
update text mp l2vpn/evpn add ... |
withdraw ipv4/unicast <p> |
update text nlri del prefix <p> |
withdraw ipv6/unicast <p> |
update text mp ipv6/unicast del prefix <p> |
withdraw vpls ... |
update text mp l2vpn/vpls del rd <rd> ve-id <n> ve-block-offset <n> ve-block-size <n> label-base <n> |
withdraw l2vpn ... |
update text mp l2vpn/evpn del ... |
The ExaBGP bridge still reads ExaBGP's announce vpls and withdraw vpls
(docs/architecture/exabgp-bridge.md); it is ze's own API that no longer has them.
Watchdog Commands
request bgp watchdog announce <name> [med <N>] [peer] # Send all routes in pool (optional MED override)
request bgp watchdog withdraw <name> [peer] # Withdraw all routes in pool from peers
A pool holds the routes the config places under a watchdog
(watchdog { name <name>; } in a peer's update block). update text and the
wire mode read watchdog <name> and refuse the command, because no pool holds
an API route (docs/architecture/api/update-syntax.md, "Watchdog Commands").
RIB Commands
show bgp rib [filters...] [terminal] # Unified route display with pipeline
source filters: received | advertised
filters: peer <selector>, path <pattern>, prefix <pattern>, community <value>,
family <afi/safi>
path pattern: <asn>[,<asn>...] is a run anywhere in the AS path;
^ first ties the run to the start of the path, $ last ties it to the end
(65001$: originated by AS 65001; ^65010,65001$: exactly that path)
terminals: count, histogram, graph (AS topology as nodes and edges, drawn as boxes in text)
received row: age is the whole seconds since the route's stored attributes last
changed; an equal re-announcement keeps it growing. Absent when the RIB
holds no time for the route, and on advertised rows
show bgp rib best [filters...] [terminal] # Best-path per prefix (RFC 4271 §9.1.2)
best row: no age, with or without the json terminal. The RIB records when the
winning route last changed, not when it became best; the age is on
that route's received row
show bgp rib status # RIB status (peer/route counts)
clear bgp rib in <selector> # Clear Adj-RIB-In (* for all peers)
clear bgp rib out <selector> [family <family>] # Resend Adj-RIB-Out (* for all, optional family)
clear bgp rib out-excluding-owner owner <id> [family <family>] # Replay except one exact configured owner
clear bgp rib advertised <selector> [family <family>] # Withdraw Adj-RIB-Out (* for all, optional family)
request bgp rib inject <peer> <family> <prefix> [attrs] # Insert synthetic forwarding candidate (no session needed)
request bgp rib withdraw <peer> <family> <prefix> # Remove matching synthetic forwarding candidate
show bgp rib rpf <family> <source-addr> # RPF lookup (longest-prefix-match in Loc-RIB)
Generic pipes apply to the answer the command produced. The operator language has exactly one statement, pipeCatalog, and docs/features/pipe-operators.generated.md is that table published; naming the operators here again is the drift this catalog exists to end. What a given command owes is published per command by ze help command --json, derived from the shape it declares, and an operator the shape cannot support is refused by name before the command runs.
For a command the daemon serves, the DAEMON runs the chain. execMiddleware splits it off an SSH exec command and applies it. It reads the exec line as the client sent it (RawCommand), so a double-quoted value stays one word and a | inside quotes is not a pipe: system command help name "show version" names the command show version. ze cli -c sends the chain intact and prints what comes back. Only the daemon holds the configuration, so only the daemon can honor environment cli format default. A command the client serves in its own process through RegisterLocalData is the exception: ServeLocal runs the same chain over the local payload, before any daemon is contacted. | save is refused on every chain the daemon expands, because the file would be written on the daemon's filesystem with the daemon's privileges.
A chain the answer's shape cannot support is refused AFTER the command has run, and the refusal then arrives as the answer itself, marked with pipe error: . ze cli -c reads that mark on the first bytes of the stream: the refusal goes to stderr and the client exits 1, so a script that redirects stdout collects no diagnostic and reads no success.
The browser's caller-side Download action saves an already authorized,
formatted finite result on the caller's computer. It does not send a save path
to the daemon or relax this pipe refusal. Complete results are bounded at
4 MiB; an incomplete, refused or oversized result is not offered as complete.
ProcessPipesDefaultFormatResult exposes the shared formatter's actual
application error separately from its output, so a transport can preserve
completion status without interpreting diagnostic-looking result bytes.
clear bgp rib out and clear bgp rib advertised act on the same table in opposite ways. out is bgp-rib's replay: it resends what each peer was sent, configured routes included, one family at a time, and brackets each family with a BoRR before and an EoRR after (RFC 7313 Section 4, a locally initiated refresh). The engine sends the two markers only to a peer that advertised Enhanced Route Refresh; a family with nothing in the Adj-RIB-Out gets no bracket. advertised is the engine's: it withdraws every route the session's Adj-RIB-Out holds, configured routes included, and forgets the peer's configured set, so a later reload sends it again. The withdrawals take the local withdraw rail, so bgp-rib drops each route from its own copy and a later out does not bring it back. A labeled route (RFC 8277, RFC 3107) is withdrawn with the Section 2.4 Compatibility field 0x800000, rebuilt from the table key, which holds no label stack. A family whose key cannot be written back as the withdrawn NLRI is refused by name rather than guessed. A selector that matches no peer is an error.
Before clear bgp rib out starts replay, bgp-rib applies its queued events.
The replay command then uses the same plugin process and connection.
Both operations share the command deadline. A failed event, stopped owner or
changed connection refuses the replay before the command is sent.
RIB route filters such as received, advertised, peer, family, prefix, path, and community are command-specific filters registered by the RIB command and handed to its handler as declared pipe operations (ValidatedArgs.PipeOperations), which it applies in the RIB iterator before route output is generated.
Inject attributes: origin <igp|egp|incomplete>, nhop|nexthop <ip>, aspath <asn,asn,...>, localpref <n>, med <n>. Peer address is a label (valid IP, no session required). Only simple prefix families (IPv4/IPv6 unicast/multicast). IPv4-mapped IPv6 next-hops accepted.
Inter-Plugin RIB Commands (GR/LLGR)
These commands are dispatched between plugins (bgp-gr to bgp-rib) and are not intended for direct user invocation:
request bgp rib retain-routes <peer> [on-down] [family ...] # Retain all or selected families
request bgp rib release-routes <peer> # Release retained routes
request bgp rib mark-stale <peer> <restart-time> [level] # Mark routes stale (level: 1=GR, 2=LLGR)
request bgp rib purge-stale <peer> [family] # Purge stale routes (optionally per-family)
request bgp rib attach-community <peer> <family> <hex> # Attach community to stale routes in family
request bgp rib delete-with-community <peer> <family> <hex> # Delete routes carrying community in family
retain-routes without on-down withdraws advertisements for families removed
by an explicit family list, even while the source remains established. GR uses
on-down during its actual session-DOWN transaction: RIB silently prunes the
nonretained sent families and the forwarding DOWN owner sends their withdrawals.
This explicit handoff does not infer lifecycle ownership from peer state.
Named Commits (Batching)
A named commit holds withdrawals and flushes them to every peer the selector
matches. There is no group start or group end: this page published that pair
until 2026-09-05 and no handler ever answered either spelling. An ExaBGP script's
group start and group end are the ExaBGP bridge's, which applies the block
through ordinary update commands (docs/architecture/exabgp-bridge.md, "A group
is applied at its end").
request commit start <name> # Open a named commit
request commit withdraw <name> route <prefix> # Queue one withdrawal
request commit show <name> # What the commit holds
request commit end <name> # Flush it
request commit eor <name> # Flush it, then End-of-RIB
request commit rollback <name> # Discard the queue
A named commit cannot carry an ANNOUNCEMENT. (*Transaction).QueueAnnounce has
no non-test caller, so nothing queues one, and send bgp <selector> update ...
announces immediately whether a commit is open or not
(plan/journal/unwired-feature.md, 2026-09-05).
end and eor answer what each peer took:
| Key | What it states |
|---|---|
routes-queued, withdrawals-queued |
What the commit HELD, offered to each matched peer |
routes-announced, routes-withdrawn, updates-sent, eor-sent |
What LEFT, summed over the peer rows |
eor-requested |
The operator asked for an End-of-RIB, which is a different fact from one being sent |
peers |
One row per matched peer, keyed by address, carrying name, state, that peer's four counters, and reasons |
A reasons entry appears exactly when that peer took less than the commit
offered it, and the vocabulary is closed: not-established, announce-refused,
routes-dropped, withdraw-refused, send-failed, eor-refused. Any such peer
makes the command answer error, and the error sentence names each one, because
an error answer's payload is dropped in transit and the sentence is all a plugin
receives. This rail drops the work for a peer with no established session rather
than queueing it, so undelivered means dropped and done would be untrue.
Action-First Syntax (Legacy)
Show Commands
show neighbor [summary|extensive|configuration]
show adj-rib in [<afi> <safi>]
show adj-rib out [<afi> <safi>]
Announce/Withdraw
All route operations now use update text syntax:
update text next <ip> [attributes...] nlri add prefix <prefix>
update text next <ip> [attributes...] mp <family> add prefix <prefix>
update text nlri del prefix <prefix>
update text mp <family> del prefix <prefix>
update text nlri eor
update text mp <family> eor
Note: Legacy
announce/withdrawcommands have been removed. See "Removed Commands" section above for migration table.
Control
teardown <peer-ip> <code> [<reason>]
shutdown
reload
restart
reset
enable-ack
disable-ack
silence-ack
help
version
API Content Configuration (Ze)
Attribute Filtering
ContentConfig.Attributes limits which path attributes are parsed for API
output. It is set by the engine, not by a peer's attach block: the
content { encoding format attribute } container inside attach process
parses and reaches no field of ProcessBinding, so a peer cannot ask for one
rendering while another peer asks for a different one.
Available attribute names:
| Name | Code | Description |
|---|---|---|
origin |
1 | ORIGIN |
as-path |
2 | AS_PATH |
next-hop |
3 | NEXT_HOP |
med |
4 | MULTI_EXIT_DISC |
local-pref |
5 | LOCAL_PREF |
atomic-aggregate |
6 | ATOMIC_AGGREGATE |
aggregator |
7 | AGGREGATOR |
community |
8 | COMMUNITIES |
originator-id |
9 | ORIGINATOR_ID |
cluster-list |
10 | CLUSTER_LIST |
extended-community |
16 | EXTENDED_COMMUNITIES |
large-community |
32 | LARGE_COMMUNITIES |
all |
- | All attributes (default) |
Benefits of partial parsing:
- Reduced CPU (only parse what's needed for routing decision)
- Reduced memory (don't store full parsed attributes)
- Wire bytes preserved for zero-copy forwarding
NLRI Family Filtering
ContentConfig.NLRI limits which address families are included in API output.
Like the attribute filter, it is engine-set: no config leaf reaches it.
Available families:
| Config Syntax | Canonical Name |
|---|---|
ipv4/unicast |
ipv4/unicast |
ipv6/unicast |
ipv6/unicast |
ipv4/multicast |
ipv4/multicast |
ipv6/multicast |
ipv6/multicast |
ipv4 mpls |
ipv4 mpls |
ipv6 mpls |
ipv6 mpls |
ipv4/mpls-vpn |
ipv4/mpls-vpn |
ipv6/mpls-vpn |
ipv6/mpls-vpn |
ipv4/flowspec |
ipv4/flowspec |
ipv6/flowspec |
ipv6/flowspec |
l2vpn/evpn |
l2vpn/evpn |
l2vpn/vpls |
l2vpn/vpls |
Special values: all (default), none
Route Attributes
Attributes are flat keyword-value pairs (no set keyword). Both short and long forms accepted.
API text output uses short forms; config output uses long forms.
next <ip> # Next-hop IP (required), long form: next-hop
origin igp|egp|incomplete # Origin attribute
path <asn>,<asn>,... # AS path, long form: as-path
pref <int> # Local preference, long form: local-preference
med <int> # Multi-exit discriminator
s-com <comm>,<comm>,... # Standard communities, long form: community
x-com <ext>,<ext>,... # Extended communities, long form: extended-community
l-com <lc>,<lc>,... # Large communities, long form: large-community
originator-id <ip> # Originator ID
cluster-list <ip>,<ip>,... # Cluster list
label <label> # MPLS label (per-NLRI-section modifier)
rd <rd> # Route distinguisher (per-NLRI-section modifier)
info <id> # ADD-PATH path ID, decimal or dotted a.b.c.d (per-NLRI-section modifier), long form: path-information
atomic-aggregate # Atomic aggregate flag
aggregator <asn> <ip> # Aggregator
aigp <value> # AIGP
split /<len> # Ze: prefix expansion (see below)
Keyword Aliases
| Long (config) | Short (API) | Also accepts |
|---|---|---|
next-hop |
next |
nhop (legacy) |
local-preference |
pref |
— |
as-path |
path |
— |
community |
s-com |
short-community |
large-community |
l-com |
— |
extended-community |
x-com |
e-com |
path-information |
info |
— |
route-distinguisher |
rd |
— |
Lists use commas (no spaces): path 65001,65002. Brackets accepted for transition: as-path [65001 65002].
Split Keyword (Ze Extension)
The split keyword expands a prefix into smaller prefixes. All attributes apply to each generated prefix.
Syntax
split /<target-length>
Example
# Announce 2 prefixes with one command
update text next 1.2.3.4 nlri add prefix 10.0.0.0/23 split /24
# → 10.0.0.0/24 next-hop 1.2.3.4
# → 10.0.1.0/24 next-hop 1.2.3.4
# With MPLS label - label applies to each prefix
update text next 1.2.3.4 mp ipv4/nlri-mpls label 100 add prefix 10.0.0.0/22 split /24
# → 10.0.0.0/24 label 100
# → 10.0.1.0/24 label 100
# → 10.0.2.0/24 label 100
# → 10.0.3.0/24 label 100
# With L3VPN - RD and label apply to each prefix
update text next 1.2.3.4 mp ipv4/mpls-vpn rd 100:1 label 200 add prefix 10.0.0.0/23 split /24
# → 10.0.0.0/24 rd 100:1 label 200
# → 10.0.1.0/24 rd 100:1 label 200
Supported Families
| Family | Split Support | Notes |
|---|---|---|
| IPv4/IPv6 unicast | ✅ | Standard prefix expansion |
| IPv4/IPv6 nlri-mpls | ✅ | Label copied to each prefix |
| IPv4/IPv6 mpls-vpn | ✅ | RD + label copied to each prefix |
| FlowSpec | ❌ | N/A - uses match rules, not prefixes |
| VPLS/EVPN | ❌ | Different NLRI structure |
Constraints
- Target length must be longer than source prefix (e.g., /23 → /24, not /24 → /23)
- Maximum expansion: implementation-dependent (avoid /8 → /32)
FlowSpec Commands
FlowSpec rules use the unified update text syntax. The match components are
the FlowSpec NLRI (mp ipv4/flow add <components>); the action is carried as
a FlowSpec extended community declared with the extended-community attribute
before the mp section (discard is sugar for traffic-rate 0).
# Match TCP traffic to 10.0.0.0/8 port 80 and drop it
update text extended-community discard \
mp ipv4/flow add \
destination 10.0.0.0/8 \
protocol tcp \
destination-port =80
# Withdraw the same FlowSpec rule (match components identify it)
update text mp ipv4/flow del \
destination 10.0.0.0/8 \
protocol tcp \
destination-port =80
Match Components
| Keyword | Description |
|---|---|
| destination | Destination prefix |
| source | Source prefix |
| destination-port | Destination port |
| source-port | Source port |
| port | Any port |
| protocol | IP protocol |
| next-header | IPv6 next header |
| tcp-flags | TCP flags |
| icmp-type | ICMP type |
| icmp-code | ICMP code |
| fragment | Fragment flags |
| dscp | DSCP value |
| traffic-class | DSCP value, under the ExaBGP spelling |
| packet-length | Packet length |
| flow-label | IPv6 flow label |
Actions (then)
| Keyword | Description |
|---|---|
| accept | Accept traffic |
| discard | Drop traffic |
| rate-limit |
Rate limit |
| redirect | Redirect to VRF |
| redirect-next-hop | Redirect to next-hop |
| mark |
Set DSCP |
| community [...] | Add community |
Filter Callbacks
The engine sends filter-update callbacks to external plugin filters during
UPDATE processing. This is a callback RPC (engine to plugin), not a user command.
One exchange carries a batch: the request is {"routes":[...]}
(rpc.FilterUpdateBatchInput), at most rpc.FilterUpdateBatchMax (64) routes
in the order the engine queued them, and the answer is {"verdicts":[...]}
(rpc.FilterUpdateBatchOutput), one verdict per route in request order, all
within one rpc.FilterUpdateTimeout (5 s). A reply with more or fewer verdicts
than routes is malformed: the engine applies none of it, and every route of the
batch takes its filter's on-error. A plugin running internal that registered
with sdk.OnFilter is called through its typed filter slot instead, with the
same verdict and no JSON (PluginConn.CallFilter).
Each route of routes:
| Field | Type | Description |
|---|---|---|
filter |
string | Filter name (declared at stage 1, dispatches to the right handler) |
direction |
string | import or export |
peer |
string | The peer that SENT the route on import, the DESTINATION peer on export |
peer-as |
uint32 | That peer's ASN, with the same meaning as peer |
fields |
object | The route fields the filter declared in reads, keyed by vocabulary field name, in the UPDATE event's attr-map shape. A field the route does not carry is left out, and the key is absent when the filter declared no route field |
raw |
bytes (base64) | The UPDATE body after the 19-byte header, sent when the filter declared the raw read |
Each verdict of verdicts:
| Field | Type | Description |
|---|---|---|
action |
string | accept, reject or modify |
sets |
list | The route fields the filter changes, on modify: each a field, an action and a value |
raw |
bytes (base64) | A whole-body replacement, on modify, from a filter that declared the raw read. It ends the chain |
teardown, notify-code, notify-subcode |
bool, uint8 | Close the session after the import chain. Honored on import only |
error |
string | The filter could not judge this route: the engine applies its on-error to this route alone and reads nothing else of the verdict |
peer and peer-as change meaning with the direction, and the callback says
so only through direction. The import chain passes the sending peer
(runIngressPolicyChainMeta) and the export chain passes the destination
(runEgressPolicyChainASN4), both through the library chain's external
member (runLibraryChain). A filter that
reads the ASN as "who sent me this" is wrong on export, where nothing in the
callback names the sender at all.
A filter's declared Direction does not gate dispatch. FilterDecl.Direction
is carried to plugin.FilterRegistration.Direction and read by nothing in the
engine, so a filter is called on whichever chain the operator's config names it
in. Direction lives on the config attachment point, and a filter that must act on
one direction only tests direction itself.
Response Format
Success (with serial prefix)
{"type":"response","response":{"serial":"1","status":"done"}}
Error
{"type":"response","response":{"serial":"1","status":"error","data":"description"}}
Rejected rows: errors and data
A handler can answer with a row generator rather than a built payload. It can reject a row while the walk continues. A consumer that reads the whole answer as one string sees the rejected rows under a SIBLING key. A partial result therefore renders, instead of collapsing into one error string.
| Answer | Rendering |
|---|---|
| rows, no rejected row | {"peers":[...]}, or a bare [...] when the handler names no envelope. Unchanged |
| rows and rejected rows | {"peers":[...],"errors":[...]} |
| rejected rows, no envelope key | {"data":[...],"errors":[...]} |
the handler names its envelope errors |
refused, on this path and on the record path |
errors appears only when a row was rejected. An ordinary answer keeps the shape
it had, and no consumer meets a key it has not seen. data is where the rows go
when the handler names no envelope and a row was rejected. A bare array has
nowhere to carry a sibling.
| count counts the rows the command produced and never the rejected ones, so
the two collections stay separately countable. A commit that applied 97 leaves
and rejected 3 renders both, rather than the 97 being lost with the error.
Two kinds of handler answer with a generator. system command list is the
engine's, and a plugin command handler is the SDK's. Every other command returns
a built payload, and none of these keys appears for it.
A plugin command answers with records
execute-command is the callback the engine sends for a command a plugin
registered. Every plugin answers it with a head, its records and a terminator,
and the engine reads that sequence for every plugin.
The handler decides what it produces, and the wire decides how it travels.
| The handler returns | On the wire | What routeToProcess builds |
|---|---|---|
| a built value | the doc item type and one record carrying that value |
plugin.RawJSON, unchanged |
a plugin.Records walk of 256 rows or fewer |
the doc item type and one record carrying the collapsed document |
plugin.RawJSON over that document |
a plugin.Records walk of more than 256 rows, declaring no columns |
the map item type and one record for each row |
plugin.Records over the arriving rows |
a plugin.Records walk of more than 256 rows, declaring its columns |
the tab item type, the names on the head, and one positional record for each row |
plugin.Records over the arriving rows, carrying the head's names |
The dispatcher branches on the head's item type and never on what the handler returned. A bounded walk is therefore the document it has always been, and only a walk that streams reaches an operator as records.
A tab answer reaches the operator as the same objects a map answer would
have carried. The engine forwards the head's column names beside the rows, and
the rendering zips each positional row against them. A command that declares a
schema and one that does not therefore answer one document for the same data.
The value a built payload carries is unchanged, byte for byte. Only the frame
around it changed, and it changed for every peer. No declaration selects the
frame: CommandDecl.Shape states what the ANSWER holds, for the pipe layer to
publish and to refuse against, and the walk length alone decides which frame
carries it. So there is one frame and every reader knows it before the first
line.
The rows are pulled as the operator's rendering writes them, so the engine never
holds the whole collection for a walk that streams. A row wider than one wire
message is rejected and the walk continues. That row reaches the operator under
errors, beside the rows that were applied.
Show Neighbor
{
"neighbor": {
"address": "192.168.1.2",
"local-address": "192.168.1.1",
"local-as": 65001,
"peer-as": 65002,
"router-id": "1.1.1.1",
"state": "established"
}
}
Show Adj-RIB
{
"routes": [
{
"nlri": "10.0.0.0/8",
"next-hop": "192.168.1.2",
"origin": "igp",
"as-path": [65002]
}
]
}
Command Dispatch
Command Tree Structure
Note: This tree shows the internal noun-first dispatch structure, not the user-facing grammar. User-facing commands are verb-first (
show/request/clear/update/monitorroots, e.g.show bgp peer <sel> detail,send bgp <sel> cached <id>,clear bgp rib in); the noun-first RPCs below remain only for internal dispatch. Nodes such aspeer/<selector>/announceandpeer/<selector>/withdrawreflect removed verbs (see "Removed Commands").
daemon
├── shutdown
├── reload
├── restart
└── status
plugin
└── session
├── ready
├── ping
└── bye
bgp
├── help
├── command
│ ├── list
│ ├── help
│ └── complete
├── event
│ └── list
├── log
│ ├── levels # Show subsystem log levels
│ └── set # Set subsystem log level at runtime
├── metrics
│ ├── values # Show Prometheus metrics (text format)
│ ├── list # List metric names
│ └── pool # Per-attribute pool occupancy and dedup rates
└── plugin
├── encoding
├── format
└── ack
peer
├── list
├── detail
├── capabilities
├── statistics
└── <selector>
├── detail
├── capabilities
├── statistics
├── teardown
├── announce
├── withdraw
└── group
rib
├── routes [| sent|advertised|received|sent-received] [| filter ...] [| count|first|last|histogram|graph]
├── best [| filter ...] [| count|first|last|histogram|graph|reason]
├── status
├── clear [in|out]
├── inject <peer> <family> <prefix> [attrs...]
└── withdraw <peer> <family> <prefix>
group
├── start
└── end
monitor
├── bgp # Live peer dashboard (TUI)
└── event # Stream live events (keeps session open)
Ze Implementation Notes
Command Dispatcher
type Handler func(ctx *Context, peers []string, remaining string) error
type DispatchTree map[string]interface{} // Handler or nested DispatchTree
func Dispatch(tree DispatchTree, tokens *Tokenizer, reactor *Reactor) (Handler, []string) {
// Walk tree consuming tokens
// Return handler and matched peers
}
The dispatcher takes the line with its pipe chain
Dispatch accepts a line with a pipe chain from every caller. It reads the
line once (command.ReadDispatchLine): the command part and the chain under
the one grammar, the chain's aliases expanded, and the chain partitioned for
the command (partitionPipeChain). An unfinished quote anywhere on the line is
refused with its column before anything resolves.
| Step | What Dispatch does with a piped line |
|---|---|
| Accounting | starts on the line as typed, chain included, masked by config.DisplayCommand; a typed accountant receives its tokens: the command's words, then a | token, the name and the argument words of each operation |
| Arguments | a word the command declares as a pipe operation is refused as an argument, with the pipe form of the line as the fix (command.RefusePipeOperationWords), before ValidateArgs binds anything |
| Authorization | a string authorizer receives the typed line; a typed one the command, its arguments, then the chain tokens, for authorization only. Read-only is the command path's flag, and a chain never changes it |
| Handler | receives the operations the command declares, in the order typed, in CommandContext.PipeOperations and ValidatedArgs.PipeOperations, and never as arguments. An override's answer is held to its generic's shape (command.CheckOverrideAnswer). An answer the handler delivers as a generator of rows is judged without being read: it is rows, which a count override never answers, and its rows are not counted |
| Answer | the residual chain runs over the answer through ApplyPipes, for every caller that does not render the chain itself. A format that prints text (table, text, yaml, ndjson) answers that text, carried as a JSON string: what ze cli -c prints for the line. json and raw answer the JSON document they print |
A caller inside the daemon that renders the chain itself states it with
plugin.CallerIdentity.RendersResidualChain; the dispatcher then answers the
handler's data and leaves the residual chain to it. The statement is false
unless a surface sets it, so a plugin's dispatch-command, MCP ze_execute,
REST execute and gRPC get the chain applied. For them the residual chain is
validated before anything resolves, on the one-shot surface: | save is
refused, because the daemon never writes a caller's file.
A plugin process receives the declared list in the request itself:
routeToProcess writes it into the pipe list of rpc.ExecuteCommandInput,
beside the arguments and never inside them, over the forked TLS connection
and over DirectBridge alike, and the SDK hands it to the OnExecuteCommand
handler as its pipe parameter. A subsystem's command receives the same list
in its request (SubsystemHandler.Handle).
The rendering surfaces send the line as typed. The SSH exec channel, the
interactive model (cli.Model, on SSH, in the web CLI's views and in ze start --cli), the web CLI terminal and the web tool pages dispatch the whole line
with RendersResidualChain set, and build their formatter from the same
partition with ProcessPipesDefaultFormatChecked (or its Local or Result
form), which applies only the residual chain. A zessh.CommandExecutor and a
cli.CommandExecutor are called only by such a renderer, so the daemon's
factories for them set the statement.
A renderer in another process holds no CallerIdentity. The editor's model
over SSH (ze config edit) and the functional-test engine steps (a plugin's
dispatch-command) therefore send DispatchLine.DeclaredLine: the command
part and only the operations the command declares, then | raw, so the
daemon runs the declared operations in the handler and answers the handler's
JSON with no pipe metadata, and the sender applies the residual chain once.
ze cli -c sends the typed line over SSH exec, where the exec channel renders
it.
No reader splits a piped line on its own. A caller that only asks which
command a line names, or whether a chain follows it (the model's monitor ping and monitor traceroute detectors, the subject an explanation is about,
the engine steps' choice of route), reads it with command.ReadCommandPart,
under the one grammar, so a quoted | stays part of a word. Every reader that
applies a chain goes through the partition. TestEveryPipeSplitGoesThroughThePartition
judges both: in the command package, a function that reads a chain must also
partition it, unless it holds no command (ze pipe, an alias expansion, the
accounting tokens, a client's presentation suffix); in every file that imports
the package, a strings call that cuts at a pipe literal, or a call of
ParsePipe, fails it. Its twin in plugin/server judges the streaming-handler
lookups.
A REST or gRPC request's structured parameters are written into the command
part, before the first pipe outside quotes, so they reach the handler as
arguments and the chain stays the one the caller typed (buildInvocation).
WriteInvocation quotes a value holding a pipe or a double quote, so a
parameter never opens an operation.
Every route that takes structured parameters also takes one optional, ordered
pipe list: a derived MCP tool, REST POST /api/v1/execute and gRPC
Execute and Stream. Each element is an operation name and its argument
words ({"name": "match", "args": ["established"]}). The adapter judges each
name against the command's pipe-operations (PipeOperationsForCommand, the
list show command help answers) and refuses any other name, naming the
valid ones, before anything runs. It then writes the list after the
parameters, and after any chain the caller typed in the line, one
| name args stage per element, in order; each argument word goes through
WriteInvocationValue, so a word holding a pipe or a quote stays one word and
opens no stage. The dispatcher partitions the result as it partitions a typed
line, so the list answers what <command> | name args answers, and the order
is the chain's: a declared operation after a generic one is refused as it is
when typed. The list's JSON Schema is declared once (PipeListSchema) and the
MCP tool schema and the OpenAPI document both publish it; its JSON form is
read strictly (DecodePipeList), so a misspelt element key is refused rather
than dropped.
A pipe inside double quotes is an argument value. ScanInvocation is shared by
the dispatcher and the pipeline boundary, so neither mistakes that value for
an operator. Inside double quotes, \", \\, \n, \r and \t preserve a
literal quote, backslash, newline, carriage return and tab. In the command
part, a backslash outside quotes, or an unknown quoted escape, is refused; the
chain after the first unquoted pipe keeps a backslash outside quotes (below).
WriteInvocationValue writes
this same grammar for client values and concrete enum corrections.
An empty value is written as "" and retained as one empty token. Spaces
inside a quoted value remain part of that value, including its trailing spaces.
The local-data route decodes these words before registry lookup and model
validation, preserving the same quoted values as daemon dispatch.
Execution requires the closing quote. ScanExecution refuses an unfinished
value before any handler runs, in the command part or in the chain, and names
the opening quote's one-based character column in the original line. The
refusal does not echo the value, which may contain a credential. Local command
execution and one-shot or streaming pipeline preparation use that same strict
reader before source work or file creation.
Completion keeps using the permissive ScanInvocation reader while the
operator types an unfinished value. Both readers use one scanner, retaining
source offsets beside decoded tokens; completion does not need a second escape
grammar, and execution does not infer a column from stripped tokens.
Accounting and authorization read the same tokens as for any other line.
dispatch-command-args never reaches the tokenizer, so a pipe in its args
is data.
The pipe chain takes the invocation's quote grammar
The chain after the first unquoted pipe is read under the quote grammar of the
command part, so a quoted value is one argument everywhere on the line
(owner decision, 2026-11-20). The chain has no grammar of its own: ScanExecution,
ParsePipe, the alias registry and ze pipe all read it through scanChain.
| Rule | The chain reads it |
|---|---|
| Where an operation ends | at a pipe outside double quotes, joined to a word or not |
| Words of one operation | split at whitespace outside double quotes; a quoted run is one word, its quotes removed |
| Escapes inside quotes | the invocation's own: \", \\, \n, \r, \t; any other is refused |
| A backslash outside quotes | a literal character, because match patterns and paths rely on it. The one difference from the command part, which refuses it |
A backslash before a quote, outside quotes (match a\"b c") |
✕ |
A quote inside a word (match ab"c d"e) |
the run belongs to that word: abc de |
| A single quote | a literal character; only the double quote groups |
| An unfinished quote | refused with the column of its opening quote, as in the command part |
| An operation's argument | the decoded words; a generic operator that takes text reads them joined by one space |
An alias expansion, and the operators of ze pipe |
read by the same grammar; an unfinished quote in an expansion refuses the alias when it is registered |
show log recent | match "error|warn" therefore hands match the ten
characters error|warn as one argument. match is a case-insensitive
substring, so this is no alternation. A pattern that holds a literal double
quote writes it escaped inside quotes: | match "\"value\":\"x\"".
A command's own operation keeps the words the chain decoded: the partition
hands them to the handler in its declared list, never rewritten into the
command line, so | path "a|b" reaches it as the one argument word a|b,
never re-split.
MCP ze_execute and run, REST execute and gRPC Execute send the whole line
as data callers: the dispatcher applies the residual chain and answers its
result in their envelope.
YANG-Typed Command Arguments
Operational commands declare their argument types as YANG leaves inside
ze:command containers. The same leaf metadata drives two consumers:
- Completer (
command/completer.go): enum values become tab-completion suggestions; keyword leaf names appear as completable tokens. - Dispatcher (
plugin/server/command.go): validates args against ArgDefs between tokenize and handler call (two-phase: keyword extraction, then positional matching).
Every route validates
command.ValidateArgs answers a command.ValidatedArgs: a copy of the tokens
it judged and the leaf a lone spare positional token filled. Its fields are
private, so only a successful call builds a non-zero value; the zero value means
no tokens and no binding. Tokens answers a copy, so neither the route nor the
handler can change what was judged. A call that leaves a mandatory leaf unfilled
is refused with a *command.ArgumentFaults containing one
*command.MissingArgumentError for each leaf it left unfilled, even when only
one is missing. Its problem names the missing leaf, its explanation carries
the leaf's declared description (or its help summary when no description is
present), and its fix is the complete corrected command. A definition with
neither text explicitly reports that the model makes the argument mandatory
without supplying further explanation; Ze does not infer a purpose from its name.
Each missing cause still reports the lone
binding, because the dispatcher adopts a positional selector before it reports
the missing leaves. The in-process routes (R2, R3, R6, R7) write the refusal to
stderr, and a missing leaf is followed, once, by hint: run '<command> help' to see the arguments it takes, because the refusal names only the leaves the line
left out and the help page names every argument (ze prefixes the command on
the ze <verb> routes, and ze cli -c takes it bare).
The validator reads the whole line before it refuses it, and names every fault
the line holds: a keyword with no value, a value its leaf refuses, a keyword
typed twice, a token no definition takes, and each missing mandatory leaf,
in declaration order. A leaf whose keyword or value is already at fault is not
also named missing. A line with one fault is refused with that fault alone,
except a value its leaf refuses or a missing mandatory argument, which is a
*command.ArgumentFaults of one so every route restates it. A line with more is refused with a
*command.ArgumentFaults, an operator error whose problem line counts the
faults, whose next lines name each fault in the order typed, and whose last line
is the fix. A refusal of one value fault is that fault, with no count: its
problem, its why, then the fix. Its Unwrap answers the operator
error and each fault, so errors.As finds a *command.MissingArgumentError
inside it as it does on its own. In the list a missing leaf also names the
words that supply it, written by the usage line's own value form
(required argument missing: asn, as in 'asn <asn>'); the cause's own explanation
and fix are kept out of that list entry, so only the refusal's last line is a
fix. A lone missing cause supplies its explanation and complete correction
without a count of faults. A refused value (*command.ValueArgumentError) reads as the config value
refusal does: the command path and the argument, the quoted value and its kind
(is not an accepted value, with (did you mean X?) when one value is close,
is outside the accepted range, is outside the accepted length (N characters), is not in the accepted format), then its why: every accepted
value on a line of its own with its ze:help, in the model's order, through the
same renderer as the config refusal (suggest.ValueLines), the enum members of
a union then its other member types named, the declared bounds, the format in
words from the nearest typedef (never the regular expression), or the
error-message the restriction declares. In a list it is its problem with its
why indented under it, and never a fix line of its own. A number that is not a
number keeps its type refusal (invalid value "x", expected unsigned integer).
The dispatcher asks for an *command.ArgumentFaults first. A list that
holds only missing arguments binds a positional selector as a lone missing
argument does, because each of them carries the same binding; a list with any
other fault binds none. A sole missing selector keeps that same typed refusal
and the selector's declared purpose, with the corrected command placing it
where the dispatcher reads it; its problem line names the command
(request peer teardown requires a selector), because the dispatcher restates
the fault (selectorMissing) and a refusal of one fault reads as that fault's
own Problem and Why (command.StatedFault), never as the cause it wraps.
Several unbound positional words still receive the selector guard's
explanation that no value could be chosen as the selector, as an operator
error with the same problem line and the keyword form as its fix.
That guard reads the validator's captured unplaced positional values, or the
successful validation's positional tokens; named keyword/value pairs do not
become ambiguous values merely because they occupy two words. The missing
cause owns that captured evidence and returns a copy to its caller.
Every route then restates the list through one function,
ArgumentFaults.RestatedForLine, so the same line reads the same on all of
them: when every fault is a missing argument or a value typed in the line,
and none was left unlisted, the fix line is the whole command, the operator's
own tokens with each refused value replaced by its correction (the close
value, the one accepted value, or the placeholder: <hex|b64>, <1..4094>,
<1..4 characters>, <value>), each missing leaf by its keyword, written
before the words of a rest-of-line leaf the line typed (send bgp 192.0.2.1 raw gzip DEADBEEF answers fix: send bgp 192.0.2.1 raw <hex|b64> DEADBEEF); any
other list keeps each fault's line and the general fix. A value fault names the
command path before its argument (send bgp raw encoding: "gzip" is not an accepted value).
A value is never quoted when its argument is a credential keyword
(redact.IsCredentialKeyword: the password family, plaintext-* and
content): the problem and the fix quote <redacted> in its place
(newValueFault), and the whole-command fix writes <redacted> for a valid
value typed after such a keyword (wholeCommand), as the recorded command line
holds it.
The shared validator refuses the exact <redacted> placeholder for these
credential arguments before dispatch, using the same value-fault path and a
correction that asks for the real value. A noncredential argument may contain
that literal text.
Concrete corrections retain their literal identity separately from placeholders:
an accepted enum named a|b is written as "a|b", while <hex|b64> remains
syntax the operator replaces. The same writer preserves every already accepted
operand in the corrected line, including quoted pipes and spaces.
The routes differ only in the head of that line. The dispatcher writes the
path with the selector where it reads it, and names a missing selector by the
guard's own refusal, with the line that supplies it (fix: create bgp peer <selector> asn <asn>). Every route that judges through the model
(command.ValidateModelArgs: the plugin process route R9, a subsystem, the RPC
wrapper R4, SSH streaming R8 and the local-data route) writes the path, then
each value it bound out of band by its keyword (selector 192.0.2.7); the
ze <verb> routes prefix ze. A refusal keeps at most 16 faults and says how
many more it did not list.
Every route that invokes a handler calls the validator, including for a path
whose model declares no definition: that call passes the tokens through
unchanged. Each route then invokes the handler only with the tokens of the
value it got. A route that holds no definitions of its own judges against the
model through command.ValidateModelArgs. The daemon builds those definitions once
at startup and seeds them (yang.SeedCommandArgDefs in NewServer), so the
first plugin command is not held up while the model loads a second time; a
process that seeds nothing loads the model on its first call.
| Route | Where | Definitions |
|---|---|---|
| R1 daemon dispatcher | Dispatcher.Dispatch |
the matched command's ArgDefs, inline selectors pre-matched |
R2 in-process local data (ze cli -c) |
command.ServeLocal |
the model, by path |
R3 the plain handler RegisterLocalData builds |
the R6 and R7 routes that run it | the model, through command.InvokeLocal |
| R4 RPC wrapper | Server.wrapHandler |
the model, the params' selector pre-matched |
| R5 ensure-exists steps | wrapWithEnsureChain |
the ancestor node's ArgDefs, the dispatcher's selectors pre-matched |
R6 ze <verb> local handlers |
cmd/ze dispatch (invokeRootLocalHandler, dispatchHelp), cmdutil.invokeLocalHandler |
the model, through command.InvokeLocal |
| R7 offline fallback | client.runOfflineFallback |
the model, through command.InvokeLocal |
R8 streaming (monitor ...) |
GetStreamingHandlerForCommand |
the model, by the streaming prefix |
| R9 plugin process and forked subsystem | Dispatcher.routeToProcess, Dispatcher.dispatchSubsystem |
the model, by the plugin's command, the dispatcher's selectors pre-matched |
The model is the one compiled into the daemon, so an external plugin's command
is judged only at a path that model declares. Every shipped plugin command that
declares an argument is also served by a builtin, which judges first (R1);
test/ui/cli-argument-refused-plugin-route.ci reaches R9 alone through a test
plugin serving show config cat, which no daemon builtin serves.
R9 judges the forwarded tokens with the selectors the context carries, so a
builtin proxy that puts the selector back into its tokens hands off a context
with none bound. The clear bgp rib in and out forwarders do this: the
bgp-rib plugin reads <selector> [<family>] positionally, the form the GR
plugin sends on the args route, and with the selector also pre-matched R9
would judge the positional one as the family.
R6 and R7 run their handler through command.InvokeLocal(path, handler, args),
which judges the tokens with ValidateModelArgs and runs the handler on the
value it returned; a process that registered no definition source refuses both.
Every handler type takes the command.ValidatedArgs itself: a daemon handler
(pluginserver.Handler, which is also the type of an ensure-exists step's
creation and rollback handlers), a streaming handler
(pluginserver.StreamingHandler), a data handler (command.LocalDataHandler)
and a local handler or offline fallback (command.LocalHandler). No route can
declare or invoke one with a token slice: R1 hands a daemon handler the value
Dispatch judged, R4 the value wrapHandler judged, R5 hands an ensure step
and its rollback the value judged against the ancestor's definitions, R8 hands
a streaming handler the value GetStreamingHandlerForCommand answered, R2
hands a data handler the value it judged, R6 and R7 hand a local handler, and
through it the plain form of a data handler (R3), the value InvokeLocal
judged, and the handler reads Tokens(), Positional(leaf) or Value(leaf).
Positional answers only a leaf the lone spare token filled; Value also
answers a leaf typed after its own keyword (peer name site-b) or bound by the
token matcher, so a handler reading a leaf by name accepts both spellings the
grammar allows. A handler that
passes part of its tokens on (the update command hands the words after the
encoding to that encoding's parser) passes a token slice to a helper that is
not a handler type. A test that calls a handler directly builds its value with
commandtest.Args, which goes through ValidateArgs with no definitions, so
the tokens it is given come back unjudged. Product code calling it would be a
bypass, and the ruleguard rule commandtestInTestsOnly refuses a call to
commandtest.Args or commandtest.Must outside a _test.go file.
A type empty leaf is a flag (ArgFlag): the keyword alone is the argument,
in any position, and no value follows it. ValidateArgs consumes it in
the keyword phase, and it is never an open definition, so a bare force never
fills a value leaf beside it (request data backup path <abs> force once
answered invalid value "force", expected unsigned integer against spare).
Usage renders it [force], the completer offers the keyword, and help and the
catalog name its kind flag.
A leaf that carries ze:keyword-only is given by its keyword and never by
position. Without it ValidateArgs offers every word no keyword introduced to
each leaf still waiting for a value, so a payload leaf could take a word typed
for something else: update data key <key> <word> wrote the word as the key's
content when it happened to be base64, and a command with a file leaf and an
optional content would judge the second file of file a b as the content.
The keyword phase binds and judges the leaf as it does any other. No later step
reads it: positionalDef skips it, the count of open definitions that decides
whether a spare word is blamed on a leaf leaves it out (awaitsPositional),
and the dispatcher's inline-selector guess never picks it
(implicitSelectorDef). A spare word beside it therefore goes where it went
before the leaf existed: to another open leaf, or to the handler. A mandatory
one left out is reported missing with its keyword form (required argument missing: content, fix content <content>). Usage writes the keyword in front
of the value whether the leaf is mandatory (update data key <key> content <content>) or not ([content <content>]), and the completer offers the
keyword and never a bare value. Declare it on a leaf the command itself
declares, whose name repeats no keyword of the command's path.
A string leaf that carries ze:rest-of-line takes every word left on the line,
joined by one space, and no word it takes is read as a keyword. Without it the
keyword phase reads every word that names a leaf as that leaf's keyword, so
request peer <sel> notify 6 2 the code is wrong was refused with invalid value "is" against code. ValidateArgs places the leaf before the keyword
phase (restStart): it starts at its own keyword (text the code is wrong, the
form command.WriteInvocation writes for MCP and the web form), or at the
first word typed once every mandatory leaf is filled, and the phases see only
the tokens in front of it. ValidatedArgs.Keyed answers it, as it answers
every value typed after its keyword, and ValidatedArgs.PositionalTokens
answers the tokens no keyword consumed and the leaf did not take, in the order
typed, for a command whose leaves have a fixed order (notify <code> <subcode>). At most one leaf of a command carries the extension, only a string
leaf, and it is declared last, because WriteInvocation writes arguments in
declaration order and every word after the leaf's keyword is the leaf's.
ValidateArgs refuses the other shapes with ErrArgDef.
A command carries more grammar than its ArgDefs hold. A modifier group states a
keyword and a value the HANDLER parses, so the dispatcher meets tokens that
belong to no definition of its own, and it MUST NOT read one of them as a bad
value. ValidateArgs counts the tokens it could not place against the
definitions still open. As many tokens as open definitions, or fewer: each token
can be attributed to a definition, so the first one is refused by that
definition's own refusal (show route lookup ip: "not-an-ip" is not in the accepted format). More tokens than open definitions: at least one token is a value for
nothing, so a missing mandatory argument is reported instead
(show policy test peer test-peer update <hex> answers required argument missing: direction, and not a complaint about the update keyword the handler
reads).
A ze:modifier "one-of" container declares no leaf of its own: it wraps sibling
modifier groups, and the operator types exactly one of them. The usage line
renders it as a required alternation, (community <value>|rate-limit <bytes-per-second>|discard) on send bgp <selector> flowspec, so the obligation
reads from the line. The wrapper's name is never typed: the completer offers the
members' keywords and never the wrapper (oneOfSuggestions), and help lists the
members rather than the container. The handler still refuses a word the options
region does not claim (announce flowspec ... discard rate-limit 500 answers
unexpected token rate-limit), because the grammar states the obligation and the
handler enforces it.
A leaf's own ze:help and description travel with the argument. argDefFor
(config/yang/command.go) reads the leaf's type and its mandatory
statement, then fills ShortHelp from GetHelpExtension over the leaf's
ze:help and Description from the entry's Description, the same two readers
every carrier uses. Neither text is derived from the other, and a leaf that
declares one leaves the other empty. A merged command node keeps the
definitions of the first module that declared them, the first-wins case of
mergeHelpText. Four readers print the pair: ze help command --json (args
entries carry short-help and description, each when declared), the site
command catalog and the wiki catalog (args entries carry the same two keys,
and their pages print the summary and the explanation beside each argument),
and the web admin command form (the summary beside each input, the
explanation under it).
command.ArgDef (argdef.go) has private fields, and only its per-kind
constructors build one. Each validates and returns an error rather than a
value:
| Constructor | Kind | Refuses |
|---|---|---|
NewStringArg(name, lengths, patterns, opts) |
ArgString |
an empty name, a nil pattern, length parts that descend, overlap or are not ascending |
NewUintArg(name, bits, ranges, opts) |
ArgUint |
an empty name, a width outside {8, 16, 32, 64}, a range above the width, range parts that descend, overlap or are not ascending |
NewEnumArg(name, values, opts) |
ArgEnum |
an empty name, no value, an empty value |
NewUnionArg(name, members, opts) |
ArgUnion |
an empty name, a member no constructor built. Its enum values are its enum members' names, flattened in member order |
NewFlagArg(name, opts) |
ArgFlag |
an empty name |
The part-order checks are RFC 7950 Sections 9.2.4 and 9.4.4: "If multiple
values or ranges are given, they all MUST be disjoint and MUST be in ascending
order." Every refusal wraps command.ErrArgDef. ArgOptions carries what
every kind shares: Mandatory, ShortHelp (the leaf's ze:help summary),
Description (its description), Anchor (an explicitly declared ancestor
path keyword), and TypeName (the source YANG type or typedef name, without
changing the constructor's validation kind). Without an explicit anchor, a
nonflag leaf whose own name occurs in the selected path follows that keyword
bare; every other leaf follows the command as a keyword argument. The
constructors copy their input slices. The accessors (Name, Kind,
Mandatory, UintBits, ShortHelp, Description, Anchor, TypeName)
return scalars, and EnumValues, Ranges,
Lengths, Patterns (the pattern source text) and UnionDefs return
iterators, so no reader can write into a validated definition.
WithAnchor returns an anchored copy. Tests outside the package build
definitions through commandtest.Must.
The zero value ArgDef{} still compiles, and it is not a definition:
ValidateArgs and ValidateArgString refuse it with an error wrapping
ErrArgDef, rather than reading it as an unrestricted string.
ArgDefs are extracted from YANG by BuildCommandTree (config/yang/command.go)
and stored on command.Node.ArgDefs. The dispatcher receives them via
RegisterOptions.ArgDefs populated by PathToArgDefs.
A boolean command leaf carries either false or true. The lowerer uses
the enum validator for those two lexical values while retaining the source
YANG type name in metadata. empty leaves use the presence-only flag
constructor. Supplied false remains an argument value through validation
and invocation writing.
yangTypeToArgDef builds every definition through these constructors and
assigns the internal ArgKind; raw argument strings never choose it. A
constructor refusal there is a BUG: goyang's type resolution sorts, coalesces
and bounds every range and length part before lowering reads it, and an
enumeration with no enum has no argument. ValidateArgString and Constraint treat an unknown internal kind
as a BUG, not successful validation or an unconstrained argument. Invalid
operator-supplied values still return their type's existing validation errors.
A string argument carries every restriction its YANG type chain declares.
goyang resolves the typedef chain before yangTypeToArgDef reads it, so
the lengths are the most restricted length along the chain and the patterns
are every pattern of every type in it. validateString refuses a value whose
character count falls outside every length range (RFC 7950 Section 9.4.4
counts Unicode characters, not bytes), naming the bound ("x" is outside the accepted length (1 characters), why <leaf> accepts 2..4 characters, or
1..8 | 16..32 for a disjoint length), and a value that fails any one pattern
(is not in the accepted format, why the format in words). A union member is judged by the same
definition, so its own length and patterns apply to it.
A pattern is translated by compilePattern (config/yang/pattern.go), the
same XSD translation the config validator uses, and anchored to the whole
value: up|down matches up and down only. Loader.Resolve and
DefaultLoader refuse a module holding a pattern that translation cannot
compile, wrapping ErrUncompilablePattern, so no argument is ever built with
its pattern missing. The error names the module, the leaf, leaf-list,
typedef or deviation the pattern restricts, the source location, and the reason, which
quotes the pattern.
A container that names an object declares the value the operator types after
its keyword, once, and every command under it takes that value:
request interface <name> up, <name> down, <name> mtu <bytes> share one
name leaf on the interface container. inheritArgDefs
(config/yang/command.go) carries such a leaf down to each command after every
module is merged, anchored to the container's name (WithAnchor), and the renderer
places the value right after that keyword. The command under such a container
that acts on no single member of the set states ze:inherit "none":
show bgp peer list reads every peer, and request interface migrate names two
interfaces of its own. The dispatcher binds the bare token after the anchor
keyword to the leaf anchored there (anchoredDef, plugin/server/command.go),
and a surface that builds a command from a name-to-value map writes the value
at that same place through command.WriteInvocation (arguments.go), which
the web admin form and the MCP tool call share. It reads only a name, an
anchor and whether the argument is a flag (command.InvocationArg): the web
form projects the node's definitions with command.InvocationArgs, and the MCP
server builds the input from its lister, which carries no type. A positional token after the
command still goes to the definition whose type constrains it most
(positionalDef).
In-process hints (e.g., registered address families) remain ValueHints
callbacks. Caller-bound runtime argument queries use ArgumentHints, which
receives the completed values and current partial and returns candidates or an
error. Static hints (log levels, FD limit "max") are YANG-declared and served
through ArgDefs. Static candidates win duplicate live names for the first
argument; subsequent arguments use the argument-aware producer alone.
Plugin Command Completion
Plugin-registered commands (from the plugin CommandRegistry, not YANG) are
absent from the YANG-derived command tree, so they are injected into the
interactive completion tree after the daemon starts.
CommandRegistry.VisibleCommandEntries() returns every non-Hidden command as a
command.CommandEntry{Name, Description}; command.MergeCommandPaths inserts
each path into the tree as completion-only nodes. The merge is non-destructive:
an existing YANG node keeps its WireMethod and description, so a plugin command
never shadows a builtin at the completion layer (mirroring dispatch precedence).
The merged leaf is marked as a command even without a WireMethod. Its
terminal arguments therefore remain attached to that command for completion
and explanations. OverlayCommandPaths preserves this marker on its copied
paths and leaves the base tree unchanged.
- SSH keeps the YANG tree per session and overlays the live plugin registry
on each completion or explanation (
pluginAwareCommandCompleter). Its argument queries use the authenticated executor with the session's context and authorization generation, so a departed plugin is absent immediately. - Web builds a throwaway overlay from the current registry for each
/cli/completerequest (web_completer.gopluginAwareCommandCompleter). The shared YANG tree stays immutable. The hub binds the web listener after plugin startup and the initial registry freeze. The per-request overlay reflects plugins that a later reload adds or removes.
SSH, web and the attached console share command.ArgumentSuggestions, the
query writer and decoder for system command complete args. The daemon checks
the target command's policy before reading runtime values. Plugin completion
inherits the caller's deadline and cancellation; denied, canceled and failed
queries remain failures rather than empty successful inventories.
- Shell completion (
ze completion words) runs in a standalone CLI process with no daemon, so it stays YANG-only; the daemon'ssystem command completeRPC completes plugin commands directly from the registry (Registry().Complete). - The attached console of
ze start --cliasks the daemon forsystem command listat attach time. It filters the compiled RPC list against that answer, then injects each non-hidden plugin command (buildRuntimeTreeFromDispatch,injectPluginCommands). Both help texts travel on that answer, so the tree carries the summary and the explanation. A plugin a later reload adds is absent until the operator attaches again.
Hidden commands still dispatch when typed in full. A YANG command tree carries
ze:hidden true on a command or ancestor through merged branches and copied
overlays. A plugin declaration cannot make a schema-hidden path visible.
They never appear in
completion, in help, in the MCP tools/list result, or in the API command list.
buildCommandMeta is the one producer of the last two surfaces, and it skips
every hidden builtin or plugin command. Daemon command-list rows retain the
hidden flag so attached clients apply the same rule. The help catalog also
checks schema visibility before publishing builtin, local or plugin paths.
Quiesce Barrier (test synchronization)
request quiesce (ze-plugin:system-quiesce) waits for every registered
subsystem to drain its pending asynchronous work before replying. Tests use
this barrier in place of a fixed time.sleep. It is the general form of
ze-bgp:peer-flush: the control plane is already synchronous (a command reply
lands after its handler runs), but downstream effects (routes flushed to peer
sockets, and later FIB/tc/listeners) complete after the reply, so a test does
send(change); request quiesce; assert on-wire with no sleep.
Subsystems register a Quiescer at runtime (they need a live reference such as
the reactor), and the handler discovers them through the registry, with no
per-subsystem switch. The BGP reactor auto-registers TWO quiescers when it
attaches to the server (registerReactorQuiescer): bgp-forward-pool (the
reactor's FlushForwardPool, draining post-establishment forwarded routes) and
bgp-peer-sync (DrainPeerSync, draining each peer's initial-sync opQueue,
which goes DIRECT to the session, and outstanding route decisions and writes
that can outlive the forward pool). Each drain is bounded by a per-subsystem
timeout, so a wedged subsystem yields an error naming it instead of hanging
the daemon.
The plugin-event-delivery quiescer joins prior event application and each
observer's declared deferred work. In the RIB this includes queued and in-flight
selected output and pending final source releases. A stopped observer is skipped;
a live observer that cannot settle fails the barrier with its cause. Other
observers continue on their own completion paths.
Invocation note: request quiesce and request peer <sel> flush are api-yang
RPCs reached through dispatch-command, not as direct wire methods. A plugin
calls api.dispatch("request quiesce") (the test SDK's ze_api.quiesce() and
ze_api.wait_for_ack() both do this); a raw _call_engine("ze-plugin:system-quiesce")
returns "unknown method" because dispatchPluginRPC routes only
ze-plugin-engine:* engine ops plus codec RPCs.
Extension point: Layer 2/3 subsystems (a kernel-FIB quiescer, a tc/qdisc
quiescer) register into the same registry and request quiesce drains them with
no change to the barrier. wait_for_ack is a thin, sleepless wrapper over
this barrier. The two BGP quiescers together cover the forward pool and the
per-peer initial-sync and route-decision drain. The wrapper therefore also
waits for cold recovery and a pending replacement flush.
What bgp-peer-sync waits for. A peer is settled only when it owes none
of the following work:
- Routes queued before its session came up.
- Its initial sync and End-of-RIB.
- A peer-up replay that has not reported done.
- A policy change that still re-sends its routes.
- Forwarded items its worker has not written yet.
- The current session's owed route decisions or pending destination-table writes.
The route-decision check waits for cold recovery even when no forward item is queued. A local takeover can remove an owed record before it flushes its useful replacement, so the pending write keeps the barrier closed too. The recovery worker's stop alone does not settle a live session's owed key. A decision or destination-table reset settles that key. A reset or rebound table contributes no route-decision debt for the captured session. Queued forwards still have their separate drain.
The End-of-RIB waits for no route process (owner ruling, 2026-09-18), so a route
server's, reflector's or RIB's peer-up replay can still be passing after the
marker. The replay fence covers that replay: it is up on an Established peer
until every process that declared it (FencesLiveForwards: bgp-rs, bgp-rr,
bgp-rib) has sent plugin session ready for the session. The peer's forward
queue (its overflow and its worker channel) covers what the replay, a live
forward or a requested End-of-RIB enqueued: bgp-forward-pool runs beside
bgp-peer-sync and can settle before the replay has enqueued anything, so the
peer-level answer reads the same per-peer counts the forward rails read. No
timer lowers the fence. A fence owner that never reports keeps the peer
pending, and the quiesce then fails when its drain ends with an answer that
names the peer, what it owes, and the process a replay waits for:
quiesce failed for: bgp-peer-sync
a subsystem still had work pending when its drain ended, so stopping the daemon or reading the result now would miss that work: bgp-peer-sync: peer 192.0.2.1: a peer-up replay to it has not reported done (waiting for bgp-rs): context deadline exceeded
fix: request quiesce
What the barrier does NOT cover. A peer with no session, and a peer whose TCP connect has not completed, are both reported settled: neither has a counterparty, and a peer nobody is listening for waits in that state for the life of the process, so counting it would hang every quiesce behind it. A peer holding a LIVE handshake (OpenSent or OpenConfirm) is waited on, because the socket is up and the far end answered, so its whole initial routing update is owed. That arm was absent until 2026-09-19, and until then a caller could quiesce, be told "done", and shut the daemon down between the OPEN exchange and the End-of-RIB.
Peer Selector Parsing
type Selector struct {
All bool
IP netip.Addr
Filters map[string]string // local-as, peer-as, local-ip, id, family
}
func ParseSelector(s string) (*Selector, error) {
if s == "*" {
return &Selector{All: true}, nil
}
if strings.HasPrefix(s, "[") {
return parseFilteredSelector(s)
}
ip, err := netip.ParseAddr(s)
return &Selector{IP: ip}, err
}
Command Registry
var Commands = []CommandInfo{
{"daemon shutdown", false, nil},
{"send bgp * update text", true, []string{"next", "origin", ...}},
// ...
}
A command's two help texts
A command node carries two help texts, and each is declared by its own YANG statement. An RPC, a plugin command and an offline local command each carry the same pair, in the declaration form their own registration uses.
| Field | Declared by | Holds |
|---|---|---|
command.Node.ShortHelp |
the ze:help extension |
the one-line SUMMARY |
command.Node.Description |
the description statement |
the LONG explanation of that one command |
Neither is derived from the other, and no reader shortens either one to guess at the other. The summary is authored short because it is a summary. No reader cuts it: every surface prints the summary whole.
mergeYANGEntry (internal/component/config/yang/command.go) writes both, and
mergeHelpText decides each field on its own when several modules contribute
one command path. A collision leaves the first value in place and logs
YANG command help text mismatch naming the field that collided.
An empty Description is a command nobody has written an explanation for, and
the help page prints its summary alone. An empty ShortHelp is a defect:
validateNode names each one by path.
An RPC carries the same two texts, in the same two YANG statements.
ExtractRPCs (internal/component/config/yang/rpc.go) writes them to
RPCMeta.ShortHelp and RPCMeta.Description, and each input, output and
notification leaf carries the same pair on LeafMeta.ShortHelp and
LeafMeta.Description (extractEntryLeaves). The hub copies the leaf pair to
api.ParamMeta and mcp.ParamInfo; api.CommandSchema and the MCP tool
inputSchema write the summary as the property's JSON Schema title and the
explanation as its description, each only when the leaf declares it; the
gRPC ParamInfo message carries short_help and description; and
ze help ai --json lists each rpc's input and output leaves and each
notification's leaves with both keys. GetHelpExtension is the ONE reader
of the extension for both carriers. A command container reaches it through
Entry.Exts, and an rpc through gyang.RPC.Exts().
./le doc yang-contract help-shape holds the two corpora to one shape.
An RPC's pair reaches an agent through the machine-readable reference.
SchemaRegistry.RegisterRPCs copies both to RegisteredRPC.ShortHelp and
RegisteredRPC.Description. aihelp.Build then publishes them under short-help
and description, the two keys ze help command --json uses for a command.
ze help ai --json and the MCP ze_reference tool read that one projection.
Build sorts the RPCs and the notifications by wire method, so the reference is
the same bytes on every run rather than the schema registry's map order.
The show schema methods and ze schema methods tables print one line for each
RPC. Both read the summary alone, as every other one-line surface does.
A PLUGIN command carries the same two texts, declared in its Stage 1 message as
short-help and description. VisibleCommandEntries reads both off the
registry, and MergeCommandPaths fills each field of the tree on its own. A
plugin that declares a summary and no explanation therefore fills the summary
alone. The plugin server spells them ShortHelp and Description too, on
Completion and on the dispatcher's builtin Command. The bound and the control-character
refusal on a declared text are in
docs/architecture/api/process-protocol.md.
command help "<name>" answers with both, under the short-help and
description keys, for a builtin and for a plugin command alike.
system command list carries both texts on every row too. The short-help key
holds the summary, and description holds the explanation. That answer is the only
place the ATTACHED console of ze start --cli reads either text from. An
explanation that does not travel here is one its ? key cannot print.
commandRows fills the pair for a builtin and for a registered plugin command
alike. A command that declares no explanation yields a row with no description
key.
On the client, applyCommandText writes the pair onto the node the row names,
in ONE walk. injectPluginCommands carries the pair into a node the tree does
not yet hold.
An OFFLINE LOCAL command carries the same two texts in a registry.Meta,
declared beside its handler in Go rather than in a YANG module. ShortHelp is
the summary and Description is the explanation, and the same empty-is-unwritten
rule holds for both. collectCommands (internal/plugins/help/help_command.go) merges these
registrations into ze help command --json after the tree, and skips one whose
path the tree already holds, so the catalog publishes the node's texts for such
a path and the registration's for every other. ./le doc yang-contract help-shape holds
this third corpus to the same seven rules, reading the registrations this binary
links from the registry and the four cmd/ze declares in package main from
its source, which is the only way to read a package Go forbids importing.
Which surface renders which field
Every surface that shows a command on ONE line reads the summary, and every one of them prints it whole. Only a surface that shows ONE command reads the long explanation: the help page in the terminal, and the two published detail surfaces.
| Surface | Producer | Reads |
|---|---|---|
| The per-command help page | commandHelpPage, rendered by helpfmt.(*Page).WriteTo |
ShortHelp on the header line, then Description in the body block, then the child rows. A node states its own two texts whether or not it has children |
| A help page's child rows | command.HelpEntries |
ShortHelp |
| A completion candidate | command.TreeCompleter.matchChildren, choiceSuggestions |
ShortHelp, copied to the candidate's Suggestion.Description |
| The interactive completion pane | internal/component/cli Model.renderDropdownBox |
nothing. A menu row is the command name alone, and a name wider than the box is clamped to the frame |
| The interactive message line | internal/component/cli Model.warningText, Model.handleKeyMsg (the ? key), Model.updateCompletions |
ShortHelp, whole, for the candidate the menu has selected |
The interactive explanation box, which the ? key opens |
internal/component/cli Model.renderExplanationBox, answered by command.TreeCompleter.Explain |
Description, whole. The attached console reads it from the description key of system command list |
| A shell-completion record | internal/plugins/completion writeCompletionRecord |
ShortHelp, read from the candidate's Suggestion.Description |
The ze help command table row |
printCommandTable |
ShortHelp |
ze help command --verbose |
printCommandVerbose |
ShortHelp, then Description |
ze help command --json |
commandEntry |
short-help, and description |
| The web admin command form | buildAdminFragmentData, rendered by the commandForm template |
ShortHelp as the lede, Description as the body |
| The web completion dropdown | HandleCLICompleteWithCommandCompleter |
ShortHelp, in the JSON description key |
| An MCP tool's action enum | buildToolDef |
ShortHelp, one line for each action |
| An MCP tool's own description | buildToolDef, commandText |
ShortHelp, then a blank line, then Description |
The OpenAPI command schema, the POST /api/v1/execute body that runs the command |
OpenAPISchema, commandRequestSchema |
ShortHelp as title, Description as description |
| The published wiki catalog | clicatalog.Render |
ShortHelp in the summary table column, Description in the ### detail block |
| The published CLI reference row | internal/le/site writeCommandRow, commandMirrorDescription |
ShortHelp |
| The published per-command detail page | internal/le/site equivalentZeCard, equivalentDetailMirror |
ShortHelp as the lede, Description as the Description body |
The llms.txt command line |
internal/le/site writeLLMSCommands |
ShortHelp, whole and with no character budget |
| An offline local command in any of the rows above | command.ListLocal, merged by collectCommands and by clicatalog.Collect |
Meta.ShortHelp and Meta.Description, in place of the node's two texts |
The machine surfaces carry the same pair. commandMeta
(cmd/ze/hub/command_meta.go) holds both halves for the API and MCP listers.
Its merge decides each half on its own, so a command with a YANG summary and a
plugin explanation keeps both. JSON Schema already names the two roles, so the
mapping is one to one: title is short and description is long. A command
that declares no explanation carries NO description key, never an empty one.
The shell-completion record is name, tab, description, newline. A summary
carrying a tab or a newline is FOLDED to single spaces there, never cut.
Folding answers the format's one-line constraint and loses no word.
NO surface cuts a summary. The TUI completion pane held the last cut in Ze, and
it went with the description column that sized it. A menu row is the command
name alone. The selected candidate's summary is on message line 2, whole
(docs/architecture/cli/error-surface.md).
Per-command declarations: what a command says about itself
Five registries let a command say something about itself to the CLI. Each one is
keyed by command path. Each resolves a command to the declaration registered on
the longest path that is a prefix of it. So show bgp rib best picks up a
declaration on show bgp rib unless it registers one of its own. A command that
must NOT inherit registers an EMPTY declaration. Absent and empty are different
answers, and that is the trap all five registries exist in.
| Registry | Declares | Read by |
|---|---|---|
RegisterShape |
whether the answer holds rows (tab, map) or one document (doc) |
validateDeclaredShape, before the command runs, and ze help command --json |
RegisterColumns |
the order the table and text renderers put this command's columns in | tableStyle.orderKeys, through the four ProcessPipes* wrappers, and the four catalog readers as column-orders |
RegisterAddressFields |
that a field of the answer holds an IP address | validateDeclaredShape, which admits | resolve and | origin only where a field is declared |
RegisterPipeFilters |
the pipe operations this command runs in its own handler, each with its argument kind (PipeFilter.Argument: none, optional, text, count, fields or path). A generic's name is an override, allowed only where the catalog entry says so (every data operator: match, count, first, last, display, fill, resolve, origin; never a format, no-more, save or log) and held to the generic's argument kind when recorded and to its answer shape when it answers: one object holding an integer count for count, the command's rows and at most N of them for first N and last N, the command's rows for every other data operator. On a monitor each event is held to it instead ("The stream route partitions in one lookup") |
partitionPipeChain, which hands them to the handler in ValidatedArgs.PipeOperations; RefusePipeOperationWords, which refuses one typed as an argument with the pipe form as its fix; CheckOverrideAnswer and, on the stream route, StreamLine.Run; the completer |
RegisterAliases |
a name an operator types in the operator slot, standing for a chain (see "Pipe aliases" below) | lookupAlias |
One implementation resolves all five: commandRegistry[T] in column_order.go.
Runtime lookup reads the shared execution grammar and matches each registered
path segment to one decoded word. Quoting one keyword preserves its identity;
one quoted value containing spaces cannot stand for several path keywords.
A command whose model declares a value inside its path is typed with that
value between two keywords: the peer selector of show bgp peer edge1 rib.
The positional match would never reach show bgp peer rib, so for a path the
model gives definitions to, lookup matches the typed words the way the
dispatcher matches the command (MatchInvocationPath, over the definitions
the YANG package registers with RegisterArgDefSource). The selector is
skipped exactly where dispatch binds it, so show bgp peer edge1 rib | received
hands received to the handler and resolves the peer RIB's columns, on the
dispatcher and on every surface's own partition. A word the model places
nowhere inside the path still does not reach the declaration. The refusal of
an operation typed as an argument names the registered path and writes its
fix from the command as typed, the selector kept: fix: show bgp peer edge1 rib | received.
An override keeps its generic's meaning as well as its answer shape, and the
shape check cannot see meaning. For match the meaning has one definition,
rowHoldsText: a row is kept when its values, lowercased and written one
after the other in the sorted order of their field names, hold the pattern.
The generic reads it over the rows of an answer (matchRows) and over one
event of a stream (applyEventMatch). A command that overrides match to
select its rows before its answer exists calls command.RowHoldsText over the
row it would answer, so it keeps exactly the rows the generic keeps over the
bare answer. The RIB does this for show bgp rib, show bgp rib protocol
and show bgp rib best, each over its own row: a show bgp rib row shows the
route's direction, a best-path row does not, and | match received keeps
rows on the first and none on the second, as the generic does. An override
that searched a field list of its own is a second definition, and it differs
from the row the day a field is added to one of the two.
TestRIBOverridesKeepGenericMeaning and
TestRIBBestOverridesKeepGenericMeaning compare each RIB override with the
generic over the same rows.
An owner can confine its shape, columns, address fields and aliases to a parent
with RegisterChildBoundary. Lookup derives an empty floor from the first typed
keyword after that parent. An equal or longer explicit declaration wins, and
removing a runtime value exposes the floor again. This is an inheritance rule,
not a command inventory: it also masks unknown typed paths, whose dispatch still
requires registration. Pipe filters keep their existing subtree inheritance.
The owner can supply an argument predicate. One accepted token after the parent
keeps the parent's metadata; two or more tokens still meet the child floor.
Quoted spaces remain inside that one argument, and virtual floor paths preserve
that word with the shared invocation writer's quoting.
The predicate runs under the registry's read lock, so it must be bounded, safe
for concurrent use and must not call the declaration registries. show bgp
passes its overview handler's isFamilyArg, which reads the family registry.
An explicit declaration on that argument path still wins. A registered child
whose name is also an accepted family token must declare its own metadata.
Two packages, one path: empty is a floor and a disagreement is a defect
The first four registries are a declarationRegistry[T], which adds one rule to
that lookup. declare reads what the path already holds:
| The value | The path holds | Result |
|---|---|---|
| anything | nothing | the value is stored |
| EMPTY | anything | what the path holds stays |
| non-empty | an EMPTY declaration | the value replaces it |
| non-empty | an equal value | ✕ |
| non-empty | a DIFFERENT non-empty value | panic("BUG:"), naming the registry, the path and both values |
An empty declaration is a FLOOR and never a claim. It stops a shorter path being
inherited, and it says nothing about what the answer holds. show bgp rib is the
case this rule was written for. The BGP peer command plugin confines the parent
metadata with RegisterChildBoundary, and the rib command plugin declares tab for
show bgp rib. Under the earlier last-writer-wins rule, package initialization
order decided which of the two the path answered.
Every in-tree caller declares from init(), so two different non-empty values
are a state only a Ze defect reaches. The panic reports it before the daemon
serves anything (docs/contributing/ze-go-style.md).
A plugin declares from a socket instead, and a bad declaration there is an
operating error rather than a Ze defect. So the first three registries carry a
second write, declareFor, which is the same four cases with the panic replaced
by an error. RegisterPluginShapes calls it, and nothing a plugin sends reaches
declare.
The ALIAS registry is the fourth, and it keeps register.
RegisterPluginAliases stores mergedAliases(path, ...), which differs from
what the path holds each time it runs, so the rule would fire on the ordinary
case.
The declared shape refuses an operator before the command runs
validateDeclaredShape reads the declared shape and refuses an operator that
shape cannot support, by name, before dispatch. A command declaring doc
answers count cannot apply here: this command answers one document, and count acts on rows. The answer's own shape refuses as well, at apply time, and that
half covers every command including the ones that declare nothing. The
declaration is what makes the published catalog true, because ze help command --json lists a declared command's operators from its shape.
An answer HAS rows in two spellings, and the second is what makes an identity
readable. A LIST is rows. A MAP whose values share one shape is rows keyed by
identity, and the key names each row: show bgp peer list maps a peer address
to that peer's record, and show bgp adj-rib-in maps a peer address to that
peer's routes. A row operator keeps the spelling it was given, so
show bgp adj-rib-in | first 1 answers one peer's routes under that peer's
address. A map that mixes an object with a list under different keys is one
document, because its keys are field names rather than identities.
Both halves of that message are derived, because one operator needs more than
rows. | fill brings back the columns a command declared. So it acts on tab
alone, and it means nothing over a map answer whose rows carry their own keys.
shapeDescription therefore calls map "rows that describe themselves". It
calls tab "rows read against a declared column order", and operatorNeeds
reads the operator's own shape set. Calling both "rows" gave a refusal that
contradicted itself, in front of an operator whose answer HAS rows.
A finite JSON answer bounds first and last storage by the rows already
present. A requested count above the result size keeps every row without
reserving memory for that count.
A declared address-field list is an ADMISSION gate AND a selector. It decides
whether | resolve and | origin run at all, and it decides what they
decorate. bindAddressFields copies the declaration onto each address operator
when the chain is parsed, so a later registry withdrawal cannot change an
in-flight chain, and resolveJSON and originJSON decorate a key only when
addressFieldSelected finds it in that list.
Standalone stdin is the one path that decorates every key.
ProcessStandalonePipesChecked sets allAddressFields on each address
operator, because stdin has no command path and therefore no declaration to
read. There addressFieldSelected returns true for every key whose value parses
as an address.
Every show bgp command declares a shape, and two channels write them. Go
compiled into the daemon declares twenty paths. Nine of those name an address
field. show bgp rib and show bgp irr are served by a plugin process, and an
in-core shim declares for them. Scope is therefore the registration site rather
than the process boundary.
A plugin process declares the other eleven in its Stage 1 message. Six sit under
show bgp rpki, two under show bgp rs, two under show bgp adj-rib-in, and
show bgp healthcheck is the eleventh. Four of the eleven name an address
field. See "A plugin declares its own answer shape" below.
A SELECTOR spelling declares nothing of its own. The registry resolves the string
the operator typed. show bgp peer detail is not a prefix of
show bgp peer 192.0.2.1 detail, so that spelling resolves the virtual empty
floor at show bgp peer. It therefore reaches no shape refusal before dispatch, and
the answer's own shape refuses after it.
A column order never enters the payload. It is captured when the formatter is
built, from the command string the wrapper already holds, and it reaches
| table and | text only. | json, | ndjson and | yaml keep their
alphabetical keys, because a program reads those three and key order carries no
meaning for a program.
A command declares one order per record shape. show bgp renders an
outer record and a list of peer rows. Both carry an uptime key in a different
position. So the renderer applies the declaration that names the most of the
keys in the record it has in hand.
| display and | fill: the operator's own answer
An operator overrides both halves of that with two generic pipe operators.
| display <field>... names the fields the answer leads with.
| fill [alpha] [reverse] says whether the fields it did not name come back at
all, and in what sequence. Each takes ONE type of argument, so no token is a
field name in one position and a keyword in another.
| fill on its own orders the remaining fields by the command's own
declaration. alpha orders them by field name instead. reverse flips
whichever way is in force. Neither way measures a column: each decides the
sequence from the key set and a declaration.
A third way was removed on 2026-08-19. | fill overall ordered columns by the
width they render at, and that width is known only after every cell of the whole
answer has been rendered. It made the first row unwritable until the last row
had been read, which is the one thing a streamed answer cannot do. overall is
now refused by name, and | fill itself is untouched.
The two halves of the request travel by different routes, and the split is what makes them work under every format:
| Half | Where it is applied | Reaches |
|---|---|---|
| Selection: which fields | applyDisplaySelect, over the payload, at the operator's position in the chain |
every format, | json, | ndjson, | yaml and | raw included |
| Sequence: in what order | columnRequest carried on tableStyle |
| table and | text only |
Selection is a data question the operator asked out loud, so a program gets the answer. Sequence is presentation, so it stops at the two renderers.
selectFields walks the same shapes tableStyle.renderValue walks. When the
operator names a container field, that explicitly chooses its containing record.
The container's value is narrowed if it holds another requested field, and is
otherwise kept whole. Thus display peers keeps the peer rows, while
display peers state keeps their state fields.
Without an explicit container, the record holding the most requested fields
wins. This distinguishes the peer rows' uptime from the outer record's
uptime: display address remote-as state uptime selects the peer rows, while
the aggregate fields in the summary alias select the outer record. The chosen
record keeps only the requested fields it holds; unknown field names do not
create columns. Selection is applied to the data before formatting, so JSON and
text retain the same fields.
An equal match at different record locations is ambiguous and is refused by
field name, without either record's values. display uptime over an answer
holding both ages cannot silently choose one. Name the container first, such
as display peers | display uptime, to resolve the choice. Row sequences remain
selected one record at a time, and an empty row sequence stays a valid empty
answer.
applyDisplaySelect decodes the payload through decodePipeJSON, the decoder
every JSON-reading operator shares. It keeps each number as written and refuses
a payload with trailing data. A uint64 wider than a float64 therefore reaches
the rendering with its digits intact.
An operation the command does not declare stays in the chain.
partitionPipeChain takes out only the operations the command's set declares,
and only while no residual operation precedes them: after the first one, a
generic name the command also declares runs as the generic, and a name only
the command declares is refused with the line reordered as its fix. Every
other kind stays in the chain ApplyPipes runs over the answer. Both sides run
in the daemon. Without that rule a kind named nowhere reached neither side, for every command that registers
filters of its own, and nothing reported the loss.
TestColumnOpsSurviveFoldFiltersOnFilteredCommand,
TestAliasSurvivesFoldFiltersOnFilteredCommand and
test/ui/display-fill-filtered-command.ci are what hold that.
A drawing for an answer: the registered text renderer
Some data reads only as a drawing. show bgp rib ... graph answers the AS
topology as data, {"graph":{"nodes":[{"asn":..,"name":..,"layer":..}],"edges":[{"from":..,"to":..}]}},
and an operator wants the box diagram, not a table of nodes. The answer stays
data, so | json, | yaml and every program read the structure, and its owner
registers the drawing under the answer's envelope key with
command.MustRegisterTextRenderer from its own register.go (bgp-rib
registers graph). The text format, the default one or an explicit | text,
draws an answer whose one envelope key has a renderer with it; the pipe
metadata key beside the answer does not count. Every other answer is the
generic text table. A renderer that cannot draw what it was given answers an
error, and the operator reads it as a pipe error naming the key, never an empty
screen. A topology past 100 ASes is refused by the command itself, with the
filter that narrows it.
Pipe aliases: a name for an operator chain
An alias is a name an operator types in the operator slot, standing for a chain
they would otherwise retype. show bgp | peers says what
show bgp | display peers says.
Two callers declare one, and both write the same registry.
| Registration | Table | Resolved |
|---|---|---|
RegisterAliases([]string{"show bgp"}, ...), from Go compiled into the daemon |
aliasRegistry, the same commandRegistry[T] the two registries above use |
by the longest command path that is a prefix of the command |
RegisterAliases(nil, ...), from the same Go |
globalAliases, a table of its own |
for every command, when the per-command lookup carries no alias of that name |
RegisterPluginAliases(owner, commands, declared), from a plugin's Stage 1 message |
aliasRegistry, on the command paths that plugin declared |
the same longest-prefix rule. A plugin reaches no global table |
The global table is separate rather than a registration on the empty command
path. commandRegistry.register skips an empty path, and
commandMatchesPrefix refuses an empty prefix against every non-empty command,
so such a registration would match nothing and report nothing.
expandAliases runs between ParsePipe and partitionPipeChain, so classification
only ever sees operators the parser already knows. It is ONE pass, and four
properties are what make one pass enough. checkAlias is the one reading of all
four, so the two callers can never disagree about which declarations are sound:
- An alias MUST NOT name another alias. Its expansion parses to pipe operators alone.
- An alias MUST NOT carry the name of a pipe operator, which
ParsePipewould read first. - An alias MUST NOT carry the name of a pipe filter of an overlapping command
path. A command's own filter resolves before anything generic, so the filter
would win at use time and nothing would say why.
RegisterPipeFiltersrefuses the same pair from its side, because package init order decides which of the two registrations runs second. - An alias takes no argument. A word after the name is refused when the chain runs, rather than dropped.
The two callers differ in the ANSWER, not in the checks. checkedAlias turns a
refusal into panic("BUG:"). Only Go in this repository reaches
RegisterAliases, so a bad registration there is a Ze defect the compiler
cannot see. RegisterPluginAliases returns the refusal as an error, because the
strings it reads arrived over a socket.
An alias never enters the payload. expandAliases replaces the name with the
operators before the chain runs, so a command handler cannot tell an alias from
the chain it stands for. The chain is expanded in the process that PARSES it,
and for a plugin's alias that process MUST be the daemon. Read "Where an alias
resolves, and where it does not" below.
show bgp registers the two in-tree aliases that exist. Both are a selection
among sibling keys, because that answer carries its aggregates and its peers
array at the same level:
| Alias | Expands to |
|---|---|
summary |
display router-id local-as uptime peers-configured peers-established |
peers |
display peers |
The BGP RPKI plugin declares a third, summary on show bgp rpki, over the
Stage 1 channel the next section describes.
A plugin declares a pipe alias in its Stage 1 message
DeclareRegistrationInput.Pipes is a list of PipeDecl, beside the lists that
carry families, commands, filters, doctor checks and enrichers. The SDK
re-exports the type, so an external author imports one package. An alias entry
carries four strings, and the engine parses the expansion once, at registration.
| Field | Meaning |
|---|---|
command |
The command path the alias sits on. It MUST be one of the commands this plugin declares in the same message |
name |
The word an operator types after the pipe character. Lowercase kebab-case, one word |
description |
The line completion and command help show beside the name |
expansion |
The operator chain the name stands for, written the way an operator would type it |
validatePipeDecls reads the shape and the ownership, in the position where
Stage 1 already validates doctor checks and enrichers, before it converts
anything. registerPluginPipes then writes the accepted set under
startupRegistrationMu, between the registry row and the runtime families. Each
later failure unwinds what the steps above it wrote.
A plugin declares a pipe operation the same way
An entry that states argument in place of expansion is a pipe OPERATION
the plugin's handler runs, the plugin's counterpart of RegisterPipeFilters.
The value is the catalog's closed argument vocabulary (none, optional,
text, count, fields, path), the one a compiled-in PipeFilter states
in its Argument field, so the partition validates a builtin's and a plugin's
operation by one rule. An entry states exactly one of the two fields:
validatePipeDecls refuses both, or neither ("expands to nothing"), by name.
registerPluginPipes hands the operations to RegisterPluginPipeFilters,
which records them into pipeFilterRegistry under the plugin's name, before
the aliases. It returns an error where RegisterPipeFilters panics, and it
refuses the whole list, recording nothing, on any of these:
| Collision | Refusal names |
|---|---|
a generic operator's name the catalog does not let a command override (a format, no-more, save or log: every generic that is not a data operator), or an override stating another argument kind than the generic's |
the operation and the generic |
| a name an alias carries on an overlapping command path, in-tree or another plugin's | the operation and the alias's path |
| a global alias's name | the operation and the global alias |
| a command path that already holds a non-empty operation set, in-tree or another plugin's | the path, its operations and their owner |
| one name twice on one path in one message | the path and the name |
The empty barrier that stops a declared set reaching the plugin's own command
below it is derived from the plugin's command list, as for aliases
(inheritanceBarriers). An alias of the same message refused after the
operations were recorded withdraws them. UnregisterPluginPipeFilters takes
the operations back on the three paths the aliases leave by (the two rollback
arms of the Stage 1 write and releasePluginRegistrations), and each path
returns to what it held before, an in-tree barrier included. At run time the
partition hands the operations the line typed to routeToProcess, which sends
them in the pipe list of execute-command (process-protocol.md,
"Command Execution"); a subsystem's command receives the same list.
A plugin names only a path it declared itself, and it reaches no global table.
A path another PLUGIN declared is refused a step earlier: PluginRegistry.Register
runs before the alias write and rejects a command name another plugin holds, so
the second plugin fails on the COMMAND and never reaches its alias.
What the check confirms is that the plugin DECLARED the path, not that the
daemon routes that path to it. A plugin that declares a name the daemon serves
itself, show bgp for one, passes here. The dispatcher's own registry rejects
that command entry later as a builtin conflict, and the plugin keeps running, so
its alias sits on a command path the daemon answers. It can only ADD a name
there, never take one: the exact-path check refuses a name the path already
carries, mergedAliases keeps what the path held, and the name leaves with the
plugin. Declaring a name a builtin already serves is a plugin defect, and the
daemon logs it as command registration rejected ... conflicts with builtin.
Collision has two populations, because there are two resolution rules
Reading collision as "any overlapping path" refuses the case the channel exists
for. show bgp carries an alias named summary, and every show bgp * path
overlaps show bgp, so that reading refuses show bgp rpki | summary before it
is written.
| Pair | Collides when | Why |
|---|---|---|
| Alias against alias | the two sit on the SAME normalized command path | lookupAlias reads the set on the longest registered prefix and never falls back to a shorter one. A longer path SHADOWS a shorter one, and that is how show bgp rpki answers summary while show bgp answers one of its own |
| Alias against pipe filter | their command paths OVERLAP | partitionPipeChain resolves a command's own filter for the whole subtree the filter covers, so an overlapping filter makes the alias unreachable |
| Alias against a built-in operator name | always | ParsePipe reads the built-in name first, so the alias is never reached |
aliasOnPath is the exact-path reading and filterShadowing is the overlapping
one. A declaration is also refused when one name appears twice on one path in
one message. A declaration naming a command path the plugin did not declare is
refused too.
A refusal fails the whole Stage 1 registration, and the plugin does not start. Nothing is registered when any one declaration is refused, so a plugin never has to undo a partial registration. The message names the plugin, the command path and the alias name. The daemon log is where an operator reads it, because the engine stops a refused plugin before it can report anything itself.
A declaration ADDS to a path. It never replaces what the path holds
commandRegistry.register stores one value for each path, so writing a declared
set straight into the registry drops every alias that path already answered to.
An in-tree package or another plugin can already declare aliases on that path.
mergedAliases adds the declared names to what the path holds. Every declared
name is checked against that same set first, so nothing merged this way replaces
anything. The show bgp parent boundary supplies an empty lookup floor without
occupying the child's registration slot.
Removal is by ENTRY for the same reason. UnregisterPluginAliases takes back the
names one owner registered, and leaves the in-tree names and other owners' names
in place. A path the owner created from nothing goes once its last entry is gone.
Without removal a plugin that stops cannot start again, because the exact-path
check then refuses it its own name.
Two call sites remove it, and they are the two that remove the registry row and
the runtime families. rollbackStartupProcess is both the failed-startup path
and the config-reload stop path. The other is the family-conflict unwind inside
onRegistration.
The engine derives the barrier that stops an alias below its command
An alias on show bgp rpki is inherited by show bgp rpki roa, because roa
registers nothing of its own and the lookup resolves the longest registered
prefix. That offers the name on a leaf whose answer cannot carry it.
aliasBarriers derives the answer from the plugin's own command list. It reads
every command the plugin declared that sits strictly below a path carrying one
of its aliases. Each such command that declares no alias itself gets an empty
declaration. The in-tree BGP owner instead registers one parent boundary in
peer.go. Its virtual floor covers every typed child branch, including newly
registered commands and selector spellings, without a child list or schema
cache. A child's own alias set still wins. A plugin author writes nothing and
does not have to know the resolution rule.
The pipe layer selects and re-sequences. It cannot compute
This is the obligation every command that wants an alias owes, and it is a property of the PAYLOAD rather than of the pipe layer.
display keeps the named keys and drops the rest. fill re-sequences what
display did not name. count replaces the answer with a number. first and
last cut the item list. match keeps the rendered lines that match a pattern.
The format operators render one payload a different way.
None of them renames a key, adds two numbers, counts the rows whose field holds
a given value, or asks the handler for anything. So a command whose second view
is a pipe alias MUST EMIT the aggregate fields beside the detail rows, as
siblings at one level. show bgp has always done this, and show bgp rpki now
does it too: overviewCommand writes appendSummaryFields and
appendCacheServers into one record, and | summary selects the first half.
Four of the seven RPKI aggregate fields are computed. vrp-count sums the two
family counts, sessions-established counts the sessions in one state,
sessions-total renames what show bgp rpki status calls sessions, and
validation-enabled is a constant. The command computes them, and the alias
only selects them.
The expansion is a second copy of the field names, and display names keys and
reports no miss. A field added to the payload and not to the expansion is
therefore dropped from the alias in silence. A conversion owes three things:
- one authored list of the field names.
- an expansion built from that list rather than repeating it.
- a test holding the list against the bytes the writer produces.
RPKI does this with summaryFieldNames and buildSummaryAliasExpansion.
Two questions send a candidate back to being a subcommand. Would the operator have to supply a value? An alias takes no argument. Does the answer need data the parent's payload does not carry? An alias reshapes what was returned.
show bgp rpki roa 192.0.2.0/24 fails both and stays a subcommand.
show bgp rpki cache fails the second one: it reports preference,
session-id, serial and three intervals that the bare answer does not carry.
preference is the cache the router connects to FIRST rather than a label:
RFC 8210 Section 10 loads from the most preferred cache that answers, and the
next one is contacted only when it does not, so the row says which cache the
records in hand came from.
Where an alias resolves, and where it does not
The chain is resolved in the process that parses it, and a plugin's alias lives in the daemon's registry alone.
| Surface | Parses the chain | A plugin's alias works |
|---|---|---|
ze cli -c "<command>", and any SSH exec channel |
the daemon, in execMiddleware |
✓ |
The TUI a plain ssh client with a pty reaches, and ze cli with no command argument, which opens that pty |
the daemon, which hosts the Bubble Tea model | ✓ |
An operational command typed in ze config edit |
the CLIENT process: sshCommandExecutor reads the line with ReadDispatchLine, sends DeclaredLine, and the editor's model applies the residual chain |
✕ |
cliClient.StreamMonitor, for a streaming monitor command |
the daemon; the client reads only the presentation suffix, where no alias is ever part of it | ✓ |
On the client-side row the operator reads
pipe error: unknown pipe operator: <name>, and Tab offers the name nowhere.
The aliases compiled into the client resolve there, which is what hid the gap.
The repair is a wire surface that carries the daemon's alias table to the
client at session start, and it is NOT built.
A surface missing from the table parses no chain of its own. A plugin's
dispatch-command, MCP ze_execute, REST execute and gRPC hand the line to the
dispatcher whole, and Dispatch resolves its aliases from the daemon's
registries, a plugin's included ("The dispatcher takes the line with its pipe
chain").
Discovery: what each catalog reader can see
A declaration a plugin makes travels TWO channels, and both carry the same
slice. The Stage 1 registration message reaches a running daemon. The plugin's
registry.Registration reaches anything that links the composition root, which
is how a catalog generator reads a declaration without starting an engine.
Commands carries the answer shape, the column order and the address fields;
Pipes carries the aliases the plugin puts on its own commands and the
operations its handler runs (an entry with an argument and no expansion).
Until 2026-09-07 the alias had no second channel, so no reader outside a daemon
could report one.
Every surface below answers what a command takes after a pipe as ONE list,
pipe-operations, from one function (command.PipeOperations; the daemon view
is command.PipeOperationsForCommand). Each entry carries name, source
(generic, override, command or alias), argument, available
(always, with-rows or when-streaming) and description; a generic and an
override also carry class, a generic overridable and local-only, and an
alias expansion. An override sits in its generic's place with the command's
own description, so the RIB's count appears once. Tab completion after |
offers exactly this list.
| Surface | Reads | Alias | Shape, column order, address fields |
|---|---|---|---|
show command help "<name>" |
the running daemon's registries | ✓ | ✓ |
| Tab completion in the daemon-hosted TUI | the running daemon's registries | ✓ | ✓ |
./le cli list |
the compiled tree and registry.All() |
✓ | ✓ |
ze help command --json |
the compiled tree and registry.All() |
✓ | ✓ |
the wiki catalog (clicatalog.Collect) |
the compiled tree and registry.All() |
✓ | ✓ |
The wiki catalog's mode column names the routes that run a command, read from
its registrations. A YANG path a daemon RPC serves is daemon, or read-only
when IsReadOnlyPath says so. When a local handler is registered at the same
path too (a local-data command, or a local command the daemon also serves, such
as show version), the command also runs in the caller's own process with no
daemon, and the mode carries both routes: daemon, offline or
read-only, offline, never the daemon's alone. A command with only a local
handler is offline, or the mode its registry.Meta declares.
An EXTERNAL plugin is the one case the last three rows still cannot answer for. It registers nothing in the composition root, so its declaration exists on the Stage 1 message alone and a running daemon is the only reader of it.
show command help lists an in-tree alias and a declared one the same way, and
it listed neither before 2026-08. It reports the expansion beside the
description. An alias takes no argument and names no other alias, so the chain
it stands for is the whole of what the name does.
command.DeclaredForCommand is the ONE reader of both channels, and the last
three rows call it. So the three catalogs agree by derivation, not because a
check reconciles them.
It weighs the two channels by PATH LENGTH together, and not one after the other.
Inside a daemon there is only one channel: registerPluginShapes
(internal/component/plugin/server/startup.go) writes each Stage 1 declaration
into the three registries at the plugin's own command path, and every later read
resolves to the longest declared path that is a prefix of the command. A reader
that asked the registries first and the plugin second gave an ancestor's
declaration to a command that declares its own, and show bgp rib help
published the eleven route columns of show bgp rib and offered | resolve on
an answer holding no address.
Two rules follow from reproducing what a daemon holds. A plugin declaration that
names no column and no address field is a BARRIER and not an absence, so a
command whose answer has no columns says so and inherits nothing. And a
declaration that states no answer shape is passed over entirely, because
registerPluginShapes writes nothing for one.
AliasesForCommand is deliberately NOT changed to read the registration. It is
what a running daemon reads, and a daemon has already written each STARTED
plugin's aliases into the registry, so adding a registration's aliases there
would offer an operator a name no running command answers to.
The alias channel is weighed by PATH LENGTH beside the registry, as the three
above are. lookupAlias reads the set on the longest registered prefix and
never falls back to a shorter one, so a plugin's alias on a longer path SHADOWS
an in-tree ancestor's rather than joining it, and the two merge only where they
sit on ONE path. The barrier holds on the read side for the same reason:
show bgp rpki answers to summary, and show bgp rpki roa answers to nothing
at all, because the daemon writes an empty declaration on a command the same
plugin declares below its alias path, and no path is longer than the command
itself. The global aliases sit under both, as they sit under every registered
set.
./le plugin declarations check gates BOTH channels. It compares what a
plugin's runner passes to p.Run against what its registry.Registration
carries, identifying a command by its name and a pipe alias by the pair its
registry keys it on, the command path and the name. A field both literals write
as a call to one parameterless function is compared by that function's identity
rather than by reading its body, because one function answers one slice.
Anything else is compared in BOTH directions and over every field an entry
states. The published catalog is generated from the registration, so a command
the registration carries and the runner never declares is a phantom on the
website, and a Shape, a Columns or a Hidden the two spell differently is a
catalog describing an answer the daemon does not give.
The gate pairs ONE runner literal to ONE registration literal in a package, and it refuses a package that builds two of either rather than pooling both sides. Pooled, two plugins wired to each other's declaration functions agree as a package and disagree one by one: dropping either plugin takes the surviving one's catalog entries with it while the daemon still serves them.
The wiki catalog is NOT built from ze help command --json. Both join the
registries in their own process, because an internal package cannot import
cmd/ze's main package. compareWikiCatalogProducer
(internal/le/doc/yangcontract/command_surfaces.go) holds what is left of that split to
one answer: the four main-package commands clicatalog.Collect carries as
literal entries, and the le paths it drops.
All three readers name a purely plugin-provided command. Each walks
registry.All() after its own registry, because a plugin's command is
dispatched through the plugin and reaches neither the YANG command tree nor the
local command registry. Until 2026-09-07 the two published catalogs named none
of them: ze help command --json answered 270 commands at ze_core,ze_bgp and
show bgp rpki roa was not one, although it declares a shape, a column order
and an address field. It answers 313 now.
Two rules govern what such an entry carries.
- A HIDDEN declaration is skipped by the two published catalogs, because the
daemon already keeps one out of
VisibleCommandEntriesand out of completion../le cli listkeeps it, because that inventory answers what ze REGISTERS. The plugin-to-plugin plumbing is hidden this way, for examplerequest bgp adj-rib-in claim-replay;./le cli listnames every one. - The YANG node WINS wherever one exists. A plugin command can be modeled and
still carry no wire method,
show vrrp interfaceamong them, so it arrives with an authored summary, long help and grammar already written. For a command no node models,usagecarries the invocation form the plugin declares andgrammarstays empty: a plugin declares its arguments as text, and a token list built from that text would state kinds nobody declared. A declared argument is spelled in ANGLE BRACKETS, because both catalogs publish the tokens verbatim and a bare identifier reads as a keyword an operator types.
A plugin declares its own answer shape
Each CommandDecl in the Stage 1 message carries three optional fields:
shape, columns and address-fields. An absent field is an undeclared field,
so a plugin written before this channel existed keeps its old behavior.
| Field | Holds |
|---|---|
shape |
doc, map or tab, the three words the answer head uses on the wire, or blob for text or bytes read as they are (a blob answer travels in a doc head) |
columns |
the answer's keys, in the order a person reads them. It needs a shape with rows |
address-fields |
the keys whose value holds an address. It needs a shape |
validateShapeDecls reads the three fields where validatePipeDecls reads the
aliases. It refuses four declarations by name:
- a spelling that is not one of the four words.
- a column or address-field list with no shape.
- a declaration on a blank command path.
- a list or a name past its bound.
The bounds are 64 columns and 16 address fields for one command, with each name 1 to 64 bytes. A refused declaration fails the plugin's startup and writes nothing.
registerPluginShapes then writes under startupRegistrationMu, between the
pipe aliases and the runtime families, and joins the same unwind.
UnregisterPluginShapes takes the whole declaration back when the plugin stops.
The conversion from a CommandDecl to what the registries hold is one function,
command.PluginShapesFromDecls. A test that renders a plugin's answers under the
plugin's own declarations calls it too, so it registers the same shapes as Stage 1.
A plugin can never panic the daemon with a declaration. The three registries
keep the panic on declare, which only Go compiled into the daemon reaches. The
plugin route is declareFor, which is the same four cases with the panic
replaced by an error. Two in-tree packages that disagree are still a Ze defect
and still panic.
Every declaration writes all THREE registries. A command that declares a shape and no column writes an EMPTY column declaration. That empty declaration is the barrier that stops the command inheriting its parent's order. Removal restores the empty declaration a shim left behind, rather than deleting the path.
The declaration lives in the daemon's registry. So | display <partial> offers
a plugin command's field names in the daemon-hosted session, and offers none in
ze cli with no command argument. That is the same client-side gap the alias
table above records, for the same reason.
The chain over a row generator
A handler that answers with a row generator runs the same chain, one record at a
time. applyPipesRecords is the record half of ApplyPipes. | match,
| count, | first, | last, | display, | resolve and | origin each act
per record, so | count holds nothing and | last 8 holds eight records.
A format operator changes no record. RenderRecords renders what the chain
produced. It writes per record for one chain alone: | ndjson, over an answer
that declares no column schema, whose chain folded no display metadata.
Every other format needs a document. A column width needs every row, and metadata
rides in the envelope.
| table and | text therefore collect. That cost is paid once, in the
renderer, and the record stage forwards the records untouched.
A chain that answers a document of its own is not filed under the command's
envelope. | count is the one operator that does: it answers {"count":N}
whatever it counted, and the whole-payload path replaces the payload for the
same reason. system command list | count therefore answers {"count":N}, the
same document every other command's | count answers, and not
{"commands":[{"count":N}]}.
Authorization is decided once, at dispatch, and the rows are produced after that decision. That is what a built payload has always done, and a generator changes only how long the gap is. There is no per-row authorization, so a handler MUST NOT yield a row the caller was not already authorized to receive when the command was accepted.
A chain the validator refuses answers one rejected row and pulls nothing, so an unreadable chain never reads as an empty answer.
Managed Config RPCs
RPCs for hub-client managed configuration. These operate over MuxConn after auth, separate from the plugin 5-stage protocol.
| Verb | Direction | Payload | Response |
|---|---|---|---|
config-fetch |
Client to hub | {"version":"<hash-or-empty>"} |
{"version":"<hash>","config":"<base64>"} or {"status":"current"} |
config-changed |
Hub to client | {"version":"<hash>"} |
{} |
config-ack |
Client to hub | {"version":"<hash>","ok":true} or {"version":"<hash>","ok":false,"error":"..."} |
{} |
ping |
Either direction | {} |
{} |
Version hash is truncated SHA-256 (16 hex characters) of config bytes.
MCP Methods
The MCP Streamable HTTP transport (revision 2026-07-28) is stateless and
strictly client-to-server. Every message is its own HTTP POST, and the server
never sends an independent JSON-RPC request on any stream. These methods are
distinct from ze's own dispatcher commands (above). They are part of the MCP
protocol contract, and each request carries the version and capabilities it
speaks in its own params._meta.
| Method | Direction | Purpose |
|---|---|---|
server/discover |
Client -> server | Advertise supportedVersions, capabilities (including for MCP Apps and for background tasks), and instructions. Mandatory for a server to implement, and optional for a client to call. extensions["io.modelcontextprotocol/ui"]extensions["io.modelcontextprotocol/tasks"] |
tools/list |
Client -> server | The tool inventory, derived from the command registry at call time, in a deterministic order. A descriptor carries _meta.ui only when the request declared the. io.modelcontextprotocol/ui |
tools/call |
Client -> server | Run a tool. Answers resultType: "task" when the command's ze:task-support annotation is required and the request declared the tasks extension. Answers resultType: "input_required" when the tool needs a value the call did not supply |
There are no server-initiated methods. notifications/tasks/status existed
under the earlier revision and was removed with the session and the GET stream it
required.
elicitation/create survives, but no longer as a method. elicitation/create
is now a value inside the inputRequests map of an InputRequiredResult. A
server RETURNS that result from tools/call (or resources/read), and the
server does not send it. The client then retries the original request with
inputResponses. See MCP Elicitation for the
full round trip.
See MCP Architecture Overview for how capabilities are declared per request.
MCP Task Methods
These are the io.modelcontextprotocol/tasks extension, not core protocol. A
tools/call on a command annotated ze:task-support required creates a
background worker and returns a CreateTaskResult immediately. The client then
polls for status, and the server pushes nothing.
| Method | Direction | Purpose |
|---|---|---|
tasks/get |
Client -> server | Current state of a task by taskId. A terminal task carries its outcome here: result when completed, error when failed |
tasks/update |
Client -> server | Answer a task's outstanding input requests. Ze raises none, so it verifies ownership and acknowledges with an empty result, ignoring unknown inputResponses keys |
tasks/cancel |
Client -> server | Request cancellation of a working task |
tasks/list and tasks/result were REMOVED this revision and are now unknown
methods, answered HTTP 404 with -32601. A poll of tasks/get replaced the
blocking tasks/result. That change is why a terminal state carries its
payload. tasks/list was dropped outright. No method enumerates tasks now, so a
client tracks the ids it was given.
All three surviving methods require the request's
_meta["io.modelcontextprotocol/clientCapabilities"] to declare
io.modelcontextprotocol/tasks under extensions. The bare tasks member that
the earlier revision used is no longer accepted. A request without the
declaration is refused with -32021 (MissingRequiredClientCapability) and
HTTP 400, carrying data.requiredCapabilities in the extension shape.
Task creation is server-directed. There is no task member on tools/call
params. The server decides per tool from the YANG ze:task-support annotation:
required always, forbidden never, and optional synchronous. A client that
did not declare the extension gets the ordinary synchronous result, not an
error.
MCP Resource Methods
| Method | Direction | Description |
|---|---|---|
resources/list |
Client -> server | List all available UI resources. The response comes from an embedded FS walk |
resources/read |
Client -> server | Read a single resource by URI. Returns content as text or base64 blob. ui:// |
Both results carry cache hints (see MCP Result and Error Envelope below).
Neither method is gated on a client capability. resources is a member of
ServerCapabilities, not of ClientCapabilities (whose members are
experimental, roots, sampling, elicitation and extensions). No
conformant client can therefore declare resources. A server that advertises
the capability in server/discover serves it.
MCP Result and Error Envelope
Every successful MCP result carries a resultType and
_meta["io.modelcontextprotocol/serverInfo"], stamped from one shared helper so
no method can omit them. resultType is complete for a finished result.
resultType is input_required for the MRTR interim result a handler produces
when it needs a value the request did not supply. The shared helper preserves
input_required and does not overwrite it. And a guard on the single path out
of dispatch refuses to emit input_required on any method other than
prompts/get, resources/read and tools/call.
Four methods additionally carry the CacheableResult fields, ttlMs and
cacheScope. Both are non-optional on those results.
| Method | ttlMs |
cacheScope |
|---|---|---|
server/discover |
60000 |
private |
tools/list |
60000 |
private |
resources/list |
3600000 |
private |
resources/read |
3600000 |
private |
tools/call and every tasks/* method carry neither field, in either result
shape. Three reasons make that correct. tools/call is absent from the
specification's cacheable-operation list. Interim input_required results are
explicitly not cacheable. And a result produced by an MRTR retry must not be
cached at all.
Ze therefore applies the hints from a per-method table on the way out of
dispatch. The shared ok() responder does not apply them, because tools/call
also uses it.
cacheScope is private on every cacheable result, which forbids a shared
gateway or caching proxy from serving one authorization context's response to
another. It is defence in depth, not the access control: per-request
authentication remains the gate.
| Code | HTTP | Meaning |
|---|---|---|
-32020 |
400 | HeaderMismatch: a required standard header is missing or disagrees with the body |
-32021 |
400 | MissingRequiredClientCapability: data.requiredCapabilities names what the client must declare |
-32022 |
400 | UnsupportedProtocolVersion: data.supported lists the server's versions, data.requested echoes the client's |
-32602 |
400 for a malformed params._meta, 200 otherwise |
Invalid params |
-32601 |
404 | Unknown method, including initialize |
| — | 405 | GET or DELETE to the MCP endpoint |
Three HTTP request headers are mandatory on every POST, and each one must agree with the body:
MCP-Protocol-Versionmirrors the_metaprotocol version.Mcp-Methodmirrorsmethod.Mcp-Namemirrorsparams.namefortools/callandprompts/get, and it mirrorsparams.uriforresources/read.
Ze decodes the =?base64?...?= sentinel in Mcp-Name first, then compares the
decoded value with the body.
Tool descriptors in tools/list carry _meta.ui.resourceUri when the command
group has a ze:ui-resource YANG extension. The _meta.ui block is emitted
unconditionally, and the ui:// asset it points at is readable by every caller.
Last Updated: 2026-07-29