Skip to content

Build an amux client

amux’s own apps are clients like any other. The terminal app and the iPhone app hold no secret API: they ask the amux running on your machine what your agents are doing, through the same documented interface that is open to you. So you can build your own:

  • an editor plugin that shows which agents need you, and answers them without leaving the file you’re in
  • a menu-bar app with a badge for every agent waiting on a question
  • a script that pings you when an agent finishes, or starts one every morning on the repository that needs it

Whatever you build gets the whole of amux for free. It sees every agent on this machine and on every machine you’ve paired with it, however amux reaches them: on your network, over SSH, or through the relay. It keeps no state of its own and holds no account token: amux does the networking, the pairing, the encryption and the sign-in, and your client asks it.

The example below is a whole working client, in one file of about a hundred lines.

amux runs as a daemon on each machine, and a client, amux’s own included, talks to it in gRPC over local sockets. Every client does the same five things:

  1. Find the installation and its front door, the socket the daemon answers on.
  2. Install or start amux when nothing answers.
  3. Pick a profile: one identity, with its own account, paired machines and agents.
  4. Sign the profile in, when the person wants to reach their other machines.
  5. Follow the profile’s agents, and act on them.

There are two ways to build one:

  • On amux’s Rust crates, which do most of that for you. This is how amux’s own clients are built (below).
  • From the protocol, in any language, with the messages and services in proto/amux/v1. The protocol, step by step explains each of the five; a client on the Rust crates reads it for what the calls mean.

The protocol is stable from 0.11.0: fields are added and never renumbered (README), so a client built against one release talks to later ones. A daemon older than 0.11.0 speaks an earlier shape of the services that later clients cannot use; GetInstallation says which version is running.

Crate What it does for you
installer Steps 1 and 2. Finds the installation and its front door; ensure starts amux, or installs it, checking the download against the release’s signed manifest. It touches nothing already running, so a client calls it at every launch.
client Typed calls to the front door (Installation) and to each profile (Client), with every socket detail below handled. What this machine’s amux answers itself is inventory(), sessions(), drafts() and admin(); acting on an agent is agent(&row), and on a machine, such as starting an agent there, host(&host_id), so every call goes to the machine it is for.
ui-runtime The drivers: Fleet follows a profile’s agents and Session one chat. They hold the streams, reconnect when amux restarts and start over when they fall behind.
ui-state, ui-view Optional. ui-state is the drivers’ model; ui-view turns it into what a screen shows (the fleet’s sections and rows, a chat’s rows and ask cards) as plain values, and leaves wording, layout and theme to the client. The terminal client and the iPhone app draw these.

Take as many as the client wants. installer stands apart. A client with its own model of the fleet takes client alone and reads client.inventory().subscribe() itself; ui-runtime on top of it handles the streams; ui-view adds the ready-made rows.

The crates are not published to crates.io. Depend on them from Git, pinned to the tag of the amux release whose daemon the client talks to:

[dependencies]
client = { git = "https://github.com/amuxhq/amux", tag = "vX.Y.Z" }
installer = { git = "https://github.com/amuxhq/amux", tag = "vX.Y.Z" }
ui-runtime = { git = "https://github.com/amuxhq/amux", tag = "vX.Y.Z" }
ui-state = { git = "https://github.com/amuxhq/amux", tag = "vX.Y.Z" }
ui-view = { git = "https://github.com/amuxhq/amux", tag = "vX.Y.Z" }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

Unlike the protocol, the crates promise nothing: their APIs change whenever amux’s own clients need them to, so moving to a newer tag can mean changing code. They are under the same licence as the rest of amux (LICENSING).

A whole client in one file. It makes sure amux is running, opens the installation’s first profile, and prints its agents again each time they change.

//! A whole amux client in one file: it makes sure amux is running, opens
//! the installation's first profile and prints its fleet, again each time
//! the fleet changes. docs/guide/build/build-a-client.md walks through it.
//!
//! cargo run -p ui-runtime --example fleet
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use client::{Clock, Installation, Surface, SystemClock};
use ui_runtime::Fleet;
use ui_view::{FleetView, SecondLine};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 1. Find amux, and install or start it. An installation named by
// AMUX_CONFIG is a development or test one: attach to it, never start it.
let config = std::env::var_os("AMUX_CONFIG").map(PathBuf::from);
let front_door = installer::front_door(config.as_deref())?;
if config.is_none() {
// Installs and starts amux; whether it also starts at login is the
// person's `start_at_login` setting, asked once it answers.
let options = installer::Options::default();
installer::ensure(&options, |step| eprintln!("{step:?}")).await?;
} else if !installer::answering(&front_door).await {
return Err(format!("amux is not running at {}", front_door.display()).into());
}
// 2. Pick a profile and open its services.
// Every call names the client making it; this one is a terminal's.
let installation = Installation::connect(&front_door, Surface::Terminal).await?;
let profiles = installation.list_profiles().await?;
let profile = profiles.first().ok_or("the installation has no profiles")?;
let client = installation.open_profile(profile).await?;
// Which host is this machine: the views say whether each agent's host
// can be reached from here.
let local_host = client.admin().get_device_identity().await?.host_id;
// 3. Follow the fleet. The driver keeps the stream open, reconnects
// when amux restarts and starts over when it falls behind.
let fleet = Fleet::connect(client, SystemClock).await?;
let mut changed = fleet.changed();
let mut shown = None;
loop {
// A change the list does not show (an agent's progress within a
// step) wakes this too; print only what looks different.
let now = view(&fleet, &local_host);
if shown.as_ref() != Some(&now) {
print(&now);
shown = Some(now);
}
if let Some(error) = fleet.ended() {
return Err(error.into());
}
changed.changed().await?;
}
}
/// The fleet as amux's own clients list it: sections of families, each row
/// with the line under its name.
fn view(fleet: &Fleet, local_host: &[u8]) -> FleetView {
let now_ms = SystemClock.now_ms();
// Read each session before the fleet, never holding both at once.
let lines: HashMap<_, _> = fleet
.sessions()
.into_iter()
.map(|session| {
let state = session.state();
(
ui_state::agent_key(state.agent()),
ui_view::session_line(&state, now_ms),
)
})
.collect();
let state = fleet.state();
let expanded = HashSet::new();
ui_view::fleet_view(&state, local_host, &lines, &expanded, &|_| true)
}
fn print(view: &FleetView) {
println!("\n{} need you, {} working", view.need_you, view.working);
for section in &view.sections {
println!("{:?}", section.kind);
for row in &section.rows {
let indent = 2 + 2 * row.depth as usize;
let card = &row.card;
let line = second_line(&row.second_line);
println!("{:indent$}{} on {}: {line}", "", card.name, card.host);
}
}
}
fn second_line(line: &SecondLine) -> String {
match line {
SecondLine::Said(said) => format!("says {said:?}"),
SecondLine::Step(step) => step.step.clone().unwrap_or_else(|| "working".into()),
SecondLine::LastSaid(said) => said.clone(),
SecondLine::Exited(cause) => format!("exited: {cause:?}"),
SecondLine::HostRevoked => "its host no longer trusts this machine".into(),
SecondLine::Blank => String::new(),
}
}

From a checkout, cargo run -p ui-runtime --example fleet runs it. With AMUX_CONFIG naming a development installation it only attaches; without, it acts on the person’s own installation, and installs amux if it is missing.

What it leaves out, and where to find it:

  • Choosing a profile. It takes the first. A real client lets the person choose, and follows subscribe_profiles so the list stays current.
  • Signing in. Listing agents needs no account. Installation::sign_in streams the sign-in (step 4).
  • Opening a chat. Fleet::open gives the agent’s Session, and ui_view::chat_rows_for turns its state into the chat’s rows. Pair every open with Fleet::close.
  • Acting on agents. Fleet::stop, and client.agent(&row) for one agent: send_input, send_message, rename, set_filing, resume, preview_delete, delete, put_blob and changes, which are the protocol’s calls of those names. A new agent starts from the machine that will run it: client.host(&host_id).agents().create(request).

Generate stubs with proto as the include root, compiling proto/amux/v1/*.proto together with the Google status protos vendored beside them in proto/google/rpc: link.proto imports google/rpc/status.proto, and the services import one another. A project that already depends on a published copy of the Google protos uses that instead. Every call has its own request and response message, beside its service; a response around one value holds it in one field, and each response on a stream holds one event.

Every socket speaks gRPC over plaintext HTTP/2, with no TLS and no credentials: only the person’s own account can reach it.

Set the HTTP/2 :authority to localhost for everything this machine’s amux answers. gRPC libraries built on gRPC’s C core (Python, Ruby, PHP, C++) otherwise send the socket’s path, which is not a valid authority. The daemon then resets the stream (INTERNAL: Stream removed, RST_STREAM error code 1), which looks like a broken daemon rather than a client setting. In those libraries it is the grpc.default_authority channel option.

To act on an agent, address its machine. Reads come from this machine’s amux, which holds every paired machine’s agents and chats. Acts (starting an agent, sending it a prompt or a message, renaming, settling, resuming or deleting it, asking what it changed) are answered by the machine the agent runs on, and a call says which machine that is by its authority: the machine’s id, the UUID in its lowercase dashed form (0192f0c8-7a51-7c3e-9d2f-3b1c5e6a7d80), which every agent row carries as host_id and every host as its own id. Open one channel per machine, on the same profile socket, with its authority set to that id; amux carries each call there and back, and says why when it can’t. Any other authority is answered by this machine, so an act on another machine’s agent sent that way is answered NOT_FOUND, naming the machine that owns it. A machine’s name is never an address: resolve it with ResolveHost and use the id.

An installation is one config file and the root directory it names. Its front door is <root>/amux.sock.

  • The config file is the one AMUX_CONFIG names, else $XDG_CONFIG_HOME/amux/config.toml, which is ~/.config/amux/config.toml when XDG_CONFIG_HOME is unset, on macOS and Linux alike, and %APPDATA%\amux\config.toml on Windows. A missing file means every default.
  • The root is the config’s top-level root key, else $XDG_DATA_HOME/amux, which is ~/.local/share/amux when XDG_DATA_HOME is unset, and %LOCALAPPDATA%\amux on Windows.
  • On Windows too, a set XDG_CONFIG_HOME or XDG_DATA_HOME wins over those defaults, as it does for amux itself.

To ask whether amux is up, call GetInstallation on the front door with a deadline of a few seconds; it answers the daemon’s version. A missing socket, a refused connection or no answer means amux is not running.

Details:

  • root is an absolute path, taken as written: no ~ and no variables.
  • A Unix socket address holds at most 103 bytes of path on macOS and 107 on Linux. When <root>/amux.sock is longer, connect through a shorter path to the same file, such as a symbolic link of the client’s own to its directory, as amux itself makes under $TMPDIR/amux-<uid>/.
  • On Windows, <root>\amux.sock is a small file holding the name of the named pipe the daemon listens on. Read it and connect to that pipe, after two checks: open the name only if it is exactly \\.\pipe\amux- followed by 32 lowercase hex digits (anything else, such as another machine’s pipe, could hand your credentials to someone else), and once it’s open, make sure the pipe’s owner is your own user (GetSecurityInfo with OWNER_SECURITY_INFORMATION); it is, even when the daemon runs elevated. If the pipe is busy, the file is briefly locked, or the pipe is not there yet, read the file again and retry for a couple of seconds: the daemon may be restarting.
  • Every other amux socket, each profile’s included, follows the same rules.

amux lives at ~/.amux/bin/amux (%USERPROFILE%\.amux\bin\amux.exe on Windows) on every machine, whichever client put it there, and serves the default installation. Whichever client arrives first installs it. From then on amux runs on its own (and starts at login once the person turns start_at_login on), and every client only attaches. Removing a client leaves amux running; amux uninstall is the one way to remove it.

  • Installed but not running (the binary exists, the front door does not answer): run ~/.amux/bin/amux server start, then try the front door every quarter second or so. amux’s own clients give it 30 seconds.

  • Not installed: install it and start it:

    Terminal window
    curl -fsSL https://amux.sh/install | sh
    ~/.amux/bin/amux server start

    On Windows the install script is PowerShell, irm https://amux.sh/install | iex; then amux server start as above. It needs no administrator, and puts amux-launch.exe beside amux.exe. The installer crate’s ensure does the same.

Details:

  • An installation AMUX_CONFIG names is a development or test one (a source checkout’s, a test’s) that may run another build. Attach to it when it answers; otherwise report it down, and never install or start anything for it. Every amux command reads AMUX_CONFIG too.
  • The login item. Installing adds none. The start_at_login setting (settings) writes one (a LaunchAgent on macOS, a systemd user unit on Linux, a Run value on Windows, which starts amux through amux-launch.exe with no window) that starts amux at every login from the next one on; ask the person, as onboarding’s keep_reachable step does.
  • PATH. An app opened from the desktop often has a sparse PATH, and the daemon records its own PATH in the login item for the agents it starts. Start amux with the person’s login-shell PATH (on macOS and Linux, what $SHELL -ilc 'printf %s "$PATH"' prints), as the installer crate does, or the agents will not find the tools they run. On Windows there is no login shell to ask and the login item records no PATH: amux adds the user’s and the system’s Path from the registry to its own whenever it starts a provider, so an app’s PATH is enough.
  • Downloading amux yourself. Read https://amux.sh/releases/stable.json, the stable channel’s signed manifest, as the install script does. Each target (aarch64-apple-darwin, x86_64-unknown-linux-gnu, x86_64-pc-windows-msvc) names a URL, a size and a SHA-256, and the manifest carries an Ed25519 signature over them. Check the download’s size and SHA-256 against it. On Windows, also install the entry x86_64-pc-windows-msvc/amux-launch as amux-launch.exe beside amux.exe, checked the same way; it is what the login item runs. A running program can’t be replaced on Windows: stop amux first (amux server stop), and rename a file something still runs (an agent runs amux.exe too) aside to amux.exe.old.<n> rather than over it, as the install script does; amux deletes those once nothing runs them.
  • Running amux server start. It returns once amux answers. What it leaves running (the supervisor and the daemon) holds none of the streams it was given, so a client reading its output through a pipe sees the end when it exits. Bound the wait all the same: the installer crate sends its standard output to nothing and its standard error to a file it reads once the command exits, and gives it 60 seconds.
  • No window on Windows. amux.exe is a console program, and Windows gives a console program started by one that has no console (a desktop app) a console window of its own. Start every amux command from a desktop app with CREATE_NO_WINDOW. Nothing amux starts after that shows a window: the supervisor, the daemon and the agents run without one.
  • Exit codes. Every amux command exits 0 on success and 1 on failure, with the reason on standard error; 2 is a usage error.
  • A packaged Windows app. An app packaged as MSIX with full containment sees %LOCALAPPDATA% through its package, which keeps what it writes there apart from the person’s own, and what it starts runs in its container, so the amux it started would keep a root of its own, apart from the command line’s. Install and start amux from outside any container: ship the app unpackaged, or as a package with an external location, so amux runs as the person’s own process with the root the command line uses.

An installation holds one or more profiles. Each is one identity on the network: an account it may be signed in to, the machines it is paired with, its agents. A client shows one profile at a time and lets the person switch.

On the front door (InstallationService), ListProfiles answers the profiles now. SubscribeProfiles answers the whole list at once, and again whenever anything about any profile changes; keep that stream open rather than polling. CreateProfile, RenameProfile and DeleteProfile manage them, and an installation always keeps at least one.

Profile field What it holds
id A 16-byte UUID. Show it in the usual dashed form, which is also how it appears in socket_path.
label The profile’s name.
email, account_name, picture_url The account’s. picture_url is an https URL, empty for none.
cloud Whether it is signed in (below).
socket_path The profile’s own socket (step 5).

A profile is signed in when cloud holds signed_in, whatever its relay link is doing. While the link is connected, its tier is the account’s plan as the relay applies it: TIER_PRO carries connections between the account’s machines, and TIER_FREE only lists them. A link in sign_in_again means the account service refused the profile’s credentials, and the person signs in again. signed_out is a profile tied to an account and signed out of it; unbound was never signed in.

Signing in binds a profile to an amux.sh account. The daemon does it, so a client never sees a password or holds a token. SignIn runs the OAuth device flow and streams what happens:

  1. A code event. Show the person user_code and open verification_uri_complete in their browser, or show verification_uri and let them type the code. The code stops working at expires_at_ms.
  2. An adopt event, only when the profile already holds agents or paired machines. Ask the person, then answer with AnswerSignIn, naming the event’s sign_in_id. Setting adopt_non_pristine in the request skips the question.
  3. A signed_in event with the profile, and the stream ends.

Leave profile_id empty to let the installation pick: the profile already bound to this account; else the installation’s only profile, when it has one and nobody has signed in on it, without the adopt question, since what it holds is already the person’s; else one that holds nothing yet; else a new one. Closing the stream abandons the sign-in.

An app that runs its own browser sign-in (authorization code with PKCE) hands the refresh token it obtained to the daemon with BindProfile, naming the OAuth client that obtained it; the daemon spends the token from then on. Signing out is SignOut on the profile’s own socket.

Everything inside a profile is on its own socket, Profile.socket_path. This machine’s amux answers these from what it holds, for every paired machine’s agents alike:

  • InventoryService: the fleet, and agents and machines found by name.
  • SessionService: reading a chat and the files it shows; the wire describes its subscriptions and items.
  • DraftService: what the person has typed into a chat and not sent.
  • ProfileAdminService: the profile’s account, pairing and peers.

Three more are answered by the machine a call is addressed to (connecting):

  • AgentService: starting agents and acting on them, sending them input and messages, and what deleting one would take.
  • HostService: what a machine’s Claude and Codex offer before any agent runs, and pinning its folders.
  • ReviewService: the files an agent changed.

InventoryService.SubscribeInventory is the fleet. It sends every host the profile knows and every agent on them, then caught_up, and from then on each change as it happens:

  • agent is one agent’s whole row. Add it, or replace the one with the same agent_id, a UUID unique across the fleet. An agent’s name is always set.
  • agent_removed removes one.
  • host and host_removed do the same for hosts.
  • lagged, before or after caught_up, means the client fell behind. The stream closes; subscribe again, and replace what you held with the new listing.

Rows from a host this machine cannot reach right now are as that host last reported them; the host’s entry says whether it is reachable.

CreateAgent, addressed to the machine that will run it, starts an agent. Name the agent program by its provider id, as the machine’s entry lists it in providers (claude, codex, or an ACP agent’s id), and put the model, effort, permission and mode to start on in settings, using values from that provider’s catalogue (HostService.GetCatalogue); leave any of them out for the machine’s own default. Leave kind unspecified and the machine starts the provider as its entry’s descriptor says. What an agent can do, and how each of its settings is changed, is its AgentCapabilities: the provider’s on the machine’s entry until the agent’s first snapshot, then the snapshot’s own. Decide what to offer from those, never from the kind or the provider’s name. SendInput sends a chat its prompts and answers, and SetFiling, ResumeAgent, RenameAgent and DeleteAgent act on an agent, each addressed to the agent’s machine. Before a delete, PreviewDelete says what it would take with it: the agent’s workspace and branch, and any work not committed.

The installation’s everyday settings are on the front door: GetSettings answers them and UpdateSettings changes the fields it sets, leaving the rest alone, and answers the settings it leaves. The config file stays where they live, so amux config and a client see the same values; a change is in force at once, and one made to the file beside the daemon within seconds, or as soon as a client asks GetSettings, which reads a changed file first.

Settings field What it is
host_name What paired devices and the phone call this machine; never empty. Setting it empty returns to the machine’s own name. A rename shows in discovery and in every pairing from then on; a device already paired keeps the name it paired with.
start_at_login Whether amux starts at login. Absent on an install without a supervisor, which has nothing to start. Turning it on writes the login item for the next login and leaves the running amux alone.
keep_awake On power the machine stays awake while amux runs; on battery only while an agent works.
chat_in Where the terminal client chats: amux’s chat or each agent’s own interface.
claude_kind Which Claude a new agent runs; unspecified follows chat_in (its own interface means terminal Claude). Every host publishes what this resolves to as the kind of its Claude provider’s ProviderDescriptor, which a create that leaves kind unspecified starts.
telemetry, auto_reports Usage events and automatic reports.
experiments Every experiment the machine’s build implements: its name, the version it implements, a one-line description, whether the settings switch it on (enabled) and whether amux is still restarting to apply that, or a change to its own settings (applying). UpdateSettings takes the whole new list of names switched on. Unlike the rest, a switch needs amux to restart, which it does on its own once its work under way settles: while applying is true, show the switch as being applied rather than on or off, and read the settings again after amux comes back. An experiment’s own data on the wire, in experimental map entries keyed by version, may change in any release; a client reads the entries of versions it knows, whatever the machine has switched on, and ignores the rest.

How amux is deployed (the supervisor, updates, where releases and data live, discovery’s scope, the agents’ tunables) stays in the file and amux config, not on this call.

Where a machine offers to start an agent is on its own entry in the inventory, as HostEntry.folders: the folders its person pinned, in their order, then the ones its agents started in, newest first, then the ones Claude Code and Codex ran in lately outside amux. Search that list in the client. HostService.PinFolder, addressed to the machine, is the only way to pin or unpin one, for a person on that machine or a paired one (an agent is refused), and the machine’s entry then says the change. The pins are kept in the repositories key of the machine’s config, and GetSettings lists them as Settings.repositories, as written there: a folder that is gone stays listed, so a settings screen can unpin it, while the entry offers only folders that are there.

Onboarding is one list of steps the daemon keeps for each profile, the same for every client. SubscribeOnboarding sends them now and again on every change; leave profile_id empty for the profile a bare amux opens, the oldest. Each step is needed, done, skipped or not_needed, in the order to show them:

Step Done when
pair_phone the profile trusts a phone
keep_reachable the person confirms starting at login and keeping awake; not needed on an install without a supervisor
sign_in the profile is signed in
repositories the person confirms the pinned folders
improve the person confirms the telemetry and automatic-reports choice
first_agent a paired device created an agent on this machine

AnswerOnboarding takes one answer and returns the steps after it: done for a step the person confirms (only keep_reachable, repositories and improve: the others are done when they happen), skip for “Later”, dismiss when the person dismisses an offer to finish setting up, which skips every needed step, shown when the client shows a step, sign_in_offer_shown when it puts a one-tap sign-in in front of the person (offerer for “Also sign in” on the signed-in side, receiver for the offer on the signed-out side). Name the client in the amux-surface request header so the answer is counted for it; with none it counts as other. After a dismissal the steps carry dismissed: every step skipped now was skipped when the person dismissed, so a client stops offering to finish them; a step skipped afterwards clears it. Confirmations are the installation’s; a skip of pair_phone, sign_in or first_agent is the profile’s. A step added in a later release appears to existing installations on its own, needed.

amux’s own clients say which they are in the amux-surface request header (terminal, mac, ios, android, browser), so the fleet subscription counts each opening as that client’s, and the prompts, answers and new agents a person sends from it are counted as that client’s too, on whichever machine runs the agent. The header is optional and only counts: a client of your own can leave it off, and is counted as other, as is any word amux doesn’t know.

Calls fail with ordinary gRPC status codes, the reason in the status message, written for a person to read: NOT_FOUND for an id the daemon does not know, or for an agent another machine runs, saying which; FAILED_PRECONDITION for an agent name that matches more than one agent, and, with the reason HOST_UNREACHABLE, for a machine that can’t be reached right now, so the call was never sent, and with the reason REFUSED for a message the agent or its machine refused, the ErrorInfo’s refusal metadata naming which (AGENT_CLOSED); ABORTED for a call that went to another machine and lost its answer, so it may have happened; and UNIMPLEMENTED with no message for a call the machine’s amux is too old for. Where a client may want to act on the reason, the status details carry a google.rpc.ErrorInfo whose reason is one of error.proto’s ErrorReason names. UNAVAILABLE on the front door means amux is not running.

No call is retried for a client. A mutation that lost its reply is the person’s to run again.

The subscriptions (SubscribeProfiles, SubscribeInventory, SubscribeSession) stay open for as long as the client wants them: give them no deadline, and cancel the call to close one. They end when the daemon stops or restarts, which an update does on its own. The client then waits for the front door to answer again and subscribes afresh, as after a lagged event. (The Rust drivers do this themselves.)

That’s the payoff. Your client isn’t a side door into amux: it’s one more client of the same amux, beside the terminal app and the iPhone app. An agent your script starts shows up in the terminal and on your phone. A question your plugin answers is answered everywhere. A prompt you send from the iPhone, on a train, lands in the chat your menu-bar app is showing.

So you build only the part you care about. Remote access from your phone, the fleet across every machine, pairing and the relay are already there, in the apps people already use, and they all work with what you made.