Compare commits
1
Commits
v0.1.2
..
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.
|
## 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.
|
## File tools (read/write/edit) obey the same paths. mode = "on" without a working backend refuses to start.
|
||||||
# [sandbox]
|
# [sandbox]
|
||||||
# mode = "off" # off | on (CLI: --sandbox / --no-sandbox; /sandbox toggles at runtime)
|
# mode = "off" # off | on (CLI: --sandbox / --no-sandbox)
|
||||||
# claude = true # false: claude (claude_cli provider) runs unconfined, no prompt
|
|
||||||
# backend = "auto" # auto | bwrap | seatbelt
|
# backend = "auto" # auto | bwrap | seatbelt
|
||||||
# network = false
|
# network = false
|
||||||
# rw = ["~/.cargo/registry", "~/.cargo/git"] # extra writable paths
|
# rw = ["~/.cargo/registry", "~/.cargo/git"] # extra writable paths
|
||||||
@@ -82,21 +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
|
# install = ["brew", "install", "zls"] # offered by the lsp tool when `zls` is missing
|
||||||
```
|
```
|
||||||
|
|
||||||
## Auto model
|
|
||||||
|
|
||||||
`/model auto` (or `model = "auto"`, `--model auto`) picks model and thinking level for every prompt, across all logged-in providers; `/model <id>` or `/provider` turns it off. No extra LLM call: the prompt is scored from cheap signals (length, keywords like `refactor`/`race condition` vs. `typo`/`explain`, a stack trace, a failed tool result in the last turn, a long session) into a tier: `fast` (Haiku/Luna), `balanced` (Sonnet/Terra), `deep` (Opus/Sol). Stepping up is immediate, stepping down needs `down_after` (default 3) light prompts in a row, because every switch costs the prompt cache. Very short replies ("ja", "continue") keep the current tier. The provider stays unless the other one has the tier exactly or the current one reported a used-up quota window. Each choice and its reason is shown as a line in the chat; the footer shows `auto→model`.
|
|
||||||
|
|
||||||
One-turn override, with or without auto: start the prompt with `@opus fix this`, `@codex ...`, `@fast ...`, `@deep ...` or `@<model id>` (any unique part of an id, 3+ chars). A file with that name wins, so `@notes.md` stays a file mention. The previous model comes back after the turn (in auto mode, the router just chooses again).
|
|
||||||
|
|
||||||
Switching provider mid-session converts history: Codex reasoning items and unsigned thinking are dropped for Claude, tool-call ids are made Anthropic-safe. `hx stats` lists requests per model and the cache re-written after each switch.
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[auto] # all optional
|
|
||||||
fast = "claude-haiku-4-5"
|
|
||||||
deep = "gpt-5.6-sol" # pins can name another provider's model
|
|
||||||
down_after = 3
|
|
||||||
```
|
|
||||||
|
|
||||||
## Subagents
|
## 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.
|
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.1",
|
|
||||||
"sha256": {
|
|
||||||
"aarch64-apple-darwin": "d1684b780a1f988babccb24ec4de341fb04e2f0eccc43d82487287337b83216a",
|
|
||||||
"x86_64-unknown-linux-musl": "6ab0530d4c97839da685462bf3acac9db28173ed443c89f3e0037cccc693a92c"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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 {
|
fn block_json(b: &ContentBlock) -> Value {
|
||||||
match b {
|
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!({
|
ContentBlock::Image { media_type, data } => json!({
|
||||||
"type": "image",
|
"type": "image",
|
||||||
"source": {"type": "base64", "media_type": media_type, "data": data}
|
"source": {"type": "base64", "media_type": media_type, "data": data}
|
||||||
}),
|
}),
|
||||||
ContentBlock::ToolUse { id, name, input } => {
|
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),
|
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
|
let mut messages: Vec<Value> = req
|
||||||
.messages
|
.messages
|
||||||
.iter()
|
.iter()
|
||||||
.map(|m| {
|
.map(|m| json!({"role": m.role, "content": m.content.iter().map(block_json).collect::<Vec<_>>()}))
|
||||||
let mut c: Vec<Value> = m
|
|
||||||
.content
|
|
||||||
.iter()
|
|
||||||
.filter(|b| !foreign(b))
|
|
||||||
.map(block_json)
|
|
||||||
.collect();
|
|
||||||
if c.is_empty() {
|
|
||||||
// message index stays aligned with `req.messages` (cache breakpoints)
|
|
||||||
c.push(json!({"type": "text", "text": "(thinking omitted)"}));
|
|
||||||
}
|
|
||||||
json!({"role": m.role, "content": c})
|
|
||||||
})
|
|
||||||
.collect();
|
.collect();
|
||||||
// Rolling breakpoints (tools+system are covered by the system one): the last message, and the
|
// 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.
|
// user message before it, which is where the previous request's breakpoint sat -> cache read.
|
||||||
@@ -427,57 +389,6 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::ToolSpec;
|
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]
|
#[test]
|
||||||
fn effort_sets_thinking_budget() {
|
fn effort_sets_thinking_budget() {
|
||||||
let mut r = req();
|
let mut r = req();
|
||||||
|
|||||||
@@ -209,8 +209,6 @@ impl Provider for ClaudeCli {
|
|||||||
let mut lines = BufReader::new(out).lines();
|
let mut lines = BufReader::new(out).lines();
|
||||||
let (mut text, mut think) = (String::new(), String::new());
|
let (mut text, mut think) = (String::new(), String::new());
|
||||||
let mut done = false;
|
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();
|
let mut quota = Quota::default();
|
||||||
while let Ok(Some(l)) = lines.next_line().await {
|
while let Ok(Some(l)) = lines.next_line().await {
|
||||||
let Ok(v) = serde_json::from_str::<Value>(&l) else {
|
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)
|
// complete tool calls (the stream events only carry partial JSON)
|
||||||
Some("assistant") => {
|
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() {
|
for b in v["message"]["content"].as_array().into_iter().flatten() {
|
||||||
if b["type"] == "tool_use" {
|
if b["type"] == "tool_use" {
|
||||||
let _ = tx.send(Ok(StreamEvent::TextDelta {
|
let _ = tx.send(Ok(StreamEvent::TextDelta {
|
||||||
@@ -289,8 +284,7 @@ impl Provider for ClaudeCli {
|
|||||||
content,
|
content,
|
||||||
},
|
},
|
||||||
stop: StopReason::EndTurn,
|
stop: StopReason::EndTurn,
|
||||||
// ponytail: billing/stats see the last request only; split Done if exact sums matter
|
usage: usage(&v["usage"]),
|
||||||
usage: usage(last.as_ref().unwrap_or(&v["usage"])),
|
|
||||||
}));
|
}));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -358,37 +352,4 @@ mod tests {
|
|||||||
assert!(p.contains("User: a") && p.contains("Assistant: b") && p.ends_with("c"));
|
assert!(p.contains("User: a") && p.contains("Assistant: b") && p.ends_with("c"));
|
||||||
assert_eq!(prompt(&m[..1], false), "a");
|
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
## Every setting is commented out and shows its default or an example; uncomment to change it.
|
## 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
|
# 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
|
# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet
|
||||||
# codex_model = "gpt-5.6-sol" # default: Codex's top-listed model
|
# 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
|
# 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
|
# ro = ["~/.cargo", "~/.rustup", "~/.local", "~/.nvm", "~/.npm"] # readable parts of $HOME
|
||||||
# env_allow = ["PATH", "HOME", "TERM", "LC_*", "CARGO_*"] # trailing * = prefix
|
# 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-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter), used with provider = "custom".
|
||||||
# [openai_compat]
|
# [openai_compat]
|
||||||
# base_url = "http://localhost:11434/v1"
|
# base_url = "http://localhost:11434/v1"
|
||||||
|
|||||||
@@ -15,12 +15,7 @@ mod rpc;
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(
|
#[command(name = "hx", version, about = "Minimal coding agent")]
|
||||||
name = "hx",
|
|
||||||
// CI sets HX_VERSION to the release version; local builds use Cargo's
|
|
||||||
version = option_env!("HX_VERSION").unwrap_or(env!("CARGO_PKG_VERSION")),
|
|
||||||
about = "Minimal coding agent"
|
|
||||||
)]
|
|
||||||
struct Cli {
|
struct Cli {
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
cmd: Option<Cmd>,
|
cmd: Option<Cmd>,
|
||||||
@@ -50,9 +45,6 @@ struct Cli {
|
|||||||
/// Force the sandbox off (overrides config).
|
/// Force the sandbox off (overrides config).
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
no_sandbox: bool,
|
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).
|
/// 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)]
|
#[arg(long, value_enum, default_value_t = Mode::Text)]
|
||||||
mode: Mode,
|
mode: Mode,
|
||||||
@@ -149,8 +141,6 @@ struct Config {
|
|||||||
mouse: Option<bool>,
|
mouse: Option<bool>,
|
||||||
/// Reuse the last model chosen with /model or /provider (default true).
|
/// Reuse the last model chosen with /model or /provider (default true).
|
||||||
remember_model: Option<bool>,
|
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.
|
/// "ask" (default) or "yolo": whether bash/write/edit prompt in the TUI.
|
||||||
permissions: Option<String>,
|
permissions: Option<String>,
|
||||||
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
|
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
|
||||||
@@ -222,7 +212,6 @@ impl Config {
|
|||||||
codemode: o.codemode.or(c.codemode),
|
codemode: o.codemode.or(c.codemode),
|
||||||
mouse: o.mouse.or(c.mouse),
|
mouse: o.mouse.or(c.mouse),
|
||||||
remember_model: o.remember_model.or(c.remember_model),
|
remember_model: o.remember_model.or(c.remember_model),
|
||||||
auto: o.auto.or(c.auto),
|
|
||||||
permissions: o.permissions.or(c.permissions),
|
permissions: o.permissions.or(c.permissions),
|
||||||
system_prompt: o.system_prompt.or(c.system_prompt),
|
system_prompt: o.system_prompt.or(c.system_prompt),
|
||||||
sandbox: o.sandbox.or(c.sandbox),
|
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.
|
/// The `claude` command: sandboxed when the sandbox is on, unless the user let it out.
|
||||||
async fn claude_command(bin: String) -> tokio::process::Command {
|
async fn claude_command(bin: String) -> tokio::process::Command {
|
||||||
if hx_core::sandbox::active().is_none()
|
if hx_core::sandbox::active().is_none() || claude_outside().await {
|
||||||
|| !hx_core::sandbox::claude_sandboxed()
|
|
||||||
|| claude_outside().await
|
|
||||||
{
|
|
||||||
return tokio::process::Command::new(bin);
|
return tokio::process::Command::new(bin);
|
||||||
}
|
}
|
||||||
hx_core::sandbox::command_with(&bin, &claude_extra(&bin))
|
hx_core::sandbox::command_with(&bin, &claude_extra(&bin))
|
||||||
@@ -574,10 +560,6 @@ async fn main() -> Result<()> {
|
|||||||
Some(Cmd::Logout { provider }) => return Ok(auth::logout(provider)?),
|
Some(Cmd::Logout { provider }) => return Ok(auth::logout(provider)?),
|
||||||
Some(Cmd::Stats { session }) => {
|
Some(Cmd::Stats { session }) => {
|
||||||
print!("{}", hx_core::stats::report(&Session::open(&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::task_report(&Session::open(&session)?));
|
||||||
print!("{}", hx_core::stats::sub_report(&session));
|
print!("{}", hx_core::stats::sub_report(&session));
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -782,13 +764,7 @@ async fn main() -> Result<()> {
|
|||||||
if cli.no_sandbox {
|
if cli.no_sandbox {
|
||||||
sb.mode = hx_core::sandbox::Mode::Off;
|
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)?;
|
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() {
|
if let Some(oc) = cfg.openai_compat.clone() {
|
||||||
let _ = COMPAT.set(oc);
|
let _ = COMPAT.set(oc);
|
||||||
}
|
}
|
||||||
@@ -832,18 +808,9 @@ async fn main() -> Result<()> {
|
|||||||
// the remembered model applies only to the provider it was chosen on
|
// the remembered model applies only to the provider it was chosen on
|
||||||
let last = last.filter(|l| l.provider == kind);
|
let last = last.filter(|l| l.provider == kind);
|
||||||
let last_effort = last.as_ref().and_then(|l| l.effort);
|
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 last_model = last.map(|l| l.model);
|
||||||
let search = web_search(&cfg);
|
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 {
|
match kind {
|
||||||
Kind::Claude => cfg.claude_model.clone(),
|
Kind::Claude => cfg.claude_model.clone(),
|
||||||
Kind::Codex => cfg.codex_model.clone(),
|
Kind::Codex => cfg.codex_model.clone(),
|
||||||
@@ -888,9 +855,7 @@ async fn main() -> Result<()> {
|
|||||||
provider: kind,
|
provider: kind,
|
||||||
model: model.clone(),
|
model: model.clone(),
|
||||||
effort: Some(effort),
|
effort: Some(effort),
|
||||||
auto: want_auto,
|
|
||||||
};
|
};
|
||||||
let auto_cfg = cfg.auto.clone().unwrap_or_default();
|
|
||||||
if hx_core::herdr::init() {
|
if hx_core::herdr::init() {
|
||||||
hx_core::herdr::set_session(&path);
|
hx_core::herdr::set_session(&path);
|
||||||
agent.bus.add(hx_core::herdr::Hook);
|
agent.bus.add(hx_core::herdr::Hook);
|
||||||
@@ -1047,9 +1012,7 @@ async fn main() -> Result<()> {
|
|||||||
files: hx_tui::project_files(&cwd),
|
files: hx_tui::project_files(&cwd),
|
||||||
session_dir: dir,
|
session_dir: dir,
|
||||||
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
|
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
|
||||||
.auto_cfg(auto_cfg.clone())
|
.remember_in(last_path.clone(), start.clone()),
|
||||||
.remember_in(last_path.clone(), start.clone())
|
|
||||||
.auto_on(want_auto),
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -1072,9 +1035,7 @@ async fn main() -> Result<()> {
|
|||||||
hx_tui::run(hx_tui::Setup {
|
hx_tui::run(hx_tui::Setup {
|
||||||
agent,
|
agent,
|
||||||
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
|
switcher: Switcher::new(kind, models.clone(), Box::new(provider))
|
||||||
.auto_cfg(auto_cfg)
|
.remember_in(last_path, start),
|
||||||
.remember_in(last_path, start)
|
|
||||||
.auto_on(want_auto),
|
|
||||||
pricing,
|
pricing,
|
||||||
specs,
|
specs,
|
||||||
open_sessions,
|
open_sessions,
|
||||||
@@ -1117,26 +1078,6 @@ async fn main() -> Result<()> {
|
|||||||
}) as _)
|
}) 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: {
|
lsp_status: {
|
||||||
let (m, l) = (mgr.clone(), lens_ref.clone());
|
let (m, l) = (mgr.clone(), lens_ref.clone());
|
||||||
Box::new(move || {
|
Box::new(move || {
|
||||||
|
|||||||
@@ -243,10 +243,6 @@ impl Agent {
|
|||||||
self.effort = e;
|
self.effort = e;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn system(&self) -> &str {
|
|
||||||
&self.system
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_system(&mut self, system: impl Into<String>) {
|
pub fn set_system(&mut self, system: impl Into<String>) {
|
||||||
self.system = system.into();
|
self.system = system.into();
|
||||||
self.publish();
|
self.publish();
|
||||||
|
|||||||
@@ -52,11 +52,7 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
|||||||
b(
|
b(
|
||||||
"model",
|
"model",
|
||||||
"show or switch model",
|
"show or switch model",
|
||||||
Enum(
|
Enum(models.iter().map(|m| m.to_string()).collect()),
|
||||||
std::iter::once("auto".to_string())
|
|
||||||
.chain(models.iter().map(|m| m.to_string()))
|
|
||||||
.collect(),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
b(
|
b(
|
||||||
"provider",
|
"provider",
|
||||||
@@ -73,11 +69,6 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
|||||||
b("clear", "alias of /new", None),
|
b("clear", "alias of /new", None),
|
||||||
b("sessions", "browse, resume, delete sessions", None),
|
b("sessions", "browse, resume, delete sessions", None),
|
||||||
b("yolo", "toggle: run every tool without asking", 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("lsp", "language server status", None),
|
||||||
b("copy", "copy the last answer to the clipboard", None),
|
b("copy", "copy the last answer to the clipboard", None),
|
||||||
b("usage", "subscription limits, resets, credits", None),
|
b("usage", "subscription limits, resets, credits", None),
|
||||||
@@ -98,11 +89,6 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
|||||||
),
|
),
|
||||||
b("btw", "side question; no tools, not saved", Free),
|
b("btw", "side question; no tools, not saved", Free),
|
||||||
b("skills", "list skills and where they load from", None),
|
b("skills", "list skills and where they load from", None),
|
||||||
b(
|
|
||||||
"reload",
|
|
||||||
"re-read AGENTS.md, skills, config, MCP prompt index",
|
|
||||||
None,
|
|
||||||
),
|
|
||||||
b(
|
b(
|
||||||
"resume",
|
"resume",
|
||||||
"resume a session file; no arg opens /sessions",
|
"resume a session file; no arg opens /sessions",
|
||||||
@@ -196,15 +182,7 @@ pub fn complete(line: &str, cur: usize, specs: &[CmdSpec], files: &[String]) ->
|
|||||||
label,
|
label,
|
||||||
detail: detail.into(),
|
detail: detail.into(),
|
||||||
};
|
};
|
||||||
let raw = tok.strip_prefix('@').unwrap_or(tok);
|
let items = if let Some(q) = tok.strip_prefix('@') {
|
||||||
let items = if is_fs_path(raw) && (start > 0 || tok.starts_with('@') || raw[1..].contains('/'))
|
|
||||||
{
|
|
||||||
let at = if tok.starts_with('@') { "@" } else { "" };
|
|
||||||
complete_path(raw)
|
|
||||||
.into_iter()
|
|
||||||
.map(|f| cand(format!("{at}{f}"), ""))
|
|
||||||
.collect()
|
|
||||||
} else if let Some(q) = tok.strip_prefix('@') {
|
|
||||||
rank(files.iter().map(String::as_str), q, MAX_ITEMS)
|
rank(files.iter().map(String::as_str), q, MAX_ITEMS)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|f| cand(format!("@{f}"), ""))
|
.map(|f| cand(format!("@{f}"), ""))
|
||||||
@@ -239,61 +217,6 @@ pub fn complete(line: &str, cur: usize, specs: &[CmdSpec], files: &[String]) ->
|
|||||||
Completion { start, items }
|
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 {
|
fn detail(s: &CmdSpec) -> String {
|
||||||
let tag = match s.source {
|
let tag = match s.source {
|
||||||
Source::Builtin => "",
|
Source::Builtin => "",
|
||||||
@@ -362,33 +285,6 @@ pub fn common_prefix<S: AsRef<str>>(xs: &[S]) -> String {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
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::*;
|
use super::*;
|
||||||
|
|
||||||
fn labels(c: &Completion) -> Vec<&str> {
|
fn labels(c: &Completion) -> Vec<&str> {
|
||||||
@@ -435,7 +331,7 @@ mod tests {
|
|||||||
assert_eq!(r.items[0].detail, "skill · code review");
|
assert_eq!(r.items[0].detail, "skill · code review");
|
||||||
let m = c("/model op");
|
let m = c("/model op");
|
||||||
assert_eq!((m.start, labels(&m)), (7, vec!["claude-opus-5-5"]));
|
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("/provider c")), ["codex", "claude"]);
|
||||||
assert_eq!(labels(&c("/fs:grep lib")), ["src/lib.rs"]);
|
assert_eq!(labels(&c("/fs:grep lib")), ["src/lib.rs"]);
|
||||||
assert!(
|
assert!(
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ mod mask;
|
|||||||
pub mod memory;
|
pub mod memory;
|
||||||
pub mod nudge;
|
pub mod nudge;
|
||||||
pub mod permit;
|
pub mod permit;
|
||||||
pub mod route;
|
|
||||||
pub mod sandbox;
|
pub mod sandbox;
|
||||||
pub mod session;
|
pub mod session;
|
||||||
pub mod stats;
|
pub mod stats;
|
||||||
|
|||||||
@@ -1,581 +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,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Tier {
|
|
||||||
pub fn name(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Tier::Fast => "fast",
|
|
||||||
Tier::Balanced => "balanced",
|
|
||||||
Tier::Deep => "deep",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Tier of a model by family name (Haiku/Luna, Sonnet/Terra, Opus/Sol); unknown models have none.
|
|
||||||
pub fn of(id: &str) -> Option<Tier> {
|
|
||||||
let has = |a: &[&str]| a.iter().any(|t| id.contains(t));
|
|
||||||
if has(&["haiku", "luna", "mini"]) {
|
|
||||||
Some(Tier::Fast)
|
|
||||||
} else if has(&["sonnet", "terra"]) {
|
|
||||||
Some(Tier::Balanced)
|
|
||||||
} else if has(&["opus", "sol"]) {
|
|
||||||
Some(Tier::Deep)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Tiers to try for a provider lacking this one: the closest first.
|
|
||||||
fn nearest(self) -> [Tier; 3] {
|
|
||||||
match self {
|
|
||||||
Tier::Fast => [Tier::Fast, Tier::Balanced, Tier::Deep],
|
|
||||||
Tier::Balanced => [Tier::Balanced, Tier::Deep, Tier::Fast],
|
|
||||||
Tier::Deep => [Tier::Deep, Tier::Balanced, Tier::Fast],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `[auto]` in config: pin a tier to a model (of any provider), tune the step-down delay.
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub struct Cfg {
|
|
||||||
pub fast: Option<String>,
|
|
||||||
pub balanced: Option<String>,
|
|
||||||
pub deep: Option<String>,
|
|
||||||
/// Light prompts in a row before dropping to a cheaper tier (default 3). Stepping up is immediate.
|
|
||||||
pub down_after: Option<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Cfg {
|
|
||||||
fn pin(&self, t: Tier) -> Option<&str> {
|
|
||||||
match t {
|
|
||||||
Tier::Fast => &self.fast,
|
|
||||||
Tier::Balanced => &self.balanced,
|
|
||||||
Tier::Deep => &self.deep,
|
|
||||||
}
|
|
||||||
.as_deref()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the prompt and the last turn say about difficulty.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct Signals {
|
|
||||||
pub score: i32,
|
|
||||||
pub tier: Tier,
|
|
||||||
/// Too short and plain ("continue", "ja") to say anything: keep the current tier.
|
|
||||||
pub keep: bool,
|
|
||||||
pub hits: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
const DEEP: &[&str] = &[
|
|
||||||
"refactor",
|
|
||||||
"architect",
|
|
||||||
"architektur",
|
|
||||||
"redesign",
|
|
||||||
"migrat",
|
|
||||||
"race condition",
|
|
||||||
"deadlock",
|
|
||||||
"concurren",
|
|
||||||
"security",
|
|
||||||
"sicherheit",
|
|
||||||
"root cause",
|
|
||||||
"performance",
|
|
||||||
"optimi",
|
|
||||||
"rewrite",
|
|
||||||
"from scratch",
|
|
||||||
"entwirf",
|
|
||||||
"design",
|
|
||||||
"implement",
|
|
||||||
"debug",
|
|
||||||
"plan",
|
|
||||||
];
|
|
||||||
const LIGHT: &[&str] = &[
|
|
||||||
"typo",
|
|
||||||
"rename",
|
|
||||||
"format",
|
|
||||||
"explain",
|
|
||||||
"erkl",
|
|
||||||
"what is",
|
|
||||||
"what does",
|
|
||||||
"was ist",
|
|
||||||
"was macht",
|
|
||||||
"show me",
|
|
||||||
"zeig",
|
|
||||||
"commit",
|
|
||||||
"comment",
|
|
||||||
"kommentar",
|
|
||||||
"summar",
|
|
||||||
"zusammenfass",
|
|
||||||
];
|
|
||||||
const TRACE: &[&str] = &[
|
|
||||||
"traceback",
|
|
||||||
"panicked at",
|
|
||||||
"error[e",
|
|
||||||
"stack trace",
|
|
||||||
"exception",
|
|
||||||
];
|
|
||||||
|
|
||||||
/// Score `prompt`; `history` is the session so far (a failed tool result in the last two messages
|
|
||||||
/// escalates).
|
|
||||||
pub fn signals(prompt: &str, history: &[Message]) -> Signals {
|
|
||||||
let p = prompt.to_lowercase();
|
|
||||||
let mut hits = vec![];
|
|
||||||
let mut score = 0;
|
|
||||||
let len = prompt.chars().count();
|
|
||||||
if len > 2000 {
|
|
||||||
score += 2;
|
|
||||||
hits.push("long prompt".into());
|
|
||||||
} else if len > 600 {
|
|
||||||
score += 1;
|
|
||||||
hits.push("long-ish prompt".into());
|
|
||||||
}
|
|
||||||
let deep: Vec<&str> = DEEP.iter().copied().filter(|k| p.contains(k)).collect();
|
|
||||||
if !deep.is_empty() {
|
|
||||||
score += 2 * deep.len().min(2) as i32;
|
|
||||||
hits.push(deep.join(","));
|
|
||||||
}
|
|
||||||
let light: Vec<&str> = LIGHT.iter().copied().filter(|k| p.contains(k)).collect();
|
|
||||||
if !light.is_empty() {
|
|
||||||
score -= 2;
|
|
||||||
hits.push(light.join(","));
|
|
||||||
}
|
|
||||||
if TRACE.iter().any(|k| p.contains(k)) {
|
|
||||||
score += 1;
|
|
||||||
hits.push("trace".into());
|
|
||||||
}
|
|
||||||
let failed = history.iter().rev().take(2).any(|m| {
|
|
||||||
m.content
|
|
||||||
.iter()
|
|
||||||
.any(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. }))
|
|
||||||
});
|
|
||||||
if failed {
|
|
||||||
score += 2;
|
|
||||||
hits.push("last turn failed".into());
|
|
||||||
}
|
|
||||||
if history.len() > 40 {
|
|
||||||
score += 1;
|
|
||||||
hits.push("long session".into());
|
|
||||||
}
|
|
||||||
let keep = hits.is_empty() && prompt.split_whitespace().count() <= 3;
|
|
||||||
let tier = match score {
|
|
||||||
i32::MIN..=-1 => Tier::Fast,
|
|
||||||
0..=2 => Tier::Balanced,
|
|
||||||
_ => Tier::Deep,
|
|
||||||
};
|
|
||||||
Signals {
|
|
||||||
score,
|
|
||||||
tier,
|
|
||||||
keep,
|
|
||||||
hits,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Thinking level for a score: lowest for light prompts, high for hard ones, else the provider default.
|
|
||||||
fn effort_for(score: i32, k: Kind) -> Effort {
|
|
||||||
let lv = Effort::levels(k);
|
|
||||||
let e = match score {
|
|
||||||
i32::MIN..=-1 => lv[0],
|
|
||||||
3..=i32::MAX => Effort::High,
|
|
||||||
_ => Effort::default_for(k),
|
|
||||||
};
|
|
||||||
if lv.contains(&e) { e } else { lv[0] }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Model of provider `k` for tier `t`: the config pin, else the catalog by family name, else the
|
|
||||||
/// closest tier it has, else its first model (custom endpoints).
|
|
||||||
pub fn model_for(k: Kind, t: Tier, models: &[ModelInfo], cfg: &Cfg) -> Option<String> {
|
|
||||||
if let Some(m) = cfg.pin(t)
|
|
||||||
&& hx_ai::models::kind_of(models, m) == Some(k)
|
|
||||||
{
|
|
||||||
return Some(m.to_string());
|
|
||||||
}
|
|
||||||
let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect();
|
|
||||||
t.nearest()
|
|
||||||
.iter()
|
|
||||||
.find_map(|t| mine.iter().find(|m| Tier::of(&m.id) == Some(*t)))
|
|
||||||
.or(mine.first())
|
|
||||||
.map(|m| m.id.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Provider for tier `t`: the config pin's provider, else `prefer` (keeps the prompt cache), else
|
|
||||||
/// any logged-in one with that exact tier, else any. `avoid` (out of quota) is skipped when
|
|
||||||
/// something else exists. Custom endpoints only serve when nothing else is logged in.
|
|
||||||
pub fn pick_for(
|
|
||||||
t: Tier,
|
|
||||||
prefer: Kind,
|
|
||||||
avoid: Option<Kind>,
|
|
||||||
models: &[ModelInfo],
|
|
||||||
cfg: &Cfg,
|
|
||||||
) -> Option<(Kind, String)> {
|
|
||||||
let mut kinds: Vec<Kind> = vec![];
|
|
||||||
for m in models {
|
|
||||||
if !kinds.contains(&m.kind) {
|
|
||||||
kinds.push(m.kind);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if kinds.iter().any(|k| *k != Kind::Custom) {
|
|
||||||
kinds.retain(|k| *k != Kind::Custom);
|
|
||||||
}
|
|
||||||
if kinds.len() > 1 && avoid.is_some() {
|
|
||||||
kinds.retain(|k| Some(*k) != avoid);
|
|
||||||
}
|
|
||||||
let pinned = cfg
|
|
||||||
.pin(t)
|
|
||||||
.and_then(|m| hx_ai::models::kind_of(models, m))
|
|
||||||
.filter(|k| kinds.contains(k));
|
|
||||||
let order: Vec<Kind> = pinned
|
|
||||||
.into_iter()
|
|
||||||
.chain(kinds.iter().copied().filter(|k| *k == prefer))
|
|
||||||
.chain(kinds.iter().copied())
|
|
||||||
.collect();
|
|
||||||
let exact = |k: &Kind| {
|
|
||||||
models
|
|
||||||
.iter()
|
|
||||||
.any(|m| m.kind == *k && Tier::of(&m.id) == Some(t))
|
|
||||||
|| cfg
|
|
||||||
.pin(t)
|
|
||||||
.is_some_and(|p| hx_ai::models::kind_of(models, p) == Some(*k))
|
|
||||||
};
|
|
||||||
let k = order.iter().find(|k| exact(k)).or(order.first()).copied()?;
|
|
||||||
model_for(k, t, models, cfg).map(|m| (k, m))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What to use for the next prompt.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct Pick {
|
|
||||||
pub kind: Kind,
|
|
||||||
pub model: String,
|
|
||||||
pub tier: Tier,
|
|
||||||
pub effort: Effort,
|
|
||||||
pub why: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
pub struct Router {
|
|
||||||
pub cfg: Cfg,
|
|
||||||
cur: Option<(Kind, Tier)>,
|
|
||||||
down: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Router {
|
|
||||||
pub fn new(cfg: Cfg) -> Self {
|
|
||||||
Self {
|
|
||||||
cfg,
|
|
||||||
cur: None,
|
|
||||||
down: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Forget the last choice (auto mode was switched on again).
|
|
||||||
pub fn reset(&mut self) {
|
|
||||||
self.cur = None;
|
|
||||||
self.down = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Choose for a prompt. Up-tiers apply at once; a cheaper tier only after `down_after` light
|
|
||||||
/// prompts in a row (a switch costs the prompt cache). `start` is the provider in use when
|
|
||||||
/// nothing was chosen yet; `avoid` is a provider that is out of quota.
|
|
||||||
pub fn route(
|
|
||||||
&mut self,
|
|
||||||
sig: &Signals,
|
|
||||||
start: Kind,
|
|
||||||
avoid: Option<Kind>,
|
|
||||||
models: &[ModelInfo],
|
|
||||||
) -> Option<Pick> {
|
|
||||||
let n = self.cfg.down_after.unwrap_or(3);
|
|
||||||
let tier = match self.cur {
|
|
||||||
Some((_, c)) if sig.keep => c,
|
|
||||||
Some((_, c)) if sig.tier < c => {
|
|
||||||
self.down += 1;
|
|
||||||
if self.down >= n {
|
|
||||||
self.down = 0;
|
|
||||||
sig.tier
|
|
||||||
} else {
|
|
||||||
c
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
self.down = 0;
|
|
||||||
sig.tier
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let prefer = self.cur.map_or(start, |(k, _)| k);
|
|
||||||
let (kind, model) = pick_for(tier, prefer, avoid, models, &self.cfg)?;
|
|
||||||
self.cur = Some((kind, tier));
|
|
||||||
let held = if tier != sig.tier && !sig.keep {
|
|
||||||
format!(", holding (wanted {})", sig.tier.name())
|
|
||||||
} else {
|
|
||||||
String::new()
|
|
||||||
};
|
|
||||||
let hits = if sig.hits.is_empty() {
|
|
||||||
String::new()
|
|
||||||
} else {
|
|
||||||
format!(": {}", sig.hits.join(" · "))
|
|
||||||
};
|
|
||||||
Some(Pick {
|
|
||||||
kind,
|
|
||||||
model,
|
|
||||||
tier,
|
|
||||||
effort: effort_for(sig.score, kind),
|
|
||||||
why: format!("{} (score {}{hits}{held})", tier.name(), sig.score),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What `@word` at the start of a prompt asks for.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub enum Target {
|
|
||||||
Tier(Tier),
|
|
||||||
Provider(Kind),
|
|
||||||
Model(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `@opus fix this` -> (model, "fix this"). The word is a tier (`fast`, `balanced`, `deep`), a
|
|
||||||
/// provider (`claude`, `codex`), a model id, or a unique part of one (min 3 chars: `opus`, `sol`).
|
|
||||||
/// Needs text after it, and a file of that name wins (`@notes.md` stays a file mention).
|
|
||||||
pub fn parse_override(
|
|
||||||
line: &str,
|
|
||||||
models: &[ModelInfo],
|
|
||||||
is_file: &dyn Fn(&str) -> bool,
|
|
||||||
) -> Option<(Target, String)> {
|
|
||||||
let (w, rest) = line.strip_prefix('@')?.split_once(char::is_whitespace)?;
|
|
||||||
let rest = rest.trim();
|
|
||||||
if rest.is_empty() || w.is_empty() || is_file(w) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let lw = w.to_lowercase();
|
|
||||||
let t = match lw.as_str() {
|
|
||||||
"fast" => Target::Tier(Tier::Fast),
|
|
||||||
"balanced" => Target::Tier(Tier::Balanced),
|
|
||||||
"deep" => Target::Tier(Tier::Deep),
|
|
||||||
_ => {
|
|
||||||
if let Some(m) = models.iter().find(|m| m.id.to_lowercase() == lw) {
|
|
||||||
Target::Model(m.id.clone())
|
|
||||||
} else if let Some(k) = ["claude", "codex"]
|
|
||||||
.contains(&lw.as_str())
|
|
||||||
.then(|| lw.parse::<Kind>().ok())
|
|
||||||
.flatten()
|
|
||||||
{
|
|
||||||
Target::Provider(k)
|
|
||||||
} else if lw.len() >= 3 && lw.starts_with(|c: char| c.is_ascii_alphabetic()) {
|
|
||||||
let hit: Vec<&ModelInfo> = models
|
|
||||||
.iter()
|
|
||||||
.filter(|m| m.id.to_lowercase().contains(&lw))
|
|
||||||
.collect();
|
|
||||||
match hit.as_slice() {
|
|
||||||
[m] => Target::Model(m.id.clone()),
|
|
||||||
// `@sonnet` with several dated snapshots: the first listed (newest)
|
|
||||||
[m, ..] if hit.iter().all(|h| h.kind == m.kind) => Target::Model(m.id.clone()),
|
|
||||||
_ => return None,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Some((t, rest.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn m(id: &str, kind: Kind) -> ModelInfo {
|
|
||||||
ModelInfo {
|
|
||||||
id: id.into(),
|
|
||||||
kind,
|
|
||||||
context_window: 1,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn cat() -> Vec<ModelInfo> {
|
|
||||||
vec![
|
|
||||||
m("claude-opus-5-5", Kind::Claude),
|
|
||||||
m("claude-sonnet-5-5", Kind::Claude),
|
|
||||||
m("claude-haiku-4-5", Kind::Claude),
|
|
||||||
m("gpt-5.6-sol", Kind::Codex),
|
|
||||||
m("gpt-5.6-terra", Kind::Codex),
|
|
||||||
m("gpt-5.6-luna", Kind::Codex),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tier(p: &str) -> Tier {
|
|
||||||
signals(p, &[]).tier
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tiers_by_name() {
|
|
||||||
assert_eq!(Tier::of("claude-haiku-4-5"), Some(Tier::Fast));
|
|
||||||
assert_eq!(Tier::of("gpt-5.6-terra"), Some(Tier::Balanced));
|
|
||||||
assert_eq!(Tier::of("gpt-5.6-sol"), Some(Tier::Deep));
|
|
||||||
assert_eq!(Tier::of("llama3"), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn prompts_score_into_tiers() {
|
|
||||||
assert_eq!(tier("fix the typo in README"), Tier::Fast);
|
|
||||||
assert_eq!(
|
|
||||||
tier("add a --foo flag to the cli parser please"),
|
|
||||||
Tier::Balanced
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
tier("refactor the auth module and remove the race condition"),
|
|
||||||
Tier::Deep
|
|
||||||
);
|
|
||||||
assert_eq!(tier(&"x ".repeat(1500)), Tier::Balanced);
|
|
||||||
assert!(signals("ja", &[]).keep && signals("continue please", &[]).keep);
|
|
||||||
assert!(!signals("fix typo", &[]).keep, "keyword hit is a signal");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn failed_tool_result_escalates() {
|
|
||||||
let h = vec![Message {
|
|
||||||
role: hx_ai::Role::User,
|
|
||||||
content: vec![ContentBlock::ToolResult {
|
|
||||||
tool_use_id: "t".into(),
|
|
||||||
content: "boom".into(),
|
|
||||||
is_error: true,
|
|
||||||
}],
|
|
||||||
}];
|
|
||||||
let s = signals("try again with a different approach", &h);
|
|
||||||
assert_eq!(s.score, 2);
|
|
||||||
assert!(s.hits.iter().any(|h| h == "last turn failed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn effort_follows_score_and_provider() {
|
|
||||||
assert_eq!(effort_for(-2, Kind::Claude), Effort::Off);
|
|
||||||
assert_eq!(effort_for(-2, Kind::Codex), Effort::Low);
|
|
||||||
assert_eq!(effort_for(0, Kind::Claude), Effort::Off);
|
|
||||||
assert_eq!(effort_for(0, Kind::Codex), Effort::Medium);
|
|
||||||
assert_eq!(effort_for(4, Kind::Claude), Effort::High);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn stays_on_provider_and_steps_down_slowly() {
|
|
||||||
let mut r = Router::new(Cfg::default());
|
|
||||||
let light = signals("fix the typo in README", &[]);
|
|
||||||
let hard = signals(
|
|
||||||
"refactor the auth module and remove the race condition",
|
|
||||||
&[],
|
|
||||||
);
|
|
||||||
let p = r.route(&hard, Kind::Codex, None, &cat()).unwrap();
|
|
||||||
assert_eq!((p.kind, p.model.as_str()), (Kind::Codex, "gpt-5.6-sol"));
|
|
||||||
// two light prompts hold the tier, the third drops it
|
|
||||||
for _ in 0..2 {
|
|
||||||
let p = r.route(&light, Kind::Codex, None, &cat()).unwrap();
|
|
||||||
assert_eq!(p.tier, Tier::Deep);
|
|
||||||
}
|
|
||||||
let p = r.route(&light, Kind::Codex, None, &cat()).unwrap();
|
|
||||||
assert_eq!((p.tier, p.model.as_str()), (Tier::Fast, "gpt-5.6-luna"));
|
|
||||||
// up again at once
|
|
||||||
assert_eq!(
|
|
||||||
r.route(&hard, Kind::Codex, None, &cat()).unwrap().tier,
|
|
||||||
Tier::Deep
|
|
||||||
);
|
|
||||||
// "ja" keeps whatever is current
|
|
||||||
let ack = signals("ja", &[]);
|
|
||||||
assert_eq!(
|
|
||||||
r.route(&ack, Kind::Codex, None, &cat()).unwrap().tier,
|
|
||||||
Tier::Deep
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn quota_and_pins_cross_providers() {
|
|
||||||
let mut r = Router::new(Cfg::default());
|
|
||||||
let p = r
|
|
||||||
.route(
|
|
||||||
&signals("add a flag to the cli parser please", &[]),
|
|
||||||
Kind::Claude,
|
|
||||||
Some(Kind::Claude),
|
|
||||||
&cat(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(p.kind, Kind::Codex, "claude out of quota");
|
|
||||||
let cfg = Cfg {
|
|
||||||
deep: Some("gpt-5.6-sol".into()),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let mut r = Router::new(cfg);
|
|
||||||
let hard = signals(
|
|
||||||
"refactor the auth module and remove the race condition",
|
|
||||||
&[],
|
|
||||||
);
|
|
||||||
let p = r.route(&hard, Kind::Claude, None, &cat()).unwrap();
|
|
||||||
assert_eq!((p.kind, p.model.as_str()), (Kind::Codex, "gpt-5.6-sol"));
|
|
||||||
let easy = signals("add a flag to the cli parser please", &[]);
|
|
||||||
let mut r2 = Router::new(Cfg::default());
|
|
||||||
assert_eq!(
|
|
||||||
r2.route(&easy, Kind::Claude, None, &cat()).unwrap().model,
|
|
||||||
"claude-sonnet-5-5"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn only_claude_logged_in_never_picks_codex() {
|
|
||||||
let only: Vec<ModelInfo> = cat()
|
|
||||||
.into_iter()
|
|
||||||
.filter(|m| m.kind == Kind::Claude)
|
|
||||||
.collect();
|
|
||||||
let mut r = Router::new(Cfg::default());
|
|
||||||
let p = r
|
|
||||||
.route(
|
|
||||||
&signals("typo", &[]),
|
|
||||||
Kind::Claude,
|
|
||||||
Some(Kind::Claude),
|
|
||||||
&only,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
p.kind,
|
|
||||||
Kind::Claude,
|
|
||||||
"avoid is ignored when nothing else exists"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn override_words() {
|
|
||||||
let no = |_: &str| false;
|
|
||||||
let p = |l: &str| parse_override(l, &cat(), &no);
|
|
||||||
assert_eq!(
|
|
||||||
p("@opus fix das"),
|
|
||||||
Some((Target::Model("claude-opus-5-5".into()), "fix das".into()))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
p("@fast what is this"),
|
|
||||||
Some((Target::Tier(Tier::Fast), "what is this".into()))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
p("@codex go"),
|
|
||||||
Some((Target::Provider(Kind::Codex), "go".into()))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
p("@gpt-5.6-sol x").unwrap().0,
|
|
||||||
Target::Model("gpt-5.6-sol".into())
|
|
||||||
);
|
|
||||||
// ambiguous across providers, too short, no text, unknown
|
|
||||||
assert_eq!(p("@5 x"), None);
|
|
||||||
assert_eq!(p("@5.6 x"), None);
|
|
||||||
assert_eq!(p("@opus"), None);
|
|
||||||
assert_eq!(p("@src/main.rs explain"), None);
|
|
||||||
// a file of that name wins
|
|
||||||
assert_eq!(parse_override("@opus hi", &cat(), &|w| w == "opus"), None);
|
|
||||||
assert_eq!(p("opus fix"), None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -12,7 +12,6 @@
|
|||||||
use std::ffi::OsStr;
|
use std::ffi::OsStr;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::OnceLock;
|
use std::sync::OnceLock;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
|
||||||
|
|
||||||
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)]
|
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)]
|
||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "lowercase")]
|
||||||
@@ -46,8 +45,6 @@ pub struct Cfg {
|
|||||||
pub ro: Vec<String>,
|
pub ro: Vec<String>,
|
||||||
/// env vars passed to children; a trailing `*` matches a prefix
|
/// env vars passed to children; a trailing `*` matches a prefix
|
||||||
pub env_allow: Vec<String>,
|
pub env_allow: Vec<String>,
|
||||||
/// run `claude` (claude_cli provider) inside the sandbox too (default true)
|
|
||||||
pub claude: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Cfg {
|
impl Default for Cfg {
|
||||||
@@ -55,7 +52,6 @@ impl Default for Cfg {
|
|||||||
let s = |v: &[&str]| v.iter().map(|s| s.to_string()).collect();
|
let s = |v: &[&str]| v.iter().map(|s| s.to_string()).collect();
|
||||||
Cfg {
|
Cfg {
|
||||||
mode: Mode::Off,
|
mode: Mode::Off,
|
||||||
claude: true,
|
|
||||||
backend: Backend::Auto,
|
backend: Backend::Auto,
|
||||||
network: false,
|
network: false,
|
||||||
rw: s(&["~/.cargo/registry", "~/.cargo/git"]),
|
rw: s(&["~/.cargo/registry", "~/.cargo/git"]),
|
||||||
@@ -102,47 +98,22 @@ pub struct Sandbox {
|
|||||||
env_allow: Vec<String>,
|
env_allow: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
static CFG: OnceLock<(Cfg, PathBuf)> = OnceLock::new();
|
static SANDBOX: OnceLock<Option<Sandbox>> = OnceLock::new();
|
||||||
/// Built lazily on first enable (the backend probe spawns a process).
|
|
||||||
static SANDBOX: OnceLock<Sandbox> = OnceLock::new();
|
|
||||||
static ENABLED: AtomicBool = AtomicBool::new(false);
|
|
||||||
static CLAUDE: AtomicBool = AtomicBool::new(true);
|
|
||||||
|
|
||||||
/// Call once at startup. Errors (never silently falls back) if `mode = on` and no backend works.
|
/// 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> {
|
pub fn init(cfg: &Cfg, cwd: &Path) -> Result<(), String> {
|
||||||
CFG.set((cfg.clone(), cwd.to_path_buf()))
|
let sb = if cfg.mode == Mode::On {
|
||||||
.map_err(|_| "sandbox already initialised".to_string())?;
|
Some(Sandbox::new(cfg, cwd)?)
|
||||||
CLAUDE.store(cfg.claude, Ordering::Relaxed);
|
} else {
|
||||||
if cfg.mode == Mode::On {
|
None
|
||||||
set_enabled(true)?;
|
};
|
||||||
}
|
SANDBOX
|
||||||
Ok(())
|
.set(sb)
|
||||||
|
.map_err(|_| "sandbox already initialised".into())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn active() -> Option<&'static Sandbox> {
|
pub fn active() -> Option<&'static Sandbox> {
|
||||||
ENABLED
|
SANDBOX.get().and_then(Option::as_ref)
|
||||||
.load(Ordering::Relaxed)
|
|
||||||
.then(|| SANDBOX.get())
|
|
||||||
.flatten()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Turn the sandbox on/off at runtime. Affects only children spawned afterwards.
|
|
||||||
pub fn set_enabled(on: bool) -> Result<(), String> {
|
|
||||||
if on && SANDBOX.get().is_none() {
|
|
||||||
let (cfg, cwd) = CFG.get().ok_or("sandbox not initialised")?;
|
|
||||||
let _ = SANDBOX.set(Sandbox::new(cfg, cwd)?);
|
|
||||||
}
|
|
||||||
ENABLED.store(on, Ordering::Relaxed);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Does `claude` run inside the sandbox (while the sandbox is on)?
|
|
||||||
pub fn claude_sandboxed() -> bool {
|
|
||||||
CLAUDE.load(Ordering::Relaxed)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_claude_sandboxed(on: bool) {
|
|
||||||
CLAUDE.store(on, Ordering::Relaxed);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drop-in for `tokio::process::Command::new` that applies the sandbox when it is on.
|
/// Drop-in for `tokio::process::Command::new` that applies the sandbox when it is on.
|
||||||
@@ -590,17 +561,4 @@ mod tests {
|
|||||||
"base unchanged"
|
"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()
|
.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> {
|
fn branch(&self) -> Vec<&Entry> {
|
||||||
let mut out = vec![];
|
let mut out = vec![];
|
||||||
let mut cur = self.head;
|
let mut cur = self.head;
|
||||||
|
|||||||
@@ -107,46 +107,6 @@ pub fn summary(s: &Session) -> Summary {
|
|||||||
o
|
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 {
|
pub fn report(s: &Session) -> String {
|
||||||
let msgs = s.messages();
|
let msgs = s.messages();
|
||||||
let mut o = String::new();
|
let mut o = String::new();
|
||||||
@@ -380,39 +340,6 @@ mod tests {
|
|||||||
assert!(r.contains("one task 1, with several 1"), "{r}");
|
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]
|
#[test]
|
||||||
fn report_counts() {
|
fn report_counts() {
|
||||||
let d = tempfile::tempdir().unwrap();
|
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.
|
//! follow. [`Switcher`] does all of that behind two calls; the TUI and the RPC server share it.
|
||||||
|
|
||||||
use crate::agent::Agent;
|
use crate::agent::Agent;
|
||||||
use crate::route::{self, Router};
|
|
||||||
use hx_ai::Provider;
|
use hx_ai::Provider;
|
||||||
use hx_ai::auth::Kind;
|
use hx_ai::auth::Kind;
|
||||||
use hx_ai::models::{self, ModelInfo};
|
use hx_ai::models::{self, ModelInfo};
|
||||||
@@ -32,9 +31,6 @@ pub struct Last {
|
|||||||
/// Thinking level; absent in files written before it was saved.
|
/// Thinking level; absent in files written before it was saved.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub effort: Option<hx_ai::Effort>,
|
pub effort: Option<hx_ai::Effort>,
|
||||||
/// `/model auto` was on.
|
|
||||||
#[serde(default)]
|
|
||||||
pub auto: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Last {
|
impl Last {
|
||||||
@@ -49,24 +45,6 @@ pub struct Switcher {
|
|||||||
kind: Kind,
|
kind: Kind,
|
||||||
models: Vec<ModelInfo>,
|
models: Vec<ModelInfo>,
|
||||||
make_provider: MakeProvider,
|
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 {
|
impl Switcher {
|
||||||
@@ -78,186 +56,9 @@ impl Switcher {
|
|||||||
kind,
|
kind,
|
||||||
models,
|
models,
|
||||||
make_provider,
|
make_provider,
|
||||||
router: None,
|
|
||||||
auto_cfg: route::Cfg::default(),
|
|
||||||
spent: vec![],
|
|
||||||
restore: None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `[auto]` config: tier pins and the step-down delay.
|
|
||||||
pub fn auto_cfg(mut self, c: route::Cfg) -> Self {
|
|
||||||
self.auto_cfg = c;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Start with auto mode on or off.
|
|
||||||
pub fn auto_on(mut self, on: bool) -> Self {
|
|
||||||
self.router = on.then(|| route::Router::new(self.auto_cfg.clone()));
|
|
||||||
if let Some((_, l)) = &mut self.remember {
|
|
||||||
l.auto = on;
|
|
||||||
}
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_auto(&self) -> bool {
|
|
||||||
self.router.is_some()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `/model auto` (true) or a pinned model (false, done by `set_model`/`set_provider`).
|
|
||||||
pub fn set_auto(&mut self, on: bool) {
|
|
||||||
self.router = on.then(|| route::Router::new(self.auto_cfg.clone()));
|
|
||||||
self.save(|l| l.auto = on);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn save(&mut self, f: impl FnOnce(&mut Last)) {
|
|
||||||
if let Some((p, l)) = &mut self.remember {
|
|
||||||
f(l);
|
|
||||||
// ponytail: failing to save must not fail the switch
|
|
||||||
let _ = serde_json::to_vec(&*l).map(|b| std::fs::write(&*p, b));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The provider reported its limits: remember one that is used up until its window resets.
|
|
||||||
pub fn note_quota(&mut self, kind: Kind, q: &hx_ai::Quota) {
|
|
||||||
let now = hx_ai::auth::now_ms() / 1000;
|
|
||||||
self.spent.retain(|(k, t)| *k != kind && *t > now);
|
|
||||||
let full: Vec<&hx_ai::QuotaWindow> =
|
|
||||||
q.windows.iter().filter(|w| w.used_pct >= 99.5).collect();
|
|
||||||
if !full.is_empty() {
|
|
||||||
let until = full
|
|
||||||
.iter()
|
|
||||||
.filter_map(|w| w.resets_at)
|
|
||||||
.max()
|
|
||||||
.unwrap_or(now + 3600);
|
|
||||||
self.spent.push((kind, until));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn out_of_quota(&self) -> Option<Kind> {
|
|
||||||
let now = hx_ai::auth::now_ms() / 1000;
|
|
||||||
self.spent.iter().find(|(_, t)| *t > now).map(|(k, _)| *k)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Before a prompt: in auto mode choose model and thinking level for it; an `@word` override
|
|
||||||
/// (`@opus`, `@codex`, `@fast`) applies to this prompt only, with or without auto. `None` =
|
|
||||||
/// leave the agent as it is. Call [`end_turn`](Self::end_turn) when the run is over.
|
|
||||||
pub fn begin_turn(
|
|
||||||
&mut self,
|
|
||||||
agent: &mut Agent,
|
|
||||||
prompt: &str,
|
|
||||||
is_file: &dyn Fn(&str) -> bool,
|
|
||||||
) -> Result<Option<Routed>, String> {
|
|
||||||
let forced = route::parse_override(prompt, &self.models, is_file);
|
|
||||||
if self.router.is_none() && forced.is_none() {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
let hist = agent.session().messages();
|
|
||||||
let (text, target) = match &forced {
|
|
||||||
Some((t, rest)) => (rest.as_str(), Some(t)),
|
|
||||||
None => (prompt, None),
|
|
||||||
};
|
|
||||||
let sig = route::signals(text, &hist);
|
|
||||||
let before = (self.kind, agent.model().to_string(), agent.effort());
|
|
||||||
let avoid = self.out_of_quota();
|
|
||||||
let pick = match target {
|
|
||||||
Some(route::Target::Model(m)) => {
|
|
||||||
let kind = models::kind_of(&self.models, m).unwrap_or(self.kind);
|
|
||||||
let tier = route::Tier::of(m).unwrap_or(sig.tier);
|
|
||||||
route::Pick {
|
|
||||||
kind,
|
|
||||||
model: m.clone(),
|
|
||||||
tier,
|
|
||||||
effort: before.2,
|
|
||||||
why: format!("@{m}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(route::Target::Provider(k)) => {
|
|
||||||
let (kind, model) =
|
|
||||||
route::pick_for(sig.tier, *k, None, &self.models_of(*k), &self.auto_cfg)
|
|
||||||
.ok_or_else(|| format!("no models for {k:?}"))?;
|
|
||||||
route::Pick {
|
|
||||||
kind,
|
|
||||||
model,
|
|
||||||
tier: sig.tier,
|
|
||||||
effort: before.2,
|
|
||||||
why: format!("@{k:?}, {} tier", sig.tier.name()).to_lowercase(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(route::Target::Tier(t)) => {
|
|
||||||
let (kind, model) =
|
|
||||||
route::pick_for(*t, self.kind, avoid, &self.models, &self.auto_cfg)
|
|
||||||
.ok_or("no models")?;
|
|
||||||
route::Pick {
|
|
||||||
kind,
|
|
||||||
model,
|
|
||||||
tier: *t,
|
|
||||||
effort: before.2,
|
|
||||||
why: format!("@{}", t.name()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
let Some(r) = &mut self.router else {
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
match r.route(&sig, self.kind, avoid, &self.models) {
|
|
||||||
Some(p) => p,
|
|
||||||
None => return Ok(None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let was_auto = self.router.is_some();
|
|
||||||
if forced.is_some() && !was_auto {
|
|
||||||
self.restore = Some(before.clone());
|
|
||||||
}
|
|
||||||
let effort = if forced.is_some() {
|
|
||||||
// the forced model keeps the user's level when it has it, else its first
|
|
||||||
let lv = hx_ai::Effort::levels(pick.kind);
|
|
||||||
if lv.contains(&before.2) {
|
|
||||||
before.2
|
|
||||||
} else {
|
|
||||||
lv[0]
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
pick.effort
|
|
||||||
};
|
|
||||||
let same = pick.kind == self.kind && pick.model == before.1;
|
|
||||||
let sw = if same {
|
|
||||||
Switched {
|
|
||||||
kind: pick.kind,
|
|
||||||
model: pick.model.clone(),
|
|
||||||
provider_changed: false,
|
|
||||||
window: models::window(&self.models, &pick.model),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// auto picks and one-turn overrides are not the user's pinned choice
|
|
||||||
self.apply_inner(agent, pick.kind, pick.model.clone(), false, false)?
|
|
||||||
};
|
|
||||||
agent.set_effort(effort);
|
|
||||||
Ok(Some(Routed {
|
|
||||||
pick: route::Pick { effort, ..pick },
|
|
||||||
sw,
|
|
||||||
forced: forced.is_some(),
|
|
||||||
prompt: text.to_string(),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// After the run: undo a one-turn override made outside auto mode. Returns what it went back to.
|
|
||||||
pub fn end_turn(&mut self, agent: &mut Agent) -> Option<Switched> {
|
|
||||||
let (kind, model, effort) = self.restore.take()?;
|
|
||||||
let sw = self.apply_inner(agent, kind, model, false, false).ok()?;
|
|
||||||
agent.set_effort(effort);
|
|
||||||
Some(sw)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn models_of(&self, k: Kind) -> Vec<ModelInfo> {
|
|
||||||
self.models
|
|
||||||
.iter()
|
|
||||||
.filter(|m| m.kind == k)
|
|
||||||
.cloned()
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Write every successful switch to `path` (best effort).
|
/// Write every successful switch to `path` (best effort).
|
||||||
/// `start` is what the agent starts with.
|
/// `start` is what the agent starts with.
|
||||||
pub fn remember_in(mut self, path: std::path::PathBuf, start: Last) -> Self {
|
pub fn remember_in(mut self, path: std::path::PathBuf, start: Last) -> Self {
|
||||||
@@ -282,8 +83,6 @@ impl Switcher {
|
|||||||
/// On error the agent and the switcher are unchanged.
|
/// On error the agent and the switcher are unchanged.
|
||||||
pub fn set_model(&mut self, agent: &mut Agent, id: &str) -> Result<Switched, String> {
|
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);
|
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)
|
self.apply(agent, kind, id.to_string(), false)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -291,8 +90,6 @@ impl Switcher {
|
|||||||
/// provider, which picks up refreshed credentials after a re-login.
|
/// provider, which picks up refreshed credentials after a re-login.
|
||||||
pub fn set_provider(&mut self, agent: &mut Agent, kind: Kind) -> Result<Switched, String> {
|
pub fn set_provider(&mut self, agent: &mut Agent, kind: Kind) -> Result<Switched, String> {
|
||||||
let model = models::default_for(kind, &self.models);
|
let model = models::default_for(kind, &self.models);
|
||||||
self.router = None;
|
|
||||||
self.save(|l| l.auto = false);
|
|
||||||
self.apply(agent, kind, model, true)
|
self.apply(agent, kind, model, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,17 +99,6 @@ impl Switcher {
|
|||||||
kind: Kind,
|
kind: Kind,
|
||||||
model: String,
|
model: String,
|
||||||
rebuild: bool,
|
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> {
|
) -> Result<Switched, String> {
|
||||||
let provider_changed = rebuild || kind != self.kind;
|
let provider_changed = rebuild || kind != self.kind;
|
||||||
if provider_changed {
|
if provider_changed {
|
||||||
@@ -322,11 +108,11 @@ impl Switcher {
|
|||||||
} else {
|
} else {
|
||||||
agent.set_model(model.as_str());
|
agent.set_model(model.as_str());
|
||||||
}
|
}
|
||||||
if remember {
|
if let Some((p, l)) = &mut self.remember {
|
||||||
self.save(|l| {
|
l.provider = kind;
|
||||||
l.provider = kind;
|
l.model = model.clone();
|
||||||
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);
|
let window = models::window(&self.models, &model);
|
||||||
agent.set_model_window(window);
|
agent.set_model_window(window);
|
||||||
@@ -475,7 +261,6 @@ mod tests {
|
|||||||
provider: Kind::Claude,
|
provider: Kind::Claude,
|
||||||
model: "m".into(),
|
model: "m".into(),
|
||||||
effort: None,
|
effort: None,
|
||||||
auto: false,
|
|
||||||
};
|
};
|
||||||
let mut sw = sw.remember_in(f.clone(), start);
|
let mut sw = sw.remember_in(f.clone(), start);
|
||||||
sw.set_model(&mut a, "gpt-x").unwrap();
|
sw.set_model(&mut a, "gpt-x").unwrap();
|
||||||
@@ -484,110 +269,12 @@ mod tests {
|
|||||||
provider: Kind::Codex,
|
provider: Kind::Codex,
|
||||||
model: "gpt-x".into(),
|
model: "gpt-x".into(),
|
||||||
effort: Some(hx_ai::Effort::High),
|
effort: Some(hx_ai::Effort::High),
|
||||||
auto: false,
|
|
||||||
};
|
};
|
||||||
assert_eq!(Last::load(&f), Some(want));
|
assert_eq!(Last::load(&f), Some(want));
|
||||||
std::fs::write(&f, "junk").unwrap();
|
std::fs::write(&f, "junk").unwrap();
|
||||||
assert_eq!(Last::load(&f), None);
|
assert_eq!(Last::load(&f), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn nofile(_: &str) -> bool {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn auto_routes_per_prompt_and_pin_turns_it_off() {
|
|
||||||
let (mut sw, mut a, made, _d) = setup(true, false);
|
|
||||||
sw.set_auto(true);
|
|
||||||
assert!(sw.is_auto());
|
|
||||||
let r = sw
|
|
||||||
.begin_turn(&mut a, "fix the typo in README", &nofile)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert!(!r.forced);
|
|
||||||
assert_eq!(
|
|
||||||
(r.pick.model.as_str(), a.model()),
|
|
||||||
("claude-haiku-x", "claude-haiku-x")
|
|
||||||
);
|
|
||||||
assert!(made.lock().unwrap().is_empty(), "same provider: no rebuild");
|
|
||||||
sw.set_model(&mut a, "claude-sonnet-x").unwrap();
|
|
||||||
assert!(!sw.is_auto());
|
|
||||||
assert!(
|
|
||||||
sw.begin_turn(&mut a, "fix the typo", &nofile)
|
|
||||||
.unwrap()
|
|
||||||
.is_none()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn override_is_one_turn_and_restores() {
|
|
||||||
let (mut sw, mut a, made, _d) = setup(true, false);
|
|
||||||
a.set_effort(hx_ai::Effort::High);
|
|
||||||
let r = sw
|
|
||||||
.begin_turn(&mut a, "@gpt-x explain this", &nofile)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert!(r.forced && r.sw.provider_changed);
|
|
||||||
assert_eq!(r.prompt, "explain this");
|
|
||||||
assert_eq!((sw.kind(), a.model()), (Kind::Codex, "gpt-x"));
|
|
||||||
let back = sw.end_turn(&mut a).unwrap();
|
|
||||||
assert_eq!(back.kind, Kind::Claude);
|
|
||||||
assert_eq!(
|
|
||||||
(sw.kind(), a.model(), a.effort()),
|
|
||||||
(Kind::Claude, "claude-sonnet-x", hx_ai::Effort::High)
|
|
||||||
);
|
|
||||||
assert_eq!(*made.lock().unwrap(), vec![Kind::Codex, Kind::Claude]);
|
|
||||||
assert!(sw.end_turn(&mut a).is_none(), "nothing left to undo");
|
|
||||||
// a file with that name is a mention, not an override
|
|
||||||
assert!(
|
|
||||||
sw.begin_turn(&mut a, "@gpt-x explain", &|w| w == "gpt-x")
|
|
||||||
.unwrap()
|
|
||||||
.is_none()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn override_in_auto_mode_keeps_auto() {
|
|
||||||
let (mut sw, mut a, _m, _d) = setup(true, false);
|
|
||||||
sw.set_auto(true);
|
|
||||||
let r = sw
|
|
||||||
.begin_turn(&mut a, "@haiku hi there", &nofile)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert!(r.forced && sw.is_auto());
|
|
||||||
assert_eq!(a.model(), "claude-haiku-x");
|
|
||||||
assert!(
|
|
||||||
sw.end_turn(&mut a).is_none(),
|
|
||||||
"auto picks again next prompt"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn spent_provider_is_avoided_until_reset() {
|
|
||||||
let (mut sw, mut a, _m, _d) = setup(true, false);
|
|
||||||
let q = hx_ai::Quota {
|
|
||||||
windows: vec![hx_ai::QuotaWindow {
|
|
||||||
label: "5h".into(),
|
|
||||||
used_pct: 100.0,
|
|
||||||
resets_at: Some(hx_ai::auth::now_ms() / 1000 + 600),
|
|
||||||
}],
|
|
||||||
credits: None,
|
|
||||||
};
|
|
||||||
sw.note_quota(Kind::Claude, &q);
|
|
||||||
sw.set_auto(true);
|
|
||||||
let r = sw
|
|
||||||
.begin_turn(&mut a, "add a flag to the parser please", &nofile)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(r.pick.kind, Kind::Codex);
|
|
||||||
let ok = hx_ai::Quota {
|
|
||||||
windows: vec![],
|
|
||||||
credits: None,
|
|
||||||
};
|
|
||||||
sw.note_quota(Kind::Claude, &ok);
|
|
||||||
assert!(sw.out_of_quota().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn configured_threshold_is_left_alone() {
|
fn configured_threshold_is_left_alone() {
|
||||||
let (mut sw, mut a, _m, _d) = setup(false, false);
|
let (mut sw, mut a, _m, _d) = setup(false, false);
|
||||||
|
|||||||
+19
-101
@@ -61,21 +61,7 @@ impl Choose {
|
|||||||
KeyCode::Backspace => {
|
KeyCode::Backspace => {
|
||||||
t.pop();
|
t.pop();
|
||||||
}
|
}
|
||||||
KeyCode::Char('w') if k.modifiers.contains(KeyModifiers::CONTROL) => {
|
KeyCode::Char(c) => t.push(c),
|
||||||
let n = t
|
|
||||||
.trim_end()
|
|
||||||
.trim_end_matches(|c: char| !c.is_whitespace())
|
|
||||||
.len();
|
|
||||||
t.truncate(n);
|
|
||||||
}
|
|
||||||
KeyCode::Char('j') if k.modifiers.contains(KeyModifiers::CONTROL) => t.push('\n'),
|
|
||||||
KeyCode::Enter
|
|
||||||
if k.modifiers
|
|
||||||
.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT) =>
|
|
||||||
{
|
|
||||||
t.push('\n')
|
|
||||||
}
|
|
||||||
KeyCode::Char(c) if !k.modifiers.contains(KeyModifiers::CONTROL) => t.push(c),
|
|
||||||
KeyCode::Enter if !t.trim().is_empty() => {
|
KeyCode::Enter if !t.trim().is_empty() => {
|
||||||
let mut v = picked;
|
let mut v = picked;
|
||||||
v.push(t.trim().to_string());
|
v.push(t.trim().to_string());
|
||||||
@@ -110,13 +96,6 @@ impl Choose {
|
|||||||
Act::None
|
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 {
|
fn enter(&mut self) -> Act {
|
||||||
if self.is_other() || self.rows() == 0 {
|
if self.is_other() || self.rows() == 0 {
|
||||||
self.typing = Some(String::new());
|
self.typing = Some(String::new());
|
||||||
@@ -127,7 +106,7 @@ impl Choose {
|
|||||||
|
|
||||||
pub fn help(&self) -> &'static str {
|
pub fn help(&self) -> &'static str {
|
||||||
if self.typing.is_some() {
|
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 {
|
} else if self.q.multi {
|
||||||
"↑↓ move · space toggle · enter confirm · esc skip"
|
"↑↓ move · space toggle · enter confirm · esc skip"
|
||||||
} else {
|
} else {
|
||||||
@@ -179,32 +158,24 @@ impl Choose {
|
|||||||
if self.is_other() {
|
if self.is_other() {
|
||||||
sel_line = lines.len();
|
sel_line = lines.len();
|
||||||
}
|
}
|
||||||
if let Some(t) = &self.typing {
|
lines.push(match &self.typing {
|
||||||
let pre = format!("{} other: ", n + 1);
|
Some(t) => Line::from(vec![
|
||||||
let rows = hard_wrap(&format!("{pre}{t}▏"), inner);
|
|
||||||
sel_line = lines.len() + rows.len() - 1;
|
|
||||||
for (i, r) in rows.into_iter().enumerate() {
|
|
||||||
if i == 0 {
|
|
||||||
let k = pre.len().min(r.len());
|
|
||||||
lines.push(Line::from(vec![
|
|
||||||
Span::styled(r[..k].to_string(), th.accent()),
|
|
||||||
Span::raw(r[k..].to_string()),
|
|
||||||
]));
|
|
||||||
} else {
|
|
||||||
lines.push(Line::raw(r));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let st = if self.is_other() {
|
|
||||||
th.sel()
|
|
||||||
} else {
|
|
||||||
th.plain()
|
|
||||||
};
|
|
||||||
lines.push(Line::from(vec![
|
|
||||||
Span::styled(format!("{} ", n + 1), th.accent()),
|
Span::styled(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())
|
let q = Paragraph::new(self.q.text.as_str())
|
||||||
.wrap(Wrap { trim: false })
|
.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).
|
/// Greedy word wrap to `w` chars (a single longer word is kept whole).
|
||||||
fn wrap(s: &str, w: usize) -> Vec<String> {
|
fn wrap(s: &str, w: usize) -> Vec<String> {
|
||||||
let mut out: Vec<String> = vec![];
|
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]
|
#[test]
|
||||||
fn typing_esc_goes_back_and_renders() {
|
fn typing_esc_goes_back_and_renders() {
|
||||||
let mut c = q(false);
|
let mut c = q(false);
|
||||||
|
|||||||
+8
-157
@@ -47,7 +47,6 @@ pub struct Setup {
|
|||||||
pub pricing: fn(&str) -> Option<hx_ai::Pricing>,
|
pub pricing: fn(&str) -> Option<hx_ai::Pricing>,
|
||||||
/// `/lsp` status lines.
|
/// `/lsp` status lines.
|
||||||
pub lsp_status: LspStatus,
|
pub lsp_status: LspStatus,
|
||||||
pub reload: Reload,
|
|
||||||
/// Extra slash commands (MCP prompts, `/mcp`): `(name, arg)` -> None = not mine,
|
/// 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.
|
/// Some(Ok(Send(text))) = send as a user prompt, Some(Ok(Show(text))) = show, Some(Err) = error.
|
||||||
pub commands: Commands,
|
pub commands: Commands,
|
||||||
@@ -89,9 +88,6 @@ pub type Commands = Box<
|
|||||||
+ Sync,
|
+ 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<
|
pub type LspStatus = Box<
|
||||||
dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<String>> + Send>> + Send,
|
dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<String>> + Send>> + Send,
|
||||||
>;
|
>;
|
||||||
@@ -202,7 +198,6 @@ struct App {
|
|||||||
impl App {
|
impl App {
|
||||||
/// Mirror a model/provider switch into what the footer shows.
|
/// Mirror a model/provider switch into what the footer shows.
|
||||||
fn apply_switch(&mut self, sw: &hx_core::switch::Switched) {
|
fn apply_switch(&mut self, sw: &hx_core::switch::Switched) {
|
||||||
self.st.auto = self.sw.is_auto();
|
|
||||||
self.st.kind = sw.kind;
|
self.st.kind = sw.kind;
|
||||||
self.st.model = sw.model.clone();
|
self.st.model = sw.model.clone();
|
||||||
// keep the level when the new provider has it, else its first (Codex has no "off")
|
// 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 {
|
fn expand_mentions(s: &str, root: &std::path::Path) -> String {
|
||||||
let mut att = String::new();
|
let mut att = String::new();
|
||||||
for w in s.split_whitespace().filter_map(|w| w.strip_prefix('@')) {
|
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)
|
if let Ok(c) = std::fs::read_to_string(&p)
|
||||||
&& c.len() < 200_000
|
&& c.len() < 200_000
|
||||||
{
|
{
|
||||||
@@ -263,7 +258,6 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
switcher,
|
switcher,
|
||||||
pricing,
|
pricing,
|
||||||
lsp_status,
|
lsp_status,
|
||||||
reload,
|
|
||||||
commands,
|
commands,
|
||||||
specs,
|
specs,
|
||||||
open_sessions,
|
open_sessions,
|
||||||
@@ -345,7 +339,6 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
cwd_label: home_short(&cwd),
|
cwd_label: home_short(&cwd),
|
||||||
git: git_head(&cwd),
|
git: git_head(&cwd),
|
||||||
st: status::Status {
|
st: status::Status {
|
||||||
auto: switcher.is_auto(),
|
|
||||||
kind: switcher.kind(),
|
kind: switcher.kind(),
|
||||||
model: agent.model().to_string(),
|
model: agent.model().to_string(),
|
||||||
effort: agent.effort(),
|
effort: agent.effort(),
|
||||||
@@ -399,7 +392,6 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
tx: &tx,
|
tx: &tx,
|
||||||
cwd: &cwd,
|
cwd: &cwd,
|
||||||
lsp_status: &lsp_status,
|
lsp_status: &lsp_status,
|
||||||
reload: &reload,
|
|
||||||
commands: &commands,
|
commands: &commands,
|
||||||
};
|
};
|
||||||
let mut term = ratatui::init();
|
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::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::Paste(s) if app.perm.is_none() && app.choose.is_none() && app.ask.is_none() => app.ed.insert(&s),
|
||||||
TEvent::Resize(..) => app.sel = None,
|
TEvent::Resize(..) => app.sel = None,
|
||||||
_ => {}
|
_ => {}
|
||||||
@@ -535,7 +522,6 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
app.st.usage.add(u);
|
app.st.usage.add(u);
|
||||||
}
|
}
|
||||||
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
|
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
|
||||||
app.sw.note_quota(app.st.kind, q);
|
|
||||||
app.st.quota = Some(q.clone());
|
app.st.quota = Some(q.clone());
|
||||||
}
|
}
|
||||||
if let Event::Stream(
|
if let Event::Stream(
|
||||||
@@ -554,14 +540,6 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
}
|
}
|
||||||
Ui::Done(r) => {
|
Ui::Done(r) => {
|
||||||
app.busy = false;
|
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);
|
app.git = git_head(&cwd);
|
||||||
match r {
|
match r {
|
||||||
Err(e) if e == "aborted" => app.t.push(Item::Info("aborted".into())),
|
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() {
|
match labels.len() {
|
||||||
0 => app.hint = "no match".into(),
|
0 => app.hint = "no match".into(),
|
||||||
1 => {
|
1 => {
|
||||||
let l = if labels[0].ends_with('/') {
|
let l = format!("{} ", labels[0]);
|
||||||
labels[0].to_string()
|
|
||||||
} else {
|
|
||||||
format!("{} ", labels[0])
|
|
||||||
};
|
|
||||||
app.ed.replace(c.start, &l);
|
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).
|
/// Commands and their arguments complete as you type; `@file` waits for Tab (the file list is big).
|
||||||
fn live_popup(app: &mut App) {
|
fn live_popup(app: &mut App) {
|
||||||
app.popup = None;
|
app.popup = None;
|
||||||
if app.ed.buf.contains('\n') {
|
if !app.ed.buf.starts_with('/') || app.ed.buf.contains('\n') {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let c = completion(app);
|
let c = completion(app);
|
||||||
let tok = &app.ed.buf[c.start..app.ed.cur];
|
if !app.ed.buf[c.start..app.ed.cur].starts_with('@') {
|
||||||
let fs = cmd::is_fs_path(tok.strip_prefix('@').unwrap_or(tok));
|
|
||||||
if fs || (app.ed.buf.starts_with('/') && !tok.starts_with('@')) {
|
|
||||||
app.popup = popup::Popup::new(c);
|
app.popup = popup::Popup::new(c);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn accept(app: &mut App) {
|
fn accept(app: &mut App) {
|
||||||
if let Some(p) = app.popup.take() {
|
if let Some(p) = app.popup.take() {
|
||||||
let l = p.selected_label();
|
app.ed
|
||||||
let sp = if l.ends_with('/') { "" } else { " " };
|
.replace(p.comp.start, &format!("{} ", p.selected_label()));
|
||||||
app.ed.replace(p.comp.start, &format!("{l}{sp}"));
|
|
||||||
live_popup(app);
|
live_popup(app);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1296,7 +1267,6 @@ struct Ctx<'a> {
|
|||||||
tx: &'a mpsc::UnboundedSender<Ui>,
|
tx: &'a mpsc::UnboundedSender<Ui>,
|
||||||
cwd: &'a std::path::Path,
|
cwd: &'a std::path::Path,
|
||||||
lsp_status: &'a LspStatus,
|
lsp_status: &'a LspStatus,
|
||||||
reload: &'a Reload,
|
|
||||||
commands: &'a Commands,
|
commands: &'a Commands,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1306,7 +1276,6 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
tx,
|
tx,
|
||||||
cwd,
|
cwd,
|
||||||
lsp_status,
|
lsp_status,
|
||||||
reload,
|
|
||||||
commands,
|
commands,
|
||||||
} = *c;
|
} = *c;
|
||||||
app.scroll.end();
|
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());
|
let r = status::report(&app.st, status::now_secs());
|
||||||
show(app, "usage", r);
|
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" => {
|
"skills" => {
|
||||||
let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd);
|
let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd);
|
||||||
let mut l = skills_list(&app.specs, &dirs);
|
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);
|
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" => {
|
"yolo" => {
|
||||||
let on = app
|
let on = app
|
||||||
.state
|
.state
|
||||||
@@ -1495,23 +1417,11 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
))),
|
))),
|
||||||
Err(e) => app.t.push(Item::Error(e)),
|
Err(e) => app.t.push(Item::Error(e)),
|
||||||
},
|
},
|
||||||
"model" if arg.is_empty() => app.t.push(Item::Info(format!(
|
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.st.model))),
|
||||||
"model: {}{}",
|
|
||||||
app.st.model,
|
|
||||||
if app.st.auto { " (auto)" } else { "" }
|
|
||||||
))),
|
|
||||||
"model" if arg == "auto" => {
|
|
||||||
app.sw.set_auto(true);
|
|
||||||
app.st.auto = true;
|
|
||||||
app.t.push(Item::Info(
|
|
||||||
"model: auto. Picked per prompt across logged-in providers; `@opus ...`, `@codex ...`, `@fast ...` force one turn.".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
"model" => {
|
"model" => {
|
||||||
let mut a = agent.lock().await;
|
let mut a = agent.lock().await;
|
||||||
match app.sw.set_model(&mut a, arg) {
|
match app.sw.set_model(&mut a, arg) {
|
||||||
Ok(sw) => {
|
Ok(sw) => {
|
||||||
app.st.auto = false;
|
|
||||||
app.apply_switch(&sw);
|
app.apply_switch(&sw);
|
||||||
app.ctx_max_from(&a);
|
app.ctx_max_from(&a);
|
||||||
app.t.push(Item::Info(format!(
|
app.t.push(Item::Info(format!(
|
||||||
@@ -1593,36 +1503,6 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
} else {
|
} else {
|
||||||
line.clone()
|
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.busy = true;
|
||||||
app.since = Instant::now();
|
app.since = Instant::now();
|
||||||
app.run_tokens = (0, 0);
|
app.run_tokens = (0, 0);
|
||||||
@@ -2556,7 +2436,6 @@ mod tests {
|
|||||||
busy: false,
|
busy: false,
|
||||||
queue: VecDeque::new(),
|
queue: VecDeque::new(),
|
||||||
st: status::Status {
|
st: status::Status {
|
||||||
auto: false,
|
|
||||||
kind: Kind::Claude,
|
kind: Kind::Claude,
|
||||||
model: "m1".into(),
|
model: "m1".into(),
|
||||||
effort: hx_ai::Effort::Off,
|
effort: hx_ai::Effort::Off,
|
||||||
@@ -2614,21 +2493,6 @@ mod tests {
|
|||||||
assert!(s.ends_with("/nonexistent-hx (missing)"), "{s}");
|
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]
|
#[test]
|
||||||
fn popup_keys_and_render() {
|
fn popup_keys_and_render() {
|
||||||
let mut app = test_app();
|
let mut app = test_app();
|
||||||
@@ -2694,7 +2558,7 @@ mod tests {
|
|||||||
for c in "/model ".chars() {
|
for c in "/model ".chars() {
|
||||||
key(&mut app, KeyCode::Char(c));
|
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 "));
|
assert_eq!(key(&mut app, KeyCode::Enter).as_deref(), Some("/model "));
|
||||||
|
|
||||||
// @file waits for tab; esc closes; up with popup closed browses history
|
// @file waits for tab; esc closes; up with popup closed browses history
|
||||||
@@ -2800,27 +2664,16 @@ mod tests {
|
|||||||
let (tx, _rx) = mpsc::unbounded_channel();
|
let (tx, _rx) = mpsc::unbounded_channel();
|
||||||
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
||||||
let cmds: Commands = Box::new(|_, _| None);
|
let cmds: Commands = Box::new(|_, _| None);
|
||||||
let rl: Reload = Box::new(|| Ok(("sys".into(), cmd::builtins(&[]))));
|
|
||||||
let ctx = Ctx {
|
let ctx = Ctx {
|
||||||
agent: &agent,
|
agent: &agent,
|
||||||
tx: &tx,
|
tx: &tx,
|
||||||
cwd: t.path(),
|
cwd: t.path(),
|
||||||
lsp_status: &ls,
|
lsp_status: &ls,
|
||||||
reload: &rl,
|
|
||||||
commands: &cmds,
|
commands: &cmds,
|
||||||
};
|
};
|
||||||
let mut app = test_app();
|
let mut app = test_app();
|
||||||
app.session_path = old.clone();
|
app.session_path = old.clone();
|
||||||
app.title = Some("first".into());
|
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;
|
submit(&mut app, "/clear".into(), &ctx).await;
|
||||||
let new = agent.lock().await.session().path().to_path_buf();
|
let new = agent.lock().await.session().path().to_path_buf();
|
||||||
assert_ne!(new, old);
|
assert_ne!(new, old);
|
||||||
@@ -2861,13 +2714,11 @@ mod tests {
|
|||||||
models.extend(hx_ai::models::fallback(Kind::Codex));
|
models.extend(hx_ai::models::fallback(Kind::Codex));
|
||||||
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
||||||
let cmds: Commands = Box::new(|_, _| None);
|
let cmds: Commands = Box::new(|_, _| None);
|
||||||
let rl: Reload = Box::new(|| Ok(("sys".into(), cmd::builtins(&[]))));
|
|
||||||
let ctx = Ctx {
|
let ctx = Ctx {
|
||||||
agent: &agent,
|
agent: &agent,
|
||||||
tx: &tx,
|
tx: &tx,
|
||||||
cwd: t.path(),
|
cwd: t.path(),
|
||||||
lsp_status: &ls,
|
lsp_status: &ls,
|
||||||
reload: &rl,
|
|
||||||
commands: &cmds,
|
commands: &cmds,
|
||||||
};
|
};
|
||||||
let mut app = test_app();
|
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.
|
/// What the status line and `/usage` report about the running session.
|
||||||
pub struct Status {
|
pub struct Status {
|
||||||
/// `/model auto` is on: the model shown was picked for the last prompt
|
|
||||||
pub auto: bool,
|
|
||||||
pub kind: Kind,
|
pub kind: Kind,
|
||||||
pub model: String,
|
pub model: String,
|
||||||
pub effort: hx_ai::Effort,
|
pub effort: hx_ai::Effort,
|
||||||
@@ -137,9 +135,8 @@ fn left_spans(st: &Status) -> Vec<Span<'static>> {
|
|||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
};
|
};
|
||||||
let model = st.model.strip_prefix("claude-").unwrap_or(&st.model);
|
let model = st.model.strip_prefix("claude-").unwrap_or(&st.model);
|
||||||
let auto = if st.auto { "auto→" } else { "" };
|
|
||||||
vec![
|
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_full.repeat(full), bar_st),
|
||||||
Span::styled(th.sym.bar_empty.repeat(10 - full), th.dim()),
|
Span::styled(th.sym.bar_empty.repeat(10 - full), th.dim()),
|
||||||
Span::styled(format!(" {:.0}%{cost}", frac * 100.0), th.sec()),
|
Span::styled(format!(" {:.0}%{cost}", frac * 100.0), th.sec()),
|
||||||
@@ -272,7 +269,6 @@ mod tests {
|
|||||||
|
|
||||||
fn st() -> Status {
|
fn st() -> Status {
|
||||||
Status {
|
Status {
|
||||||
auto: false,
|
|
||||||
kind: Kind::Claude,
|
kind: Kind::Claude,
|
||||||
model: "claude-m1".into(),
|
model: "claude-m1".into(),
|
||||||
effort: hx_ai::Effort::Off,
|
effort: hx_ai::Effort::Off,
|
||||||
|
|||||||
@@ -6,64 +6,37 @@
|
|||||||
outputs =
|
outputs =
|
||||||
{ self, nixpkgs }:
|
{ self, nixpkgs }:
|
||||||
let
|
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});
|
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
|
in
|
||||||
{
|
{
|
||||||
packages = forAll (
|
packages = forAll (pkgs: rec {
|
||||||
pkgs:
|
hx = pkgs.rustPlatform.buildRustPackage {
|
||||||
let
|
pname = "hx";
|
||||||
target = targets.${pkgs.stdenv.hostPlatform.system} or "";
|
version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).workspace.package.version;
|
||||||
hasBin = bin.sha256 ? ${target};
|
src = pkgs.lib.cleanSource ./.;
|
||||||
|
cargoLock.lockFile = ./Cargo.lock;
|
||||||
hx = pkgs.rustPlatform.buildRustPackage {
|
cargoBuildFlags = [ "-p" "hx-cli" ];
|
||||||
pname = "hx";
|
# ponytail: tests skipped (need git/network); enable when hermetic.
|
||||||
version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).workspace.package.version;
|
doCheck = false;
|
||||||
src = pkgs.lib.cleanSource ./.;
|
# rustls may build aws-lc-sys (cmake) depending on feature set.
|
||||||
cargoLock.lockFile = ./Cargo.lock;
|
nativeBuildInputs = [ pkgs.cmake pkgs.perl ];
|
||||||
cargoBuildFlags = [ "-p" "hx-cli" ];
|
dontUseCmakeConfigure = true;
|
||||||
# ponytail: tests skipped (need git/network); enable when hermetic.
|
meta = {
|
||||||
doCheck = false;
|
description = "Minimal Rust coding agent using existing subscriptions";
|
||||||
# rustls may build aws-lc-sys (cmake) depending on feature set.
|
license = pkgs.lib.licenses.unlicense;
|
||||||
nativeBuildInputs = [ pkgs.cmake pkgs.perl ];
|
mainProgram = "hx";
|
||||||
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;
|
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: {
|
devShells = forAll (pkgs: {
|
||||||
default = pkgs.mkShell {
|
default = pkgs.mkShell {
|
||||||
|
|||||||
+1
-14
@@ -79,26 +79,13 @@ send(b"/usage\r")
|
|||||||
check("usage report", "58% left, resets in 2h1")
|
check("usage report", "58% left, resets in 2h1")
|
||||||
check("1M window", "of 900k")
|
check("1M window", "of 900k")
|
||||||
send(b"/model claude-opus-5-5\r")
|
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")
|
send(b"/model gpt-5.6-sol\r")
|
||||||
check("gpt model needs codex login", "not logged in to Codex")
|
check("gpt model needs codex login", "not logged in to Codex")
|
||||||
send(b"/model claude-sonnet-5-6-preview\r")
|
send(b"/model claude-sonnet-5-6-preview\r")
|
||||||
check("live catalog window", "2000k")
|
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))
|
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""
|
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 ")
|
send(b"/provider ")
|
||||||
check("only logged-in providers offered", "claude")
|
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")
|
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