Files
hx/README.md
T

228 lines
16 KiB
Markdown

# 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-<provider>.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
[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
```
## 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.
The model can call `task(prompt, kind)` 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 `<session>.sub/`; `hx stats` 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 `<dir>/<name>/SKILL.md` files with `name:` / `description:` frontmatter. Only the name and
description go into the system prompt; the model reads the file when a task matches. Looked up in
`~/.agents/skills` (shared with other agents), `~/.hx/skills`, then `.agents/skills` and `.hx/skills` in
the project; a later directory wins when names collide. `/skills` lists what loaded and the searched dirs.
A `load:` frontmatter key sets when a skill reaches the model: `auto` (default, listed by description; the
model reads it when the task matches, so write the description as "use when ..."), `always` (body inlined in
the system prompt every turn) or `manual` (only via `/<name>`, never mentioned to the model).
Each skill is also a command: `/<name> [args]` sends the skill file plus `args` as the prompt. 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/<slug>.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/<project>/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 <name>` 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 <name>` 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 <file>` 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: <reason>`) |
| `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`, `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`.