Agent-First UI

Human-in-the-loop UI delivery for AI agents — open an isolated window, link, or host-managed session with live bidirectional state and a single typed outcome, without embedding a browser or design system.

Ask your agent: “Show me that in a window and wait for my answer before you continue.”

Ask a question without building a page

afui show ask puts a few questions with suggested answers in front of a person and returns one structured result, with room for their own words — no Provider or HTML needed. afui show view draws view messages you write yourself the same way. See Show a person a page.

The problem: an agent that needs you has nowhere to put you

An agent can ask a question in chat. What it cannot do in chat is show you twelve drafts and let you approve four, put a diff in front of you, stream live service state while you issue an inspection command, or hand you a form that validates as you type. So the moment a task needs something shaped like a page, the agent either flattens it into text or invents a web server — a port, a token, a browser tab left open, and no reliable way to know when that interaction ended.

AFUI is that missing step: one person, one interface, one bounded lifetime. A Provider may use only the terminal outcome, or attach the typed session runtime for retained state, calls, progress, ordered events, and managed byte bodies.

What AFUI owns, and what stays yours

You bring an Axum Router and decide what a finished interaction means. AFUI brings the mechanics nobody wants to write twice:

  • a revocable access credential, and the decision of when it lapses;
  • secure response headers, exact-origin and exact-host checks;
  • an isolated desktop window with non-persistent web data — never your browser, never your cookies;
  • one versioned live runtime with AFUI-owned correlation, reconnect, replay, cancellation, bounds, and retained latest state;
  • cleanup, and a typed outcome: Completed(T), Closed, or Expired.

A session carries stable provider_id, ui_kind, and session_id, so several interfaces can be open at once and each remains bound to the process that owns it.

AFUI never interprets what you put on the page. It does not know what a case, an invoice, or a query is.

How a session reaches a person

A window is the common one: AFUI opens it, the person acts, the call returns their answer. A window bounds its own session — someone who leaves it open all afternoon is still using it — so a window credential does not expire. It ends when a handler completes it or the person closes the window.

A link is for when the person is not at this machine. AFUI keeps the Provider session on loopback and hands out one public URL that redirects to a reverse-proxied copy of exactly that session. AFUI supplies the attention policy, grace period, proxy isolation and public credential; the Provider never chooses or implements its lifetime.

A session is registered and nothing more, for a host to present — in its own window, or on another device where the person actually is, such as a phone while the agent works on a laptop. afui host serve exposes the sessions on this machine to that host’s own client and reverse-proxies each one, so that 127.0.0.1, which on a phone is the phone, stops being the problem. It serves discovery, attention and proxies, never a dashboard: the host owns its windows and panes.

A direct link and a host-served mount share one attention policy — by default 15 minutes unattended, then a 5-minute grace period. A lapse ends a direct link with Expired; a host-served mount only loses its credential, and the session behind it keeps running until it is reopened or ended. AFUI does not supply network reachability or TLS: put a trusted tunnel, VPN or TLS reverse proxy in front.

UiDeliveryPlan resolves all three from one plan instead of each Provider writing its own match, and a launch file naming a registry makes session the default. The modes, the launch file and how a host opens a registered session are in Delivery; the attention clock and the host HTTP contract are in Remote access.

Several at once, on one port

Sessions and ports are orthogonal. Bind a UiHost once and attach as many sessions as you like: each is reached by its own credential, each outcome and live runtime stays with its owner, and ending one leaves its neighbours serving. That also survives the places a session has to live — a container with one mapped port, a machine behind a firewall, a single tunnel.

A Provider that already runs a server does not have to give the port up. A UiMount is the same routing without a listener of its own: nest its router() under a prefix on the Axum router you already have, and attach sessions to it. They are ordinary sessions — same credentials, same expiry and revocation, same security policy, same typed outcome, and still listed by afui host list.

Not every interface worth listing is one this crate serves. UiUpstream names one that already exists somewhere else — a third-party web client behind its own listener and its own credential, say — and the same deliveries apply to it. Its owner keeps one obligation AFUI cannot perform remotely: keep the private credential live while the delivery exists, and revoke it when the delivery ends. See When the page is not this crate’s to serve.

Finding what is already open

A session lives inside whichever process created it, so nothing could see across them. Every active session announces itself, and afui host list shows what is waiting — including whether it is waiting on a decision or merely being watched, and how long it has been open — afui host open <id> puts a window onto one, and afui session close <id> asks it to end: whoever created it gets Outcome::Closed, on any delivery, the same as if they had closed a window themselves. The command reports that the request was accepted; the owning process notices a moment later.

The credential never appears in that listing — a session URL carries one, and stdout is where an agent reads. open hands the URL straight to a window instead of printing it. How entries are written, protected, checked for liveness and pruned is in Registry, launch files and discovery.

Write a surface with a script

afui session serve-script --request file:/absolute/launch.json publishes a page directory and a type declaration, with the script’s stdin/stdout as AFDATA JSONL. The script receives calls and focus, and emits complete state, ordered events and replies. Its exit ends the surface. The child inherits no environment; credentials must be explicitly supplied in environment_secret. See the embedded surface authoring guide.

What you depend on

Choose the features for the capabilities your program uses:

FeatureWhat it addsWhat it costs
(none)the frontend script guard, frontend discovery, the trust gate, the per-file overlayfile reading and hashing — no server
clithe delivery flag declaration (UiDeliveryOffer::arg), and reading it back as a UiDeliveryMode; resolving that into a UiDeliveryPlan needs sessionAFDATA CLI types
pagetemplate rendering, markup guards, and page contract checksminijinja
view (default)the view model: the catalog, validation of view messages, the state they build up. Bound to a live session when session is on as wellAFDATA lint rules, URL parsing; no session, server or schema engine
view-template (default)the templates afui show renders, including the standard question page: a template’s input is checked against its own schema, then rendered into view messagesview, page, JSON Schema validation
apiapi::UiApi, the authenticated HTTP carrier for a Provider’s exposed operations, and the api serve / api export commandsaxum and tokio; no session, window or registry
host-clientUiSessionIsolation and resolve_session_mount for validating a native viewer’s mount addressesURL parsing; no network client, listener or registry
runtime-clientruntime_client::UiRuntimeClient: latest values, messages, correlated requests, cancellation, focus, bytes and attention (UiControlClient)Tokio, WebSocket and HTTP clients; no listener, registry or browser launcher
session (default)UiSession, UiSessionRuntime, offered bytes, UiHost, UiMount, UiWindow, credentials, security policy, the registry, UiUpstream, UiFrontend::assets_router, host controls and reverse proxycli, runtime-client, axum with WebSockets, tokio, tower, hyper, minijinja
test-supportInstalledFrontend, RuntimeClient, stub_browser, and registry waits for testing a Provider through AFUIsession and runtime-client; test drivers use the production client; take it as a dev-dependency only

The afui binary requires both session and view-template. The default feature set includes both, so source installs and release packages expose the full CLI.

The featureless tier exists because keeping a frontend honest is not the same job as hosting one. A Provider whose human UI is itself an optional feature still has to refuse a smuggled <script> in the build where that UI is compiled out — so reject_frontend_script has to be reachable without dragging a web server into a build that has no port to bind. Take it with default-features = false, and add agent-first-ui/session to whichever of your own features opens a window.

Bring your own frontend

The interface a Provider ships is a default, not a decision. afui frontend lets you replace it with your own — scaffold one, preview it, and enable it when it is ready. Run afui frontend --help for the full set.

Workspace trust is content-addressed: workspace code stays ignored until you enable its exact fingerprint, and any later edit revokes that trust until you look again. The files that were trusted are read once, when the fingerprint is checked, and a running session serves exactly those bytes — an edit made afterwards reaches nothing until the next start, where it faces the gate again. --safe-mode ignores overrides entirely.

Global frontends are trusted user configuration: installing or editing their files affects the next session without a workspace enable step. frontend enable and disable control workspace trust only; safe mode suppresses both scopes.

A replacement starts from a floor, not from nothing. Every session serves one AFUI-owned stylesheet that a page links and an override cannot remove: the palette in both themes, the focus ring, a hidden that actually hides, what a control looks like while a call is in flight, and an inset that clears the edges of the phone a session was opened on. It is a floor and not a design system — no components, no layout, no grid — so a replacement can be one template and no CSS at all and still open as a page that belongs here, and retuning it is one declaration rather than a fork.

A Provider reaches all of that through UiFrontend, which is the delivery half and only that: it resolves whether a trusted override exists for a provider_id + ui_kind, hands back a named file when the override supplies one, serves the override’s assets/, and turns “unloadable” or “wrong ui_api_version” into an error that names safe mode rather than a quiet built-in page. UiFrontend resolves files without rendering them. The optional UiPage builder renders the Provider’s typed document and checks its markup and binding contract; the Provider still defines what the data means and how the page presents it.

# fn example() -> agent_first_ui::Result<()> {
use agent_first_ui::UiFrontend;

let frontend = UiFrontend::resolve(std::path::Path::new("."), "inspector", "table_inspect", "1")?;
// `None` means "this override did not supply that file", not "there is no
// override": the overlay is per file, so replacing one page keeps every other
// file the Provider ships — including its language packs.
let page = frontend.text("templates/page.html.j2")?;
let assets = frontend.assets_router();
// Every Provider supplies its own built-in SVG. An override may replace only
// `assets/app-icon.svg`; the resolved icon then follows the frontend into its
// browser favicon and desktop window rather than being chosen by AFUI.
let app_icon = frontend.app_icon(include_str!("examples/app-icon.svg"))?;
# let _ = (page, assets, app_icon);
# Ok(())
# }

AFUI enforces these rules rather than describing them, because a Provider that binds its own behaviour under a nonce depends on them: an override may not supply a file whose name says it is a script, and reject_frontend_script refuses one hiding inside a template it does supply.

Live values in both directions

Completion and live I/O are separate. Outcome<T> still says how the session ended exactly once. UiSession::with_runtime adds everything that happens before then without asking each Provider to design transport semantics:

  • publish_value replaces the retained latest value of a key without waiting for a browser, for everyone, for the viewers watching it, or for one viewer; every initial connection and reconnect receives it before becoming live;
  • requests carry actions in and return progress, result, or caller-safe error through UiRequest; request identity never enters a Provider payload;
  • send_message delivers, in order, facts where every occurrence matters;
  • reconnect resends unacknowledged requests under the same identity, so the Provider sees one request rather than a retry protocol of its own;
  • byte offers let the Provider hand over bounded bytes while AFUI owns unguessable URLs, media allowlists, response headers, release and cleanup.

The wire is the explicit, versioned afui-session-v2 binary wire, implemented by AFUI on both sides. Provider types contain only domain data. The page calls afui.connect(); it never names a WebSocket path or injects a request id.

use agent_first_ui::{UiAudience, UiIncoming, UiSession};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum SurfaceAction {
    Inspect { target: String },
}

#[derive(Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum SurfaceReply {
    Inspection { target: String, details: String },
}

#[derive(Serialize)]
struct SurfaceState {
    load_percent: u8,
}

# async fn example() -> agent_first_ui::Result<()> {
let (session, runtime) = UiSession::<()>::new("inspector", "live_status")?
    .with_runtime()?;
runtime.publish_value(UiAudience::All, "state", &SurfaceState { load_percent: 42 })?;

tokio::spawn(async move {
    while let Some(incoming) = runtime.recv().await? {
        let UiIncoming::Request(request) = incoming else { continue };
        match request.payload::<SurfaceAction>() {
            Ok(SurfaceAction::Inspect { target }) => {
                request.finish(&SurfaceReply::Inspection {
                    details: format!("inspected {target}"),
                    target,
                })?;
            }
            Err(error) => request.fail(error)?,
        }
    }
    Ok::<(), agent_first_ui::Error>(())
});

// Deliver `session` with the Provider's Router in the ordinary way.
# let _ = session;
# Ok(())
# }

Build the page policy with .allow_runtime() on UiPagePolicy; the switches are in What your page may load. The runtime receives the same credential, exact-host/origin checks, revocation, proxying, and session shutdown as every AFUI-owned route. A hand-written CSP is an escape hatch, but AFUI cannot prove that such a string permits the runtime.

From Rust

This read-only surface stays open until the person closes its window. Opening or loading the page does not complete a decision.

use agent_first_ui::{Outcome, UiAppIcon, UiSession, UiWindowConfig};
use axum::{Router, response::Html, routing::get};

# async fn example() -> agent_first_ui::Result<()> {
let app_icon = UiAppIcon::from_svg(include_str!("examples/app-icon.svg"))?;
let session = UiSession::<()>::new("inspector", "status")?
    .with_app_icon(app_icon);
let router = Router::new().route(
    "/",
    get(|| async {
        Html(r#"<!doctype html>
<html lang="en">
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Status</title>
  <link rel="stylesheet" href="__afui/base.css">
</head>
<body><main>
  <h1>Inspection ready</h1>
  <p>Close this window when finished.</p>
</main></body>
</html>"#)
    }),
);

let outcome = session.window(router, &UiWindowConfig::default()).await?;
assert!(matches!(outcome, Outcome::Closed));
# Ok(())
# }

For decisions, collect an explicit action through the typed runtime or UiDecisionRuntime with UiSurface; see decision controls. Keep Closed and Expired as no decision, and never complete an approval from a GET handler.

What AFUI is not

Delivery infrastructure, and nothing else: not a domain UI protocol, not a conversation store, not a remote-access transport, not a frontend package format. It proxies a Provider’s UI and transports its typed values without understanding one byte of either.

Install

# prebuilt binary
brew install agentfirstkit/tap/afui   # macOS / Linux
scoop bucket add agentfirstkit https://github.com/agentfirstkit/scoop-bucket && scoop install afui   # Windows

# or from source, after reviewing the repo
cargo install agent-first-ui

A source install builds the same feature set as the published packages. A Provider depending on this crate as a library wants the opposite: default-features = false and only the tier it uses.

Prebuilt archives are also available from GitHub Releases.

Agent Skill

Then install the embedded Agent Skill so the agent follows AFUI’s rules for handing a person an interface — when a step needs a window at all, which delivery reaches them, and what an override may and may not change. skill install writes the standard skill folders agents read (--skills-dir names one folder instead); skill status reports whether each install is present, valid and current:

afui skill install --scope workspace
afui skill status

Docs

In the order a reader usually needs them:

  • Show a person a page — afui show: the ask question page, the view template, and templates of your own, with no Provider code
  • Building a Provider UI — is your UI a session, the live runtime, delivery and the registry, what an override may do to it, and how a decision control stays safe when its template is replaced
  • Remote access — the attention clock and its configuration, a host’s own client, what the proxy forwards and holds, and per-session origins
  • Native host clients — validating mount addresses, per-session data stores, and what a native viewer tells and answers
  • View renderer contract — what a renderer that draws view sessions owes AFUI, rule by rule, with shared fixtures
  • CLI — generated command and flag reference

Agent-First UI v0.9.0: Trust Belongs to One Checkout

Trusting a workspace frontend now trusts that directory and no other, so two checkouts no longer revoke each other. A remote Provider can take as long to answer as the viewer is willing to wait, a minimised macOS window no longer ends its question, and the remote view and ask page speak Traditional Chinese.

Agent-First UI v0.8.0: A Credential Stays Where It Was Handed

An AFUI session URL is its own credential, and this release follows it everywhere it went: process arguments, Referer headers, redirects, debug output, and streams that outlived a revocation. A question can now show images, tables, and diffs as evidence, and every ending of a session goes through one slot.

Agent-First UI v0.7.0: A Question Without a Page

`afui ask` puts a few questions with suggested answers in front of a person and returns one structured result, with no Provider, page, or button bindings to write. Notes sit on the choice they qualify, a written answer is one more card, and a caller whose commands time out can start a question, walk away, and collect the answer later.

Agent-First UI v0.6.0: Remote Until Proven Local

A page can now open a link outside itself, in the system browser for a local window and in a new tab for a remote view. Deciding which case it was is the whole risk, so a surface counts as remote unless it presents a key only AFUI's own window holds. Also: sessions that close the way they say, streams that end when their attention budget does, and a registry that is written atomically on every platform.

Agent-First UI v0.5.0: The Boundary Moves to Where the Copies Were

v0.4.0 shipped a channel that refused to mean anything, and every page then built the same meaning on top of it. Roughly seven hundred lines of page runtime, four private event streams, four hand-written content policies and five wildcard error arms later, the measurement is unambiguous: AFUI now owns the typed session runtime, the page kernel, page composition, delivery facts and credential routing — plus three places where its own contract said something the code did not do.

Agent-First UI v0.4.0: A Session Is a Lifetime, Not a Question

One interface, one person, one answer was almost right. The part that was wrong is that some interfaces are not a question: they show changing state while a person acts on it. v0.4.0 adds a bounded full-duplex channel that carries Provider values and refuses to mean anything by them, and finishes the delivery boundary around it — one page assembly, one delivery call, and an ending every delivery can express.

Agent-First UI v0.3.0: Everything Except the Interface

Handing a person a UI is not a rendering problem, it is a delivery problem: a credential, a lifetime, an origin, a window, a cleanup, and an answer that comes back typed. v0.3.0 replaces the view-hint protocol with a library that owns exactly that boundary and never sees a domain value.

Agent-First UI v0.2.0: One Space, Many Views

v0.2.0 reworks the protocol from a single surface a tool draws into a shared live space that each participant sees as their own projection. Owners are self-generated ids, capabilities and facts project per-participant, whispers reach one viewer, and a separate advisory view-hint layer suggests layout without ever running code.

Agent-First UI v0.1.0: Describe the Interface, Don't Ship It

The first release of Agent-First UI — a protocol where a tool describes its interface as data instead of shipping UI code. A trusted host you own renders the screens and actions, redacts secrets, and gates risky operations, so nothing the tool sends can run on your machine. v0.1.0 ships the wire protocol, a JSON schema, conformance fixtures, and a lightweight Rust SDK.