# hx Minimal Rust coding agent. Uses your existing subscriptions, no API keys. ```sh nix run git+https://git.jokresner.de/johannes/hx # Nix: run directly (flake; also `nix profile install`) cargo build --release hx login claude # Claude Pro/Max hx login codex # ChatGPT Plus/Pro hx # interactive TUI hx -p "hello" # one-shot, Claude hx --provider codex -p "hello" # one-shot, Codex hx -c # continue last session in this directory hx -r # pick a session to resume hx -r parser # resume the session whose title best matches "parser" ``` TUI: `enter` send, `shift-enter`/`alt-enter`/`ctrl-j` newline (or end a line with `\` and press enter), `esc` abort, `ctrl-o` expand tool output. Shift-enter needs a terminal that reports it; hx turns on the kitty keyboard protocol when the terminal answers the probe. Works in ghostty, kitty, WezTerm (`enable_kitty_keyboard = true`), iTerm2, foot, Alacritty 0.13+, Windows Terminal (map shift-enter to `\u001b[13;2u`) and zellij 0.41+. tmux 3.2+ needs `set -g extended-keys on` and `set -g extended-keys-format csi-u`. Elsewhere use `alt-enter`, `ctrl-j` or a trailing `\`. `/keys` prints every key as hx receives it, to see what a terminal or multiplexer (e.g. herdr) passes through. Long input lines wrap; the box grows up to 10 rows. Scrolling (chat, side panel, agent view): mouse wheel (3 lines, targets the region under the pointer), `pgup`/`pgdn` half a page, `alt-pgup`/`alt-pgdn` a full page, `alt-↑`/`alt-↓` 3 lines, `ctrl-home`/`ctrl-end` top / back to the live bottom. A scrolled-up view stays put while new text streams in (footer shows `↑N` lines below); reaching the bottom or sending a prompt follows again. The wheel needs mouse capture, which disables plain terminal text selection (use shift-drag): turn it off with `mouse = false` in config or `HX_MOUSE=0`. `/help` lists commands: builtins (`/model`, `/provider`, `/compact`, `/clear`, `/lsp`, `/mcp`, `/skills`, `/new`, `/sessions`, `/resume`, `/usage`, `/quit`), MCP prompts (`/server:prompt`) and skills. Typing `/` opens a completion popup for commands and their arguments (`up`/`down` select, `tab`/`enter` accept, `esc` close); `tab` completes `@file` (mentioned files are attached). `ctrl-p` opens a picker over commands, skills, models and the 5 newest sessions. Models: the list comes from the provider (`/v1/models` for Claude, the Codex backend's model list), cached a day in `~/.hx/models-.json`, with a built-in list as fallback. Only logged-in providers are offered; the default provider is the configured one, else the first logged in. The context bar and auto-compaction follow the active model's window (e.g. 1M for Claude 5.x). Usage: once a response arrives, the footer shows subscription limits from the provider's headers: time windows with used % and time to reset (`5h 42%  2h13m · week 13%`) and, for credit billing, the credit balance or extra-usage state. `/usage` shows the details. Sessions: `/new` (or `/clear`) starts a new session file; the old one stays resumable. `/sessions` opens a full-screen picker with a preview: type to filter by title, `tab` toggles this project / all projects, `ctrl-d` deletes (asks first), `enter` resumes. The title (first prompt) shows in the footer and the terminal window title. Lens findings and affected-test results appear after each turn as a `┄ lens ┄` block. At 140+ columns, `/help`, `/skills`, `/lsp`, `/mcp` open in a side panel (`esc` closes). `NO_COLOR` disables colour, `HX_ASCII=1` uses ASCII symbols. Messages typed while the agent works are queued. Config: `~/.hx/config.toml`, overridden per project by `.hx/config.toml`. `hx config init [--project] [--force]` writes a fully commented sample with every key. Example: ```toml provider = "claude" # or "codex" # claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet # codex_model = "gpt-5.6-sol" # default: Codex's top-listed model # compact_at = 900000 # default: 90% of the model's context window max_tokens = 16384 # mouse = true # wheel scrolling; false keeps terminal text selection # codemode = false # add the `codemode` tool: JS scripts that call other tools in a sandbox # explore_model = "claude-haiku-4-5" # model for read-only `task` subagents; default: cheapest tier of the provider # system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended ## Sandbox: bash, LSP servers, lens and test runners run under bwrap (Linux) / sandbox-exec (macOS). ## Project dir + /tmp writable, $HOME hidden except `ro`/`rw`, filtered env (no API keys/tokens), no network. ## File tools (read/write/edit) obey the same paths. mode = "on" without a working backend refuses to start. # [sandbox] # mode = "off" # off | on (CLI: --sandbox / --no-sandbox; /sandbox toggles at runtime) # claude = true # false: claude (claude_cli provider) runs unconfined, no prompt # backend = "auto" # auto | bwrap | seatbelt # network = false # rw = ["~/.cargo/registry", "~/.cargo/git"] # extra writable paths # ro = ["~/.cargo", "~/.rustup", "~/.local", "~/.nvm", "~/.npm"] # readable parts of $HOME # env_allow = ["PATH", "HOME", "TERM", "LC_*", "CARGO_*"] # trailing * = prefix [lsp] mode = "turn_end" # turn_end | agent_end | off disable = ["clangd"] enable_runners = ["clippy"] # opt-in (slow): clippy disable_runners = ["rustfmt"] # any of: ruff, biome, eslint, ast-grep, rustfmt, ruff-format, biome-format tests = "turn_end" # affected tests: turn_end | agent_end | off # [[lsp.servers]] # add or override (same id replaces built-in) # id = "zls" # language = "zig" # extensions = ["zig"] # command = ["zls"] # roots = ["build.zig"] # install = ["brew", "install", "zls"] # offered by the lsp tool when `zls` is missing ``` ## Auto model `/model auto` (or `model = "auto"`, `--model auto`) picks model and thinking level for every prompt, across all logged-in providers; `/model ` or `/provider` turns it off. No extra LLM call: the prompt is scored from cheap signals (length, keywords like `refactor`/`race condition` vs. `typo`/`explain`, a stack trace, a failed tool result in the last turn, a long session) into a tier: `fast` (Haiku/Luna), `balanced` (Sonnet/Terra), `deep` (Opus/Sol). Stepping up is immediate, stepping down needs `down_after` (default 3) light prompts in a row, because every switch costs the prompt cache. Very short replies ("ja", "continue") keep the current tier. The provider stays unless the other one has the tier exactly or the current one reported a used-up quota window. Each choice and its reason is shown as a line in the chat; the footer shows `auto→model`. One-turn override, with or without auto: start the prompt with `@opus fix this`, `@codex ...`, `@fast ...`, `@deep ...` or `@` (any unique part of an id, 3+ chars). A file with that name wins, so `@notes.md` stays a file mention. The previous model comes back after the turn (in auto mode, the router just chooses again). Switching provider mid-session converts history: Codex reasoning items and unsigned thinking are dropped for Claude, tool-call ids are made Anthropic-safe. `hx stats` lists requests per model and the cache re-written after each switch. ```toml [auto] # all optional fast = "claude-haiku-4-5" deep = "gpt-5.6-sol" # pins can name another provider's model down_after = 3 ``` ## Subagents Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt; `read` and read-only `bash` (`ls cat head tail wc grep rg fd pwd echo stat file du df which tree diff`, `git status|log|diff|show|branch|blame|ls-files|rev-parse`) run freely, unless chained/redirected or a path looks secret (`.env*`, `.ssh/`, `.aws/`, `*.pem`, `*.key`, `id_rsa*`, `.netrc`, `.git-credentials`, `auth.json`), which asks first. `--yolo` skips all prompts; `/yolo` toggles it live (also while a turn runs), `!` on a permission prompt allows it and turns yolo on. The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet. A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens. ## Skills Skills are `//SKILL.md` files with YAML frontmatter (`name`, `description`, `load`, `disable-model-invocation`, `argument-hint`; other keys such as `license` are ignored, `>` / `|` block descriptions work). Name and full description go into the system prompt; the model loads the body with the `skill` tool (output: `Base directory for this skill: ` + body without frontmatter). Looked up in `~/.claude/skills`, `~/.agents/skills` (shared with other agents), `~/.hx/skills`, then `.agents/skills`, `.claude/skills` and `.hx/skills` in the project; a later directory wins when names collide. `/skills` lists what loaded, the searched dirs, and skills skipped for invalid YAML (quote descriptions that contain `: `). A `load:` frontmatter key sets when a skill reaches the model: `auto` (default, listed by description, so write it as "use when ..."), `always` (body inlined in the system prompt every turn) or `manual`. `disable-model-invocation: true` (alias: `load: manual`) keeps a skill out of the prompt and refuses it in the `skill` tool; only `/` runs it. Each skill is also a command: `/ [args]` sends the skill body (frontmatter stripped, base directory line first) plus `args` as the prompt; `argument-hint` shows next to the name in `/` completion and `/help`. Builtin commands win when names collide. ## Memory The agent keeps notes across sessions with `memory_write` / `memory_forget`. `MEMORY.md` (one hook line per topic, max 50) is in the system prompt; the full text lives in `topics/.md` and is read on demand. Global: `~/.hx/memory/`, project: `.hx/memory/` (add it to `.gitignore`). The index is read at session start, so new entries show up next session. `hx prefix` shows its size. ## Lens After every tool round, hx asks the language server about files the agent wrote or edited and appends errors/warnings to the next request, so the model fixes them without being told. Built in: rust-analyzer, typescript-language-server, pyright, gopls, clangd (used when on `PATH`). The `lsp` tool gives the model diagnostics, definition, references, hover and symbols on demand. If the language server for a file is missing, the `lsp` tool asks you (`[y/n]` in the footer) whether to install it, once per server per session: `rustup component add rust-analyzer`, `npm install -g typescript-language-server typescript`, `npm install -g pyright`, `go install golang.org/x/tools/gopls@latest` (only offered when the installer is on `PATH`; clangd is manual). Custom servers can set `install = ["cmd", "args"]`. Print mode never installs. `/lsp` in the TUI shows server status, missing tools and triage marks. Besides the language server, changed files go through (when installed and the project uses them): ruff (Python), biome (with `biome.json`), eslint (with an eslint config), ast-grep (rules in `.hx/rules/*.yml`), and clippy (opt-in). Formatters run only when configured for the project (`rustfmt.toml`, `ruff.toml`, `biome.json`); their changes don't trip the read-guard. Files edited outside hx are picked up at the next turn. `diag_mark` lets the model silence a finding (`false_positive` = forever, `defer` = until the file changes), stored in `~/.hx/projects//triage.json`. Runner timings go to `~/.hx/latency.log`. Affected tests run after each tool round that changed files; only failures are injected (plus one "all pass now" notice after they're fixed). Supported: cargo, pytest, vitest, jest, `go test`. Selection is a heuristic: Rust runs the changed crate and crates depending on it; Go the changed package and importers; Python/JS the test files that are changed or import a changed file (up to 3 hops). Rust/Go therefore over-select (whole crates/packages); dynamic imports, fixtures and data files are not tracked. Existing Claude Code (`~/.claude/.credentials.json`) and Codex CLI (`~/.codex/auth.json`) logins are picked up automatically. Credentials are stored in `~/.hx/auth.json` (mode 0600) and refreshed automatically. On a headless box, open the printed URL elsewhere and paste the final redirect URL back into the terminal. ## MCP Servers come from `~/.hx/mcp.json` and `.hx/mcp.json` (project entries replace global ones with the same name), in the Claude Code `mcpServers` shape. `${VAR}` and `${VAR:-default}` are expanded. ```json {"mcpServers": { "fs": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "${HOME}/src"]}, "web": {"type": "http", "url": "https://example.com/mcp", "headers": {"Authorization": "Bearer ${TOKEN}"}, "allow": ["search"], "eager": true, "timeoutSecs": 30} }} ``` Transports: stdio and streamable HTTP (static headers, or OAuth). hx extras: `allow` (tool allowlist), `eager`, `timeoutSecs` (per call, default 60), `disabled`. Output is capped at 30k chars; a crashed stdio server is restarted on the next call (at most 3 times). OAuth (HTTP servers without an `Authorization` header): `hx mcp login ` discovers the auth server (RFC 9728/8414), registers dynamically (RFC 7591), runs PKCE in the browser (URL printed; redirect on a random localhost port, or paste the redirect URL) and stores tokens in `~/.hx/mcp-auth.json` (0600). Tokens refresh on 401. `hx mcp logout ` forgets them. Servers without dynamic registration: `"oauth": {"clientId": "…", "clientSecret": "…", "scope": "…", "callbackPort": 8123}`. A server needing login shows `(run hx mcp login …)` in `/mcp`. Lazy by default: the system prompt carries one line per tool (`server.tool: description`); the model gets the schema with `mcp_describe` and calls through `mcp_call` (arguments are checked against the cached schema). Servers whose full schemas cost at most ~400 tokens are registered as native tools instead (`server__tool`); `eager: true|false` overrides. Resources are listed in the prompt and read with `mcp_read`; prompts become slash commands (`/server:prompt args`). `/mcp` in the TUI and `hx mcp` show tools and token costs. Measured (`hx mcp`, bytes/4): | server | tools | lazy index | eager schemas | |-------------|------:|-----------:|--------------:| | context7 | 2 | ~63 tok | ~1147 tok | | everything | 13 | ~319 tok | ~1235 tok | | filesystem | 14 | ~453 tok | ~1996 tok | | playwright | 25 | ~537 tok | ~4397 tok | Lazy costs one extra round trip (`mcp_describe`) per tool on first use in a session. Since tool count is a poor proxy (context7: 2 tools, 1.1k tokens), the eager rule is schema size, not count. `hx mcp-serve` runs hx as a stdio MCP server exposing the `lsp` tool (diagnostics, definition, references, hover, symbols) to other clients. ## Herdr Inside a [herdr](https://herdr.dev) pane (`HERDR_ENV=1`) hx reports `idle` / `working` / `blocked` (permission, ask and choose prompts) to the sidebar, `herdr agent list` and `herdr agent wait`. It also reports `hx --session ` as resume command, so a herdr server restart reopens the same session, and releases the pane on quit. Outside herdr nothing happens. ## Machine interfaces ### Event stream (`hx -p "..." --mode json`) One JSON object per line on stdout. `type` is one of: | type | fields | |---|---| | `session_start`, `turn_start`, `turn_end`, `agent_end` | none | | `stream` | `event`: `{type: "text_delta", text}` · `{type: "thinking_delta", text}` · `{type: "tool_use_start", id, name}` · `{type: "done", message, stop, usage}` | | `message` | `message`: `{role, content: [{type: "text", text} \| {type: "tool_use", id, name, input} \| {type: "tool_result", tool_use_id, content, is_error}]}` | | `tool_call` | `id`, `name`, `args` | | `tool_result` | `id`, `name`, `args`, `content`, `is_error` (blocked calls: `is_error: true`, content `blocked: `) | | `info` | `text` | | `sub_usage` | `usage`: tokens spent by `task` subagents in the tools just run (already in the session total) | | `injected` | `texts`: hook reports added to the conversation at turn end (lens diagnostics, affected tests) | | `done` (last line) | `error` (null on success), `usage`, `session` | ### RPC (`hx --mode rpc`) JSON-RPC 2.0, one message per line on stdin/stdout. Events arrive as `event` notifications (params = the event object above). Methods: `prompt {text}` (replies `{message, usage}` when the run ends), `abort`, `state`, `messages`, `fork {id}`, `clear` (alias of `new`: new session file next to the current one), `set_model {model}`, `compact`, `complete {line, cursor?}` (replies `{start, items: [{label, detail}]}`; `label` replaces `line[start..cursor]`, cursor is a byte offset defaulting to the end). One prompt at a time; other methods are rejected while it runs (except `abort` and `complete`). Sessions: `sessions {scope?: "project"|"all"}` (path, title, messages, model, branches, project, modified), `new`, `resume {path}`; `state` includes `title`. Example client: `examples/rpc_client.py`. ### Extensions ```toml # ~/.hx/config.toml or .hx/config.toml (lists are concatenated) [[extensions]] command = ["python3", "/path/to/ext_guard.py", "rm -rf"] timeout_secs = 10 ``` An extension is a process speaking JSON-RPC over stdio. hx sends `initialize {protocolVersion, cwd}`; the reply `{subscribe: ["tool_call", ...] | ["*"], tools: [{name, description, inputSchema}]}` picks events and registers tools. Each subscribed event is sent as `event {event}`; reply `{action: "continue"}`, `{action: "block", reason}` (tool_call), `{action: "mutate", args}` (tool_call) or `{action: "inject", text}` (turn_end / agent_end). Tools are called as `tool/call {name, args}` -> `{content, is_error}`. Errors and timeouts count as `continue`; extensions run before the lens. Sample: `examples/ext_guard.py`.