26 Commits
Author SHA1 Message Date
johannesandClaude Opus 5.5 fe6811540a ci: allow manual build runs
build / version (push) Successful in 7s
build / build (aarch64-apple-darwin) (push) Successful in 5m39s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m5s
build / release (push) Successful in 20s
The previous commit mentioned the skip marker in its body, so Gitea
skipped it; this one triggers the build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:36:15 +01:00
johannesandClaude Opus 5.5 10b2ccf60a nix: use release binaries as default package
The release job records the tarball hashes in bin.json and commits it
([skip ci]); flake.nix fetches the binary from the release on
x86_64-linux and aarch64-darwin and builds from source elsewhere.
Drop x86_64-darwin, nixpkgs no longer evaluates it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:33:03 +01:00
johannes d0f23421cd ci: add build caching
ci / check (push) Canceled after 0s
build / version (push) Successful in 6s
build / build (aarch64-apple-darwin) (push) Successful in 5m16s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m58s
build / release (push) Successful in 12s
2026-11-02 15:37:13 +01:00
johannes ee5d8371d0 ci: add release step
build / version (push) Successful in 6s
build / build (aarch64-apple-darwin) (push) Successful in 5m13s
build / release (push) Canceled after 0s
build / build (x86_64-unknown-linux-musl) (push) Canceled after 2m59s
2026-11-02 15:34:35 +01:00
johannes 926bcbf978 ci: add build pipeline
build / build (aarch64-apple-darwin) (push) Successful in 5m48s
build / build (x86_64-unknown-linux-gnu) (push) Successful in 3m40s
2026-11-02 15:08:21 +01:00
hermes 4161095d4d Merge pull request 'sandbox: runtime /sandbox toggle + sandbox.claude option' (#175) from feat/sandbox-toggle into main 2026-11-02 12:29:30 +00:00
hermes a0cd7946c3 sandbox: runtime /sandbox toggle, sandbox.claude config, --no-claude-sandbox 2026-11-02 12:28:52 +00:00
hermes d1bfa22580 Merge pull request 'tui: path completion for ~/ / ./ ../' (#174) from feat/path-completion into main 2026-11-02 10:59:03 +00:00
hermes 0b97958bd8 tui: live path completion for ~/ / ./ ../ tokens, @~ mentions 2026-11-02 10:58:35 +00:00
hermes 15a5034709 Merge pull request 'auto model selection + @override per turn' (#173) from feat/auto-model into main 2026-10-26 21:53:37 +00:00
hermes b8fc96a3d2 auto model: per-prompt model/effort routing across providers, @override per turn 2026-10-26 21:52:50 +00:00
hermes f1343295d4 Merge pull request 'tui: ask popup own answer wraps and grows' (#172) from fix/ask-input-wrap into main 2026-10-22 19:19:41 +00:00
hermes 19937d0063 tui: ask popup own answer wraps, grows, supports paste/newline/ctrl-w 2026-10-22 19:16:37 +00:00
hermes e96f4a6cb8 Merge pull request 'claude_cli: show subscription usage' (#171) from feat/claude-cli-usage into main 2026-10-19 13:51:54 +00:00
hermes e05f443e52 claude_cli: map rate_limit_event to Quota (statusbar and /usage) 2026-10-19 13:51:37 +00:00
hermes 28c3d79286 Merge pull request 'tui: yolo while a prompt is running' (#170) from feat/yolo-while-busy into main 2026-10-17 13:54:48 +00:00
hermes 5171e7458a tui: /yolo works while a turn runs; '!' on permission prompt allows and enables yolo 2026-10-17 13:52:39 +00:00
hermes 94f2b15f9d Merge pull request 'claude_cli: fix >100% context bar (usage summed over internal requests)' (#169) from fix/claude-cli-ctx-usage into main 2026-10-17 13:37:06 +00:00
hermes da78581712 claude_cli: report last request usage as context size, not the summed result 2026-10-17 13:36:32 +00:00
hermes 43944eb6b5 Merge pull request 'claude_cli: show thinking text (--thinking-display summarized)' (#168) from fix/claude-cli-empty-thinking into main 2026-10-17 10:21:55 +00:00
hermes ca819f8c90 claude_cli: request summarized thinking, skip empty thinking deltas
claude -p defaults to thinking display 'omitted' on new models, so the
thinking text was empty and the TUI showed 'thought · 0 words'. Pass
--thinking-display summarized (verified on claude 2.1.295) and drop empty
deltas.
2026-10-17 09:45:20 +00:00
hermes d69c56b3c8 Merge pull request 'claude_cli: codemode for claude' (#167) from feat/claude-cli-codemode into main 2026-10-16 20:44:24 +00:00
hermes c7b25a1848 Merge pull request 'claude_cli: show what each claude tool runs' (#166) from fix/claude-cli-tool-detail into main 2026-10-16 20:44:20 +00:00
hermes fdeaaf5cf2 claude_cli: offer codemode to claude (codemode = true), hx tools inside it ask via the permission bridge 2026-10-16 20:42:10 +00:00
hermes acdb4fcf0d clippy 2026-10-16 20:37:11 +00:00
hermes 15b037ceca claude_cli: show the command/path of each claude tool call 2026-10-16 20:36:47 +00:00
24 changed files with 1969 additions and 142 deletions

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
name: build
on:
push:
branches: [main]
paths-ignore: [bin.json]
workflow_dispatch:
env:
MACOS_SDK: "14.5"
jobs:
# next version = highest vX.Y.Z tag with the patch bumped; push a tag by hand for minor/major
version:
runs-on: ubuntu-latest
outputs:
version: ${{ steps.next.outputs.version }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- id: next
run: |
last=$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' --sort=-v:refname | head -n1)
if [ -z "$last" ]; then
next=0.1.0
else
last=${last#v}
next="${last%.*}.$(( ${last##*.} + 1 ))"
fi
echo "version=$next" >> "$GITHUB_OUTPUT"
build:
needs: version
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
target: [x86_64-unknown-linux-musl, aarch64-apple-darwin]
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
# caches ~/.cargo registry/git and target/, keyed on Cargo.lock + toolchain
- uses: Swatinem/rust-cache@v2
with:
key: ${{ matrix.target }}
# zig as cross C compiler/linker for both musl and macOS
- run: pip install ziglang cargo-zigbuild
# macOS: Apple SDK for Security.framework etc.
- if: matrix.target == 'aarch64-apple-darwin'
id: sdk-cache
uses: actions/cache@v4
with:
path: ~/MacOSX${{ env.MACOS_SDK }}.sdk
key: macos-sdk-${{ env.MACOS_SDK }}
- if: matrix.target == 'aarch64-apple-darwin' && steps.sdk-cache.outputs.cache-hit != 'true'
run: curl -fsSL "https://github.com/joseluisq/macosx-sdks/releases/download/${MACOS_SDK}/MacOSX${MACOS_SDK}.sdk.tar.xz" | tar -xJ -C "$HOME"
- if: matrix.target == 'aarch64-apple-darwin'
run: echo "SDKROOT=$HOME/MacOSX${MACOS_SDK}.sdk" >> "$GITHUB_ENV"
- run: cargo zigbuild --release --locked --target ${{ matrix.target }} -p hx-cli
env:
HX_VERSION: ${{ needs.version.outputs.version }}
- uses: actions/upload-artifact@v3
with:
name: hx-${{ matrix.target }}
path: target/${{ matrix.target }}/release/hx
release:
needs: [build, version]
runs-on: ubuntu-latest
steps:
# main, not the build sha: bin.json is committed on top of it
- uses: actions/checkout@v4
with:
ref: main
- uses: actions/download-artifact@v3
with:
path: dist
# artifacts lose the executable bit, restore it before packaging
- working-directory: dist
run: |
for t in hx-*; do
chmod +x "$t/hx"
tar -czf "$t.tar.gz" -C "$t" hx
done
sha256sum *.tar.gz > SHA256SUMS
- env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
API: ${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}
TAG: v${{ needs.version.outputs.version }}
SHA: ${{ gitea.sha }}
# Gitea creates the tag at target_commitish when it doesn't exist
run: |
id=$(curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"target_commitish\":\"$SHA\"}" "$API/releases" | jq -r .id)
for f in dist/*.tar.gz dist/SHA256SUMS; do
curl -fsS -X POST -H "Authorization: token $TOKEN" \
-F "attachment=@$f" "$API/releases/$id/assets?name=$(basename "$f")"
done
# flake.nix reads bin.json to fetch these tarballs instead of building from source
- env:
VERSION: ${{ needs.version.outputs.version }}
run: |
jq -Rn --arg v "$VERSION" \
'{version: $v, sha256: ([inputs | split(" ") | {(.[1] | ltrimstr("hx-") | rtrimstr(".tar.gz")): .[0]}] | add)}' \
< dist/SHA256SUMS > bin.json
git config user.name gitea-actions
git config user.email gitea-actions@git.jokresner.de
git add bin.json
git commit -m "ci: bin.json v$VERSION"
git pull --rebase origin main
git push origin HEAD:main
-21
View File
@@ -1,21 +0,0 @@
name: ci
on: [push, pull_request]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy, rust-analyzer
- run: cargo fmt --all --check
- run: cargo clippy --workspace --all-targets -- -D warnings
- run: cargo test --workspace
- run: cargo build && sh tests/e2e.sh
- run: python3 tests/tui_smoke.py
- run: sh tests/lens_e2e.sh
- run: pip install ruff && sh tests/m4_e2e.sh
- run: sh tests/m5_e2e.sh
- run: sh tests/m6_e2e.sh
- run: python3 tests/tui_lspinstall.py
- run: sh tests/m7_e2e.sh
+18 -2
View File
@@ -59,7 +59,8 @@ max_tokens = 16384
## 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)
# 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
@@ -81,9 +82,24 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off
# 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 <id>` 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 `@<model id>` (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.
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 `<session>.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.
+7
View File
@@ -0,0 +1,7 @@
{
"version": "0.1.0",
"sha256": {
"aarch64-apple-darwin": "b6c5b91a839ceb80be69d24a94fb8114f4150a039b7f8873381aa1efcb35a26c",
"x86_64-unknown-linux-musl": "a5079b8655af0046b4cca0af76e118b3d91c3048f6c3eab4f763a1bd4f85ba62"
}
}
+91 -2
View File
@@ -61,14 +61,40 @@ impl Anthropic {
}
}
/// Anthropic accepts `[a-zA-Z0-9_-]` in tool ids; Codex ids look like `call|item`.
fn wire_id(id: &str) -> String {
id.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
c
} else {
'_'
}
})
.collect()
}
/// Thinking written by another provider (no signature, or a Codex reasoning item) is invalid here.
fn foreign(b: &ContentBlock) -> bool {
matches!(b, ContentBlock::Thinking { signature, .. }
if signature.as_deref().is_none_or(|s| s.starts_with('{')))
}
fn block_json(b: &ContentBlock) -> Value {
match b {
ContentBlock::ToolResult {
tool_use_id,
content,
is_error,
} => {
json!({"type": "tool_result", "tool_use_id": wire_id(tool_use_id), "content": content, "is_error": is_error})
}
ContentBlock::Image { media_type, data } => json!({
"type": "image",
"source": {"type": "base64", "media_type": media_type, "data": data}
}),
ContentBlock::ToolUse { id, name, input } => {
json!({"type": "tool_use", "id": id, "name": to_cc(name), "input": input})
json!({"type": "tool_use", "id": wire_id(id), "name": to_cc(name), "input": input})
}
other => serde_json::to_value(other).unwrap_or(Value::Null),
}
@@ -86,7 +112,19 @@ pub fn body(req: &Request) -> Value {
let mut messages: Vec<Value> = req
.messages
.iter()
.map(|m| json!({"role": m.role, "content": m.content.iter().map(block_json).collect::<Vec<_>>()}))
.map(|m| {
let mut c: Vec<Value> = m
.content
.iter()
.filter(|b| !foreign(b))
.map(block_json)
.collect();
if c.is_empty() {
// message index stays aligned with `req.messages` (cache breakpoints)
c.push(json!({"type": "text", "text": "(thinking omitted)"}));
}
json!({"role": m.role, "content": c})
})
.collect();
// Rolling breakpoints (tools+system are covered by the system one): the last message, and the
// user message before it, which is where the previous request's breakpoint sat -> cache read.
@@ -389,6 +427,57 @@ mod tests {
use super::*;
use crate::ToolSpec;
#[test]
fn foreign_history_is_made_valid() {
let mut r = req();
r.messages = vec![
Message::user("go"),
Message {
role: Role::Assistant,
content: vec![
ContentBlock::Thinking {
thinking: "x".into(),
signature: Some("{\"type\":\"reasoning\"}".into()),
},
ContentBlock::ToolUse {
id: "call_1|fc_2".into(),
name: "read".into(),
input: json!({}),
},
],
},
Message {
role: Role::User,
content: vec![ContentBlock::ToolResult {
tool_use_id: "call_1|fc_2".into(),
content: "ok".into(),
is_error: false,
}],
},
Message {
role: Role::Assistant,
content: vec![ContentBlock::Thinking {
thinking: "y".into(),
signature: None,
}],
},
];
let b = body(&r);
let m = &b["messages"];
// reasoning from another provider is dropped, ids use only [A-Za-z0-9_-]
assert_eq!(m[1]["content"].as_array().unwrap().len(), 1);
assert_eq!(m[1]["content"][0]["id"], "call_1_fc_2");
assert_eq!(m[2]["content"][0]["tool_use_id"], "call_1_fc_2");
// a message left empty keeps its slot and gets a placeholder
assert_eq!(m[3]["content"][0]["type"], "text");
// signed Claude thinking stays
r.messages[3].content = vec![ContentBlock::Thinking {
thinking: "y".into(),
signature: Some("abc".into()),
}];
assert_eq!(body(&r)["messages"][3]["content"][0]["type"], "thinking");
}
#[test]
fn effort_sets_thinking_budget() {
let mut r = req();
+138 -12
View File
@@ -6,7 +6,8 @@
//! `--input-format stream-json` process if startup latency hurts.
use crate::{
ContentBlock, Error, Message, Provider, Request, Result, Role, StopReason, StreamEvent, Usage,
ContentBlock, Error, Message, Provider, Quota, QuotaWindow, Request, Result, Role, StopReason,
StreamEvent, Usage,
};
use futures::StreamExt;
use futures::stream::BoxStream;
@@ -94,6 +95,26 @@ fn prompt(msgs: &[Message], resumed: bool) -> String {
s + "\nCurrent request:\n" + &msgs[last].text()
}
/// `Bash: cargo test`, `Edit: src/a.rs`; other tools show their input, shortened.
fn tool_line(b: &Value) -> String {
let name = b["name"].as_str().unwrap_or("tool");
let i = &b["input"];
let d = [
"command",
"file_path",
"notebook_path",
"pattern",
"url",
"query",
"description",
]
.iter()
.find_map(|k| i[*k].as_str().map(String::from))
.unwrap_or_else(|| i.to_string());
let d: String = d.chars().take(300).collect();
format!("{name}: {d}")
}
fn usage(u: &Value) -> Usage {
let n = |k: &str| u[k].as_u64().unwrap_or(0);
Usage {
@@ -104,6 +125,30 @@ fn usage(u: &Value) -> Usage {
}
}
/// `rate_limit_event` -> window. claude reports `utilization` (0..1) when known, else only a
/// status; `surpassedThreshold` is the best percent then. ponytail: no percent -> no window.
fn window(v: &Value) -> Option<QuotaWindow> {
let i = &v["rate_limit_info"];
let label = match i["rateLimitType"].as_str()? {
"five_hour" => "5h".to_string(),
"seven_day" => "7d".into(),
"seven_day_opus" => "7d opus".into(),
"seven_day_sonnet" => "7d sonnet".into(),
o => o.replace('_', " "),
};
let used_pct = match (i["utilization"].as_f64(), i["surpassedThreshold"].as_f64()) {
(Some(u), _) => u * 100.0,
_ if i["status"] == "rejected" => 100.0,
(_, Some(t)) => t * 100.0,
_ => return None,
};
Some(QuotaWindow {
label,
used_pct,
resets_at: i["resetsAt"].as_u64(),
})
}
#[async_trait::async_trait]
impl Provider for ClaudeCli {
async fn models(&self) -> Result<Vec<crate::models::ModelInfo>> {
@@ -122,6 +167,10 @@ impl Provider for ClaudeCli {
"stream-json",
"--verbose",
"--include-partial-messages",
// print mode defaults to display "omitted" (empty thinking text) on new models
// ponytail: hidden flag; an older claude that rejects it needs a version probe
"--thinking-display",
"summarized",
"--model",
&req.model,
]);
@@ -160,6 +209,9 @@ impl Provider for ClaudeCli {
let mut lines = BufReader::new(out).lines();
let (mut text, mut think) = (String::new(), String::new());
let mut done = false;
// usage of the last API request: the real context size (`result` sums all requests)
let mut last: Option<Value> = None;
let mut quota = Quota::default();
while let Ok(Some(l)) = lines.next_line().await {
let Ok(v) = serde_json::from_str::<Value>(&l) else {
continue;
@@ -170,8 +222,8 @@ impl Provider for ClaudeCli {
match v["type"].as_str() {
Some("stream_event") => {
let e = &v["event"];
match e["type"].as_str() {
Some("content_block_delta") => match e["delta"]["type"].as_str() {
if e["type"] == "content_block_delta" {
match e["delta"]["type"].as_str() {
Some("text_delta") => {
let t = e["delta"]["text"].as_str().unwrap_or_default();
text += t;
@@ -179,22 +231,36 @@ impl Provider for ClaudeCli {
}
Some("thinking_delta") => {
let t = e["delta"]["thinking"].as_str().unwrap_or_default();
// omitted thinking: claude sends empty deltas (signature only)
if t.trim().is_empty() {
continue;
}
think += t;
let _ =
tx.send(Ok(StreamEvent::ThinkingDelta { text: t.into() }));
}
_ => {}
},
// claude runs its tools itself; show them, don't hand them to hx
Some("content_block_start")
if e["content_block"]["type"] == "tool_use" =>
{
let n = e["content_block"]["name"].as_str().unwrap_or("tool");
}
}
}
// complete tool calls (the stream events only carry partial JSON)
Some("assistant") => {
if v["message"]["usage"].is_object() {
last = Some(v["message"]["usage"].clone());
}
for b in v["message"]["content"].as_array().into_iter().flatten() {
if b["type"] == "tool_use" {
let _ = tx.send(Ok(StreamEvent::TextDelta {
text: format!("\n[claude tool: {n}]\n"),
text: format!("\n[claude {}]\n", tool_line(b)),
}));
}
_ => {}
}
}
Some("rate_limit_event") => {
if let Some(w) = window(&v) {
quota.windows.retain(|x| x.label != w.label);
quota.windows.push(w);
let _ = tx.send(Ok(StreamEvent::Quota(quota.clone())));
}
}
Some("result") => {
@@ -223,7 +289,8 @@ impl Provider for ClaudeCli {
content,
},
stop: StopReason::EndTurn,
usage: usage(&v["usage"]),
// ponytail: billing/stats see the last request only; split Done if exact sums matter
usage: usage(last.as_ref().unwrap_or(&v["usage"])),
}));
break;
}
@@ -250,6 +317,32 @@ impl Provider for ClaudeCli {
mod tests {
use super::*;
#[test]
fn tool_line_shows_what_runs() {
let b = json!({"name": "Bash", "input": {"command": "cargo test", "description": "run"}});
assert_eq!(tool_line(&b), "Bash: cargo test");
let b = json!({"name": "Edit", "input": {"file_path": "a.rs", "old_string": "x"}});
assert_eq!(tool_line(&b), "Edit: a.rs");
let b = json!({"name": "X", "input": {"a": 1}});
assert_eq!(tool_line(&b), "X: {\"a\":1}");
}
#[test]
fn rate_limit_event_maps_to_window() {
let w = |i: Value| window(&json!({"rate_limit_info": i}));
let a =
w(json!({"rateLimitType": "five_hour", "utilization": 0.42, "resetsAt": 99})).unwrap();
assert_eq!(
(a.label.as_str(), a.used_pct.round(), a.resets_at),
("5h", 42.0, Some(99))
);
let b = w(json!({"rateLimitType": "seven_day", "status": "rejected"})).unwrap();
assert_eq!(b.used_pct, 100.0);
let c = w(json!({"rateLimitType": "seven_day", "status": "allowed_warning", "surpassedThreshold": 0.75})).unwrap();
assert_eq!(c.used_pct, 75.0);
assert!(w(json!({"rateLimitType": "five_hour", "status": "allowed"})).is_none());
}
#[test]
fn prompt_replays_history_only_on_fresh_session() {
let m = vec![
@@ -265,4 +358,37 @@ mod tests {
assert!(p.contains("User: a") && p.contains("Assistant: b") && p.ends_with("c"));
assert_eq!(prompt(&m[..1], false), "a");
}
#[tokio::test]
async fn done_usage_is_last_request_not_the_sum() {
use futures::StreamExt;
let out = [
r#"{"type":"assistant","message":{"content":[],"usage":{"input_tokens":1,"cache_read_input_tokens":90000,"output_tokens":5}}}"#,
r#"{"type":"assistant","message":{"content":[],"usage":{"input_tokens":1,"cache_read_input_tokens":91000,"output_tokens":7}}}"#,
r#"{"type":"result","result":"ok","usage":{"input_tokens":2,"cache_read_input_tokens":181000,"output_tokens":12}}"#,
]
.join("\n");
let p = ClaudeCli::new(vec![]).with_spawner(Arc::new(move |_| {
let o = out.clone();
Box::pin(async move {
let mut c = tokio::process::Command::new("sh");
c.args(["-c", &format!("printf '%s\\n' '{o}'"), "sh"]);
c
})
}));
let req = Request {
model: "m".into(),
system: String::new(),
messages: vec![Message::user("hi")],
tools: vec![],
max_tokens: 100,
effort: crate::Effort::levels(crate::auth::Kind::Claude)[0],
};
let evs: Vec<_> = p.stream(req).await.unwrap().collect().await;
let Some(Ok(StreamEvent::Done { usage, .. })) = evs.last() else {
panic!("{evs:?}")
};
assert_eq!(usage.cache_read_tokens, 91_000);
assert_eq!(usage.output_tokens, 7);
}
}
+8 -1
View File
@@ -2,7 +2,7 @@
## Every setting is commented out and shows its default or an example; uncomment to change it.
# provider = "claude" # claude | codex | custom; default: the first logged-in provider
# model = "claude-sonnet-5-5" # model for the chosen provider
# model = "claude-sonnet-5-5" # model for the chosen provider; "auto" = pick per prompt (see [auto])
# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet
# codex_model = "gpt-5.6-sol" # default: Codex's top-listed model
# explore_model = "claude-haiku-4-5" # read-only `task` subagents; default: cheapest tier of the provider
@@ -25,6 +25,13 @@
# ro = ["~/.cargo", "~/.rustup", "~/.local", "~/.nvm", "~/.npm"] # readable parts of $HOME
# env_allow = ["PATH", "HOME", "TERM", "LC_*", "CARGO_*"] # trailing * = prefix
## Auto model (/model auto): pin a tier to a model, even of another provider.
# [auto]
# fast = "claude-haiku-4-5"
# balanced = "claude-sonnet-5-5"
# deep = "gpt-5.6-sol"
# down_after = 3 # light prompts in a row before dropping to a cheaper tier
## OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter), used with provider = "custom".
# [openai_compat]
# base_url = "http://localhost:11434/v1"
+81 -14
View File
@@ -15,7 +15,12 @@ mod rpc;
use std::sync::Arc;
#[derive(Parser)]
#[command(name = "hx", version, about = "Minimal coding agent")]
#[command(
name = "hx",
// CI sets HX_VERSION to the release version; local builds use Cargo's
version = option_env!("HX_VERSION").unwrap_or(env!("CARGO_PKG_VERSION")),
about = "Minimal coding agent"
)]
struct Cli {
#[command(subcommand)]
cmd: Option<Cmd>,
@@ -45,6 +50,9 @@ struct Cli {
/// Force the sandbox off (overrides config).
#[arg(long)]
no_sandbox: bool,
/// Run `claude` unconfined even when the sandbox is on (overrides config).
#[arg(long)]
no_claude_sandbox: bool,
/// Output mode: text (default for -p), json (NDJSON events on stdout; needs -p), rpc (JSON-RPC on stdio).
#[arg(long, value_enum, default_value_t = Mode::Text)]
mode: Mode,
@@ -141,6 +149,8 @@ struct Config {
mouse: Option<bool>,
/// Reuse the last model chosen with /model or /provider (default true).
remember_model: Option<bool>,
/// `/model auto`: tier pins (`fast`, `balanced`, `deep` = model ids) and `down_after`.
auto: Option<hx_core::route::Cfg>,
/// "ask" (default) or "yolo": whether bash/write/edit prompt in the TUI.
permissions: Option<String>,
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
@@ -212,6 +222,7 @@ impl Config {
codemode: o.codemode.or(c.codemode),
mouse: o.mouse.or(c.mouse),
remember_model: o.remember_model.or(c.remember_model),
auto: o.auto.or(c.auto),
permissions: o.permissions.or(c.permissions),
system_prompt: o.system_prompt.or(c.system_prompt),
sandbox: o.sandbox.or(c.sandbox),
@@ -314,7 +325,10 @@ fn claude_extra(bin: &str) -> hx_core::sandbox::Extra {
/// The `claude` command: sandboxed when the sandbox is on, unless the user let it out.
async fn claude_command(bin: String) -> tokio::process::Command {
if hx_core::sandbox::active().is_none() || claude_outside().await {
if hx_core::sandbox::active().is_none()
|| !hx_core::sandbox::claude_sandboxed()
|| claude_outside().await
{
return tokio::process::Command::new(bin);
}
hx_core::sandbox::command_with(&bin, &claude_extra(&bin))
@@ -454,6 +468,8 @@ fn pricing(model: &str) -> Option<hx_ai::Pricing> {
/// `[openai_compat]` from config, set once at startup.
static COMPAT: std::sync::OnceLock<hx_ai::openai_compat::Config> = std::sync::OnceLock::new();
/// `codemode` from config: also offer the codemode tool to claude.
static CODEMODE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
/// `claude_cli` from config: extra args for the `claude` binary.
static CLAUDE_CLI: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
@@ -464,11 +480,14 @@ fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
hx_ai::claude_cli::ClaudeCli::new(CLAUDE_CLI.get().cloned().unwrap_or_default());
let c = c.with_spawner(Arc::new(|bin| Box::pin(claude_command(bin))));
Arc::new(match std::env::current_exe() {
Ok(e) => c.with_mcp(
e.to_string_lossy().into(),
vec!["mcp-serve".into()],
serde_json::json!({ hx_core::approve::ENV: hx_core::approve::sock_path() }),
),
Ok(e) => c.with_mcp(e.to_string_lossy().into(), vec!["mcp-serve".into()], {
let mut env =
serde_json::json!({ hx_core::approve::ENV: hx_core::approve::sock_path() });
if CODEMODE.get().copied().unwrap_or(false) {
env["HX_CODEMODE"] = "1".into();
}
env
}),
Err(_) => c,
})
}
@@ -555,6 +574,10 @@ async fn main() -> Result<()> {
Some(Cmd::Logout { provider }) => return Ok(auth::logout(provider)?),
Some(Cmd::Stats { session }) => {
print!("{}", hx_core::stats::report(&Session::open(&session)?));
print!(
"{}",
hx_core::stats::model_report(&Session::open(&session)?)
);
print!("{}", hx_core::stats::task_report(&Session::open(&session)?));
print!("{}", hx_core::stats::sub_report(&session));
return Ok(());
@@ -708,13 +731,35 @@ async fn main() -> Result<()> {
));
let mut reg = hx_core::tool::Registry::default();
reg.add(hx_lens::LspTool::new(mgr.clone()));
if let Some(p) = std::env::var_os(hx_core::approve::ENV) {
reg.add(hx_core::approve::Approve(p.into()));
}
let cx = ToolCtx {
cwd,
cwd: cwd.clone(),
state: Default::default(),
};
let sock = std::env::var_os(hx_core::approve::ENV);
if let Some(p) = &sock {
reg.add(hx_core::approve::Approve(p.into()));
// tools run by codemode ask hx for permission like any other
let _ = cx
.state
.permit
.set(hx_core::approve::remote_permit(p.into()));
}
if std::env::var_os("HX_CODEMODE").is_some() {
// claude keeps its own tools; only `codemode` is added, and scripts may call the hx tools
let cfg = Config::load(&cwd)?;
let hub = Arc::new(
hx_mcp::Hub::start(
hx_mcp::config::load(&context::hx_home(), &cwd)
.map_err(anyhow::Error::msg)?,
)
.await,
);
let mut all = hx_tools::registry();
hx_tools::web::register(&mut all, web_search(&cfg));
hub.register(&mut all);
all.add(hx_lens::LspTool::new(mgr.clone()));
reg.add(hx_tools::codemode::Codemode::new(&all));
}
hx_mcp::serve::serve(
reg,
cx,
@@ -737,7 +782,13 @@ async fn main() -> Result<()> {
if cli.no_sandbox {
sb.mode = hx_core::sandbox::Mode::Off;
}
if cli.no_claude_sandbox {
sb.claude = false;
}
hx_core::sandbox::init(&sb, &cwd).map_err(anyhow::Error::msg)?;
if sb.mode == hx_core::sandbox::Mode::On && !sb.claude {
eprintln!("hx: sandbox on, but claude runs unconfined (sandbox.claude = false)");
}
if let Some(oc) = cfg.openai_compat.clone() {
let _ = COMPAT.set(oc);
}
@@ -749,6 +800,7 @@ async fn main() -> Result<()> {
&& hx_ai::claude_cli::ClaudeCli::available())
.then(Vec::new),
};
let _ = CODEMODE.set(cfg.codemode.unwrap_or(false));
if let Some(a) = cli_args {
let _ = CLAUDE_CLI.set(a);
}
@@ -780,9 +832,18 @@ async fn main() -> Result<()> {
// the remembered model applies only to the provider it was chosen on
let last = last.filter(|l| l.provider == kind);
let last_effort = last.as_ref().and_then(|l| l.effort);
// auto mode: `--model auto` / `model = "auto"`, else whatever was on last time
let want_auto = match cli.model.as_deref().or(cfg.model.as_deref()) {
Some(m) => m == "auto",
None => last.as_ref().is_some_and(|l| l.auto),
};
let (cli_model, cfg_model) = (
cli.model.clone().filter(|m| m != "auto"),
cfg.model.clone().filter(|m| m != "auto"),
);
let last_model = last.map(|l| l.model);
let search = web_search(&cfg);
let model = cli.model.or(cfg.model).or(last_model).unwrap_or_else(|| {
let model = cli_model.or(cfg_model).or(last_model).unwrap_or_else(|| {
match kind {
Kind::Claude => cfg.claude_model.clone(),
Kind::Codex => cfg.codex_model.clone(),
@@ -827,7 +888,9 @@ async fn main() -> Result<()> {
provider: kind,
model: model.clone(),
effort: Some(effort),
auto: want_auto,
};
let auto_cfg = cfg.auto.clone().unwrap_or_default();
if hx_core::herdr::init() {
hx_core::herdr::set_session(&path);
agent.bus.add(hx_core::herdr::Hook);
@@ -984,7 +1047,9 @@ async fn main() -> Result<()> {
files: hx_tui::project_files(&cwd),
session_dir: dir,
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
.remember_in(last_path.clone(), start.clone()),
.auto_cfg(auto_cfg.clone())
.remember_in(last_path.clone(), start.clone())
.auto_on(want_auto),
},
)
.await;
@@ -1007,7 +1072,9 @@ async fn main() -> Result<()> {
hx_tui::run(hx_tui::Setup {
agent,
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
.remember_in(last_path, start),
.auto_cfg(auto_cfg)
.remember_in(last_path, start)
.auto_on(want_auto),
pricing,
specs,
open_sessions,
+65 -16
View File
@@ -77,9 +77,23 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
return;
}
let v: Value = serde_json::from_str(&line).unwrap_or_default();
let ok = match question(v["tool_name"].as_str().unwrap_or_default(), &v["input"]) {
None => true,
Some(q) => gate(&cx, q).await,
// hx tools run by `codemode` inside mcp-serve ask for their own permission
let ok = if let Some(q) = v.get("permit") {
let s = |k: &str| q[k].as_str().unwrap_or_default().to_string();
gate(
&cx,
Request {
tool: s("tool"),
detail: s("detail"),
rule: s("rule"),
},
)
.await
} else {
match question(v["tool_name"].as_str().unwrap_or_default(), &v["input"]) {
None => true,
Some(q) => gate(&cx, q).await,
}
};
let _ = w
.write_all(format!("{}\n", json!({"allow": ok})).as_bytes())
@@ -88,6 +102,38 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
}
}
async fn roundtrip(path: &Path, msg: Value) -> bool {
let ask = async {
let mut c = UnixStream::connect(path).await?;
c.write_all(format!("{msg}\n").as_bytes()).await?;
let mut l = String::new();
BufReader::new(c).read_line(&mut l).await?;
std::io::Result::Ok(l)
};
ask.await
.ok()
.and_then(|l| serde_json::from_str::<Value>(&l).ok())
.is_some_and(|v| v["allow"] == true)
}
/// Permission hook for tools that run in another process (`hx mcp-serve`): ask the owner of the socket.
/// Unreachable socket = deny.
pub fn remote_permit(path: PathBuf) -> crate::permit::Permit {
use crate::permit::Decision;
std::sync::Arc::new(move |r| {
let path = path.clone();
Box::pin(async move {
let m = json!({"permit": {"tool": r.tool, "detail": r.detail, "rule": r.rule}});
// the owner stores "always" itself; here a yes is a plain yes
if roundtrip(&path, m).await {
Decision::Once
} else {
Decision::Deny
}
})
})
}
/// MCP tool `approve` for `--permission-prompt-tool`.
pub struct Approve(pub PathBuf);
@@ -103,18 +149,7 @@ impl Tool for Approve {
}
}
async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult {
let ask = async {
let mut c = UnixStream::connect(&self.0).await?;
c.write_all(format!("{args}\n").as_bytes()).await?;
let mut l = String::new();
BufReader::new(c).read_line(&mut l).await?;
std::io::Result::Ok(l)
};
let ok = ask
.await
.ok()
.and_then(|l| serde_json::from_str::<Value>(&l).ok())
.is_some_and(|v| v["allow"] == true);
let ok = roundtrip(&self.0, args.clone()).await;
ToolResult::ok(if ok {
json!({"behavior": "allow", "updatedInput": args["input"]})
} else {
@@ -175,6 +210,20 @@ mod tests {
};
assert!(ask("cargo test").await.contains("\"allow\""));
assert!(ask("rm -rf x").await.contains("\"deny\""));
let _ = std::fs::remove_file(path);
// tools run in another process ask through the same socket
let remote = remote_permit(path.clone());
let req = |d: &str| crate::permit::Request {
tool: "bash".into(),
detail: d.into(),
rule: String::new(),
};
assert_eq!(remote(req("cargo test")).await, Decision::Once);
assert_eq!(remote(req("rm -rf x")).await, Decision::Deny);
let _ = std::fs::remove_file(&path);
assert_eq!(
remote(req("cargo test")).await,
Decision::Deny,
"no socket = deny"
);
}
}
+102 -3
View File
@@ -52,7 +52,11 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
b(
"model",
"show or switch model",
Enum(models.iter().map(|m| m.to_string()).collect()),
Enum(
std::iter::once("auto".to_string())
.chain(models.iter().map(|m| m.to_string()))
.collect(),
),
),
b(
"provider",
@@ -69,6 +73,11 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
b("clear", "alias of /new", None),
b("sessions", "browse, resume, delete sessions", None),
b("yolo", "toggle: run every tool without asking", None),
b(
"sandbox",
"sandbox on/off; `claude` toggles it for claude; no arg: status",
Enum(["on", "off", "claude"].map(String::from).into()),
),
b("lsp", "language server status", None),
b("copy", "copy the last answer to the clipboard", None),
b("usage", "subscription limits, resets, credits", None),
@@ -182,7 +191,15 @@ pub fn complete(line: &str, cur: usize, specs: &[CmdSpec], files: &[String]) ->
label,
detail: detail.into(),
};
let items = if let Some(q) = tok.strip_prefix('@') {
let raw = tok.strip_prefix('@').unwrap_or(tok);
let items = if is_fs_path(raw) && (start > 0 || tok.starts_with('@') || raw[1..].contains('/'))
{
let at = if tok.starts_with('@') { "@" } else { "" };
complete_path(raw)
.into_iter()
.map(|f| cand(format!("{at}{f}"), ""))
.collect()
} else if let Some(q) = tok.strip_prefix('@') {
rank(files.iter().map(String::as_str), q, MAX_ITEMS)
.into_iter()
.map(|f| cand(format!("@{f}"), ""))
@@ -217,6 +234,61 @@ pub fn complete(line: &str, cur: usize, specs: &[CmdSpec], files: &[String]) ->
Completion { start, items }
}
pub fn is_fs_path(t: &str) -> bool {
t == "~"
|| t.starts_with(['/', '~']) && t.contains('/')
|| t.starts_with("./")
|| t.starts_with("../")
}
/// Expand a leading `~/` to `$HOME`.
pub fn expand_home(p: &str) -> PathBuf {
match (p.strip_prefix("~/"), std::env::var_os("HOME")) {
(Some(rest), Some(h)) => PathBuf::from(h).join(rest),
_ => PathBuf::from(p),
}
}
/// Live directory listing for a `~/`, `/`, `./` or `../` token; the typed form is kept in labels.
/// Directories first and suffixed `/`; dotfiles only when the prefix starts with `.`.
fn complete_path(tok: &str) -> Vec<String> {
if tok == "~" {
return vec!["~/".into()];
}
let (dir, pre) = tok.rsplit_once('/').map_or(("", tok), |(d, p)| (d, p));
let shown = format!("{dir}/");
let real = if dir.is_empty() {
PathBuf::from("/")
} else {
expand_home(&shown)
};
let Ok(rd) = std::fs::read_dir(real) else {
return vec![];
};
let pre_l = pre.to_lowercase();
let mut v: Vec<(bool, String)> = rd
.flatten()
.filter_map(|e| {
let n = e.file_name().to_string_lossy().into_owned();
if (n.starts_with('.') && !pre.starts_with('.'))
|| !n.to_lowercase().starts_with(&pre_l)
{
return None;
}
let d = e.path().is_dir();
Some((d, if d { format!("{n}/") } else { n }))
})
.collect();
v.sort_by(|a, b| {
b.0.cmp(&a.0)
.then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase()))
});
v.into_iter()
.take(MAX_ENUM_ITEMS)
.map(|(_, n)| format!("{shown}{n}"))
.collect()
}
fn detail(s: &CmdSpec) -> String {
let tag = match s.source {
Source::Builtin => "",
@@ -285,6 +357,33 @@ pub fn common_prefix<S: AsRef<str>>(xs: &[S]) -> String {
#[cfg(test)]
mod tests {
#[test]
fn fs_paths_complete() {
let d = tempfile::tempdir().unwrap();
let r = d.path();
std::fs::create_dir_all(r.join("Docs/sub")).unwrap();
std::fs::write(r.join("doc.txt"), "").unwrap();
std::fs::write(r.join(".hid"), "").unwrap();
let t = |l: &str| -> Vec<String> {
super::complete(l, l.len(), &[], &[])
.items
.into_iter()
.map(|c| c.label)
.collect()
};
let b = r.display();
assert_eq!(
t(&format!("see {b}/do")),
[format!("{b}/Docs/"), format!("{b}/doc.txt")]
);
assert_eq!(t(&format!("@{b}/Docs/")), [format!("@{b}/Docs/sub/")]);
assert_eq!(t(&format!("{b}/.")), [format!("{b}/.hid")]);
assert!(t(&format!("{b}/nope/x")).is_empty());
assert_eq!(t("x ~"), ["~/"]);
// slash command stays a command
assert!(t("/etc").is_empty());
}
use super::*;
fn labels(c: &Completion) -> Vec<&str> {
@@ -331,7 +430,7 @@ mod tests {
assert_eq!(r.items[0].detail, "skill · code review");
let m = c("/model op");
assert_eq!((m.start, labels(&m)), (7, vec!["claude-opus-5-5"]));
assert_eq!(c("/model ").items.len(), 3);
assert_eq!(c("/model ").items.len(), 4, "auto + 3 models");
assert_eq!(labels(&c("/provider c")), ["codex", "claude"]);
assert_eq!(labels(&c("/fs:grep lib")), ["src/lib.rs"]);
assert!(
+1
View File
@@ -12,6 +12,7 @@ mod mask;
pub mod memory;
pub mod nudge;
pub mod permit;
pub mod route;
pub mod sandbox;
pub mod session;
pub mod stats;
+4
View File
@@ -366,6 +366,10 @@ impl Allow {
})
}
pub fn yolo_on(&self) -> bool {
self.yolo
}
/// Toggle: allow everything (not persisted); returns the new state.
pub fn toggle_yolo(&mut self) -> bool {
self.yolo = !self.yolo;
+581
View File
@@ -0,0 +1,581 @@
//! Automatic model choice per prompt (`/model auto`) and one-turn overrides (`@opus fix this`).
//!
//! Pure functions plus a small [`Router`] that remembers the last tier for hysteresis. No LLM call:
//! a prompt is scored from cheap signals (length, keywords, trace, last turn failed), the score
//! maps to a [`Tier`], and the tier maps to a model per provider by name.
//! ponytail: keyword heuristics; replace [`signals`] with a classifier call if stats show misses.
use hx_ai::auth::Kind;
use hx_ai::models::ModelInfo;
use hx_ai::{ContentBlock, Effort, Message};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Tier {
Fast,
Balanced,
Deep,
}
impl Tier {
pub fn name(self) -> &'static str {
match self {
Tier::Fast => "fast",
Tier::Balanced => "balanced",
Tier::Deep => "deep",
}
}
/// Tier of a model by family name (Haiku/Luna, Sonnet/Terra, Opus/Sol); unknown models have none.
pub fn of(id: &str) -> Option<Tier> {
let has = |a: &[&str]| a.iter().any(|t| id.contains(t));
if has(&["haiku", "luna", "mini"]) {
Some(Tier::Fast)
} else if has(&["sonnet", "terra"]) {
Some(Tier::Balanced)
} else if has(&["opus", "sol"]) {
Some(Tier::Deep)
} else {
None
}
}
/// Tiers to try for a provider lacking this one: the closest first.
fn nearest(self) -> [Tier; 3] {
match self {
Tier::Fast => [Tier::Fast, Tier::Balanced, Tier::Deep],
Tier::Balanced => [Tier::Balanced, Tier::Deep, Tier::Fast],
Tier::Deep => [Tier::Deep, Tier::Balanced, Tier::Fast],
}
}
}
/// `[auto]` in config: pin a tier to a model (of any provider), tune the step-down delay.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Cfg {
pub fast: Option<String>,
pub balanced: Option<String>,
pub deep: Option<String>,
/// Light prompts in a row before dropping to a cheaper tier (default 3). Stepping up is immediate.
pub down_after: Option<u32>,
}
impl Cfg {
fn pin(&self, t: Tier) -> Option<&str> {
match t {
Tier::Fast => &self.fast,
Tier::Balanced => &self.balanced,
Tier::Deep => &self.deep,
}
.as_deref()
}
}
/// What the prompt and the last turn say about difficulty.
#[derive(Debug, Clone, PartialEq)]
pub struct Signals {
pub score: i32,
pub tier: Tier,
/// Too short and plain ("continue", "ja") to say anything: keep the current tier.
pub keep: bool,
pub hits: Vec<String>,
}
const DEEP: &[&str] = &[
"refactor",
"architect",
"architektur",
"redesign",
"migrat",
"race condition",
"deadlock",
"concurren",
"security",
"sicherheit",
"root cause",
"performance",
"optimi",
"rewrite",
"from scratch",
"entwirf",
"design",
"implement",
"debug",
"plan",
];
const LIGHT: &[&str] = &[
"typo",
"rename",
"format",
"explain",
"erkl",
"what is",
"what does",
"was ist",
"was macht",
"show me",
"zeig",
"commit",
"comment",
"kommentar",
"summar",
"zusammenfass",
];
const TRACE: &[&str] = &[
"traceback",
"panicked at",
"error[e",
"stack trace",
"exception",
];
/// Score `prompt`; `history` is the session so far (a failed tool result in the last two messages
/// escalates).
pub fn signals(prompt: &str, history: &[Message]) -> Signals {
let p = prompt.to_lowercase();
let mut hits = vec![];
let mut score = 0;
let len = prompt.chars().count();
if len > 2000 {
score += 2;
hits.push("long prompt".into());
} else if len > 600 {
score += 1;
hits.push("long-ish prompt".into());
}
let deep: Vec<&str> = DEEP.iter().copied().filter(|k| p.contains(k)).collect();
if !deep.is_empty() {
score += 2 * deep.len().min(2) as i32;
hits.push(deep.join(","));
}
let light: Vec<&str> = LIGHT.iter().copied().filter(|k| p.contains(k)).collect();
if !light.is_empty() {
score -= 2;
hits.push(light.join(","));
}
if TRACE.iter().any(|k| p.contains(k)) {
score += 1;
hits.push("trace".into());
}
let failed = history.iter().rev().take(2).any(|m| {
m.content
.iter()
.any(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. }))
});
if failed {
score += 2;
hits.push("last turn failed".into());
}
if history.len() > 40 {
score += 1;
hits.push("long session".into());
}
let keep = hits.is_empty() && prompt.split_whitespace().count() <= 3;
let tier = match score {
i32::MIN..=-1 => Tier::Fast,
0..=2 => Tier::Balanced,
_ => Tier::Deep,
};
Signals {
score,
tier,
keep,
hits,
}
}
/// Thinking level for a score: lowest for light prompts, high for hard ones, else the provider default.
fn effort_for(score: i32, k: Kind) -> Effort {
let lv = Effort::levels(k);
let e = match score {
i32::MIN..=-1 => lv[0],
3..=i32::MAX => Effort::High,
_ => Effort::default_for(k),
};
if lv.contains(&e) { e } else { lv[0] }
}
/// Model of provider `k` for tier `t`: the config pin, else the catalog by family name, else the
/// closest tier it has, else its first model (custom endpoints).
pub fn model_for(k: Kind, t: Tier, models: &[ModelInfo], cfg: &Cfg) -> Option<String> {
if let Some(m) = cfg.pin(t)
&& hx_ai::models::kind_of(models, m) == Some(k)
{
return Some(m.to_string());
}
let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect();
t.nearest()
.iter()
.find_map(|t| mine.iter().find(|m| Tier::of(&m.id) == Some(*t)))
.or(mine.first())
.map(|m| m.id.clone())
}
/// Provider for tier `t`: the config pin's provider, else `prefer` (keeps the prompt cache), else
/// any logged-in one with that exact tier, else any. `avoid` (out of quota) is skipped when
/// something else exists. Custom endpoints only serve when nothing else is logged in.
pub fn pick_for(
t: Tier,
prefer: Kind,
avoid: Option<Kind>,
models: &[ModelInfo],
cfg: &Cfg,
) -> Option<(Kind, String)> {
let mut kinds: Vec<Kind> = vec![];
for m in models {
if !kinds.contains(&m.kind) {
kinds.push(m.kind);
}
}
if kinds.iter().any(|k| *k != Kind::Custom) {
kinds.retain(|k| *k != Kind::Custom);
}
if kinds.len() > 1 && avoid.is_some() {
kinds.retain(|k| Some(*k) != avoid);
}
let pinned = cfg
.pin(t)
.and_then(|m| hx_ai::models::kind_of(models, m))
.filter(|k| kinds.contains(k));
let order: Vec<Kind> = pinned
.into_iter()
.chain(kinds.iter().copied().filter(|k| *k == prefer))
.chain(kinds.iter().copied())
.collect();
let exact = |k: &Kind| {
models
.iter()
.any(|m| m.kind == *k && Tier::of(&m.id) == Some(t))
|| cfg
.pin(t)
.is_some_and(|p| hx_ai::models::kind_of(models, p) == Some(*k))
};
let k = order.iter().find(|k| exact(k)).or(order.first()).copied()?;
model_for(k, t, models, cfg).map(|m| (k, m))
}
/// What to use for the next prompt.
#[derive(Debug, Clone, PartialEq)]
pub struct Pick {
pub kind: Kind,
pub model: String,
pub tier: Tier,
pub effort: Effort,
pub why: String,
}
#[derive(Debug, Default)]
pub struct Router {
pub cfg: Cfg,
cur: Option<(Kind, Tier)>,
down: u32,
}
impl Router {
pub fn new(cfg: Cfg) -> Self {
Self {
cfg,
cur: None,
down: 0,
}
}
/// Forget the last choice (auto mode was switched on again).
pub fn reset(&mut self) {
self.cur = None;
self.down = 0;
}
/// Choose for a prompt. Up-tiers apply at once; a cheaper tier only after `down_after` light
/// prompts in a row (a switch costs the prompt cache). `start` is the provider in use when
/// nothing was chosen yet; `avoid` is a provider that is out of quota.
pub fn route(
&mut self,
sig: &Signals,
start: Kind,
avoid: Option<Kind>,
models: &[ModelInfo],
) -> Option<Pick> {
let n = self.cfg.down_after.unwrap_or(3);
let tier = match self.cur {
Some((_, c)) if sig.keep => c,
Some((_, c)) if sig.tier < c => {
self.down += 1;
if self.down >= n {
self.down = 0;
sig.tier
} else {
c
}
}
_ => {
self.down = 0;
sig.tier
}
};
let prefer = self.cur.map_or(start, |(k, _)| k);
let (kind, model) = pick_for(tier, prefer, avoid, models, &self.cfg)?;
self.cur = Some((kind, tier));
let held = if tier != sig.tier && !sig.keep {
format!(", holding (wanted {})", sig.tier.name())
} else {
String::new()
};
let hits = if sig.hits.is_empty() {
String::new()
} else {
format!(": {}", sig.hits.join(" · "))
};
Some(Pick {
kind,
model,
tier,
effort: effort_for(sig.score, kind),
why: format!("{} (score {}{hits}{held})", tier.name(), sig.score),
})
}
}
/// What `@word` at the start of a prompt asks for.
#[derive(Debug, Clone, PartialEq)]
pub enum Target {
Tier(Tier),
Provider(Kind),
Model(String),
}
/// `@opus fix this` -> (model, "fix this"). The word is a tier (`fast`, `balanced`, `deep`), a
/// provider (`claude`, `codex`), a model id, or a unique part of one (min 3 chars: `opus`, `sol`).
/// Needs text after it, and a file of that name wins (`@notes.md` stays a file mention).
pub fn parse_override(
line: &str,
models: &[ModelInfo],
is_file: &dyn Fn(&str) -> bool,
) -> Option<(Target, String)> {
let (w, rest) = line.strip_prefix('@')?.split_once(char::is_whitespace)?;
let rest = rest.trim();
if rest.is_empty() || w.is_empty() || is_file(w) {
return None;
}
let lw = w.to_lowercase();
let t = match lw.as_str() {
"fast" => Target::Tier(Tier::Fast),
"balanced" => Target::Tier(Tier::Balanced),
"deep" => Target::Tier(Tier::Deep),
_ => {
if let Some(m) = models.iter().find(|m| m.id.to_lowercase() == lw) {
Target::Model(m.id.clone())
} else if let Some(k) = ["claude", "codex"]
.contains(&lw.as_str())
.then(|| lw.parse::<Kind>().ok())
.flatten()
{
Target::Provider(k)
} else if lw.len() >= 3 && lw.starts_with(|c: char| c.is_ascii_alphabetic()) {
let hit: Vec<&ModelInfo> = models
.iter()
.filter(|m| m.id.to_lowercase().contains(&lw))
.collect();
match hit.as_slice() {
[m] => Target::Model(m.id.clone()),
// `@sonnet` with several dated snapshots: the first listed (newest)
[m, ..] if hit.iter().all(|h| h.kind == m.kind) => Target::Model(m.id.clone()),
_ => return None,
}
} else {
return None;
}
}
};
Some((t, rest.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
fn m(id: &str, kind: Kind) -> ModelInfo {
ModelInfo {
id: id.into(),
kind,
context_window: 1,
}
}
fn cat() -> Vec<ModelInfo> {
vec![
m("claude-opus-5-5", Kind::Claude),
m("claude-sonnet-5-5", Kind::Claude),
m("claude-haiku-4-5", Kind::Claude),
m("gpt-5.6-sol", Kind::Codex),
m("gpt-5.6-terra", Kind::Codex),
m("gpt-5.6-luna", Kind::Codex),
]
}
fn tier(p: &str) -> Tier {
signals(p, &[]).tier
}
#[test]
fn tiers_by_name() {
assert_eq!(Tier::of("claude-haiku-4-5"), Some(Tier::Fast));
assert_eq!(Tier::of("gpt-5.6-terra"), Some(Tier::Balanced));
assert_eq!(Tier::of("gpt-5.6-sol"), Some(Tier::Deep));
assert_eq!(Tier::of("llama3"), None);
}
#[test]
fn prompts_score_into_tiers() {
assert_eq!(tier("fix the typo in README"), Tier::Fast);
assert_eq!(
tier("add a --foo flag to the cli parser please"),
Tier::Balanced
);
assert_eq!(
tier("refactor the auth module and remove the race condition"),
Tier::Deep
);
assert_eq!(tier(&"x ".repeat(1500)), Tier::Balanced);
assert!(signals("ja", &[]).keep && signals("continue please", &[]).keep);
assert!(!signals("fix typo", &[]).keep, "keyword hit is a signal");
}
#[test]
fn failed_tool_result_escalates() {
let h = vec![Message {
role: hx_ai::Role::User,
content: vec![ContentBlock::ToolResult {
tool_use_id: "t".into(),
content: "boom".into(),
is_error: true,
}],
}];
let s = signals("try again with a different approach", &h);
assert_eq!(s.score, 2);
assert!(s.hits.iter().any(|h| h == "last turn failed"));
}
#[test]
fn effort_follows_score_and_provider() {
assert_eq!(effort_for(-2, Kind::Claude), Effort::Off);
assert_eq!(effort_for(-2, Kind::Codex), Effort::Low);
assert_eq!(effort_for(0, Kind::Claude), Effort::Off);
assert_eq!(effort_for(0, Kind::Codex), Effort::Medium);
assert_eq!(effort_for(4, Kind::Claude), Effort::High);
}
#[test]
fn stays_on_provider_and_steps_down_slowly() {
let mut r = Router::new(Cfg::default());
let light = signals("fix the typo in README", &[]);
let hard = signals(
"refactor the auth module and remove the race condition",
&[],
);
let p = r.route(&hard, Kind::Codex, None, &cat()).unwrap();
assert_eq!((p.kind, p.model.as_str()), (Kind::Codex, "gpt-5.6-sol"));
// two light prompts hold the tier, the third drops it
for _ in 0..2 {
let p = r.route(&light, Kind::Codex, None, &cat()).unwrap();
assert_eq!(p.tier, Tier::Deep);
}
let p = r.route(&light, Kind::Codex, None, &cat()).unwrap();
assert_eq!((p.tier, p.model.as_str()), (Tier::Fast, "gpt-5.6-luna"));
// up again at once
assert_eq!(
r.route(&hard, Kind::Codex, None, &cat()).unwrap().tier,
Tier::Deep
);
// "ja" keeps whatever is current
let ack = signals("ja", &[]);
assert_eq!(
r.route(&ack, Kind::Codex, None, &cat()).unwrap().tier,
Tier::Deep
);
}
#[test]
fn quota_and_pins_cross_providers() {
let mut r = Router::new(Cfg::default());
let p = r
.route(
&signals("add a flag to the cli parser please", &[]),
Kind::Claude,
Some(Kind::Claude),
&cat(),
)
.unwrap();
assert_eq!(p.kind, Kind::Codex, "claude out of quota");
let cfg = Cfg {
deep: Some("gpt-5.6-sol".into()),
..Default::default()
};
let mut r = Router::new(cfg);
let hard = signals(
"refactor the auth module and remove the race condition",
&[],
);
let p = r.route(&hard, Kind::Claude, None, &cat()).unwrap();
assert_eq!((p.kind, p.model.as_str()), (Kind::Codex, "gpt-5.6-sol"));
let easy = signals("add a flag to the cli parser please", &[]);
let mut r2 = Router::new(Cfg::default());
assert_eq!(
r2.route(&easy, Kind::Claude, None, &cat()).unwrap().model,
"claude-sonnet-5-5"
);
}
#[test]
fn only_claude_logged_in_never_picks_codex() {
let only: Vec<ModelInfo> = cat()
.into_iter()
.filter(|m| m.kind == Kind::Claude)
.collect();
let mut r = Router::new(Cfg::default());
let p = r
.route(
&signals("typo", &[]),
Kind::Claude,
Some(Kind::Claude),
&only,
)
.unwrap();
assert_eq!(
p.kind,
Kind::Claude,
"avoid is ignored when nothing else exists"
);
}
#[test]
fn override_words() {
let no = |_: &str| false;
let p = |l: &str| parse_override(l, &cat(), &no);
assert_eq!(
p("@opus fix das"),
Some((Target::Model("claude-opus-5-5".into()), "fix das".into()))
);
assert_eq!(
p("@fast what is this"),
Some((Target::Tier(Tier::Fast), "what is this".into()))
);
assert_eq!(
p("@codex go"),
Some((Target::Provider(Kind::Codex), "go".into()))
);
assert_eq!(
p("@gpt-5.6-sol x").unwrap().0,
Target::Model("gpt-5.6-sol".into())
);
// ambiguous across providers, too short, no text, unknown
assert_eq!(p("@5 x"), None);
assert_eq!(p("@5.6 x"), None);
assert_eq!(p("@opus"), None);
assert_eq!(p("@src/main.rs explain"), None);
// a file of that name wins
assert_eq!(parse_override("@opus hi", &cat(), &|w| w == "opus"), None);
assert_eq!(p("opus fix"), None);
}
}
+52 -10
View File
@@ -12,6 +12,7 @@
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
@@ -45,6 +46,8 @@ pub struct Cfg {
pub ro: Vec<String>,
/// env vars passed to children; a trailing `*` matches a prefix
pub env_allow: Vec<String>,
/// run `claude` (claude_cli provider) inside the sandbox too (default true)
pub claude: bool,
}
impl Default for Cfg {
@@ -52,6 +55,7 @@ impl Default for Cfg {
let s = |v: &[&str]| v.iter().map(|s| s.to_string()).collect();
Cfg {
mode: Mode::Off,
claude: true,
backend: Backend::Auto,
network: false,
rw: s(&["~/.cargo/registry", "~/.cargo/git"]),
@@ -98,22 +102,47 @@ pub struct Sandbox {
env_allow: Vec<String>,
}
static SANDBOX: OnceLock<Option<Sandbox>> = OnceLock::new();
static CFG: OnceLock<(Cfg, PathBuf)> = OnceLock::new();
/// Built lazily on first enable (the backend probe spawns a process).
static SANDBOX: OnceLock<Sandbox> = OnceLock::new();
static ENABLED: AtomicBool = AtomicBool::new(false);
static CLAUDE: AtomicBool = AtomicBool::new(true);
/// Call once at startup. Errors (never silently falls back) if `mode = on` and no backend works.
pub fn init(cfg: &Cfg, cwd: &Path) -> Result<(), String> {
let sb = if cfg.mode == Mode::On {
Some(Sandbox::new(cfg, cwd)?)
} else {
None
};
SANDBOX
.set(sb)
.map_err(|_| "sandbox already initialised".into())
CFG.set((cfg.clone(), cwd.to_path_buf()))
.map_err(|_| "sandbox already initialised".to_string())?;
CLAUDE.store(cfg.claude, Ordering::Relaxed);
if cfg.mode == Mode::On {
set_enabled(true)?;
}
Ok(())
}
pub fn active() -> Option<&'static Sandbox> {
SANDBOX.get().and_then(Option::as_ref)
ENABLED
.load(Ordering::Relaxed)
.then(|| SANDBOX.get())
.flatten()
}
/// Turn the sandbox on/off at runtime. Affects only children spawned afterwards.
pub fn set_enabled(on: bool) -> Result<(), String> {
if on && SANDBOX.get().is_none() {
let (cfg, cwd) = CFG.get().ok_or("sandbox not initialised")?;
let _ = SANDBOX.set(Sandbox::new(cfg, cwd)?);
}
ENABLED.store(on, Ordering::Relaxed);
Ok(())
}
/// Does `claude` run inside the sandbox (while the sandbox is on)?
pub fn claude_sandboxed() -> bool {
CLAUDE.load(Ordering::Relaxed)
}
pub fn set_claude_sandboxed(on: bool) {
CLAUDE.store(on, Ordering::Relaxed);
}
/// Drop-in for `tokio::process::Command::new` that applies the sandbox when it is on.
@@ -561,4 +590,17 @@ mod tests {
"base unchanged"
);
}
#[test]
fn toggle() {
assert!(set_enabled(true).is_err(), "needs init");
let _ = init(&Cfg::default(), Path::new("/tmp"));
assert!(active().is_none());
if set_enabled(true).is_ok() {
assert!(active().is_some());
set_enabled(false).unwrap();
assert!(active().is_none());
}
assert!(Cfg::default().claude);
}
}
+8
View File
@@ -137,6 +137,14 @@ impl Session {
.collect()
}
/// Model and usage of every request, in file order (entries from before models were logged have none).
pub fn model_usages(&self) -> Vec<(Option<&str>, &hx_ai::Usage)> {
self.entries
.iter()
.filter_map(|e| e.usage.as_ref().map(|u| (e.model.as_deref(), u)))
.collect()
}
fn branch(&self) -> Vec<&Entry> {
let mut out = vec![];
let mut cur = self.head;
+73
View File
@@ -107,6 +107,46 @@ pub fn summary(s: &Session) -> Summary {
o
}
/// Requests, tokens and cache use per model, plus what model switches cost: the request right
/// after a switch (auto mode, `/model`, `@opus`) re-reads the history uncached. Empty with one model.
pub fn model_report(s: &Session) -> String {
let mut per: Vec<(String, [u64; 5])> = vec![];
let (mut switches, mut lost, mut prev) = (0u64, 0u64, None::<&str>);
for (m, u) in s.model_usages() {
let m = m.unwrap_or("?");
let i = per.iter().position(|(n, _)| n == m).unwrap_or_else(|| {
per.push((m.to_string(), [0; 5]));
per.len() - 1
});
let a = &mut per[i].1;
a[0] += 1;
a[1] += u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
a[2] += u.cache_read_tokens;
a[3] += u.cache_write_tokens;
a[4] += u.output_tokens;
if prev.is_some_and(|p| p != m) {
switches += 1;
lost += u.cache_write_tokens;
}
prev = Some(m);
}
if per.len() < 2 {
return String::new();
}
let mut o = String::from("models:\n");
for (m, [n, inp, cr, cw, out]) in &per {
let _ = writeln!(
o,
" {m}: {n} requests, input {inp} (cache read {cr}, write {cw}), output {out}"
);
}
let _ = writeln!(
o,
" model switches: {switches}, cache written on the first request after a switch: {lost} tok"
);
o
}
pub fn report(s: &Session) -> String {
let msgs = s.messages();
let mut o = String::new();
@@ -340,6 +380,39 @@ mod tests {
assert!(r.contains("one task 1, with several 1"), "{r}");
}
#[test]
fn model_report_counts_switches() {
let dir = tempfile::tempdir().unwrap();
let mut s = Session::open(dir.path().join("s.jsonl")).unwrap();
let u = |cr, cw| hx_ai::Usage {
input_tokens: 1,
output_tokens: 10,
cache_read_tokens: cr,
cache_write_tokens: cw,
};
for (m, usage) in [
("a", u(0, 100)),
("a", u(100, 5)),
("b", u(0, 120)),
("b", u(120, 5)),
] {
s.append_full(hx_ai::Message::user("x"), Some(m.into()), Some(usage))
.unwrap();
}
let r = model_report(&s);
assert!(r.contains("a: 2 requests"), "{r}");
assert!(
r.contains(
"model switches: 1, cache written on the first request after a switch: 120 tok"
),
"{r}"
);
let mut one = Session::open(dir.path().join("o.jsonl")).unwrap();
one.append_full(hx_ai::Message::user("x"), Some("a".into()), Some(u(0, 1)))
.unwrap();
assert_eq!(model_report(&one), "");
}
#[test]
fn report_counts() {
let d = tempfile::tempdir().unwrap();
+318 -5
View File
@@ -5,6 +5,7 @@
//! follow. [`Switcher`] does all of that behind two calls; the TUI and the RPC server share it.
use crate::agent::Agent;
use crate::route::{self, Router};
use hx_ai::Provider;
use hx_ai::auth::Kind;
use hx_ai::models::{self, ModelInfo};
@@ -31,6 +32,9 @@ pub struct Last {
/// Thinking level; absent in files written before it was saved.
#[serde(default)]
pub effort: Option<hx_ai::Effort>,
/// `/model auto` was on.
#[serde(default)]
pub auto: bool,
}
impl Last {
@@ -45,6 +49,24 @@ pub struct Switcher {
kind: Kind,
models: Vec<ModelInfo>,
make_provider: MakeProvider,
/// `Some` while `/model auto` is on.
router: Option<Router>,
auto_cfg: route::Cfg,
/// Providers out of quota until a unix second.
spent: Vec<(Kind, u64)>,
/// What to go back to after a one-turn override outside auto mode.
restore: Option<(Kind, String, hx_ai::Effort)>,
}
/// The pick for one prompt, and how the agent was switched to it.
#[derive(Debug, Clone, PartialEq)]
pub struct Routed {
pub pick: route::Pick,
pub sw: Switched,
/// The pick came from an `@word` override, not from auto.
pub forced: bool,
/// The prompt without the `@word`.
pub prompt: String,
}
impl Switcher {
@@ -56,9 +78,186 @@ impl Switcher {
kind,
models,
make_provider,
router: None,
auto_cfg: route::Cfg::default(),
spent: vec![],
restore: None,
}
}
/// `[auto]` config: tier pins and the step-down delay.
pub fn auto_cfg(mut self, c: route::Cfg) -> Self {
self.auto_cfg = c;
self
}
/// Start with auto mode on or off.
pub fn auto_on(mut self, on: bool) -> Self {
self.router = on.then(|| route::Router::new(self.auto_cfg.clone()));
if let Some((_, l)) = &mut self.remember {
l.auto = on;
}
self
}
pub fn is_auto(&self) -> bool {
self.router.is_some()
}
/// `/model auto` (true) or a pinned model (false, done by `set_model`/`set_provider`).
pub fn set_auto(&mut self, on: bool) {
self.router = on.then(|| route::Router::new(self.auto_cfg.clone()));
self.save(|l| l.auto = on);
}
fn save(&mut self, f: impl FnOnce(&mut Last)) {
if let Some((p, l)) = &mut self.remember {
f(l);
// ponytail: failing to save must not fail the switch
let _ = serde_json::to_vec(&*l).map(|b| std::fs::write(&*p, b));
}
}
/// The provider reported its limits: remember one that is used up until its window resets.
pub fn note_quota(&mut self, kind: Kind, q: &hx_ai::Quota) {
let now = hx_ai::auth::now_ms() / 1000;
self.spent.retain(|(k, t)| *k != kind && *t > now);
let full: Vec<&hx_ai::QuotaWindow> =
q.windows.iter().filter(|w| w.used_pct >= 99.5).collect();
if !full.is_empty() {
let until = full
.iter()
.filter_map(|w| w.resets_at)
.max()
.unwrap_or(now + 3600);
self.spent.push((kind, until));
}
}
fn out_of_quota(&self) -> Option<Kind> {
let now = hx_ai::auth::now_ms() / 1000;
self.spent.iter().find(|(_, t)| *t > now).map(|(k, _)| *k)
}
/// Before a prompt: in auto mode choose model and thinking level for it; an `@word` override
/// (`@opus`, `@codex`, `@fast`) applies to this prompt only, with or without auto. `None` =
/// leave the agent as it is. Call [`end_turn`](Self::end_turn) when the run is over.
pub fn begin_turn(
&mut self,
agent: &mut Agent,
prompt: &str,
is_file: &dyn Fn(&str) -> bool,
) -> Result<Option<Routed>, String> {
let forced = route::parse_override(prompt, &self.models, is_file);
if self.router.is_none() && forced.is_none() {
return Ok(None);
}
let hist = agent.session().messages();
let (text, target) = match &forced {
Some((t, rest)) => (rest.as_str(), Some(t)),
None => (prompt, None),
};
let sig = route::signals(text, &hist);
let before = (self.kind, agent.model().to_string(), agent.effort());
let avoid = self.out_of_quota();
let pick = match target {
Some(route::Target::Model(m)) => {
let kind = models::kind_of(&self.models, m).unwrap_or(self.kind);
let tier = route::Tier::of(m).unwrap_or(sig.tier);
route::Pick {
kind,
model: m.clone(),
tier,
effort: before.2,
why: format!("@{m}"),
}
}
Some(route::Target::Provider(k)) => {
let (kind, model) =
route::pick_for(sig.tier, *k, None, &self.models_of(*k), &self.auto_cfg)
.ok_or_else(|| format!("no models for {k:?}"))?;
route::Pick {
kind,
model,
tier: sig.tier,
effort: before.2,
why: format!("@{k:?}, {} tier", sig.tier.name()).to_lowercase(),
}
}
Some(route::Target::Tier(t)) => {
let (kind, model) =
route::pick_for(*t, self.kind, avoid, &self.models, &self.auto_cfg)
.ok_or("no models")?;
route::Pick {
kind,
model,
tier: *t,
effort: before.2,
why: format!("@{}", t.name()),
}
}
None => {
let Some(r) = &mut self.router else {
return Ok(None);
};
match r.route(&sig, self.kind, avoid, &self.models) {
Some(p) => p,
None => return Ok(None),
}
}
};
let was_auto = self.router.is_some();
if forced.is_some() && !was_auto {
self.restore = Some(before.clone());
}
let effort = if forced.is_some() {
// the forced model keeps the user's level when it has it, else its first
let lv = hx_ai::Effort::levels(pick.kind);
if lv.contains(&before.2) {
before.2
} else {
lv[0]
}
} else {
pick.effort
};
let same = pick.kind == self.kind && pick.model == before.1;
let sw = if same {
Switched {
kind: pick.kind,
model: pick.model.clone(),
provider_changed: false,
window: models::window(&self.models, &pick.model),
}
} else {
// auto picks and one-turn overrides are not the user's pinned choice
self.apply_inner(agent, pick.kind, pick.model.clone(), false, false)?
};
agent.set_effort(effort);
Ok(Some(Routed {
pick: route::Pick { effort, ..pick },
sw,
forced: forced.is_some(),
prompt: text.to_string(),
}))
}
/// After the run: undo a one-turn override made outside auto mode. Returns what it went back to.
pub fn end_turn(&mut self, agent: &mut Agent) -> Option<Switched> {
let (kind, model, effort) = self.restore.take()?;
let sw = self.apply_inner(agent, kind, model, false, false).ok()?;
agent.set_effort(effort);
Some(sw)
}
fn models_of(&self, k: Kind) -> Vec<ModelInfo> {
self.models
.iter()
.filter(|m| m.kind == k)
.cloned()
.collect()
}
/// Write every successful switch to `path` (best effort).
/// `start` is what the agent starts with.
pub fn remember_in(mut self, path: std::path::PathBuf, start: Last) -> Self {
@@ -83,6 +282,8 @@ impl Switcher {
/// On error the agent and the switcher are unchanged.
pub fn set_model(&mut self, agent: &mut Agent, id: &str) -> Result<Switched, String> {
let kind = models::kind_of(&self.models, id).unwrap_or(self.kind);
self.router = None;
self.save(|l| l.auto = false);
self.apply(agent, kind, id.to_string(), false)
}
@@ -90,6 +291,8 @@ impl Switcher {
/// provider, which picks up refreshed credentials after a re-login.
pub fn set_provider(&mut self, agent: &mut Agent, kind: Kind) -> Result<Switched, String> {
let model = models::default_for(kind, &self.models);
self.router = None;
self.save(|l| l.auto = false);
self.apply(agent, kind, model, true)
}
@@ -99,6 +302,17 @@ impl Switcher {
kind: Kind,
model: String,
rebuild: bool,
) -> Result<Switched, String> {
self.apply_inner(agent, kind, model, rebuild, true)
}
fn apply_inner(
&mut self,
agent: &mut Agent,
kind: Kind,
model: String,
rebuild: bool,
remember: bool,
) -> Result<Switched, String> {
let provider_changed = rebuild || kind != self.kind;
if provider_changed {
@@ -108,11 +322,11 @@ impl Switcher {
} else {
agent.set_model(model.as_str());
}
if let Some((p, l)) = &mut self.remember {
l.provider = kind;
l.model = model.clone();
// ponytail: failing to save must not fail the switch
let _ = serde_json::to_vec(&*l).map(|b| std::fs::write(&*p, b));
if remember {
self.save(|l| {
l.provider = kind;
l.model = model.clone();
});
}
let window = models::window(&self.models, &model);
agent.set_model_window(window);
@@ -261,6 +475,7 @@ mod tests {
provider: Kind::Claude,
model: "m".into(),
effort: None,
auto: false,
};
let mut sw = sw.remember_in(f.clone(), start);
sw.set_model(&mut a, "gpt-x").unwrap();
@@ -269,12 +484,110 @@ mod tests {
provider: Kind::Codex,
model: "gpt-x".into(),
effort: Some(hx_ai::Effort::High),
auto: false,
};
assert_eq!(Last::load(&f), Some(want));
std::fs::write(&f, "junk").unwrap();
assert_eq!(Last::load(&f), None);
}
fn nofile(_: &str) -> bool {
false
}
#[test]
fn auto_routes_per_prompt_and_pin_turns_it_off() {
let (mut sw, mut a, made, _d) = setup(true, false);
sw.set_auto(true);
assert!(sw.is_auto());
let r = sw
.begin_turn(&mut a, "fix the typo in README", &nofile)
.unwrap()
.unwrap();
assert!(!r.forced);
assert_eq!(
(r.pick.model.as_str(), a.model()),
("claude-haiku-x", "claude-haiku-x")
);
assert!(made.lock().unwrap().is_empty(), "same provider: no rebuild");
sw.set_model(&mut a, "claude-sonnet-x").unwrap();
assert!(!sw.is_auto());
assert!(
sw.begin_turn(&mut a, "fix the typo", &nofile)
.unwrap()
.is_none()
);
}
#[test]
fn override_is_one_turn_and_restores() {
let (mut sw, mut a, made, _d) = setup(true, false);
a.set_effort(hx_ai::Effort::High);
let r = sw
.begin_turn(&mut a, "@gpt-x explain this", &nofile)
.unwrap()
.unwrap();
assert!(r.forced && r.sw.provider_changed);
assert_eq!(r.prompt, "explain this");
assert_eq!((sw.kind(), a.model()), (Kind::Codex, "gpt-x"));
let back = sw.end_turn(&mut a).unwrap();
assert_eq!(back.kind, Kind::Claude);
assert_eq!(
(sw.kind(), a.model(), a.effort()),
(Kind::Claude, "claude-sonnet-x", hx_ai::Effort::High)
);
assert_eq!(*made.lock().unwrap(), vec![Kind::Codex, Kind::Claude]);
assert!(sw.end_turn(&mut a).is_none(), "nothing left to undo");
// a file with that name is a mention, not an override
assert!(
sw.begin_turn(&mut a, "@gpt-x explain", &|w| w == "gpt-x")
.unwrap()
.is_none()
);
}
#[test]
fn override_in_auto_mode_keeps_auto() {
let (mut sw, mut a, _m, _d) = setup(true, false);
sw.set_auto(true);
let r = sw
.begin_turn(&mut a, "@haiku hi there", &nofile)
.unwrap()
.unwrap();
assert!(r.forced && sw.is_auto());
assert_eq!(a.model(), "claude-haiku-x");
assert!(
sw.end_turn(&mut a).is_none(),
"auto picks again next prompt"
);
}
#[test]
fn spent_provider_is_avoided_until_reset() {
let (mut sw, mut a, _m, _d) = setup(true, false);
let q = hx_ai::Quota {
windows: vec![hx_ai::QuotaWindow {
label: "5h".into(),
used_pct: 100.0,
resets_at: Some(hx_ai::auth::now_ms() / 1000 + 600),
}],
credits: None,
};
sw.note_quota(Kind::Claude, &q);
sw.set_auto(true);
let r = sw
.begin_turn(&mut a, "add a flag to the parser please", &nofile)
.unwrap()
.unwrap();
assert_eq!(r.pick.kind, Kind::Codex);
let ok = hx_ai::Quota {
windows: vec![],
credits: None,
};
sw.note_quota(Kind::Claude, &ok);
assert!(sw.out_of_quota().is_none());
}
#[test]
fn configured_threshold_is_left_alone() {
let (mut sw, mut a, _m, _d) = setup(false, false);
+101 -19
View File
@@ -61,7 +61,21 @@ impl Choose {
KeyCode::Backspace => {
t.pop();
}
KeyCode::Char(c) => t.push(c),
KeyCode::Char('w') if k.modifiers.contains(KeyModifiers::CONTROL) => {
let n = t
.trim_end()
.trim_end_matches(|c: char| !c.is_whitespace())
.len();
t.truncate(n);
}
KeyCode::Char('j') if k.modifiers.contains(KeyModifiers::CONTROL) => t.push('\n'),
KeyCode::Enter
if k.modifiers
.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT) =>
{
t.push('\n')
}
KeyCode::Char(c) if !k.modifiers.contains(KeyModifiers::CONTROL) => t.push(c),
KeyCode::Enter if !t.trim().is_empty() => {
let mut v = picked;
v.push(t.trim().to_string());
@@ -96,6 +110,13 @@ impl Choose {
Act::None
}
/// Bracketed paste: append to the own answer while typing.
pub fn paste(&mut self, s: &str) {
if let Some(t) = &mut self.typing {
t.push_str(&s.replace("\r\n", "\n").replace('\r', "\n"));
}
}
fn enter(&mut self) -> Act {
if self.is_other() || self.rows() == 0 {
self.typing = Some(String::new());
@@ -106,7 +127,7 @@ impl Choose {
pub fn help(&self) -> &'static str {
if self.typing.is_some() {
"enter send · esc back"
"enter send · shift/alt-enter newline · ctrl-w word · esc back"
} else if self.q.multi {
"↑↓ move · space toggle · enter confirm · esc skip"
} else {
@@ -158,24 +179,32 @@ impl Choose {
if self.is_other() {
sel_line = lines.len();
}
lines.push(match &self.typing {
Some(t) => Line::from(vec![
if let Some(t) = &self.typing {
let pre = format!("{} other: ", n + 1);
let rows = hard_wrap(&format!("{pre}{t}▏"), inner);
sel_line = lines.len() + rows.len() - 1;
for (i, r) in rows.into_iter().enumerate() {
if i == 0 {
let k = pre.len().min(r.len());
lines.push(Line::from(vec![
Span::styled(r[..k].to_string(), th.accent()),
Span::raw(r[k..].to_string()),
]));
} else {
lines.push(Line::raw(r));
}
}
} else {
let st = if self.is_other() {
th.sel()
} else {
th.plain()
};
lines.push(Line::from(vec![
Span::styled(format!("{} ", n + 1), th.accent()),
Span::styled("other: ", th.accent()),
Span::raw(format!("{t}▏")),
]),
None => Line::from(vec![
Span::styled(format!("{} ", n + 1), th.accent()),
Span::styled(
"other…",
if self.is_other() {
th.sel()
} else {
th.plain()
},
),
]),
});
Span::styled("other…", st),
]));
}
}
let q = Paragraph::new(self.q.text.as_str())
.wrap(Wrap { trim: false })
@@ -211,6 +240,24 @@ impl Choose {
}
}
/// Wrap to `w` chars keeping all spaces/newlines; break at last space, else hard.
fn hard_wrap(s: &str, w: usize) -> Vec<String> {
let w = w.max(1);
let mut out = vec![];
for para in s.split('\n') {
let mut cur: Vec<char> = vec![];
for c in para.chars() {
if cur.len() >= w {
let at = cur.iter().rposition(|&x| x == ' ').map_or(w, |i| i + 1);
out.push(cur.drain(..at).collect());
}
cur.push(c);
}
out.push(cur.into_iter().collect());
}
out
}
/// Greedy word wrap to `w` chars (a single longer word is kept whole).
fn wrap(s: &str, w: usize) -> Vec<String> {
let mut out: Vec<String> = vec![];
@@ -289,6 +336,41 @@ mod tests {
);
}
#[test]
fn long_answer_wraps_and_stays_visible() {
let mut c = q(false);
c.key(k(KeyCode::Char('3')));
for ch in "word ".repeat(30).chars().chain("END".chars()) {
c.key(k(KeyCode::Char(ch)));
}
c.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT));
c.paste("pasted\r\nmore");
c.key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL));
assert!(
c.typing
.as_deref()
.unwrap()
.ends_with("pasted\nmore".trim_end_matches("more"))
);
for ch in "tail".chars() {
c.key(k(KeyCode::Char(ch)));
}
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 24)).unwrap();
term.draw(|f| c.draw(f, 23)).unwrap();
let b = term.backend().buffer().clone();
let all: String = (0..24)
.map(|y| {
(0..80)
.map(|x| b[(x, y)].symbol().to_string())
.collect::<String>()
+ "\n"
})
.collect();
assert!(all.contains("END") && all.contains("tail▏"), "{all}");
assert_eq!(hard_wrap("aaaa bbbb cccc", 9), ["aaaa ", "bbbb cccc"]);
assert_eq!(hard_wrap("abcdefgh", 3), ["abc", "def", "gh"]);
}
#[test]
fn typing_esc_goes_back_and_renders() {
let mut c = q(false);
+132 -9
View File
@@ -198,6 +198,7 @@ struct App {
impl App {
/// Mirror a model/provider switch into what the footer shows.
fn apply_switch(&mut self, sw: &hx_core::switch::Switched) {
self.st.auto = self.sw.is_auto();
self.st.kind = sw.kind;
self.st.model = sw.model.clone();
// keep the level when the new provider has it, else its first (Codex has no "off")
@@ -242,7 +243,7 @@ pub fn project_files(root: &std::path::Path) -> Vec<String> {
fn expand_mentions(s: &str, root: &std::path::Path) -> String {
let mut att = String::new();
for w in s.split_whitespace().filter_map(|w| w.strip_prefix('@')) {
let p = root.join(w);
let p = root.join(cmd::expand_home(w));
if let Ok(c) = std::fs::read_to_string(&p)
&& c.len() < 200_000
{
@@ -339,6 +340,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
cwd_label: home_short(&cwd),
git: git_head(&cwd),
st: status::Status {
auto: switcher.is_auto(),
kind: switcher.kind(),
model: agent.model().to_string(),
effort: agent.effort(),
@@ -453,6 +455,18 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
dirty = true;
match ev {
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.perm.is_some() => {
if k.code == KeyCode::Char('!') {
let mut a = app.state.allow.lock().unwrap_or_else(|e| e.into_inner());
if !a.yolo_on() {
a.toggle_yolo();
}
drop(a);
if let Some((p, reply)) = app.perm.take() {
app.t.push(Item::Info(format!("yolo on; allowed {} {}", p.req.tool, p.req.detail)));
let _ = reply.send(hx_core::permit::Decision::Once);
}
continue;
}
if let Some((p, _)) = &mut app.perm
&& let Some(d) = p.key(k)
&& let Some((p, reply)) = app.perm.take()
@@ -494,6 +508,11 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
}
}
TEvent::Mouse(m) => on_mouse(&mut app, m),
TEvent::Paste(s) if app.choose.is_some() => {
if let Some((c, _)) = &mut app.choose {
c.paste(&s);
}
}
TEvent::Paste(s) if app.perm.is_none() && app.choose.is_none() && app.ask.is_none() => app.ed.insert(&s),
TEvent::Resize(..) => app.sel = None,
_ => {}
@@ -510,6 +529,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
app.st.usage.add(u);
}
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
app.sw.note_quota(app.st.kind, q);
app.st.quota = Some(q.clone());
}
if let Event::Stream(
@@ -528,6 +548,14 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
}
Ui::Done(r) => {
app.busy = false;
{
let mut a = agent.lock().await;
if let Some(sw) = app.sw.end_turn(&mut a) {
app.apply_switch(&sw);
app.st.effort = a.effort();
app.ctx_max_from(&a);
}
}
app.git = git_head(&cwd);
match r {
Err(e) if e == "aborted" => app.t.push(Item::Info("aborted".into())),
@@ -1200,7 +1228,11 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
match labels.len() {
0 => app.hint = "no match".into(),
1 => {
let l = format!("{} ", labels[0]);
let l = if labels[0].ends_with('/') {
labels[0].to_string()
} else {
format!("{} ", labels[0])
};
app.ed.replace(c.start, &l);
}
_ => {
@@ -1232,19 +1264,22 @@ fn completion(app: &App) -> Completion {
/// Commands and their arguments complete as you type; `@file` waits for Tab (the file list is big).
fn live_popup(app: &mut App) {
app.popup = None;
if !app.ed.buf.starts_with('/') || app.ed.buf.contains('\n') {
if app.ed.buf.contains('\n') {
return;
}
let c = completion(app);
if !app.ed.buf[c.start..app.ed.cur].starts_with('@') {
let tok = &app.ed.buf[c.start..app.ed.cur];
let fs = cmd::is_fs_path(tok.strip_prefix('@').unwrap_or(tok));
if fs || (app.ed.buf.starts_with('/') && !tok.starts_with('@')) {
app.popup = popup::Popup::new(c);
}
}
fn accept(app: &mut App) {
if let Some(p) = app.popup.take() {
app.ed
.replace(p.comp.start, &format!("{} ", p.selected_label()));
let l = p.selected_label();
let sp = if l.ends_with('/') { "" } else { " " };
app.ed.replace(p.comp.start, &format!("{l}{sp}"));
live_popup(app);
}
}
@@ -1272,7 +1307,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
let (c, arg) = cmd
.split_once(' ')
.map_or((cmd, ""), |(a, b)| (a, b.trim()));
if app.busy && !matches!(c, "quit" | "btw") {
if app.busy && !matches!(c, "quit" | "btw" | "yolo") {
app.t.push(Item::Error("busy; esc to abort first".into()));
return;
}
@@ -1349,6 +1384,36 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
}
show(app, "skills", l);
}
"sandbox" => {
use hx_core::sandbox as sb;
let r = match arg {
"" => Ok(()),
"on" => sb::set_enabled(true),
"off" => sb::set_enabled(false),
"claude" => {
sb::set_claude_sandboxed(!sb::claude_sandboxed());
Ok(())
}
_ => Err("usage: /sandbox [on|off|claude]".into()),
};
app.t.push(match r {
Ok(()) => Item::Info(format!(
"sandbox {} · claude {}{}",
if sb::active().is_some() { "on" } else { "off" },
if sb::claude_sandboxed() {
"sandboxed"
} else {
"unconfined"
},
if arg.is_empty() {
""
} else {
" · applies to new processes (restart LSP with /lsp)"
}
)),
Err(e) => Item::Error(e),
});
}
"yolo" => {
let on = app
.state
@@ -1405,11 +1470,23 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
))),
Err(e) => app.t.push(Item::Error(e)),
},
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.st.model))),
"model" if arg.is_empty() => app.t.push(Item::Info(format!(
"model: {}{}",
app.st.model,
if app.st.auto { " (auto)" } else { "" }
))),
"model" if arg == "auto" => {
app.sw.set_auto(true);
app.st.auto = true;
app.t.push(Item::Info(
"model: auto. Picked per prompt across logged-in providers; `@opus ...`, `@codex ...`, `@fast ...` force one turn.".into(),
));
}
"model" => {
let mut a = agent.lock().await;
match app.sw.set_model(&mut a, arg) {
Ok(sw) => {
app.st.auto = false;
app.apply_switch(&sw);
app.ctx_max_from(&a);
app.t.push(Item::Info(format!(
@@ -1491,6 +1568,36 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
} else {
line.clone()
}));
// auto mode / `@opus ...` override: choose model and thinking for this prompt
let routed = {
let mut a = agent.lock().await;
let is_file = |w: &str| cwd.join(w).is_file();
match app.sw.begin_turn(&mut a, &line, &is_file) {
Ok(r) => {
if let Some(r) = &r {
app.apply_switch(&r.sw);
app.st.effort = r.pick.effort;
app.ctx_max_from(&a);
}
r
}
Err(e) => {
app.t.push(Item::Error(format!("model choice: {e}")));
None
}
}
};
if let Some(r) = routed {
app.t.push(Item::Info(format!(
"{} {} ({:?}, think {}): {}",
if r.forced { "forced" } else { "auto" },
r.pick.model,
r.pick.kind,
r.pick.effort.name(),
r.pick.why
)));
line = r.prompt;
}
app.busy = true;
app.since = Instant::now();
app.run_tokens = (0, 0);
@@ -2424,6 +2531,7 @@ mod tests {
busy: false,
queue: VecDeque::new(),
st: status::Status {
auto: false,
kind: Kind::Claude,
model: "m1".into(),
effort: hx_ai::Effort::Off,
@@ -2481,6 +2589,21 @@ mod tests {
assert!(s.ends_with("/nonexistent-hx (missing)"), "{s}");
}
#[test]
fn fs_path_popup_opens_live_and_dirs_keep_going() {
let d = tempfile::tempdir().unwrap();
std::fs::create_dir_all(d.path().join("alpha/inner")).unwrap();
let mut app = test_app();
for c in format!("look {}/al", d.path().display()).chars() {
key(&mut app, KeyCode::Char(c));
}
assert!(app.popup.is_some());
key(&mut app, KeyCode::Tab);
assert!(app.ed.buf.ends_with("/alpha/"), "{}", app.ed.buf);
key(&mut app, KeyCode::Tab);
assert!(app.ed.buf.ends_with("/alpha/inner/"), "{}", app.ed.buf);
}
#[test]
fn popup_keys_and_render() {
let mut app = test_app();
@@ -2546,7 +2669,7 @@ mod tests {
for c in "/model ".chars() {
key(&mut app, KeyCode::Char(c));
}
assert_eq!(labels(&app).unwrap().0, ["opus", "sonnet"]);
assert_eq!(labels(&app).unwrap().0, ["auto", "opus", "sonnet"]);
assert_eq!(key(&mut app, KeyCode::Enter).as_deref(), Some("/model "));
// @file waits for tab; esc closes; up with popup closed browses history
+5 -1
View File
@@ -11,6 +11,8 @@ use ratatui::text::{Line, Span};
/// What the status line and `/usage` report about the running session.
pub struct Status {
/// `/model auto` is on: the model shown was picked for the last prompt
pub auto: bool,
pub kind: Kind,
pub model: String,
pub effort: hx_ai::Effort,
@@ -135,8 +137,9 @@ fn left_spans(st: &Status) -> Vec<Span<'static>> {
.unwrap_or_default(),
};
let model = st.model.strip_prefix("claude-").unwrap_or(&st.model);
let auto = if st.auto { "auto→" } else { "" };
vec![
Span::styled(format!("{model} {} ctx ", th.sym.info), th.sec()),
Span::styled(format!("{auto}{model} {} ctx ", th.sym.info), th.sec()),
Span::styled(th.sym.bar_full.repeat(full), bar_st),
Span::styled(th.sym.bar_empty.repeat(10 - full), th.dim()),
Span::styled(format!(" {:.0}%{cost}", frac * 100.0), th.sec()),
@@ -269,6 +272,7 @@ mod tests {
fn st() -> Status {
Status {
auto: false,
kind: Kind::Claude,
model: "claude-m1".into(),
effort: hx_ai::Effort::Off,
+49 -22
View File
@@ -6,37 +6,64 @@
outputs =
{ self, nixpkgs }:
let
systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ];
systems = [ "x86_64-linux" "aarch64-linux" "aarch64-darwin" ];
forAll = f: nixpkgs.lib.genAttrs systems (s: f nixpkgs.legacyPackages.${s});
# release binaries, bin.json is rewritten by the release job in .gitea/workflows/build.yml
bin = builtins.fromJSON (builtins.readFile ./bin.json);
targets = {
x86_64-linux = "x86_64-unknown-linux-musl";
aarch64-darwin = "aarch64-apple-darwin";
};
in
{
packages = forAll (pkgs: rec {
hx = pkgs.rustPlatform.buildRustPackage {
pname = "hx";
version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).workspace.package.version;
src = pkgs.lib.cleanSource ./.;
cargoLock.lockFile = ./Cargo.lock;
cargoBuildFlags = [ "-p" "hx-cli" ];
# ponytail: tests skipped (need git/network); enable when hermetic.
doCheck = false;
# rustls may build aws-lc-sys (cmake) depending on feature set.
nativeBuildInputs = [ pkgs.cmake pkgs.perl ];
dontUseCmakeConfigure = true;
meta = {
description = "Minimal Rust coding agent using existing subscriptions";
license = pkgs.lib.licenses.unlicense;
mainProgram = "hx";
packages = forAll (
pkgs:
let
target = targets.${pkgs.stdenv.hostPlatform.system} or "";
hasBin = bin.sha256 ? ${target};
hx = pkgs.rustPlatform.buildRustPackage {
pname = "hx";
version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).workspace.package.version;
src = pkgs.lib.cleanSource ./.;
cargoLock.lockFile = ./Cargo.lock;
cargoBuildFlags = [ "-p" "hx-cli" ];
# ponytail: tests skipped (need git/network); enable when hermetic.
doCheck = false;
# rustls may build aws-lc-sys (cmake) depending on feature set.
nativeBuildInputs = [ pkgs.cmake pkgs.perl ];
dontUseCmakeConfigure = true;
meta = {
description = "Minimal Rust coding agent using existing subscriptions";
license = pkgs.lib.licenses.unlicense;
mainProgram = "hx";
};
};
};
default = hx;
});
hx-bin = pkgs.runCommand "hx-${bin.version}" { meta.mainProgram = "hx"; } ''
mkdir -p $out/bin
tar -xzf ${
pkgs.fetchurl {
url = "https://git.jokresner.de/johannes/hx/releases/download/v${bin.version}/hx-${target}.tar.gz";
sha256 = bin.sha256.${target};
}
} -C $out/bin hx
'';
in
{
inherit hx;
# prebuilt binary where the release has one, source build elsewhere
default = if hasBin then hx-bin else hx;
}
// pkgs.lib.optionalAttrs hasBin { inherit hx-bin; }
);
apps = forAll (pkgs: rec {
hx = { type = "app"; program = "${self.packages.${pkgs.system}.hx}/bin/hx"; };
hx = { type = "app"; program = "${self.packages.${pkgs.system}.default}/bin/hx"; };
default = hx;
});
overlays.default = _: prev: { hx = self.packages.${prev.system}.hx; };
overlays.default = _: prev: { hx = self.packages.${prev.system}.default; };
devShells = forAll (pkgs: {
default = pkgs.mkShell {
+3 -2
View File
@@ -5,11 +5,12 @@ root=$(cd "$(dirname "$0")/.." && pwd)
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
mkdir -p "$tmp/home/.hx" "$tmp/repo"
printf 'claude_cli = []\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml"
printf 'claude_cli = []\ncodemode = true\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml"
chmod +x "$root/tests/fake_claude.py"
cd "$tmp/repo"
export HOME="$tmp/home" HX_CLAUDE_BIN="$root/tests/fake_claude.py" FAKE_CLAUDE_LOG="$tmp/argv"
"$root/target/debug/hx" -p "hi" -s "$tmp/s.jsonl" > "$tmp/out" 2> "$tmp/err" || { echo "FAIL run"; cat "$tmp/err"; exit 1; }
grep -q "approve: allow" "$tmp/out" || { echo "FAIL text"; cat "$tmp/out" "$tmp/err"; exit 1; }
grep -q "claude Bash: echo hi-from-tool" "$tmp/out" && grep -q "approve: allow" "$tmp/out" || { echo "FAIL text"; cat "$tmp/out" "$tmp/err"; exit 1; }
grep -q '"--permission-prompt-tool"' "$tmp/argv" && grep -q '"--mcp-config"' "$tmp/argv" && grep -q '"stream-json"' "$tmp/argv" || { echo "FAIL argv"; cat "$tmp/argv"; exit 1; }
grep -q "cm-ok" "$tmp/out" || { echo "FAIL codemode"; cat "$tmp/out" "$tmp/err"; exit 1; }
echo "claude cli e2e ok"
+9 -2
View File
@@ -15,12 +15,19 @@ if "--permission-prompt-tool" in sys.argv: # act like claude: ask hx whether `r
{"tool_name": "Bash", "input": {"command": "rm -rf x"}}}}
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n" + json.dumps(call) + "\n")
p.stdin.flush()
lines = [json.loads(p.stdout.readline()) for _ in range(2)]
cm = {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "codemode", "arguments":
{"script": "return await tools.bash({command: 'echo cm-' + 'ok > cm.txt; cat cm.txt'})"}}}
if "HX_CODEMODE" in cfg["env"]:
p.stdin.write(json.dumps(cm) + "\n"); p.stdin.flush()
lines = [json.loads(p.stdout.readline()) for _ in range(2 + ("HX_CODEMODE" in cfg["env"]))]
p.stdin.close()
reply = "approve: " + json.loads(lines[1]["result"]["content"][0]["text"])["behavior"]
if len(lines) == 3:
reply += " " + lines[2]["result"]["content"][0]["text"]
out({"type": "system", "subtype": "init", "session_id": "S1"})
ev = lambda e: out({"type": "stream_event", "session_id": "S1", "event": e})
ev({"type": "content_block_start", "content_block": {"type": "tool_use", "name": "Read"}})
out({"type": "assistant", "session_id": "S1", "message": {"content": [
{"type": "tool_use", "name": "Bash", "input": {"command": "echo hi-from-tool"}}]}})
ev({"type": "content_block_delta", "delta": {"type": "text_delta", "text": reply + " "}})
ev({"type": "content_block_delta", "delta": {"type": "text_delta", "text": "from claude"}})
out({"type": "result", "session_id": "S1", "is_error": False, "result": "hello from claude",
+14 -1
View File
@@ -79,13 +79,26 @@ send(b"/usage\r")
check("usage report", "58% left, resets in 2h1")
check("1M window", "of 900k")
send(b"/model claude-opus-5-5\r")
check("model switch", "opus-5-5 (Claude) · context 1000k")
check("model switch", "model → claude-opus-5-5 (Claude)")
send(b"/model gpt-5.6-sol\r")
check("gpt model needs codex login", "not logged in to Codex")
send(b"/model claude-sonnet-5-6-preview\r")
check("live catalog window", "2000k")
check("live catalog cached", "") if os.path.exists(f"{tmp}/home/.hx/models-claude.json") else (print("FAIL no model cache"), globals().update(ok=False))
buf = b""
# auto mode: per-prompt choice, one-turn @override, pinning turns it off
send(b"/model auto\r")
check("auto on", "model: auto")
send(b"fix the typo in notes.md\r", 3)
check("auto picks the cheap tier for a typo", "auto claude-haiku-4-5")
check("footer marks auto", "auto→")
send(b"@opus say hi\r", 4)
check("override forces one turn", "forced")
send(b"/model claude-sonnet-5-5\r")
send(b"fix the typo again\r", 3)
check("pinned model: no routing", "")
ok &= "auto claude-haiku-4-5 (Claude, think off): fast (score -2: typo)\n" not in plain().split("fix the typo again")[-1]
buf = b""
send(b"/provider ")
check("only logged-in providers offered", "claude")
ok &= "codex" not in plain(); print("PASS no codex without login" if "codex" not in plain() else "FAIL codex offered")