Compare commits
1
Commits
v0.1.5
..
7f6ca8d353
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f6ca8d353 |
No files matched your search
@@ -1,109 +0,0 @@
|
||||
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
|
||||
@@ -0,0 +1,21 @@
|
||||
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
|
||||
@@ -59,8 +59,7 @@ 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; /sandbox toggles at runtime)
|
||||
# claude = true # false: claude (claude_cli provider) runs unconfined, no prompt
|
||||
# mode = "off" # off | on (CLI: --sandbox / --no-sandbox)
|
||||
# backend = "auto" # auto | bwrap | seatbelt
|
||||
# network = false
|
||||
# rw = ["~/.cargo/registry", "~/.cargo/git"] # extra writable paths
|
||||
@@ -82,26 +81,6 @@ 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. Common words (`implement`, `design`, `debug`, `plan`) count one point, not a tier; failed tool results escalate (+2, +4 when the last two turns failed), and many recent edits add a point. With a big history (>100k tokens) the default `down_after` is 5, since a switch re-reads it uncached. Each choice and its reason is shown as a line in the chat; the footer shows `auto→model`.
|
||||
|
||||
**Fable** is never chosen by default. `/fable on` (or `[auto] fable = true`; the command is remembered across starts and wins over the config) lets auto escalate to a fifth `max` tier (Fable, $10/$50 per Mtok) after two failed turns in a row or a score of 7+; the next ordinary prompt drops back at once. Without Fable in the catalog it stays on `deep`. `/fable` shows the state; `@fable ...` / `@max ...` always work for one turn.
|
||||
|
||||
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).
|
||||
|
||||
Within a tier the highest-versioned model is used (`claude-opus-5-5` over `claude-opus-4-1-20250805`, `gpt-5.6-sol` over `gpt-5.5-sol`), whatever order the API lists them in; no model id is hard-coded except the offline fallback list and your `[auto]` pins.
|
||||
|
||||
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` shows the auto choices (prompts and mean score per tier, how often a tier was held, how often the next prompt went up again; raw lines in `<session>.route`) and 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
|
||||
fable = false # same as /fable on|off
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"version": "0.1.4",
|
||||
"sha256": {
|
||||
"aarch64-apple-darwin": "58694e7424080ba5735835ad23be90229daf884b8575c722c985802744e11b79",
|
||||
"x86_64-unknown-linux-musl": "ac27b39c24b7d7f59e2649a118c854a5ed973175b52e260616a123eb2e8ff7df"
|
||||
}
|
||||
}
|
||||
@@ -61,40 +61,14 @@ 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": wire_id(id), "name": to_cc(name), "input": input})
|
||||
json!({"type": "tool_use", "id": id, "name": to_cc(name), "input": input})
|
||||
}
|
||||
other => serde_json::to_value(other).unwrap_or(Value::Null),
|
||||
}
|
||||
@@ -112,19 +86,7 @@ pub fn body(req: &Request) -> Value {
|
||||
let mut messages: Vec<Value> = req
|
||||
.messages
|
||||
.iter()
|
||||
.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})
|
||||
})
|
||||
.map(|m| json!({"role": m.role, "content": m.content.iter().map(block_json).collect::<Vec<_>>()}))
|
||||
.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.
|
||||
@@ -427,57 +389,6 @@ 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();
|
||||
|
||||
@@ -209,8 +209,6 @@ 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 {
|
||||
@@ -245,9 +243,6 @@ impl Provider for ClaudeCli {
|
||||
}
|
||||
// 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 {
|
||||
@@ -289,8 +284,7 @@ impl Provider for ClaudeCli {
|
||||
content,
|
||||
},
|
||||
stop: StopReason::EndTurn,
|
||||
// ponytail: billing/stats see the last request only; split Done if exact sums matter
|
||||
usage: usage(last.as_ref().unwrap_or(&v["usage"])),
|
||||
usage: usage(&v["usage"]),
|
||||
}));
|
||||
break;
|
||||
}
|
||||
@@ -358,37 +352,4 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -39,40 +39,14 @@ pub fn fallback(k: Kind) -> Vec<ModelInfo> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Version of a model id: its numbers in order, a date snapshot (8+ digits) after the rest, so
|
||||
/// `claude-opus-5-5` > `claude-opus-4-1-20250805` and `gpt-5.6-sol` > `gpt-5.5-sol`.
|
||||
fn version(id: &str) -> Vec<u64> {
|
||||
let n: Vec<u64> = id
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.filter_map(|p| p.parse().ok())
|
||||
.collect();
|
||||
let (dates, mut v): (Vec<u64>, Vec<u64>) = n.into_iter().partition(|n| *n >= 10_000_000);
|
||||
v.extend(dates);
|
||||
v
|
||||
}
|
||||
|
||||
/// Stable models rank above previews, then by version.
|
||||
fn key(m: &ModelInfo) -> (bool, Vec<u64>) {
|
||||
(!m.id.contains("preview"), version(&m.id))
|
||||
}
|
||||
|
||||
/// The highest-versioned model of `ms` (the first listed on a tie), whatever order the API lists them in.
|
||||
pub fn newest<'a>(ms: impl IntoIterator<Item = &'a ModelInfo>) -> Option<&'a ModelInfo> {
|
||||
ms.into_iter()
|
||||
.fold(None, |b: Option<&ModelInfo>, m| match b {
|
||||
Some(b) if key(b) >= key(m) => Some(b),
|
||||
_ => Some(m),
|
||||
})
|
||||
}
|
||||
|
||||
/// Default model for a provider: Sonnet for Claude, the provider's first-listed model otherwise.
|
||||
pub fn default_for(k: Kind, models: &[ModelInfo]) -> String {
|
||||
let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect();
|
||||
let pick = match k {
|
||||
Kind::Claude => newest(mine.iter().copied().filter(|m| m.id.contains("sonnet"))),
|
||||
Kind::Claude => mine.iter().find(|m| m.id.contains("sonnet")),
|
||||
Kind::Codex | Kind::Custom => None,
|
||||
};
|
||||
pick.or(mine.first().copied())
|
||||
pick.or(mine.first())
|
||||
.map(|m| m.id.clone())
|
||||
.or_else(|| fallback(k).first().map(|m| m.id.clone()))
|
||||
.unwrap_or_default()
|
||||
@@ -85,7 +59,10 @@ pub fn cheap_for(k: Kind, models: &[ModelInfo]) -> Option<String> {
|
||||
Kind::Codex => "luna",
|
||||
Kind::Custom => return None,
|
||||
};
|
||||
newest(models.iter().filter(|m| m.kind == k && m.id.contains(tag))).map(|m| m.id.clone())
|
||||
models
|
||||
.iter()
|
||||
.find(|m| m.kind == k && m.id.contains(tag))
|
||||
.map(|m| m.id.clone())
|
||||
}
|
||||
|
||||
/// Context window for `id`: exact match, then dated-snapshot prefix match, then a family guess.
|
||||
|
||||
@@ -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; "auto" = pick per prompt (see [auto])
|
||||
# model = "claude-sonnet-5-5" # model for the chosen provider
|
||||
# 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,13 +25,6 @@
|
||||
# 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"
|
||||
|
||||
@@ -15,12 +15,7 @@ mod rpc;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[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"
|
||||
)]
|
||||
#[command(name = "hx", version, about = "Minimal coding agent")]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
cmd: Option<Cmd>,
|
||||
@@ -50,9 +45,6 @@ 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,
|
||||
@@ -149,8 +141,6 @@ 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).
|
||||
@@ -222,7 +212,6 @@ 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),
|
||||
@@ -325,10 +314,7 @@ 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()
|
||||
|| !hx_core::sandbox::claude_sandboxed()
|
||||
|| claude_outside().await
|
||||
{
|
||||
if hx_core::sandbox::active().is_none() || claude_outside().await {
|
||||
return tokio::process::Command::new(bin);
|
||||
}
|
||||
hx_core::sandbox::command_with(&bin, &claude_extra(&bin))
|
||||
@@ -574,12 +560,7 @@ 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::route_report(&session));
|
||||
print!("{}", hx_core::stats::sub_report(&session));
|
||||
return Ok(());
|
||||
}
|
||||
@@ -783,13 +764,7 @@ 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);
|
||||
}
|
||||
@@ -831,21 +806,11 @@ async fn main() -> Result<()> {
|
||||
_ => kind,
|
||||
};
|
||||
// the remembered model applies only to the provider it was chosen on
|
||||
let last_fable = last.as_ref().and_then(|l| l.fable);
|
||||
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(),
|
||||
@@ -890,11 +855,7 @@ async fn main() -> Result<()> {
|
||||
provider: kind,
|
||||
model: model.clone(),
|
||||
effort: Some(effort),
|
||||
auto: want_auto,
|
||||
fable: last_fable,
|
||||
};
|
||||
let mut auto_cfg = cfg.auto.clone().unwrap_or_default();
|
||||
auto_cfg.fable = last_fable.or(auto_cfg.fable);
|
||||
if hx_core::herdr::init() {
|
||||
hx_core::herdr::set_session(&path);
|
||||
agent.bus.add(hx_core::herdr::Hook);
|
||||
@@ -1051,9 +1012,7 @@ async fn main() -> Result<()> {
|
||||
files: hx_tui::project_files(&cwd),
|
||||
session_dir: dir,
|
||||
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
|
||||
.auto_cfg(auto_cfg.clone())
|
||||
.remember_in(last_path.clone(), start.clone())
|
||||
.auto_on(want_auto),
|
||||
.remember_in(last_path.clone(), start.clone()),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
@@ -1076,9 +1035,7 @@ async fn main() -> Result<()> {
|
||||
hx_tui::run(hx_tui::Setup {
|
||||
agent,
|
||||
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
|
||||
.auto_cfg(auto_cfg)
|
||||
.remember_in(last_path, start)
|
||||
.auto_on(want_auto),
|
||||
.remember_in(last_path, start),
|
||||
pricing,
|
||||
specs,
|
||||
open_sessions,
|
||||
@@ -1121,26 +1078,6 @@ 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 || {
|
||||
|
||||
@@ -243,10 +243,6 @@ 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();
|
||||
|
||||
@@ -78,12 +78,7 @@ 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 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 ok = if let Some(q) = v.get("permit") {
|
||||
let s = |k: &str| q[k].as_str().unwrap_or_default().to_string();
|
||||
gate(
|
||||
&cx,
|
||||
@@ -101,40 +96,13 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
||||
}
|
||||
};
|
||||
let _ = w
|
||||
.write_all(format!("{}\n", json!({"allow": ok, "input": input})).as_bytes())
|
||||
.write_all(format!("{}\n", json!({"allow": ok})).as_bytes())
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
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?;
|
||||
@@ -145,7 +113,7 @@ async fn roundtrip(path: &Path, msg: Value) -> Option<Value> {
|
||||
ask.await
|
||||
.ok()
|
||||
.and_then(|l| serde_json::from_str::<Value>(&l).ok())
|
||||
.filter(|v| v["allow"] == true)
|
||||
.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.
|
||||
@@ -157,7 +125,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.is_some() {
|
||||
if roundtrip(&path, m).await {
|
||||
Decision::Once
|
||||
} else {
|
||||
Decision::Deny
|
||||
@@ -181,10 +149,9 @@ impl Tool for Approve {
|
||||
}
|
||||
}
|
||||
async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult {
|
||||
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})
|
||||
let ok = roundtrip(&self.0, args.clone()).await;
|
||||
ToolResult::ok(if ok {
|
||||
json!({"behavior": "allow", "updatedInput": args["input"]})
|
||||
} else {
|
||||
json!({"behavior": "deny", "message": "denied by the user; do not retry, ask what to do instead"})
|
||||
}
|
||||
@@ -212,20 +179,6 @@ 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;
|
||||
|
||||
@@ -52,16 +52,7 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
||||
b(
|
||||
"model",
|
||||
"show or switch model",
|
||||
Enum(
|
||||
std::iter::once("auto".to_string())
|
||||
.chain(models.iter().map(|m| m.to_string()))
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
b(
|
||||
"fable",
|
||||
"let auto mode escalate to Fable (costly)",
|
||||
Enum(vec!["on".into(), "off".into()]),
|
||||
Enum(models.iter().map(|m| m.to_string()).collect()),
|
||||
),
|
||||
b(
|
||||
"provider",
|
||||
@@ -78,11 +69,6 @@ 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),
|
||||
@@ -103,11 +89,6 @@ 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",
|
||||
@@ -201,15 +182,7 @@ pub fn complete(line: &str, cur: usize, specs: &[CmdSpec], files: &[String]) ->
|
||||
label,
|
||||
detail: detail.into(),
|
||||
};
|
||||
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('@') {
|
||||
let items = if let Some(q) = tok.strip_prefix('@') {
|
||||
rank(files.iter().map(String::as_str), q, MAX_ITEMS)
|
||||
.into_iter()
|
||||
.map(|f| cand(format!("@{f}"), ""))
|
||||
@@ -244,61 +217,6 @@ 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 => "",
|
||||
@@ -367,33 +285,6 @@ 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> {
|
||||
@@ -440,7 +331,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(), 4, "auto + 3 models");
|
||||
assert_eq!(c("/model ").items.len(), 3);
|
||||
assert_eq!(labels(&c("/provider c")), ["codex", "claude"]);
|
||||
assert_eq!(labels(&c("/fs:grep lib")), ["src/lib.rs"]);
|
||||
assert!(
|
||||
|
||||
@@ -97,34 +97,6 @@ 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> {
|
||||
@@ -161,11 +133,7 @@ pub fn parse_skill(p: &Path, s: &str) -> Result<Skill, String> {
|
||||
let f: Front = if fm.trim().is_empty() {
|
||||
Front::default()
|
||||
} else {
|
||||
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())?,
|
||||
}
|
||||
serde_norway::from_str(fm).map_err(|e| e.to_string())?
|
||||
};
|
||||
let load = match f.load.as_deref() {
|
||||
Some("always") => Load::Always,
|
||||
@@ -339,7 +307,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, "---\noops: [oops\n---\nB").is_err());
|
||||
assert!(parse_skill(p, "---\ndescription: [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!(
|
||||
@@ -361,8 +329,7 @@ load: manual
|
||||
for (n, fm) in [
|
||||
("ok", "description: fine"),
|
||||
("hid", "description: secret\ndisable-model-invocation: true"),
|
||||
("bad", "oops: [oops"),
|
||||
("colon", "description: before code exists: when asked"),
|
||||
("bad", "description: [oops"),
|
||||
] {
|
||||
let d = t.path().join("s").join(n);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
@@ -370,8 +337,7 @@ 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, ["colon", "hid", "ok"]);
|
||||
assert_eq!(sk[0].description, "before code exists: when asked");
|
||||
assert_eq!(names, ["hid", "ok"]);
|
||||
assert!(
|
||||
warn.len() == 1 && warn[0].contains("bad/SKILL.md"),
|
||||
"{warn:?}"
|
||||
|
||||
@@ -12,7 +12,6 @@ mod mask;
|
||||
pub mod memory;
|
||||
pub mod nudge;
|
||||
pub mod permit;
|
||||
pub mod route;
|
||||
pub mod sandbox;
|
||||
pub mod session;
|
||||
pub mod stats;
|
||||
|
||||
@@ -1,759 +0,0 @@
|
||||
//! 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,
|
||||
/// Fable: only with `[auto] fable` / `/fable on`, for repeated failures and the hardest prompts.
|
||||
Max,
|
||||
}
|
||||
|
||||
impl Tier {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Tier::Fast => "fast",
|
||||
Tier::Balanced => "balanced",
|
||||
Tier::Deep => "deep",
|
||||
Tier::Max => "max",
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 if has(&["fable"]) {
|
||||
Some(Tier::Max)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Tiers to try for a provider lacking this one: the closest first.
|
||||
fn nearest(self) -> &'static [Tier] {
|
||||
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],
|
||||
Tier::Max => &[Tier::Max, 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>,
|
||||
/// Let auto mode escalate to Fable (repeated failures, very hard prompts). Off by default;
|
||||
/// `/fable on|off` overrides it.
|
||||
pub fable: Option<bool>,
|
||||
}
|
||||
|
||||
impl Cfg {
|
||||
fn pin(&self, t: Tier) -> Option<&str> {
|
||||
match t {
|
||||
Tier::Fast => &self.fast,
|
||||
Tier::Balanced => &self.balanced,
|
||||
Tier::Deep => &self.deep,
|
||||
Tier::Max => &None,
|
||||
}
|
||||
.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>,
|
||||
/// Hard enough for Fable when that is on: score 7+ or two failed turns in a row.
|
||||
pub max: bool,
|
||||
/// Estimated tokens of history (a tier switch re-reads them uncached).
|
||||
pub ctx: usize,
|
||||
}
|
||||
|
||||
const DEEP: &[&str] = &[
|
||||
"refactor",
|
||||
"architect",
|
||||
"architektur",
|
||||
"redesign",
|
||||
"migrat",
|
||||
"race condition",
|
||||
"deadlock",
|
||||
"concurren",
|
||||
"security",
|
||||
"sicherheit",
|
||||
"root cause",
|
||||
"performance",
|
||||
"optimi",
|
||||
"rewrite",
|
||||
"from scratch",
|
||||
"entwirf",
|
||||
];
|
||||
/// Common words: worth one point, never a whole tier on their own. Matched as word starts.
|
||||
const WEAK: &[&str] = &["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 weak = p
|
||||
.split(|c: char| !c.is_alphanumeric())
|
||||
.find(|w| WEAK.iter().any(|k| w.starts_with(k)));
|
||||
if let Some(w) = weak {
|
||||
score += 1;
|
||||
hits.push(w.to_string());
|
||||
}
|
||||
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());
|
||||
}
|
||||
// consecutive turns (tool-result messages) that failed, newest first
|
||||
let streak = history
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|m| {
|
||||
m.content
|
||||
.iter()
|
||||
.any(|b| matches!(b, ContentBlock::ToolResult { .. }))
|
||||
})
|
||||
.map(|m| {
|
||||
m.content
|
||||
.iter()
|
||||
.any(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. }))
|
||||
})
|
||||
.take_while(|f| *f)
|
||||
.count();
|
||||
if streak > 0 {
|
||||
score += if streak > 1 { 4 } else { 2 };
|
||||
hits.push(format!("{streak} failed in a row"));
|
||||
}
|
||||
let edits = history
|
||||
.iter()
|
||||
.rev()
|
||||
.take(20)
|
||||
.flat_map(|m| &m.content)
|
||||
.filter(|b| matches!(b, ContentBlock::ToolUse { name, .. } if name == "edit" || name == "write"))
|
||||
.count();
|
||||
if edits >= 4 {
|
||||
score += 1;
|
||||
hits.push(format!("{edits} recent edits"));
|
||||
}
|
||||
if history.len() > 40 {
|
||||
score += 1;
|
||||
hits.push("long session".into());
|
||||
}
|
||||
let ctx = serde_json::to_vec(history).map_or(0, |v| v.len() / 4);
|
||||
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,
|
||||
max: score >= 7 || streak >= 2,
|
||||
ctx,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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| {
|
||||
hx_ai::models::newest(mine.iter().copied().filter(|m| Tier::of(&m.id) == Some(*t)))
|
||||
})
|
||||
.or(mine.first().copied())
|
||||
.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> {
|
||||
// a switch re-reads the history uncached: the bigger it is, the longer a tier is held;
|
||||
// Fable is dropped at once, it costs the most
|
||||
let n = self
|
||||
.cfg
|
||||
.down_after
|
||||
.unwrap_or(if sig.ctx > 100_000 { 5 } else { 3 });
|
||||
let want = if sig.max && self.cfg.fable == Some(true) {
|
||||
Tier::Max
|
||||
} else {
|
||||
sig.tier
|
||||
};
|
||||
let tier = match self.cur {
|
||||
Some((_, c)) if sig.keep => c,
|
||||
Some((_, c)) if want < c => {
|
||||
self.down += 1;
|
||||
if self.down >= if c == Tier::Max { 1 } else { n } {
|
||||
self.down = 0;
|
||||
want
|
||||
} else {
|
||||
c
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.down = 0;
|
||||
want
|
||||
}
|
||||
};
|
||||
let prefer = self.cur.map_or(start, |(k, _)| k);
|
||||
let (kind, model) = pick_for(tier, prefer, avoid, models, &self.cfg)?;
|
||||
// no Fable in the catalog: it ran as Deep
|
||||
let tier = if tier == Tier::Max && Tier::of(&model) != Some(Tier::Max) {
|
||||
Tier::Deep
|
||||
} else {
|
||||
tier
|
||||
};
|
||||
self.cur = Some((kind, tier));
|
||||
let held = if tier != want && !sig.keep {
|
||||
format!(", holding (wanted {})", want.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),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One line per routed prompt in `<session>.route` (JSON), read back by `hx stats`: the data to
|
||||
/// tune the keyword lists and thresholds from. Best effort.
|
||||
pub fn log(session: &std::path::Path, sig: &Signals, p: &Pick, effort: Effort, forced: bool) {
|
||||
use std::io::Write;
|
||||
let line = serde_json::json!({
|
||||
"ts": hx_ai::auth::now_ms() / 1000,
|
||||
"model": p.model,
|
||||
"tier": p.tier.name(),
|
||||
"wanted": sig.tier.name(),
|
||||
"score": sig.score,
|
||||
"effort": effort.name(),
|
||||
"ctx": sig.ctx,
|
||||
"hits": sig.hits,
|
||||
"forced": forced,
|
||||
});
|
||||
// ponytail: a failed log write must not fail the prompt
|
||||
let _ = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(session.with_extension("route"))
|
||||
.and_then(|mut f| writeln!(f, "{line}"));
|
||||
}
|
||||
|
||||
/// 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),
|
||||
"max" => Target::Tier(Tier::Max),
|
||||
_ => {
|
||||
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 == "1 failed in a row"));
|
||||
}
|
||||
|
||||
fn fail() -> Message {
|
||||
Message {
|
||||
role: hx_ai::Role::User,
|
||||
content: vec![ContentBlock::ToolResult {
|
||||
tool_use_id: "t".into(),
|
||||
content: "boom".into(),
|
||||
is_error: true,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weak_words_alone_stay_balanced() {
|
||||
assert_eq!(tier("implement the --foo flag"), Tier::Balanced);
|
||||
assert_eq!(tier("plan the release notes"), Tier::Balanced);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fable_only_when_on_and_escalates_on_repeated_failure() {
|
||||
let mut models = cat();
|
||||
models.push(m("claude-fable-5-1", Kind::Claude));
|
||||
let h = vec![fail(), fail()];
|
||||
let s = signals("try again", &h);
|
||||
assert!(s.max && !signals("try again", &h[..1]).max);
|
||||
let mut off = Router::new(Cfg::default());
|
||||
let p = off.route(&s, Kind::Claude, None, &models).unwrap();
|
||||
assert_eq!(p.model, "claude-opus-5-5");
|
||||
let on = Cfg {
|
||||
fable: Some(true),
|
||||
..Default::default()
|
||||
};
|
||||
let mut r = Router::new(on.clone());
|
||||
let p = r.route(&s, Kind::Claude, None, &models).unwrap();
|
||||
assert_eq!((p.tier, p.model.as_str()), (Tier::Max, "claude-fable-5-1"));
|
||||
// one light prompt drops Fable at once
|
||||
let light = signals("fix the typo in README", &[]);
|
||||
assert_ne!(
|
||||
r.route(&light, Kind::Claude, None, &models).unwrap().tier,
|
||||
Tier::Max
|
||||
);
|
||||
// on, but no Fable in the catalog: Deep
|
||||
let mut r = Router::new(on);
|
||||
let p = r.route(&s, Kind::Claude, None, &cat()).unwrap();
|
||||
assert_eq!((p.tier, p.model.as_str()), (Tier::Deep, "claude-opus-5-5"));
|
||||
assert_eq!(
|
||||
parse_override("@max go", &cat(), &|_| false).unwrap().0,
|
||||
Target::Tier(Tier::Max)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newest_version_wins_whatever_the_list_order() {
|
||||
let ms = vec![
|
||||
m("claude-opus-4-1-20250805", Kind::Claude),
|
||||
m("claude-opus-5-5", Kind::Claude),
|
||||
m("claude-opus-4-5", Kind::Claude),
|
||||
m("claude-sonnet-5-5", Kind::Claude),
|
||||
m("claude-sonnet-5-6-preview", Kind::Claude),
|
||||
];
|
||||
let c = Cfg::default();
|
||||
assert_eq!(
|
||||
model_for(Kind::Claude, Tier::Deep, &ms, &c).unwrap(),
|
||||
"claude-opus-5-5"
|
||||
);
|
||||
assert_eq!(
|
||||
hx_ai::models::default_for(Kind::Claude, &ms),
|
||||
"claude-sonnet-5-5"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_context_holds_the_tier_longer() {
|
||||
let mut r = Router::new(Cfg::default());
|
||||
let hard = signals(
|
||||
"refactor the auth module and remove the race condition",
|
||||
&[],
|
||||
);
|
||||
r.route(&hard, Kind::Codex, None, &cat()).unwrap();
|
||||
let mut light = signals("fix the typo in README", &[]);
|
||||
light.ctx = 200_000;
|
||||
for _ in 0..4 {
|
||||
assert_eq!(
|
||||
r.route(&light, Kind::Codex, None, &cat()).unwrap().tier,
|
||||
Tier::Deep
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
r.route(&light, Kind::Codex, None, &cat()).unwrap().tier,
|
||||
Tier::Fast
|
||||
);
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@
|
||||
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")]
|
||||
@@ -46,8 +45,6 @@ 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 {
|
||||
@@ -55,7 +52,6 @@ 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"]),
|
||||
@@ -102,47 +98,22 @@ pub struct Sandbox {
|
||||
env_allow: Vec<String>,
|
||||
}
|
||||
|
||||
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);
|
||||
static SANDBOX: OnceLock<Option<Sandbox>> = OnceLock::new();
|
||||
|
||||
/// 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> {
|
||||
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(())
|
||||
let sb = if cfg.mode == Mode::On {
|
||||
Some(Sandbox::new(cfg, cwd)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
SANDBOX
|
||||
.set(sb)
|
||||
.map_err(|_| "sandbox already initialised".into())
|
||||
}
|
||||
|
||||
pub fn active() -> Option<&'static Sandbox> {
|
||||
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);
|
||||
SANDBOX.get().and_then(Option::as_ref)
|
||||
}
|
||||
|
||||
/// Drop-in for `tokio::process::Command::new` that applies the sandbox when it is on.
|
||||
@@ -590,17 +561,4 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -137,14 +137,6 @@ 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;
|
||||
|
||||
@@ -47,59 +47,6 @@ pub fn task_report(s: &Session) -> String {
|
||||
}
|
||||
|
||||
/// One line per subagent log in `<session>.sub/` (empty when there are none).
|
||||
/// Auto-mode choices from `<session>.route`: turns per tier, how often the tier was held back
|
||||
/// or forced, and how often the next prompt had to go up again (a pick that was too low).
|
||||
pub fn route_report(session_path: &std::path::Path) -> String {
|
||||
let Ok(t) = std::fs::read_to_string(session_path.with_extension("route")) else {
|
||||
return String::new();
|
||||
};
|
||||
let rows: Vec<serde_json::Value> = t
|
||||
.lines()
|
||||
.filter_map(|l| serde_json::from_str(l).ok())
|
||||
.collect();
|
||||
if rows.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let rank = |s: &str| {
|
||||
["fast", "balanced", "deep", "max"]
|
||||
.iter()
|
||||
.position(|x| *x == s)
|
||||
};
|
||||
let s = |r: &serde_json::Value, k: &str| r[k].as_str().unwrap_or("?").to_string();
|
||||
let (mut per, mut held, mut forced, mut up) = (HashMap::<String, (u32, i64)>::new(), 0, 0, 0);
|
||||
for (i, r) in rows.iter().enumerate() {
|
||||
if r["forced"].as_bool() == Some(true) {
|
||||
forced += 1;
|
||||
continue;
|
||||
}
|
||||
let e = per.entry(s(r, "tier")).or_default();
|
||||
e.0 += 1;
|
||||
e.1 += r["score"].as_i64().unwrap_or(0);
|
||||
held += (s(r, "tier") != s(r, "wanted")) as u32;
|
||||
if let Some(n) = rows.get(i + 1)
|
||||
&& n["forced"].as_bool() != Some(true)
|
||||
&& rank(&s(n, "tier")) > rank(&s(r, "tier"))
|
||||
{
|
||||
up += 1;
|
||||
}
|
||||
}
|
||||
let mut o = String::from("auto routing:\n");
|
||||
for t in ["fast", "balanced", "deep", "max"] {
|
||||
if let Some((n, sum)) = per.get(t) {
|
||||
let _ = writeln!(
|
||||
o,
|
||||
" {t}: {n} prompts, mean score {:.1}",
|
||||
*sum as f64 / *n as f64
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = writeln!(
|
||||
o,
|
||||
" held back by hysteresis: {held}, next prompt went up a tier: {up}, forced with @: {forced}"
|
||||
);
|
||||
o
|
||||
}
|
||||
|
||||
pub fn sub_report(session_path: &std::path::Path) -> String {
|
||||
let mut files: Vec<_> = std::fs::read_dir(session_path.with_extension("sub"))
|
||||
.into_iter()
|
||||
@@ -160,46 +107,6 @@ 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();
|
||||
@@ -433,39 +340,6 @@ 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();
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
//! 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};
|
||||
@@ -32,12 +31,6 @@ 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,
|
||||
/// `/fable on|off`; overrides `[auto] fable` in the config.
|
||||
#[serde(default)]
|
||||
pub fable: Option<bool>,
|
||||
}
|
||||
|
||||
impl Last {
|
||||
@@ -52,24 +45,6 @@ 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 {
|
||||
@@ -81,206 +56,9 @@ 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
|
||||
}
|
||||
|
||||
/// Allow (or forbid) Fable in auto mode; saved for the next start.
|
||||
pub fn set_fable(&mut self, on: bool) {
|
||||
self.auto_cfg.fable = Some(on);
|
||||
if let Some(r) = &mut self.router {
|
||||
r.cfg.fable = Some(on);
|
||||
}
|
||||
self.save(|l| l.fable = Some(on));
|
||||
}
|
||||
|
||||
pub fn fable(&self) -> bool {
|
||||
self.auto_cfg.fable == Some(true)
|
||||
}
|
||||
|
||||
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);
|
||||
route::log(
|
||||
agent.session().path(),
|
||||
&sig,
|
||||
&pick,
|
||||
effort,
|
||||
forced.is_some(),
|
||||
);
|
||||
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 {
|
||||
@@ -305,8 +83,6 @@ 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)
|
||||
}
|
||||
|
||||
@@ -314,8 +90,6 @@ 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)
|
||||
}
|
||||
|
||||
@@ -325,17 +99,6 @@ 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 {
|
||||
@@ -345,11 +108,11 @@ impl Switcher {
|
||||
} else {
|
||||
agent.set_model(model.as_str());
|
||||
}
|
||||
if remember {
|
||||
self.save(|l| {
|
||||
l.provider = kind;
|
||||
l.model = model.clone();
|
||||
});
|
||||
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));
|
||||
}
|
||||
let window = models::window(&self.models, &model);
|
||||
agent.set_model_window(window);
|
||||
@@ -498,8 +261,6 @@ mod tests {
|
||||
provider: Kind::Claude,
|
||||
model: "m".into(),
|
||||
effort: None,
|
||||
auto: false,
|
||||
fable: None,
|
||||
};
|
||||
let mut sw = sw.remember_in(f.clone(), start);
|
||||
sw.set_model(&mut a, "gpt-x").unwrap();
|
||||
@@ -508,113 +269,12 @@ mod tests {
|
||||
provider: Kind::Codex,
|
||||
model: "gpt-x".into(),
|
||||
effort: Some(hx_ai::Effort::High),
|
||||
auto: false,
|
||||
fable: None,
|
||||
};
|
||||
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");
|
||||
let rep = crate::stats::route_report(a.session().path());
|
||||
assert!(rep.contains("fast: 1 prompts"), "{rep}");
|
||||
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);
|
||||
|
||||
+19
-101
@@ -61,21 +61,7 @@ impl Choose {
|
||||
KeyCode::Backspace => {
|
||||
t.pop();
|
||||
}
|
||||
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::Char(c) => t.push(c),
|
||||
KeyCode::Enter if !t.trim().is_empty() => {
|
||||
let mut v = picked;
|
||||
v.push(t.trim().to_string());
|
||||
@@ -110,13 +96,6 @@ 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());
|
||||
@@ -127,7 +106,7 @@ impl Choose {
|
||||
|
||||
pub fn help(&self) -> &'static str {
|
||||
if self.typing.is_some() {
|
||||
"enter send · shift/alt-enter newline · ctrl-w word · esc back"
|
||||
"enter send · esc back"
|
||||
} else if self.q.multi {
|
||||
"↑↓ move · space toggle · enter confirm · esc skip"
|
||||
} else {
|
||||
@@ -179,32 +158,24 @@ impl Choose {
|
||||
if self.is_other() {
|
||||
sel_line = lines.len();
|
||||
}
|
||||
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![
|
||||
lines.push(match &self.typing {
|
||||
Some(t) => Line::from(vec![
|
||||
Span::styled(format!("{} ", n + 1), th.accent()),
|
||||
Span::styled("other…", st),
|
||||
]));
|
||||
}
|
||||
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()
|
||||
},
|
||||
),
|
||||
]),
|
||||
});
|
||||
}
|
||||
let q = Paragraph::new(self.q.text.as_str())
|
||||
.wrap(Wrap { trim: false })
|
||||
@@ -240,24 +211,6 @@ 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![];
|
||||
@@ -336,41 +289,6 @@ 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);
|
||||
|
||||
+8
-170
@@ -47,7 +47,6 @@ 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,
|
||||
@@ -89,9 +88,6 @@ 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,
|
||||
>;
|
||||
@@ -202,7 +198,6 @@ 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")
|
||||
@@ -247,7 +242,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(cmd::expand_home(w));
|
||||
let p = root.join(w);
|
||||
if let Ok(c) = std::fs::read_to_string(&p)
|
||||
&& c.len() < 200_000
|
||||
{
|
||||
@@ -263,7 +258,6 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
switcher,
|
||||
pricing,
|
||||
lsp_status,
|
||||
reload,
|
||||
commands,
|
||||
specs,
|
||||
open_sessions,
|
||||
@@ -345,7 +339,6 @@ 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(),
|
||||
@@ -399,7 +392,6 @@ 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();
|
||||
@@ -514,11 +506,6 @@ 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,
|
||||
_ => {}
|
||||
@@ -535,7 +522,6 @@ 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(
|
||||
@@ -554,14 +540,6 @@ 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())),
|
||||
@@ -1234,11 +1212,7 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
match labels.len() {
|
||||
0 => app.hint = "no match".into(),
|
||||
1 => {
|
||||
let l = if labels[0].ends_with('/') {
|
||||
labels[0].to_string()
|
||||
} else {
|
||||
format!("{} ", labels[0])
|
||||
};
|
||||
let l = format!("{} ", labels[0]);
|
||||
app.ed.replace(c.start, &l);
|
||||
}
|
||||
_ => {
|
||||
@@ -1270,22 +1244,19 @@ 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.contains('\n') {
|
||||
if !app.ed.buf.starts_with('/') || app.ed.buf.contains('\n') {
|
||||
return;
|
||||
}
|
||||
let c = completion(app);
|
||||
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('@')) {
|
||||
if !app.ed.buf[c.start..app.ed.cur].starts_with('@') {
|
||||
app.popup = popup::Popup::new(c);
|
||||
}
|
||||
}
|
||||
|
||||
fn accept(app: &mut App) {
|
||||
if let Some(p) = app.popup.take() {
|
||||
let l = p.selected_label();
|
||||
let sp = if l.ends_with('/') { "" } else { " " };
|
||||
app.ed.replace(p.comp.start, &format!("{l}{sp}"));
|
||||
app.ed
|
||||
.replace(p.comp.start, &format!("{} ", p.selected_label()));
|
||||
live_popup(app);
|
||||
}
|
||||
}
|
||||
@@ -1296,7 +1267,6 @@ struct Ctx<'a> {
|
||||
tx: &'a mpsc::UnboundedSender<Ui>,
|
||||
cwd: &'a std::path::Path,
|
||||
lsp_status: &'a LspStatus,
|
||||
reload: &'a Reload,
|
||||
commands: &'a Commands,
|
||||
}
|
||||
|
||||
@@ -1306,7 +1276,6 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
tx,
|
||||
cwd,
|
||||
lsp_status,
|
||||
reload,
|
||||
commands,
|
||||
} = *c;
|
||||
app.scroll.end();
|
||||
@@ -1384,23 +1353,6 @@ 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);
|
||||
@@ -1409,36 +1361,6 @@ 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
|
||||
@@ -1495,36 +1417,11 @@ 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,
|
||||
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(),
|
||||
));
|
||||
}
|
||||
"fable" if arg.is_empty() => app.t.push(Item::Info(format!(
|
||||
"fable in auto mode: {}",
|
||||
if app.sw.fable() { "on" } else { "off" }
|
||||
))),
|
||||
"fable" if arg == "on" || arg == "off" => {
|
||||
app.sw.set_fable(arg == "on");
|
||||
app.t.push(Item::Info(if arg == "on" {
|
||||
"fable on: auto escalates to Fable after 2 failed turns in a row or a very hard prompt ($10/$50 per Mtok). `@fable ...` always works.".into()
|
||||
} else {
|
||||
"fable off".into()
|
||||
}));
|
||||
}
|
||||
"fable" => app.t.push(Item::Error("/fable on|off".into())),
|
||||
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.st.model))),
|
||||
"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!(
|
||||
@@ -1606,36 +1503,6 @@ 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);
|
||||
@@ -2569,7 +2436,6 @@ mod tests {
|
||||
busy: false,
|
||||
queue: VecDeque::new(),
|
||||
st: status::Status {
|
||||
auto: false,
|
||||
kind: Kind::Claude,
|
||||
model: "m1".into(),
|
||||
effort: hx_ai::Effort::Off,
|
||||
@@ -2627,21 +2493,6 @@ 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();
|
||||
@@ -2707,7 +2558,7 @@ mod tests {
|
||||
for c in "/model ".chars() {
|
||||
key(&mut app, KeyCode::Char(c));
|
||||
}
|
||||
assert_eq!(labels(&app).unwrap().0, ["auto", "opus", "sonnet"]);
|
||||
assert_eq!(labels(&app).unwrap().0, ["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
|
||||
@@ -2813,27 +2664,16 @@ 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);
|
||||
@@ -2874,13 +2714,11 @@ 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();
|
||||
|
||||
@@ -11,8 +11,6 @@ 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,
|
||||
@@ -137,9 +135,8 @@ 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!("{auto}{model} {} ctx ", th.sym.info), th.sec()),
|
||||
Span::styled(format!("{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()),
|
||||
@@ -272,7 +269,6 @@ mod tests {
|
||||
|
||||
fn st() -> Status {
|
||||
Status {
|
||||
auto: false,
|
||||
kind: Kind::Claude,
|
||||
model: "claude-m1".into(),
|
||||
effort: hx_ai::Effort::Off,
|
||||
|
||||
@@ -6,64 +6,37 @@
|
||||
outputs =
|
||||
{ self, nixpkgs }:
|
||||
let
|
||||
systems = [ "x86_64-linux" "aarch64-linux" "aarch64-darwin" ];
|
||||
systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "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:
|
||||
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";
|
||||
};
|
||||
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";
|
||||
};
|
||||
|
||||
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}.default}/bin/hx"; };
|
||||
};
|
||||
default = hx;
|
||||
});
|
||||
|
||||
overlays.default = _: prev: { hx = self.packages.${prev.system}.default; };
|
||||
apps = forAll (pkgs: rec {
|
||||
hx = { type = "app"; program = "${self.packages.${pkgs.system}.hx}/bin/hx"; };
|
||||
default = hx;
|
||||
});
|
||||
|
||||
overlays.default = _: prev: { hx = self.packages.${prev.system}.hx; };
|
||||
|
||||
devShells = forAll (pkgs: {
|
||||
default = pkgs.mkShell {
|
||||
|
||||
+1
-14
@@ -79,26 +79,13 @@ 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", "model → claude-opus-5-5 (Claude)")
|
||||
check("model switch", "opus-5-5 (Claude) · context 1000k")
|
||||
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")
|
||||
|
||||
Reference in new issue
Block a user