Herdr2 Architecture and Implementation Deep Dive
An in-depth look at Herdr2's dual-plane hybrid runtime, binary multiplexing protocol, headless ACP engine, and cross-machine federation engineering.
This document provides a comprehensive engineering breakdown of Herdr2 (herdr-core/crates/herdr2 + herdr-app), covering its design decisions, Core dual-plane state machine, headless ACP engine, Ghostty/PTY human workspace recovery, cross-machine federation, and the Linux → Windows cross-compilation pipeline.
1. Overall Layered Architecture: Dual-Plane Isolation (PTY Workspace + Headless ACP Sub-Agents)
Section titled “1. Overall Layered Architecture: Dual-Plane Isolation (PTY Workspace + Headless ACP Sub-Agents)”During Herdr2’s architectural evolution, a pure-headless prototype replaced the desktop UI entirely with fixed chat panels and removed interactive terminals—making it impossible to open a shell or run interactive CLIs directly in the workspace. The finalized Herdr2 Hybrid Architecture establishes two cleanly separated planes within a single daemon and desktop framework:
- Human Workspace Plane (PTY/ConPTY +
libghostty-vt): Serves interactive terminals, shells, and interactive CLIs (addressed ast1,t2, …). Each terminal runs inside a persistentholdersubprocess, while the desktop client renders hardware-accelerated text grids and full keyboard/mouse encoding viaghostty-sys. - Background Sub-Agent Plane (Headless ACP over stdio NDJSON): Serves autonomous collaborative sub-agents spawned by a primary agent or human terminal (addressed as
a1,a2, …). They allocate no PTY/ConPTY, expose no terminal or filesystem capabilities, open no popups or screen panes, and are driven over strongly typed JSON-RPC 2.0 with a built-in MCP feedback loop.
2. Core Dual-Plane Runtime (herdr-core/crates/herdr2)
Section titled “2. Core Dual-Plane Runtime (herdr-core/crates/herdr2)”2.1 Unified Addressing Key and Separate Registries (runtime.rs, runtime/pty.rs)
Section titled “2.1 Unified Addressing Key and Separate Registries (runtime.rs, runtime/pty.rs)”To allow the same state machine, wait queues, event subscriptions, parent-child notifications, and cross-machine federation to operate uniformly without cross-contamination, Core enforces explicit type-level isolation:
TargetKey::{Agent(u32), Terminal(u32)}(runtime.rs): Parsesa*andt*addresses as a unified index key acrosswaiting,notes, notification queues, anddie_with_parentmappings.- Dual Registry Persistence:
State.reg(agents.json) +transcripts/<addr>.jsonl: Persists all headless ACP agent records and structured conversation histories.State.pty_reg(terminals.json) +holderprocess links (Link): Persists interactive workspace terminals,screens(server-sideghostty_vt::Terminalmirrors), and window state.
- Strict API Separation and Name Deduplication:
api/pty.rsservesterminal.*(14 methods:terminal.run,terminal.list,terminal.get,terminal.kill,terminal.rm,terminal.keep,terminal.label,terminal.read,terminal.attach,terminal.send,terminal.wait,terminal.keys,terminal.interrupt,terminal.put).api/run.rsandapi.rsserveagent.*.- Neither registry allows claiming a
--namealias currently held by a live (is_live()) entry in the other registry within the same session, keepingh2 get <name>andh2 read <name>unambiguous. - When
agent.{rm,read,send,interrupt,put}receives unified CLI addresses or legacy frontend requests, it resolves theTargetKeyviaresolve_anyand dispatches accurately to either theagentorptyhandler; meanwhile,terminal.listandagent.listremain strictly isolated and never leak into one another.
2.2 Binary Multiplexing Protocol and Flow Control (wire.rs, viewers.rs)
Section titled “2.2 Binary Multiplexing Protocol and Flow Control (wire.rs, viewers.rs)”Clients connect to Core over a Unix Domain Socket ($XDG_RUNTIME_DIR/herdr2/<session>.sock), Windows Named Pipe, or SSH stdio. The handshake begins as plaintext NDJSON; once "hello" includes framed: true and Core acknowledges it (server.rs), the connection switches to a 9-byte little-endian binary framing protocol (wire::HEADER = 9, MAX_PAYLOAD = 16 MiB):
0 1 2 3 4 5 6 7 8 9 ... 9+len+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+-------+| channel (u32 LE) | k | len (u32 LE) | payload |+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+-------+ ^ kind: 0=DATA, 1=CREDIT, 2=CLOSE, 3=RESIZE, 4=FOCUS, 5=FACTS, 6=AUTOMATIC_INPUT- Channel
0(JSON-RPC 2.0 Control Channel): Carries RPC requests and responses with a backlog ceiling ofMAX_CONTROL = 64 MiB. - Channel
N > 0(Event Streams and Live Terminal Screen Views):events.subscribeallocates a dedicated channel broadcastingagents/terminalsstate snapshots and incremental deltas, ACPtranscriptentries, anddocupdate notifications. Memory is bounded by a 256 KiB sliding credit window (CREDIT) and aMAX_PENDING = 4 MiBmissedresync mechanism.terminal.attach(used by both desktop panes and CLIh2 attach) uses an independent channel for bidirectional VT output snapshots/byte streams, viewport size changes (RESIZE), focus synchronization (FOCUS), theme/font metrics (FACTS), and automatic terminal response suppression (AUTOMATIC_INPUT). When multiple clients view the same terminal simultaneously,foreground.rsandviewers.rsarbitrate foreground dimensions so a smaller background window does not steal viewport resolution.
2.3 Workspace PTY and Environment Setup (api/pty.rs, holder.rs, runtime/pty.rs)
Section titled “2.3 Workspace PTY and Environment Setup (api/pty.rs, holder.rs, runtime/pty.rs)”Whenever the desktop client creates a Space, Tab, or Split:
terminal_envinjectsH2_TERMINAL_ID=t*,H2_TERMINAL_SOCKET=<socket>, an isolation scope token (sweep::VAR), and the initial working directoryPWD.pty_child_envstripsIDENTITY_VARS(H2_AGENT_ID,H2_AGENT_SOCKET,H2_TERMINAL_ID,H2_TERMINAL_SOCKET), re-injects the terminal identity, and setsTERM=xterm-256color,COLORTERM=truecolor, andTERM_PROGRAM=ghostty.- A framed spawn request (
holder_proto::SPAWN) instructs the residentholdersubprocess to spawn a PTY/ConPTY (on Windows, backed by bundledprograms/h2/conpty/{conpty.dll, x64/OpenConsole.exe}). All raw terminal output streams back into the server-sideghostty_vt::Terminal(tracking cursor, title, state, and snapshots) and fans out to all subscribed frontends.
2.4 Headless ACP Engine and Strict Capability Masking (acp/*, api/run.rs)
Section titled “2.4 Headless ACP Engine and Strict Capability Masking (acp/*, api/run.rs)”Calls through h2 run, the built-in h2_run MCP tool, or agent.run follow a completely separate ACP path:
- Zero-Terminal Process Environment (
api/run.rs):child_envstrips anyTERMINAL_VARSinherited from the host shell (TERM,COLORTERM,TERM_PROGRAM,TERM_PROGRAM_VERSION) along withH2_TERMINAL_*, retaining only the runtime identity variablesH2_AGENT_ID,H2_AGENT_SOCKET, andH2_SESSION. - Protocol Handshake Masking and Capability Negotiation (
acp/proto.rs): SendsInitializeParams::herdr2()explicitly declaringClientCapabilities::headless():fs: { readTextFile: false, writeTextFile: false },terminal: false(strictly terminal-free).session.configOptions.boolean: {}: Declares support for real-time boolean and enum configuration negotiation with compatible adapters (such asmodel,reasoning_effort/thought_level,fast-mode,mode, andcollaboration_mode), while retaining legacymodels/modesfallback parsing and liveagent.config/h2 configoverrides (synchronized via"config"subscription events and reapplied during--keepsession/load;agent.liststays compact whileagent.getand"config"events carry the fullconfig_options).
- Three-Task Async Transport (
acp/transport.rs): Uses asynchronous piped stdin/stdout/stderr withHANDSHAKE_TIMEOUT = 30s, retains the last64lines ofstderr(up to512bytes per line) for precise handshake failure diagnostics, and attaches a platformAgentGuardto prevent orphaned child processes. - Automatic Built-In MCP Injection and Schema Fallback (
acp/mod.rs): Wheninject_mcpis enabled,session/newandsession/loadautomatically inject{ type: "stdio", name: "herdr2", command: <self_exe>, args: ["mcp"], env: ... }. If an older adapter rejects the payload with-32602, Core automatically strips"type"and retries. Model selection preferssession/set_config_optionand falls back tosession/set_modelon-32601.
2.5 Serial Inbox, --steer Preemption, Transcripts, and Permission Arbitration
Section titled “2.5 Serial Inbox, --steer Preemption, Transcripts, and Permission Arbitration”- Serial Inbox State Machine (
acp/mod.rs): Each ACP session uses a single actor to consume queued prompts (QueuedPrompt). Only onesession/promptexecutes at a time per session, eliminating concurrent out-of-order turns. Passing--steerinserts the new prompt at the head of the queue and sendsSessionCommand::Steer→ ACPsession/cancelto stop the current turn at a clean boundary before immediately popping and running the front item. - Strongly Typed 8-Kind Transcript (
transcript.rs): DefinesEntry::{User, Thought, Assistant, ToolCall, Plan, Permission, Error, Stderr}(bounded in memory byMAX_ENTRIES = 2000/MAX_BYTES = 2 MiBand persisted to disk as JSONL), pushed in real time overevents.subscribe. - Permission State Machine (
permissions.rs):PermissionModesupportsApproveAll,ApproveReads(default: automatically approves read-only operations such asread/search/think/fetch/list/glob/grep, while suspending write/exec requests in theblockedstate and exposingPendingPermissionoptions to upstreamapprove/deny),DenyAll, andAsk.
2.6 Hybrid Parent-Child Orchestration (mcp.rs, notes.rs, api/waiting.rs)
Section titled “2.6 Hybrid Parent-Child Orchestration (mcp.rs, notes.rs, api/waiting.rs)”- Adaptive Caller Identity Detection (
mcp.rs:148&api/run.rs): Bothh2 mcpand theh2CLI useclient::agent_id().or_else(client::terminal_id)to detect automatically whether the caller is a background ACP agent (a*) or a desktop human workspace terminal (t*). - Hybrid Parent-Child Trees and Notification Delivery (
notes.rs):a*→a*: Child status notifications are queued directly into the parent agent’s inbox wrapped in an<h2 from="...">envelope.t*→a*: When a headless sub-agent spawned by a human workspace terminal hits a permission block, error, or exit, notifications are safely pasted into the parent terminal viapty_input(respectingnotes_quietquiet-window delays anddraft_waitinput-draft backoff, or immediately waking an activeh2 wait --childreninvocation).- Closing desktop terminal pane
t*triggersJob::Orphaned(TargetKey::Terminal(id)), automatically cleaning up all descendant ACP sub-agents not marked--outlive-parent.
3. Native Desktop Client (herdr2 App / herdr-app) Implementation
Section titled “3. Native Desktop Client (herdr2 App / herdr-app) Implementation”3.1 ghostty-sys + GPUI Hardware-Accelerated Workspace Views
Section titled “3.1 ghostty-sys + GPUI Hardware-Accelerated Workspace Views”While renamed to herdr2 (0.2.0) with full side-by-side isolation, herdr-app preserves the battle-tested native desktop experience:
crates/ghostty-sysandsrc/vt.rs: Statically linkslibghostty-vtwithbindgen-generated FFI bindings. Each frontendTerminalViewmaintains a locallibghostty-vtstate machine synchronized with Core (consuming Channel N incremental screen bytes and resize feedback), while GPUI handles ligatures, adaptive color contrast (minimum_contrast), smooth scrolling, and keyboard/mouse encoding.- Unified Entry Points and Full-Permission Launches (
defaults/mods/new-menu/main.js,defaults/programs.json,src/window.rs): The+menu keepsTerminalalongside automatic path discovery for dozens of preconfigured local CLIs. Built-in coding agents (claude,codex,opencode,cursor,copilot,amp,agy,kimi,kiro,hermes,qoder,crush,gemini, etc.) launch with full-permission flags inside real PTYs viaCore::run(terminal.run). On Windows,powershell_argv/agent_argvautomatically include-ExecutionPolicy Bypassso.ps1shims execute cleanly, andprograms.rsdetects both generic PowerShell wrappers andshell_child_seentransitions soagent: falseis restored accurately once the child CLI exits back to the shell prompt. - Dual-Channel
AgentsSidebar, Non-7501 State Inference, and Synchronized Cleanup (src/hc.rs,src/terminal.rs,src/window.rs,defaults/mods/agents/main.js,defaults/mods/peek/main.js):- Dual Event Consumption:
EventLinesconsumes both"terminals"and"agents"snapshots and incremental events fromevents.subscribe(includingstatus,pending_permission,inbox_len,transcript, andlabels) and normalizes cross-machineparentaddresses uniformly across both planes. - Non-OSC-7501 State Machine:
OSC 7501(reported == true) retains top priority. When an interactive agent does not emit7501andprogram.agent == true,TerminalView::inferred_agent_state+infer_pty_agent_stateinspects, in order: raw title indicators/spinners (raw_titlepreserves pre-stripped glyphs) → live PTY output activity (last_output_at, filtering attach replays and short keystroke echoes) → trailing interactive approval prompts (Vt::tail_lines(6)), updating working/blocked/idle state everytend_terminalstick (≤500 ms) and driving the unfocuseddonestate. - Headless ACP Integration, T3 Code Conversation Overlay, Live Capability Bar, and Workspace Tab Mounting:
window.rsroutes headlessa*addresses viais_acp_addr(pin/seen writes toagent.label, kill writes toagent.kill, state/config changes flow throughhc.rs::EventLines). Clicking an ACP row invokesterminal.peekto open a large frameless conversation overlay (width: 0.86,height: 0.88,frame: "none"). Runningterminal.keepor clicking↗ Open as TabpersistsContent::Mod { mod: "peek", props: { acp: true, tab: true, terminal } }into the Space’s shared Tab tree vialayout.rs(Node::acp_terminal/Node::any_terminal),mirror.rs(cross-machine prefix mapping),model.rs(any_address_of/acp_pane_of), andwindow.rs, simultaneously closing the overlay and deduplicatingheadless_agents. Callingterminal.parkor clicking↙ Background(or the tab context menu’s"Detach to background") unmounts the tab while keeping the background session alive. On the frontend,defaults/mods/peek/acp_model.jsanddefaults/mods/peek/main.jscallh2 read --json <agent>andh2 get --json <agent>to render work logs, Markdown code cards, inlinepending_permissionapproval controls, theTextareaStatecomposer bar, and a bottom capability strip with live search/custom-value dropdowns and toggles (backed byh2 config --json). Hovering parent or child rows in theAgentssidebar reveals an✕remove button (pane.closeorterminal.kill);space.closematches owned ACP sessions viaspace_folderswith multi-space deduplication, andkill()filtersclosing_terminalsalongside immediatepublish_terminals/syncfor same-frame visual and process teardown.
- Dual Event Consumption:
- Core Connection and Shared Layout (
src/hc.rs,src/mirror_sync.rs,src/control.rs): The desktop client connects to the daemon via$LOCALAPPDATA/Programs/h2/h2.exeor~/.local/bin/h2, persists the Space/Tab/Pane layout tree under Core document key"herdr2-app", and servesherdr2 ls/status/do/shotcontrol commands over$HERDR2_APP_HOME/herdr2-app.sock(HERDR2_APP_HOMEdefaults to~/.config/herdr2-app).
4. Key Engineering Breakthroughs in Linux → Windows Cross-Compilation
Section titled “4. Key Engineering Breakthroughs in Linux → Windows Cross-Compilation”Native Windows x86_64-pc-windows-msvc release builds—combining Rust, Direct3D 11, QuickJS, Zig 0.16, and libghostty-vt (mixed C/C++/Zig compilation)—are cross-compiled directly from a Linux / WSL2 host:
- Explicit MSVC
--libcForwarding for Zigtranslate-c:cargo-xwinmounts the MSVC CRT (crt/include,crt/lib/x86_64) and Windows SDK UCRT/UM (sdk/include/ucrt,sdk/lib/{ucrt,um}/x86_64) under~/.cache/cargo-xwin/xwin/.- In Ghostty’s
pkg/wuffs/build.zig, whentarget.os.tag == .windowsenables.link_libc = true, standard ZigCompilesteps inheritzig build --libc <file>, but upstreamtranslate_c.initfailed to forwardb.libc_fileto thetranslate-cchild step (causing'stdlib.h' not found). Patchingvendor/ghostty/pkg/wuffs/build.zigin both repositories to forward.libc_file = if (b.libc_file) |p| .{ .direct = .{ .cwd_relative = p } } else .detect_darwin,allowssimdutf,highway,wuffs_c, andghostty-vtto compile and link cleanly on the first pass under-Dcpu=baseline.
- GPUI Direct3D 11 Runtime HLSL Compilation (
vendor/gpui-pre-windows):- Release builds bypass native Windows
fxc.exeby injecting thegpui_runtime_d3dcompilecfg flag inbuild.rs. At startup, GPUI invokes Windows’s built-inD3DCompile(d3dcompiler_47.dll,D3DCOMPILE_OPTIMIZATION_LEVEL3) in memory to compile embedded HLSL shaders on the fly.
- Release builds bypass native Windows
- Bundled ConPTY Runtime and Process Guard:
- Compatible
conpty.dllandx64/OpenConsole.exebinaries are bundled underPrograms/h2/conpty/, ensuringpowershell.exeand other interactive terminals spawn reliably across Windows 10/11 regardless of the system ConPTY version while injectingH2_TERMINAL_IDinto child processes.
- Compatible
5. Side-by-Side Isolation Matrix
Section titled “5. Side-by-Side Isolation Matrix”| Isolation Boundary | Original Herdr | Herdr2 |
|---|---|---|
| Core binary & CLI name | herdr-core / hc |
herdr2 / h2 (Windows includes h2.exe & herdr2-core.exe) |
| Desktop binary & window title | herdr-app / "Herdr" |
herdr2 (includes herdr2-app.exe) / "Herdr2" |
| Core version negotiation prefix | "hc " |
"h2 " |
| Core environment variable prefix | HC_* (HC_SESSION, HC_AGENT_ID, HC_TERMINAL_ID, HC_SOCKET) |
H2_* (H2_SESSION, H2_AGENT_ID, H2_TERMINAL_ID, H2_SOCKET) |
| App environment variable prefix | HERDR_APP_HOME, HERDR_TEST_WINDOW, HERDR_TELEMETRY |
HERDR2_APP_HOME, HERDR2_TEST_WINDOW, HERDR2_APP_ID, HERDR2_TELEMETRY |
| Local control socket | ~/.config/herdr-app/herdr-app.sock |
~/.config/herdr2-app/herdr2-app.sock |
| Core layout sync document key | "herdr-app" |
"herdr2-app" |
| Core runtime state directory | ~/.local/state/herdr-core/ / %LOCALAPPDATA%\herdr-core\ |
~/.local/state/herdr2/ / %LOCALAPPDATA%\herdr2\ |