Server, Relay & Frontend Internals
This page explains how hya-server serves HTTP and gRPC from one port, how hya-relay encrypts remote connections without trusting the proxy, and how packages/hya-tui and packages/hya-tui-web render the UI.
1. Single-Port Dual-Protocol Server (crates/hya-server)
hya_server::build constructs one Axum router backed by AppState that serves both HTTP (/v2/* JSON, SSE, WebSocket) and tonic gRPC (V2Grpc) on the same TCP listener:
- Protocol dispatch: Incoming requests with
content-type: application/grpc*dispatch toV2Grpc; everything else routes to/v2HTTP handlers. - Zero drift by construction:
cargo run -p xtask -- gen-apigeneratesgrpc_generated.rsfromproto/hya/v2/*.proto(// hya.http:annotations) so almost every unary gRPC method encodes its path/query/body and calls the exact same Axum handler in-process. Only streaming and loopback-only RPCs (StreamSessionEvents,StreamGlobalEvents,StreamPty,Invoke*BundleApi,WaitTurn, andRelayControl) have explicit adapters ingrpc.rs. - Host allowlist guard (
host.rs): Rejects any HTTPHostor gRPC:authorityoutsidelocalhost,127.0.0.1,[::1], a specific--bindIP, or--allow-hostnames before CORS or route dispatch—blocking DNS-rebinding attacks from browsers. - Ephemeral session reaper (
ephemeral.rs): Speculatively created unused sessions (ephemeral: true) are automatically reaped ~5 seconds after their lastStreamSessionEventswatcher disconnects (or 30 seconds on startup recovery) if no message, title, archive, or fork ever touched them. - Attachment and terminal services:
Processstays in the serving surface because the launcher and reconnect paths useHealthandGetBootstrapbefore opening a session.Ptystays there because its bidirectionalStreamPtyand WebSocket frame contract require a streaming transport.BundleApiexposes unary invocations.
2. Blind Zero-Trust Relay (crates/hya-relay)
hya-relay (proto/hya/relay/v1) has zero dependency on runtime crates and splits remote access into three roles:
sequenceDiagram
participant TUI as Local TUI + Bridge<br/>(127.0.0.1:port + bridge token)
participant Proxy as Untrusted hya proxy<br/>(Stateless Room Map)
participant Host as Backend relay_host<br/>(inside hya serve)
Host->>Proxy: RegisterRoom (Ed25519 challenge signature + open_token hash)
TUI->>Proxy: OpenStream (room_id + HMAC open_token over gRPC or WS)
Proxy->>Host: Splice raw encrypted byte streams
TUI<<->>Host: Noise_NKpsk0_25519_ChaChaPoly_BLAKE2s handshake
TUI<<->>Host: Encrypted HTTP/1.1, SSE, PTY WS, or gRPC stream (Origin::Relay)
- Identity & Link (
hya://host/room?t=auto#x25519_pub.psk): Derived from<db>.relay-identity.json(0600).room_idisbase32(sha256(ed25519_pub))[..26]. Rotating the link (hya serve relay rotate) swapspskand updates the proxy’s open-token hash live, cutting off old links at the proxy before they even reach your machine. - Stateless
hya proxy: Verifies Ed25519 room ownership and HMAC open tokens, enforces room/stream/bandwidth caps, and splices ciphertext bytes over either HTTP/2 gRPC or WebSocket (t=autoprobes gRPC first and falls back to WebSocket behind proxies that strip trailers). - Loopback
hya bridge&Origin::Relay: The client bridge requires a random 256-bitx-hya-bridge-tokenon every local TCP connection so arbitrary local processes or web pages cannot hijack the tunnel. On the backend, decrypted requests carryOrigin::Relay, which blocks browserOrigin/Sec-Fetch-*headers,Process.DisposeProcess/UpgradeProcess, and loopback-onlyRelayControlRPCs.
3. OpenTUI Frontend (packages/hya-tui)
packages/hya-tui (Solid + @opentui/solid on Bun) is Hya’s sole interactive UI:
- Pure
hya.v2transport: BothHyaClient(HTTP/JSON+SSE under/v2/*) andGrpcHyaClient(src/proto/hya/v2/*.proto) speak exclusivelyhya.v2. Domain-specific endpoints (multi-agent roster/steer/archive, workflow listing/state/commands, channel inboxes) are never hardcoded inpackages/hya-tui; bundles invoke their own endpoints through confinedBundleApicalls. - Server projection is authoritative: The TUI never builds a competing state model from raw SSE tokens. Live
seq = 0deltas animate the active streaming block insrc/state/store.ts, while durable boundaries (messageFinished,sessionReverted,catalogUpdated,extensionEvent,resync) reconcile directly against/v2server projections (SessionInfo,SessionInfo.extensions, messages). - Minimal core panes + dynamic bundle pane dispatch:
src/state/panes.tsandsrc/components/paneRegistry.tsxrender only the five core panes (conversation,composer,activity,status,layout), delegate workspace slots (projects,sessions,todos,context,jobs) tohya/basic-tui-components, and dispatch all domain panes (hya/multi-agent#subagents,hya/multi-agent#subagent-viewer,hya/workflow#workflows, or third-party<bundleId>#<paneId>) generically via theextensionpane kind. - v2-only layout persistence: Saved
tui-state.jsonpaneLayouttrees strictly require schemaversion: 4(n-ary containers with core/bundled/extension leaf kinds). Legacy v1→v2tui.json/tui.tomlmigration lives exclusively incrates/hya-migration, never inpackages/hya-tui. - Hot supervisor reload: Bare
hyalaunchespackages/hya-tuiunder a tiny wrapper (src/supervisor.ts). Afterhya serve restart(or/reload-tui), the TUI restarts its own JS bundle in place while keeping your open session ID and unsent composer draft intact. - Confined TUI extensions: Bundle
tui:extensions (api_version: 2,sdk: "2.0.0") run in a separate child process (packages/hya-tui-sdk) inside QuickJS WebAssembly VMs (64 MiB cap, 2s call deadline) or trusted JSC realms, wrapped in Linux Landlock + seccomp or macOSsandbox_init. - Zero-bundle bare startup (
hya --bare): WhenGET /v2/tui-extensionsadvertises an empty catalog,ExtensionManager.settled()resolves immediately without waiting forhya/basic-tui-components.visiblePaneRootandstatusLineShowngracefully collapse unavailable bundled sidebar panes (projects,sessions,todos,context,jobs, andextensionpanes) back tochatPaneLayout()(conversation+activity+composer+ status line) with zero"Loading…"or missing-pane placeholders, while core overlays (ProviderView,McpView,SkillsView,BundlesView,RulesView,DiffView) remain operational.
4. Browser WebUI & PTY Host (packages/hya-tui-web)
packages/hya-tui-web is intentionally generic: it knows nothing about Hya’s domain logic.
- For each browser tab on
http://127.0.0.1:3250, it spawnsbun packages/hya-tui/src/main.ts ... --web-tabon a real OS PTY (Bun.spawn({ terminal })) and exchangesPtyClientFrame/PtyServerFrameWebSocket messages withxterm.jsin the browser. - Standard terminal escape sequences drive browser features naturally: OSC 0/2 sets
document.title, OSC 9/777 triggers deduplicated browser desktopNotifications when the tab is unfocused, OSC 52 copies text to the clipboard, and dropped/pasted files upload to a0700temp directory and paste their quoted local paths into the PTY.