22 Commits
Author SHA1 Message Date
hermes 39a4e0c625 Merge pull request 'claude_cli: AskUserQuestion shows hx popup' (#177) from fix/claude-ask-question into main
build / version (push) Successful in 10s
build / build (aarch64-apple-darwin) (push) Successful in 5m45s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m55s
build / release (push) Successful in 21s
2026-11-05 19:29:30 +00:00
hermes dc0a329ae1 claude_cli: route AskUserQuestion to hx popup, no permission prompt 2026-11-05 19:27:44 +00:00
gitea-actions ca6b917b17 ci: bin.json v0.1.3 2026-11-03 22:47:35 +00:00
johannes 042f1ed3b5 Merge branch 'fix/lenient-skill-frontmatter'
build / version (push) Successful in 9s
build / build (aarch64-apple-darwin) (push) Successful in 5m29s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m54s
build / release (push) Successful in 21s
2026-11-03 23:36:29 +01:00
johannesandClaude Sonnet 5.5 9843e5305c skills: fall back to line-based frontmatter when YAML is invalid
Descriptions with an unquoted ': ' (e.g. floorplan) failed strict YAML and
the skill was silently dropped. Read single-line known keys instead; skills
with no recognised key are still skipped and reported in /skills.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 23:36:18 +01:00
gitea-actions 047e781ca4 ci: bin.json v0.1.2 2026-11-03 21:32:24 +00:00
hermes cfb517e806 Merge pull request '/reload: re-read AGENTS.md, skills, config' (#176) from feat/reload into main
build / version (push) Successful in 11s
build / build (aarch64-apple-darwin) (push) Successful in 4m54s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m31s
build / release (push) Successful in 19s
2026-11-03 21:22:27 +00:00
hermes dac2320503 tui: /reload re-reads AGENTS.md, skills, config, MCP prompt index 2026-11-03 21:21:28 +00:00
gitea-actions 130704b8b3 ci: bin.json v0.1.1 2026-11-02 15:47:28 +00:00
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
22 changed files with 1859 additions and 111 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
+17 -1
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,6 +82,21 @@ 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; `/yolo` toggles it live (also while a turn runs), `!` on a permission prompt allows it and turns yolo on.
+7
View File
@@ -0,0 +1,7 @@
{
"version": "0.1.3",
"sha256": {
"aarch64-apple-darwin": "0fa455f5cc4c63df942224602ecad0b83ee91847cef6fde8f0e4704bf0913810",
"x86_64-unknown-linux-musl": "8bc56e52a403088229e25470ccd12b2b7fe9e1195062206827beff9be630f3f7"
}
}
+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();
+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"
+64 -5
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))
@@ -560,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(());
@@ -764,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);
}
@@ -808,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(),
@@ -855,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);
@@ -1012,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;
@@ -1035,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,
@@ -1078,6 +1117,26 @@ async fn main() -> Result<()> {
}) as _)
})
},
reload: {
let (mcp, cwd, models, kinds) =
(mcp.clone(), cwd.clone(), models.clone(), kinds.clone());
Box::new(move || {
let cfg = Config::load(&cwd).map_err(|e| e.to_string())?;
let mut sys = format!(
"{}{}",
cfg.system_prompt
.as_deref()
.unwrap_or(context::DEFAULT_PROMPT),
context::prompt_tail(&context::hx_home(), &cwd)
);
let idx = mcp.system_prompt();
if !idx.is_empty() {
sys.push_str("\n\n");
sys.push_str(&idx);
}
Ok((sys, command_specs(&mcp, &cwd, &models, &kinds)))
})
},
lsp_status: {
let (m, l) = (mgr.clone(), lens_ref.clone());
Box::new(move || {
+4
View File
@@ -243,6 +243,10 @@ impl Agent {
self.effort = e;
}
pub fn system(&self) -> &str {
&self.system
}
pub fn set_system(&mut self, system: impl Into<String>) {
self.system = system.into();
self.publish();
+55 -8
View File
@@ -78,7 +78,12 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
}
let v: Value = serde_json::from_str(&line).unwrap_or_default();
// hx tools run by `codemode` inside mcp-serve ask for their own permission
let ok = if let Some(q) = v.get("permit") {
let mut input = None;
let ok = if v["tool_name"] == "AskUserQuestion" {
// claude's own question tool: show hx's popup, hand the answers back as input
input = ask(&cx, &v["input"]).await;
input.is_some()
} else if let Some(q) = v.get("permit") {
let s = |k: &str| q[k].as_str().unwrap_or_default().to_string();
gate(
&cx,
@@ -96,13 +101,40 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
}
};
let _ = w
.write_all(format!("{}\n", json!({"allow": ok})).as_bytes())
.write_all(format!("{}\n", json!({"allow": ok, "input": input})).as_bytes())
.await;
});
}
}
async fn roundtrip(path: &Path, msg: Value) -> bool {
/// Run each `AskUserQuestion` question through the popup; `input` plus `answers` (question -> label(s)).
/// None = no frontend or dismissed.
async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
let mut answers = serde_json::Map::new();
for q in input["questions"].as_array()? {
let text = q["question"].as_str().unwrap_or_default();
let options = q["options"].as_array().into_iter().flatten().map(|o| {
let s = |k| o[k].as_str().unwrap_or_default().to_string();
(s("label"), s("description"))
});
let r = cx
.state
.choose(crate::Question {
text: text.into(),
options: options.collect(),
multi: q["multiSelect"].as_bool().unwrap_or(false),
other: true,
})
.await
.ok()??;
answers.insert(text.into(), r.join(", ").into());
}
let mut out = input.clone();
out["answers"] = answers.into();
Some(out)
}
async fn roundtrip(path: &Path, msg: Value) -> Option<Value> {
let ask = async {
let mut c = UnixStream::connect(path).await?;
c.write_all(format!("{msg}\n").as_bytes()).await?;
@@ -113,7 +145,7 @@ async fn roundtrip(path: &Path, msg: Value) -> bool {
ask.await
.ok()
.and_then(|l| serde_json::from_str::<Value>(&l).ok())
.is_some_and(|v| v["allow"] == true)
.filter(|v| v["allow"] == true)
}
/// Permission hook for tools that run in another process (`hx mcp-serve`): ask the owner of the socket.
@@ -125,7 +157,7 @@ pub fn remote_permit(path: PathBuf) -> crate::permit::Permit {
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 {
if roundtrip(&path, m).await.is_some() {
Decision::Once
} else {
Decision::Deny
@@ -149,9 +181,10 @@ impl Tool for Approve {
}
}
async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult {
let ok = roundtrip(&self.0, args.clone()).await;
ToolResult::ok(if ok {
json!({"behavior": "allow", "updatedInput": args["input"]})
let r = roundtrip(&self.0, args.clone()).await;
ToolResult::ok(if let Some(r) = r {
let input = if r["input"].is_null() { &args["input"] } else { &r["input"] };
json!({"behavior": "allow", "updatedInput": input})
} else {
json!({"behavior": "deny", "message": "denied by the user; do not retry, ask what to do instead"})
}
@@ -179,6 +212,20 @@ mod tests {
assert_eq!(question("Foo", &json!({})).unwrap().rule, "claude:Foo");
}
#[tokio::test]
async fn ask_user_question_uses_popup() {
let cx = ToolCtx {
cwd: ".".into(),
state: Default::default(),
};
let inp = json!({"questions": [{"question": "Which?", "options": [{"label": "A"}, {"label": "B"}]}]});
assert!(ask(&cx, &inp).await.is_none(), "no frontend = deny");
let _ = cx.state.choose.set(std::sync::Arc::new(|q| {
Box::pin(async move { Some(vec![q.options[1].0.clone()]) })
}));
assert_eq!(ask(&cx, &inp).await.unwrap()["answers"]["Which?"], "B");
}
#[tokio::test]
async fn socket_round_trip_allows_and_denies() {
use crate::permit::Decision;
+107 -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),
@@ -89,6 +98,11 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
),
b("btw", "side question; no tools, not saved", Free),
b("skills", "list skills and where they load from", None),
b(
"reload",
"re-read AGENTS.md, skills, config, MCP prompt index",
None,
),
b(
"resume",
"resume a session file; no arg opens /sessions",
@@ -182,7 +196,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 +239,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 +362,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 +435,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!(
+38 -4
View File
@@ -97,6 +97,34 @@ struct Front {
argument_hint: Option<String>,
}
/// Fallback for frontmatter that is not valid YAML: `key: value` on one line, value taken verbatim
/// (surrounding quotes stripped). None when no known key is found.
fn lenient_front(fm: &str) -> Option<Front> {
let mut f = Front::default();
let mut found = false;
for line in fm.lines() {
let Some((k, v)) = line.split_once(':') else {
continue;
};
let v = v.trim();
let v = v
.strip_prefix('"')
.and_then(|x| x.strip_suffix('"'))
.unwrap_or(v)
.to_string();
match k {
"name" => f.name = Some(v),
"description" => f.description = Some(v),
"load" => f.load = Some(v),
"disable-model-invocation" => f.disable_model_invocation = Some(v == "true"),
"argument-hint" => f.argument_hint = Some(v),
_ => continue,
}
found = true;
}
found.then_some(f)
}
/// Skill dirs, lowest priority first: `~/.claude/skills`, `~/.agents/skills` (shared with other agents),
/// `<hx home>/skills`, `<project>/.agents/skills`, `<project>/.claude/skills`, `<project>/.hx/skills`.
pub fn skill_dirs(home: &Path, cwd: &Path) -> Vec<PathBuf> {
@@ -133,7 +161,11 @@ pub fn parse_skill(p: &Path, s: &str) -> Result<Skill, String> {
let f: Front = if fm.trim().is_empty() {
Front::default()
} else {
serde_norway::from_str(fm).map_err(|e| e.to_string())?
match serde_norway::from_str(fm) {
Ok(f) => f,
// strict YAML failed (e.g. unquoted `: ` in a description): read single-line top-level keys
Err(e) => lenient_front(fm).ok_or_else(|| e.to_string())?,
}
};
let load = match f.load.as_deref() {
Some("always") => Load::Always,
@@ -307,7 +339,7 @@ mod tests {
assert!(!k.model_invocable && k.load == Load::Auto);
let k = parse_skill(p, "---\nname: n\ndescription: |\n a\n b\n---\n").unwrap();
assert_eq!(k.description, "a b");
assert!(parse_skill(p, "---\ndescription: [oops\n---\nB").is_err());
assert!(parse_skill(p, "---\noops: [oops\n---\nB").is_err());
let k = parse_skill(p, "no frontmatter").unwrap();
assert_eq!((k.name.as_str(), k.body.as_str()), ("n", "no frontmatter"));
assert!(
@@ -329,7 +361,8 @@ load: manual
for (n, fm) in [
("ok", "description: fine"),
("hid", "description: secret\ndisable-model-invocation: true"),
("bad", "description: [oops"),
("bad", "oops: [oops"),
("colon", "description: before code exists: when asked"),
] {
let d = t.path().join("s").join(n);
std::fs::create_dir_all(&d).unwrap();
@@ -337,7 +370,8 @@ load: manual
}
let (sk, warn) = scan_skills(&[t.path().join("s")]);
let names: Vec<_> = sk.iter().map(|k| k.name.as_str()).collect();
assert_eq!(names, ["hid", "ok"]);
assert_eq!(names, ["colon", "hid", "ok"]);
assert_eq!(sk[0].description, "before code exists: when asked");
assert!(
warn.len() == 1 && warn[0].contains("bad/SKILL.md"),
"{warn:?}"
+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;
+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);
+157 -8
View File
@@ -47,6 +47,7 @@ pub struct Setup {
pub pricing: fn(&str) -> Option<hx_ai::Pricing>,
/// `/lsp` status lines.
pub lsp_status: LspStatus,
pub reload: Reload,
/// Extra slash commands (MCP prompts, `/mcp`): `(name, arg)` -> None = not mine,
/// Some(Ok(Send(text))) = send as a user prompt, Some(Ok(Show(text))) = show, Some(Err) = error.
pub commands: Commands,
@@ -88,6 +89,9 @@ pub type Commands = Box<
+ Sync,
>;
/// Rebuilds `(system prompt, slash commands)` from disk for `/reload`.
pub type Reload = Box<dyn Fn() -> Result<(String, Vec<CmdSpec>), String> + Send + Sync>;
pub type LspStatus = Box<
dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<String>> + Send>> + Send,
>;
@@ -198,6 +202,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 +247,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
{
@@ -258,6 +263,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
switcher,
pricing,
lsp_status,
reload,
commands,
specs,
open_sessions,
@@ -339,6 +345,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(),
@@ -392,6 +399,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
tx: &tx,
cwd: &cwd,
lsp_status: &lsp_status,
reload: &reload,
commands: &commands,
};
let mut term = ratatui::init();
@@ -506,6 +514,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,
_ => {}
@@ -522,6 +535,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(
@@ -540,6 +554,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())),
@@ -1212,7 +1234,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);
}
_ => {
@@ -1244,19 +1270,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);
}
}
@@ -1267,6 +1296,7 @@ struct Ctx<'a> {
tx: &'a mpsc::UnboundedSender<Ui>,
cwd: &'a std::path::Path,
lsp_status: &'a LspStatus,
reload: &'a Reload,
commands: &'a Commands,
}
@@ -1276,6 +1306,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
tx,
cwd,
lsp_status,
reload,
commands,
} = *c;
app.scroll.end();
@@ -1353,6 +1384,23 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
let r = status::report(&app.st, status::now_secs());
show(app, "usage", r);
}
"reload" => match reload() {
Err(e) => app.t.push(Item::Error(format!("/reload: {e}"))),
Ok((sys, specs)) => {
let mut a = agent.lock().await;
// unchanged prompt: leave it alone, a rewrite would drop the prompt cache
let same = a.system() == sys;
if !same {
a.set_system(sys);
}
let (old, new) = (app.specs.len(), specs.len());
app.specs = specs;
app.t.push(Item::Info(format!(
"reloaded: prompt {}, commands {old} → {new}",
if same { "unchanged" } else { "updated" }
)));
}
},
"skills" => {
let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd);
let mut l = skills_list(&app.specs, &dirs);
@@ -1361,6 +1409,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
@@ -1417,11 +1495,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!(
@@ -1503,6 +1593,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);
@@ -2436,6 +2556,7 @@ mod tests {
busy: false,
queue: VecDeque::new(),
st: status::Status {
auto: false,
kind: Kind::Claude,
model: "m1".into(),
effort: hx_ai::Effort::Off,
@@ -2493,6 +2614,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();
@@ -2558,7 +2694,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
@@ -2664,16 +2800,27 @@ mod tests {
let (tx, _rx) = mpsc::unbounded_channel();
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
let cmds: Commands = Box::new(|_, _| None);
let rl: Reload = Box::new(|| Ok(("sys".into(), cmd::builtins(&[]))));
let ctx = Ctx {
agent: &agent,
tx: &tx,
cwd: t.path(),
lsp_status: &ls,
reload: &rl,
commands: &cmds,
};
let mut app = test_app();
app.session_path = old.clone();
app.title = Some("first".into());
// /reload swaps prompt + commands; same prompt twice is reported unchanged
app.specs = vec![];
submit(&mut app, "/reload".into(), &ctx).await;
assert_eq!(agent.lock().await.system(), "sys");
assert!(app.specs.iter().any(|s| s.name == "reload"));
submit(&mut app, "/reload".into(), &ctx).await;
assert!(
matches!(app.t.items.last(), Some(Item::Info(m)) if m.contains("prompt unchanged"))
);
submit(&mut app, "/clear".into(), &ctx).await;
let new = agent.lock().await.session().path().to_path_buf();
assert_ne!(new, old);
@@ -2714,11 +2861,13 @@ mod tests {
models.extend(hx_ai::models::fallback(Kind::Codex));
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
let cmds: Commands = Box::new(|_, _| None);
let rl: Reload = Box::new(|| Ok(("sys".into(), cmd::builtins(&[]))));
let ctx = Ctx {
agent: &agent,
tx: &tx,
cwd: t.path(),
lsp_status: &ls,
reload: &rl,
commands: &cmds,
};
let mut app = test_app();
+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 {
+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")