Compare commits
18
Commits
4161095d4d
...
v0.1.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6222fcab17 | ||
|
|
c6c4add124 | ||
|
|
478c007271 | ||
|
|
410385dcfb | ||
|
|
39a4e0c625 | ||
|
|
dc0a329ae1 | ||
|
|
ca6b917b17 | ||
|
|
042f1ed3b5 | ||
|
|
9843e5305c | ||
|
|
047e781ca4 | ||
|
|
cfb517e806 | ||
|
|
dac2320503 | ||
|
|
130704b8b3 | ||
|
|
fe6811540a | ||
|
|
10b2ccf60a | ||
|
|
d0f23421cd | ||
|
|
ee5d8371d0 | ||
|
|
926bcbf978 |
No files matched your search
@@ -0,0 +1,109 @@
|
||||
name: build
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore: [bin.json]
|
||||
workflow_dispatch:
|
||||
env:
|
||||
MACOS_SDK: "14.5"
|
||||
jobs:
|
||||
# next version = highest vX.Y.Z tag with the patch bumped; push a tag by hand for minor/major
|
||||
version:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.next.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- id: next
|
||||
run: |
|
||||
last=$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' --sort=-v:refname | head -n1)
|
||||
if [ -z "$last" ]; then
|
||||
next=0.1.0
|
||||
else
|
||||
last=${last#v}
|
||||
next="${last%.*}.$(( ${last##*.} + 1 ))"
|
||||
fi
|
||||
echo "version=$next" >> "$GITHUB_OUTPUT"
|
||||
build:
|
||||
needs: version
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
target: [x86_64-unknown-linux-musl, aarch64-apple-darwin]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
# caches ~/.cargo registry/git and target/, keyed on Cargo.lock + toolchain
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
key: ${{ matrix.target }}
|
||||
# zig as cross C compiler/linker for both musl and macOS
|
||||
- run: pip install ziglang cargo-zigbuild
|
||||
# macOS: Apple SDK for Security.framework etc.
|
||||
- if: matrix.target == 'aarch64-apple-darwin'
|
||||
id: sdk-cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/MacOSX${{ env.MACOS_SDK }}.sdk
|
||||
key: macos-sdk-${{ env.MACOS_SDK }}
|
||||
- if: matrix.target == 'aarch64-apple-darwin' && steps.sdk-cache.outputs.cache-hit != 'true'
|
||||
run: curl -fsSL "https://github.com/joseluisq/macosx-sdks/releases/download/${MACOS_SDK}/MacOSX${MACOS_SDK}.sdk.tar.xz" | tar -xJ -C "$HOME"
|
||||
- if: matrix.target == 'aarch64-apple-darwin'
|
||||
run: echo "SDKROOT=$HOME/MacOSX${MACOS_SDK}.sdk" >> "$GITHUB_ENV"
|
||||
- run: cargo zigbuild --release --locked --target ${{ matrix.target }} -p hx-cli
|
||||
env:
|
||||
HX_VERSION: ${{ needs.version.outputs.version }}
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: hx-${{ matrix.target }}
|
||||
path: target/${{ matrix.target }}/release/hx
|
||||
release:
|
||||
needs: [build, version]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# main, not the build sha: bin.json is committed on top of it
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
path: dist
|
||||
# artifacts lose the executable bit, restore it before packaging
|
||||
- working-directory: dist
|
||||
run: |
|
||||
for t in hx-*; do
|
||||
chmod +x "$t/hx"
|
||||
tar -czf "$t.tar.gz" -C "$t" hx
|
||||
done
|
||||
sha256sum *.tar.gz > SHA256SUMS
|
||||
- env:
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
API: ${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}
|
||||
TAG: v${{ needs.version.outputs.version }}
|
||||
SHA: ${{ gitea.sha }}
|
||||
# Gitea creates the tag at target_commitish when it doesn't exist
|
||||
run: |
|
||||
id=$(curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"target_commitish\":\"$SHA\"}" "$API/releases" | jq -r .id)
|
||||
for f in dist/*.tar.gz dist/SHA256SUMS; do
|
||||
curl -fsS -X POST -H "Authorization: token $TOKEN" \
|
||||
-F "attachment=@$f" "$API/releases/$id/assets?name=$(basename "$f")"
|
||||
done
|
||||
# flake.nix reads bin.json to fetch these tarballs instead of building from source
|
||||
- env:
|
||||
VERSION: ${{ needs.version.outputs.version }}
|
||||
run: |
|
||||
jq -Rn --arg v "$VERSION" \
|
||||
'{version: $v, sha256: ([inputs | split(" ") | {(.[1] | ltrimstr("hx-") | rtrimstr(".tar.gz")): .[0]}] | add)}' \
|
||||
< dist/SHA256SUMS > bin.json
|
||||
git config user.name gitea-actions
|
||||
git config user.email gitea-actions@git.jokresner.de
|
||||
git add bin.json
|
||||
git commit -m "ci: bin.json v$VERSION"
|
||||
git pull --rebase origin main
|
||||
git push origin HEAD:main
|
||||
@@ -1,21 +0,0 @@
|
||||
name: ci
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt, clippy, rust-analyzer
|
||||
- run: cargo fmt --all --check
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
- run: cargo test --workspace
|
||||
- run: cargo build && sh tests/e2e.sh
|
||||
- run: python3 tests/tui_smoke.py
|
||||
- run: sh tests/lens_e2e.sh
|
||||
- run: pip install ruff && sh tests/m4_e2e.sh
|
||||
- run: sh tests/m5_e2e.sh
|
||||
- run: sh tests/m6_e2e.sh
|
||||
- run: python3 tests/tui_lspinstall.py
|
||||
- run: sh tests/m7_e2e.sh
|
||||
@@ -84,17 +84,22 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off
|
||||
|
||||
## 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`.
|
||||
`/model auto` (or `model = "auto"`, `--model auto`) picks model and thinking level for every prompt, across all logged-in providers; `/model <id>` or `/provider` turns it off. No extra LLM call: the prompt is scored from cheap signals (length, keywords like `refactor`/`race condition` vs. `typo`/`explain`, a stack trace, a failed tool result in the last turn, a long session) into a tier: `fast` (Haiku/Luna), `balanced` (Sonnet/Terra), `deep` (Opus/Sol). Stepping up is immediate, stepping down needs `down_after` (default 3) light prompts in a row, because every switch costs the prompt cache. Very short replies ("ja", "continue") keep the current tier. The provider stays unless the other one has the tier exactly or the current one reported a used-up quota window. Common words (`implement`, `design`, `debug`, `plan`) count one point, not a tier; failed tool results escalate (+2, +4 when the last two turns failed), and many recent edits add a point. With a big history (>100k tokens) the default `down_after` is 5, since a switch re-reads it uncached. Each choice and its reason is shown as a line in the chat; the footer shows `auto→model`.
|
||||
|
||||
**Fable** is never chosen by default. `/fable on` (or `[auto] fable = true`; the command is remembered across starts and wins over the config) lets auto escalate to a fifth `max` tier (Fable, $10/$50 per Mtok) after two failed turns in a row or a score of 7+; the next ordinary prompt drops back at once. Without Fable in the catalog it stays on `deep`. `/fable` shows the state; `@fable ...` / `@max ...` always work for one turn.
|
||||
|
||||
One-turn override, with or without auto: start the prompt with `@opus fix this`, `@codex ...`, `@fast ...`, `@deep ...` or `@<model id>` (any unique part of an id, 3+ chars). A file with that name wins, so `@notes.md` stays a file mention. The previous model comes back after the turn (in auto mode, the router just chooses again).
|
||||
|
||||
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.
|
||||
Within a tier the highest-versioned model is used (`claude-opus-5-5` over `claude-opus-4-1-20250805`, `gpt-5.6-sol` over `gpt-5.5-sol`), whatever order the API lists them in; no model id is hard-coded except the offline fallback list and your `[auto]` pins.
|
||||
|
||||
Switching provider mid-session converts history: Codex reasoning items and unsigned thinking are dropped for Claude, tool-call ids are made Anthropic-safe. `hx stats` shows the auto choices (prompts and mean score per tier, how often a tier was held, how often the next prompt went up again; raw lines in `<session>.route`) and lists requests per model and the cache re-written after each switch.
|
||||
|
||||
```toml
|
||||
[auto] # all optional
|
||||
fast = "claude-haiku-4-5"
|
||||
deep = "gpt-5.6-sol" # pins can name another provider's model
|
||||
down_after = 3
|
||||
fable = false # same as /fable on|off
|
||||
```
|
||||
|
||||
## Subagents
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "0.1.4",
|
||||
"sha256": {
|
||||
"aarch64-apple-darwin": "58694e7424080ba5735835ad23be90229daf884b8575c722c985802744e11b79",
|
||||
"x86_64-unknown-linux-musl": "ac27b39c24b7d7f59e2649a118c854a5ed973175b52e260616a123eb2e8ff7df"
|
||||
}
|
||||
}
|
||||
@@ -39,14 +39,40 @@ pub fn fallback(k: Kind) -> Vec<ModelInfo> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Version of a model id: its numbers in order, a date snapshot (8+ digits) after the rest, so
|
||||
/// `claude-opus-5-5` > `claude-opus-4-1-20250805` and `gpt-5.6-sol` > `gpt-5.5-sol`.
|
||||
fn version(id: &str) -> Vec<u64> {
|
||||
let n: Vec<u64> = id
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.filter_map(|p| p.parse().ok())
|
||||
.collect();
|
||||
let (dates, mut v): (Vec<u64>, Vec<u64>) = n.into_iter().partition(|n| *n >= 10_000_000);
|
||||
v.extend(dates);
|
||||
v
|
||||
}
|
||||
|
||||
/// Stable models rank above previews, then by version.
|
||||
fn key(m: &ModelInfo) -> (bool, Vec<u64>) {
|
||||
(!m.id.contains("preview"), version(&m.id))
|
||||
}
|
||||
|
||||
/// The highest-versioned model of `ms` (the first listed on a tie), whatever order the API lists them in.
|
||||
pub fn newest<'a>(ms: impl IntoIterator<Item = &'a ModelInfo>) -> Option<&'a ModelInfo> {
|
||||
ms.into_iter()
|
||||
.fold(None, |b: Option<&ModelInfo>, m| match b {
|
||||
Some(b) if key(b) >= key(m) => Some(b),
|
||||
_ => Some(m),
|
||||
})
|
||||
}
|
||||
|
||||
/// Default model for a provider: Sonnet for Claude, the provider's first-listed model otherwise.
|
||||
pub fn default_for(k: Kind, models: &[ModelInfo]) -> String {
|
||||
let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect();
|
||||
let pick = match k {
|
||||
Kind::Claude => mine.iter().find(|m| m.id.contains("sonnet")),
|
||||
Kind::Claude => newest(mine.iter().copied().filter(|m| m.id.contains("sonnet"))),
|
||||
Kind::Codex | Kind::Custom => None,
|
||||
};
|
||||
pick.or(mine.first())
|
||||
pick.or(mine.first().copied())
|
||||
.map(|m| m.id.clone())
|
||||
.or_else(|| fallback(k).first().map(|m| m.id.clone()))
|
||||
.unwrap_or_default()
|
||||
@@ -59,10 +85,7 @@ pub fn cheap_for(k: Kind, models: &[ModelInfo]) -> Option<String> {
|
||||
Kind::Codex => "luna",
|
||||
Kind::Custom => return None,
|
||||
};
|
||||
models
|
||||
.iter()
|
||||
.find(|m| m.kind == k && m.id.contains(tag))
|
||||
.map(|m| m.id.clone())
|
||||
newest(models.iter().filter(|m| m.kind == k && m.id.contains(tag))).map(|m| m.id.clone())
|
||||
}
|
||||
|
||||
/// Context window for `id`: exact match, then dated-snapshot prefix match, then a family guess.
|
||||
|
||||
@@ -15,7 +15,12 @@ mod rpc;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "hx", version, about = "Minimal coding agent")]
|
||||
#[command(
|
||||
name = "hx",
|
||||
// CI sets HX_VERSION to the release version; local builds use Cargo's
|
||||
version = option_env!("HX_VERSION").unwrap_or(env!("CARGO_PKG_VERSION")),
|
||||
about = "Minimal coding agent"
|
||||
)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
cmd: Option<Cmd>,
|
||||
@@ -574,6 +579,7 @@ async fn main() -> Result<()> {
|
||||
hx_core::stats::model_report(&Session::open(&session)?)
|
||||
);
|
||||
print!("{}", hx_core::stats::task_report(&Session::open(&session)?));
|
||||
print!("{}", hx_core::stats::route_report(&session));
|
||||
print!("{}", hx_core::stats::sub_report(&session));
|
||||
return Ok(());
|
||||
}
|
||||
@@ -825,6 +831,7 @@ async fn main() -> Result<()> {
|
||||
_ => kind,
|
||||
};
|
||||
// the remembered model applies only to the provider it was chosen on
|
||||
let last_fable = last.as_ref().and_then(|l| l.fable);
|
||||
let last = last.filter(|l| l.provider == kind);
|
||||
let last_effort = last.as_ref().and_then(|l| l.effort);
|
||||
// auto mode: `--model auto` / `model = "auto"`, else whatever was on last time
|
||||
@@ -884,8 +891,10 @@ async fn main() -> Result<()> {
|
||||
model: model.clone(),
|
||||
effort: Some(effort),
|
||||
auto: want_auto,
|
||||
fable: last_fable,
|
||||
};
|
||||
let auto_cfg = cfg.auto.clone().unwrap_or_default();
|
||||
let mut auto_cfg = cfg.auto.clone().unwrap_or_default();
|
||||
auto_cfg.fable = last_fable.or(auto_cfg.fable);
|
||||
if hx_core::herdr::init() {
|
||||
hx_core::herdr::set_session(&path);
|
||||
agent.bus.add(hx_core::herdr::Hook);
|
||||
@@ -1112,6 +1121,26 @@ async fn main() -> Result<()> {
|
||||
}) as _)
|
||||
})
|
||||
},
|
||||
reload: {
|
||||
let (mcp, cwd, models, kinds) =
|
||||
(mcp.clone(), cwd.clone(), models.clone(), kinds.clone());
|
||||
Box::new(move || {
|
||||
let cfg = Config::load(&cwd).map_err(|e| e.to_string())?;
|
||||
let mut sys = format!(
|
||||
"{}{}",
|
||||
cfg.system_prompt
|
||||
.as_deref()
|
||||
.unwrap_or(context::DEFAULT_PROMPT),
|
||||
context::prompt_tail(&context::hx_home(), &cwd)
|
||||
);
|
||||
let idx = mcp.system_prompt();
|
||||
if !idx.is_empty() {
|
||||
sys.push_str("\n\n");
|
||||
sys.push_str(&idx);
|
||||
}
|
||||
Ok((sys, command_specs(&mcp, &cwd, &models, &kinds)))
|
||||
})
|
||||
},
|
||||
lsp_status: {
|
||||
let (m, l) = (mgr.clone(), lens_ref.clone());
|
||||
Box::new(move || {
|
||||
|
||||
@@ -243,6 +243,10 @@ impl Agent {
|
||||
self.effort = e;
|
||||
}
|
||||
|
||||
pub fn system(&self) -> &str {
|
||||
&self.system
|
||||
}
|
||||
|
||||
pub fn set_system(&mut self, system: impl Into<String>) {
|
||||
self.system = system.into();
|
||||
self.publish();
|
||||
|
||||
@@ -78,7 +78,12 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
||||
}
|
||||
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
||||
// hx tools run by `codemode` inside mcp-serve ask for their own permission
|
||||
let ok = if let Some(q) = v.get("permit") {
|
||||
let mut input = None;
|
||||
let ok = if v["tool_name"] == "AskUserQuestion" {
|
||||
// claude's own question tool: show hx's popup, hand the answers back as input
|
||||
input = ask(&cx, &v["input"]).await;
|
||||
input.is_some()
|
||||
} else if let Some(q) = v.get("permit") {
|
||||
let s = |k: &str| q[k].as_str().unwrap_or_default().to_string();
|
||||
gate(
|
||||
&cx,
|
||||
@@ -96,13 +101,40 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
||||
}
|
||||
};
|
||||
let _ = w
|
||||
.write_all(format!("{}\n", json!({"allow": ok})).as_bytes())
|
||||
.write_all(format!("{}\n", json!({"allow": ok, "input": input})).as_bytes())
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn roundtrip(path: &Path, msg: Value) -> bool {
|
||||
/// Run each `AskUserQuestion` question through the popup; `input` plus `answers` (question -> label(s)).
|
||||
/// None = no frontend or dismissed.
|
||||
async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
|
||||
let mut answers = serde_json::Map::new();
|
||||
for q in input["questions"].as_array()? {
|
||||
let text = q["question"].as_str().unwrap_or_default();
|
||||
let options = q["options"].as_array().into_iter().flatten().map(|o| {
|
||||
let s = |k| o[k].as_str().unwrap_or_default().to_string();
|
||||
(s("label"), s("description"))
|
||||
});
|
||||
let r = cx
|
||||
.state
|
||||
.choose(crate::Question {
|
||||
text: text.into(),
|
||||
options: options.collect(),
|
||||
multi: q["multiSelect"].as_bool().unwrap_or(false),
|
||||
other: true,
|
||||
})
|
||||
.await
|
||||
.ok()??;
|
||||
answers.insert(text.into(), r.join(", ").into());
|
||||
}
|
||||
let mut out = input.clone();
|
||||
out["answers"] = answers.into();
|
||||
Some(out)
|
||||
}
|
||||
|
||||
async fn roundtrip(path: &Path, msg: Value) -> Option<Value> {
|
||||
let ask = async {
|
||||
let mut c = UnixStream::connect(path).await?;
|
||||
c.write_all(format!("{msg}\n").as_bytes()).await?;
|
||||
@@ -113,7 +145,7 @@ async fn roundtrip(path: &Path, msg: Value) -> bool {
|
||||
ask.await
|
||||
.ok()
|
||||
.and_then(|l| serde_json::from_str::<Value>(&l).ok())
|
||||
.is_some_and(|v| v["allow"] == true)
|
||||
.filter(|v| v["allow"] == true)
|
||||
}
|
||||
|
||||
/// Permission hook for tools that run in another process (`hx mcp-serve`): ask the owner of the socket.
|
||||
@@ -125,7 +157,7 @@ pub fn remote_permit(path: PathBuf) -> crate::permit::Permit {
|
||||
Box::pin(async move {
|
||||
let m = json!({"permit": {"tool": r.tool, "detail": r.detail, "rule": r.rule}});
|
||||
// the owner stores "always" itself; here a yes is a plain yes
|
||||
if roundtrip(&path, m).await {
|
||||
if roundtrip(&path, m).await.is_some() {
|
||||
Decision::Once
|
||||
} else {
|
||||
Decision::Deny
|
||||
@@ -149,9 +181,10 @@ impl Tool for Approve {
|
||||
}
|
||||
}
|
||||
async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult {
|
||||
let ok = roundtrip(&self.0, args.clone()).await;
|
||||
ToolResult::ok(if ok {
|
||||
json!({"behavior": "allow", "updatedInput": args["input"]})
|
||||
let r = roundtrip(&self.0, args.clone()).await;
|
||||
ToolResult::ok(if let Some(r) = r {
|
||||
let input = if r["input"].is_null() { &args["input"] } else { &r["input"] };
|
||||
json!({"behavior": "allow", "updatedInput": input})
|
||||
} else {
|
||||
json!({"behavior": "deny", "message": "denied by the user; do not retry, ask what to do instead"})
|
||||
}
|
||||
@@ -179,6 +212,20 @@ mod tests {
|
||||
assert_eq!(question("Foo", &json!({})).unwrap().rule, "claude:Foo");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ask_user_question_uses_popup() {
|
||||
let cx = ToolCtx {
|
||||
cwd: ".".into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let inp = json!({"questions": [{"question": "Which?", "options": [{"label": "A"}, {"label": "B"}]}]});
|
||||
assert!(ask(&cx, &inp).await.is_none(), "no frontend = deny");
|
||||
let _ = cx.state.choose.set(std::sync::Arc::new(|q| {
|
||||
Box::pin(async move { Some(vec![q.options[1].0.clone()]) })
|
||||
}));
|
||||
assert_eq!(ask(&cx, &inp).await.unwrap()["answers"]["Which?"], "B");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn socket_round_trip_allows_and_denies() {
|
||||
use crate::permit::Decision;
|
||||
|
||||
@@ -58,6 +58,11 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
b(
|
||||
"fable",
|
||||
"let auto mode escalate to Fable (costly)",
|
||||
Enum(vec!["on".into(), "off".into()]),
|
||||
),
|
||||
b(
|
||||
"provider",
|
||||
"switch provider",
|
||||
@@ -98,6 +103,11 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
||||
),
|
||||
b("btw", "side question; no tools, not saved", Free),
|
||||
b("skills", "list skills and where they load from", None),
|
||||
b(
|
||||
"reload",
|
||||
"re-read AGENTS.md, skills, config, MCP prompt index",
|
||||
None,
|
||||
),
|
||||
b(
|
||||
"resume",
|
||||
"resume a session file; no arg opens /sessions",
|
||||
|
||||
@@ -97,6 +97,34 @@ struct Front {
|
||||
argument_hint: Option<String>,
|
||||
}
|
||||
|
||||
/// Fallback for frontmatter that is not valid YAML: `key: value` on one line, value taken verbatim
|
||||
/// (surrounding quotes stripped). None when no known key is found.
|
||||
fn lenient_front(fm: &str) -> Option<Front> {
|
||||
let mut f = Front::default();
|
||||
let mut found = false;
|
||||
for line in fm.lines() {
|
||||
let Some((k, v)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let v = v.trim();
|
||||
let v = v
|
||||
.strip_prefix('"')
|
||||
.and_then(|x| x.strip_suffix('"'))
|
||||
.unwrap_or(v)
|
||||
.to_string();
|
||||
match k {
|
||||
"name" => f.name = Some(v),
|
||||
"description" => f.description = Some(v),
|
||||
"load" => f.load = Some(v),
|
||||
"disable-model-invocation" => f.disable_model_invocation = Some(v == "true"),
|
||||
"argument-hint" => f.argument_hint = Some(v),
|
||||
_ => continue,
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
found.then_some(f)
|
||||
}
|
||||
|
||||
/// Skill dirs, lowest priority first: `~/.claude/skills`, `~/.agents/skills` (shared with other agents),
|
||||
/// `<hx home>/skills`, `<project>/.agents/skills`, `<project>/.claude/skills`, `<project>/.hx/skills`.
|
||||
pub fn skill_dirs(home: &Path, cwd: &Path) -> Vec<PathBuf> {
|
||||
@@ -133,7 +161,11 @@ pub fn parse_skill(p: &Path, s: &str) -> Result<Skill, String> {
|
||||
let f: Front = if fm.trim().is_empty() {
|
||||
Front::default()
|
||||
} else {
|
||||
serde_norway::from_str(fm).map_err(|e| e.to_string())?
|
||||
match serde_norway::from_str(fm) {
|
||||
Ok(f) => f,
|
||||
// strict YAML failed (e.g. unquoted `: ` in a description): read single-line top-level keys
|
||||
Err(e) => lenient_front(fm).ok_or_else(|| e.to_string())?,
|
||||
}
|
||||
};
|
||||
let load = match f.load.as_deref() {
|
||||
Some("always") => Load::Always,
|
||||
@@ -307,7 +339,7 @@ mod tests {
|
||||
assert!(!k.model_invocable && k.load == Load::Auto);
|
||||
let k = parse_skill(p, "---\nname: n\ndescription: |\n a\n b\n---\n").unwrap();
|
||||
assert_eq!(k.description, "a b");
|
||||
assert!(parse_skill(p, "---\ndescription: [oops\n---\nB").is_err());
|
||||
assert!(parse_skill(p, "---\noops: [oops\n---\nB").is_err());
|
||||
let k = parse_skill(p, "no frontmatter").unwrap();
|
||||
assert_eq!((k.name.as_str(), k.body.as_str()), ("n", "no frontmatter"));
|
||||
assert!(
|
||||
@@ -329,7 +361,8 @@ load: manual
|
||||
for (n, fm) in [
|
||||
("ok", "description: fine"),
|
||||
("hid", "description: secret\ndisable-model-invocation: true"),
|
||||
("bad", "description: [oops"),
|
||||
("bad", "oops: [oops"),
|
||||
("colon", "description: before code exists: when asked"),
|
||||
] {
|
||||
let d = t.path().join("s").join(n);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
@@ -337,7 +370,8 @@ load: manual
|
||||
}
|
||||
let (sk, warn) = scan_skills(&[t.path().join("s")]);
|
||||
let names: Vec<_> = sk.iter().map(|k| k.name.as_str()).collect();
|
||||
assert_eq!(names, ["hid", "ok"]);
|
||||
assert_eq!(names, ["colon", "hid", "ok"]);
|
||||
assert_eq!(sk[0].description, "before code exists: when asked");
|
||||
assert!(
|
||||
warn.len() == 1 && warn[0].contains("bad/SKILL.md"),
|
||||
"{warn:?}"
|
||||
|
||||
+204
-26
@@ -15,6 +15,8 @@ pub enum Tier {
|
||||
Fast,
|
||||
Balanced,
|
||||
Deep,
|
||||
/// Fable: only with `[auto] fable` / `/fable on`, for repeated failures and the hardest prompts.
|
||||
Max,
|
||||
}
|
||||
|
||||
impl Tier {
|
||||
@@ -23,6 +25,7 @@ impl Tier {
|
||||
Tier::Fast => "fast",
|
||||
Tier::Balanced => "balanced",
|
||||
Tier::Deep => "deep",
|
||||
Tier::Max => "max",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,17 +38,20 @@ impl Tier {
|
||||
Some(Tier::Balanced)
|
||||
} else if has(&["opus", "sol"]) {
|
||||
Some(Tier::Deep)
|
||||
} else if has(&["fable"]) {
|
||||
Some(Tier::Max)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Tiers to try for a provider lacking this one: the closest first.
|
||||
fn nearest(self) -> [Tier; 3] {
|
||||
fn nearest(self) -> &'static [Tier] {
|
||||
match self {
|
||||
Tier::Fast => [Tier::Fast, Tier::Balanced, Tier::Deep],
|
||||
Tier::Balanced => [Tier::Balanced, Tier::Deep, Tier::Fast],
|
||||
Tier::Deep => [Tier::Deep, Tier::Balanced, Tier::Fast],
|
||||
Tier::Fast => &[Tier::Fast, Tier::Balanced, Tier::Deep],
|
||||
Tier::Balanced => &[Tier::Balanced, Tier::Deep, Tier::Fast],
|
||||
Tier::Deep => &[Tier::Deep, Tier::Balanced, Tier::Fast],
|
||||
Tier::Max => &[Tier::Max, Tier::Deep, Tier::Balanced, Tier::Fast],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,6 +65,9 @@ pub struct Cfg {
|
||||
pub deep: Option<String>,
|
||||
/// Light prompts in a row before dropping to a cheaper tier (default 3). Stepping up is immediate.
|
||||
pub down_after: Option<u32>,
|
||||
/// Let auto mode escalate to Fable (repeated failures, very hard prompts). Off by default;
|
||||
/// `/fable on|off` overrides it.
|
||||
pub fable: Option<bool>,
|
||||
}
|
||||
|
||||
impl Cfg {
|
||||
@@ -67,6 +76,7 @@ impl Cfg {
|
||||
Tier::Fast => &self.fast,
|
||||
Tier::Balanced => &self.balanced,
|
||||
Tier::Deep => &self.deep,
|
||||
Tier::Max => &None,
|
||||
}
|
||||
.as_deref()
|
||||
}
|
||||
@@ -80,6 +90,10 @@ pub struct Signals {
|
||||
/// Too short and plain ("continue", "ja") to say anything: keep the current tier.
|
||||
pub keep: bool,
|
||||
pub hits: Vec<String>,
|
||||
/// Hard enough for Fable when that is on: score 7+ or two failed turns in a row.
|
||||
pub max: bool,
|
||||
/// Estimated tokens of history (a tier switch re-reads them uncached).
|
||||
pub ctx: usize,
|
||||
}
|
||||
|
||||
const DEEP: &[&str] = &[
|
||||
@@ -99,11 +113,9 @@ const DEEP: &[&str] = &[
|
||||
"rewrite",
|
||||
"from scratch",
|
||||
"entwirf",
|
||||
"design",
|
||||
"implement",
|
||||
"debug",
|
||||
"plan",
|
||||
];
|
||||
/// Common words: worth one point, never a whole tier on their own. Matched as word starts.
|
||||
const WEAK: &[&str] = &["design", "implement", "debug", "plan"];
|
||||
const LIGHT: &[&str] = &[
|
||||
"typo",
|
||||
"rename",
|
||||
@@ -149,6 +161,13 @@ pub fn signals(prompt: &str, history: &[Message]) -> Signals {
|
||||
score += 2 * deep.len().min(2) as i32;
|
||||
hits.push(deep.join(","));
|
||||
}
|
||||
let weak = p
|
||||
.split(|c: char| !c.is_alphanumeric())
|
||||
.find(|w| WEAK.iter().any(|k| w.starts_with(k)));
|
||||
if let Some(w) = weak {
|
||||
score += 1;
|
||||
hits.push(w.to_string());
|
||||
}
|
||||
let light: Vec<&str> = LIGHT.iter().copied().filter(|k| p.contains(k)).collect();
|
||||
if !light.is_empty() {
|
||||
score -= 2;
|
||||
@@ -158,19 +177,42 @@ pub fn signals(prompt: &str, history: &[Message]) -> Signals {
|
||||
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());
|
||||
// consecutive turns (tool-result messages) that failed, newest first
|
||||
let streak = history
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|m| {
|
||||
m.content
|
||||
.iter()
|
||||
.any(|b| matches!(b, ContentBlock::ToolResult { .. }))
|
||||
})
|
||||
.map(|m| {
|
||||
m.content
|
||||
.iter()
|
||||
.any(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. }))
|
||||
})
|
||||
.take_while(|f| *f)
|
||||
.count();
|
||||
if streak > 0 {
|
||||
score += if streak > 1 { 4 } else { 2 };
|
||||
hits.push(format!("{streak} failed in a row"));
|
||||
}
|
||||
let edits = history
|
||||
.iter()
|
||||
.rev()
|
||||
.take(20)
|
||||
.flat_map(|m| &m.content)
|
||||
.filter(|b| matches!(b, ContentBlock::ToolUse { name, .. } if name == "edit" || name == "write"))
|
||||
.count();
|
||||
if edits >= 4 {
|
||||
score += 1;
|
||||
hits.push(format!("{edits} recent edits"));
|
||||
}
|
||||
if history.len() > 40 {
|
||||
score += 1;
|
||||
hits.push("long session".into());
|
||||
}
|
||||
let ctx = serde_json::to_vec(history).map_or(0, |v| v.len() / 4);
|
||||
let keep = hits.is_empty() && prompt.split_whitespace().count() <= 3;
|
||||
let tier = match score {
|
||||
i32::MIN..=-1 => Tier::Fast,
|
||||
@@ -182,6 +224,8 @@ pub fn signals(prompt: &str, history: &[Message]) -> Signals {
|
||||
tier,
|
||||
keep,
|
||||
hits,
|
||||
max: score >= 7 || streak >= 2,
|
||||
ctx,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,8 +251,10 @@ pub fn model_for(k: Kind, t: Tier, models: &[ModelInfo], cfg: &Cfg) -> Option<St
|
||||
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())
|
||||
.find_map(|t| {
|
||||
hx_ai::models::newest(mine.iter().copied().filter(|m| Tier::of(&m.id) == Some(*t)))
|
||||
})
|
||||
.or(mine.first().copied())
|
||||
.map(|m| m.id.clone())
|
||||
}
|
||||
|
||||
@@ -297,28 +343,44 @@ impl Router {
|
||||
avoid: Option<Kind>,
|
||||
models: &[ModelInfo],
|
||||
) -> Option<Pick> {
|
||||
let n = self.cfg.down_after.unwrap_or(3);
|
||||
// a switch re-reads the history uncached: the bigger it is, the longer a tier is held;
|
||||
// Fable is dropped at once, it costs the most
|
||||
let n = self
|
||||
.cfg
|
||||
.down_after
|
||||
.unwrap_or(if sig.ctx > 100_000 { 5 } else { 3 });
|
||||
let want = if sig.max && self.cfg.fable == Some(true) {
|
||||
Tier::Max
|
||||
} else {
|
||||
sig.tier
|
||||
};
|
||||
let tier = match self.cur {
|
||||
Some((_, c)) if sig.keep => c,
|
||||
Some((_, c)) if sig.tier < c => {
|
||||
Some((_, c)) if want < c => {
|
||||
self.down += 1;
|
||||
if self.down >= n {
|
||||
if self.down >= if c == Tier::Max { 1 } else { n } {
|
||||
self.down = 0;
|
||||
sig.tier
|
||||
want
|
||||
} else {
|
||||
c
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.down = 0;
|
||||
sig.tier
|
||||
want
|
||||
}
|
||||
};
|
||||
let prefer = self.cur.map_or(start, |(k, _)| k);
|
||||
let (kind, model) = pick_for(tier, prefer, avoid, models, &self.cfg)?;
|
||||
// no Fable in the catalog: it ran as Deep
|
||||
let tier = if tier == Tier::Max && Tier::of(&model) != Some(Tier::Max) {
|
||||
Tier::Deep
|
||||
} else {
|
||||
tier
|
||||
};
|
||||
self.cur = Some((kind, tier));
|
||||
let held = if tier != sig.tier && !sig.keep {
|
||||
format!(", holding (wanted {})", sig.tier.name())
|
||||
let held = if tier != want && !sig.keep {
|
||||
format!(", holding (wanted {})", want.name())
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
@@ -337,6 +399,29 @@ impl Router {
|
||||
}
|
||||
}
|
||||
|
||||
/// One line per routed prompt in `<session>.route` (JSON), read back by `hx stats`: the data to
|
||||
/// tune the keyword lists and thresholds from. Best effort.
|
||||
pub fn log(session: &std::path::Path, sig: &Signals, p: &Pick, effort: Effort, forced: bool) {
|
||||
use std::io::Write;
|
||||
let line = serde_json::json!({
|
||||
"ts": hx_ai::auth::now_ms() / 1000,
|
||||
"model": p.model,
|
||||
"tier": p.tier.name(),
|
||||
"wanted": sig.tier.name(),
|
||||
"score": sig.score,
|
||||
"effort": effort.name(),
|
||||
"ctx": sig.ctx,
|
||||
"hits": sig.hits,
|
||||
"forced": forced,
|
||||
});
|
||||
// ponytail: a failed log write must not fail the prompt
|
||||
let _ = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(session.with_extension("route"))
|
||||
.and_then(|mut f| writeln!(f, "{line}"));
|
||||
}
|
||||
|
||||
/// What `@word` at the start of a prompt asks for.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Target {
|
||||
@@ -363,6 +448,7 @@ pub fn parse_override(
|
||||
"fast" => Target::Tier(Tier::Fast),
|
||||
"balanced" => Target::Tier(Tier::Balanced),
|
||||
"deep" => Target::Tier(Tier::Deep),
|
||||
"max" => Target::Tier(Tier::Max),
|
||||
_ => {
|
||||
if let Some(m) = models.iter().find(|m| m.id.to_lowercase() == lw) {
|
||||
Target::Model(m.id.clone())
|
||||
@@ -454,7 +540,99 @@ mod tests {
|
||||
}];
|
||||
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"));
|
||||
assert!(s.hits.iter().any(|h| h == "1 failed in a row"));
|
||||
}
|
||||
|
||||
fn fail() -> Message {
|
||||
Message {
|
||||
role: hx_ai::Role::User,
|
||||
content: vec![ContentBlock::ToolResult {
|
||||
tool_use_id: "t".into(),
|
||||
content: "boom".into(),
|
||||
is_error: true,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weak_words_alone_stay_balanced() {
|
||||
assert_eq!(tier("implement the --foo flag"), Tier::Balanced);
|
||||
assert_eq!(tier("plan the release notes"), Tier::Balanced);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fable_only_when_on_and_escalates_on_repeated_failure() {
|
||||
let mut models = cat();
|
||||
models.push(m("claude-fable-5-1", Kind::Claude));
|
||||
let h = vec![fail(), fail()];
|
||||
let s = signals("try again", &h);
|
||||
assert!(s.max && !signals("try again", &h[..1]).max);
|
||||
let mut off = Router::new(Cfg::default());
|
||||
let p = off.route(&s, Kind::Claude, None, &models).unwrap();
|
||||
assert_eq!(p.model, "claude-opus-5-5");
|
||||
let on = Cfg {
|
||||
fable: Some(true),
|
||||
..Default::default()
|
||||
};
|
||||
let mut r = Router::new(on.clone());
|
||||
let p = r.route(&s, Kind::Claude, None, &models).unwrap();
|
||||
assert_eq!((p.tier, p.model.as_str()), (Tier::Max, "claude-fable-5-1"));
|
||||
// one light prompt drops Fable at once
|
||||
let light = signals("fix the typo in README", &[]);
|
||||
assert_ne!(
|
||||
r.route(&light, Kind::Claude, None, &models).unwrap().tier,
|
||||
Tier::Max
|
||||
);
|
||||
// on, but no Fable in the catalog: Deep
|
||||
let mut r = Router::new(on);
|
||||
let p = r.route(&s, Kind::Claude, None, &cat()).unwrap();
|
||||
assert_eq!((p.tier, p.model.as_str()), (Tier::Deep, "claude-opus-5-5"));
|
||||
assert_eq!(
|
||||
parse_override("@max go", &cat(), &|_| false).unwrap().0,
|
||||
Target::Tier(Tier::Max)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newest_version_wins_whatever_the_list_order() {
|
||||
let ms = vec![
|
||||
m("claude-opus-4-1-20250805", Kind::Claude),
|
||||
m("claude-opus-5-5", Kind::Claude),
|
||||
m("claude-opus-4-5", Kind::Claude),
|
||||
m("claude-sonnet-5-5", Kind::Claude),
|
||||
m("claude-sonnet-5-6-preview", Kind::Claude),
|
||||
];
|
||||
let c = Cfg::default();
|
||||
assert_eq!(
|
||||
model_for(Kind::Claude, Tier::Deep, &ms, &c).unwrap(),
|
||||
"claude-opus-5-5"
|
||||
);
|
||||
assert_eq!(
|
||||
hx_ai::models::default_for(Kind::Claude, &ms),
|
||||
"claude-sonnet-5-5"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_context_holds_the_tier_longer() {
|
||||
let mut r = Router::new(Cfg::default());
|
||||
let hard = signals(
|
||||
"refactor the auth module and remove the race condition",
|
||||
&[],
|
||||
);
|
||||
r.route(&hard, Kind::Codex, None, &cat()).unwrap();
|
||||
let mut light = signals("fix the typo in README", &[]);
|
||||
light.ctx = 200_000;
|
||||
for _ in 0..4 {
|
||||
assert_eq!(
|
||||
r.route(&light, Kind::Codex, None, &cat()).unwrap().tier,
|
||||
Tier::Deep
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
r.route(&light, Kind::Codex, None, &cat()).unwrap().tier,
|
||||
Tier::Fast
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -47,6 +47,59 @@ pub fn task_report(s: &Session) -> String {
|
||||
}
|
||||
|
||||
/// One line per subagent log in `<session>.sub/` (empty when there are none).
|
||||
/// Auto-mode choices from `<session>.route`: turns per tier, how often the tier was held back
|
||||
/// or forced, and how often the next prompt had to go up again (a pick that was too low).
|
||||
pub fn route_report(session_path: &std::path::Path) -> String {
|
||||
let Ok(t) = std::fs::read_to_string(session_path.with_extension("route")) else {
|
||||
return String::new();
|
||||
};
|
||||
let rows: Vec<serde_json::Value> = t
|
||||
.lines()
|
||||
.filter_map(|l| serde_json::from_str(l).ok())
|
||||
.collect();
|
||||
if rows.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let rank = |s: &str| {
|
||||
["fast", "balanced", "deep", "max"]
|
||||
.iter()
|
||||
.position(|x| *x == s)
|
||||
};
|
||||
let s = |r: &serde_json::Value, k: &str| r[k].as_str().unwrap_or("?").to_string();
|
||||
let (mut per, mut held, mut forced, mut up) = (HashMap::<String, (u32, i64)>::new(), 0, 0, 0);
|
||||
for (i, r) in rows.iter().enumerate() {
|
||||
if r["forced"].as_bool() == Some(true) {
|
||||
forced += 1;
|
||||
continue;
|
||||
}
|
||||
let e = per.entry(s(r, "tier")).or_default();
|
||||
e.0 += 1;
|
||||
e.1 += r["score"].as_i64().unwrap_or(0);
|
||||
held += (s(r, "tier") != s(r, "wanted")) as u32;
|
||||
if let Some(n) = rows.get(i + 1)
|
||||
&& n["forced"].as_bool() != Some(true)
|
||||
&& rank(&s(n, "tier")) > rank(&s(r, "tier"))
|
||||
{
|
||||
up += 1;
|
||||
}
|
||||
}
|
||||
let mut o = String::from("auto routing:\n");
|
||||
for t in ["fast", "balanced", "deep", "max"] {
|
||||
if let Some((n, sum)) = per.get(t) {
|
||||
let _ = writeln!(
|
||||
o,
|
||||
" {t}: {n} prompts, mean score {:.1}",
|
||||
*sum as f64 / *n as f64
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = writeln!(
|
||||
o,
|
||||
" held back by hysteresis: {held}, next prompt went up a tier: {up}, forced with @: {forced}"
|
||||
);
|
||||
o
|
||||
}
|
||||
|
||||
pub fn sub_report(session_path: &std::path::Path) -> String {
|
||||
let mut files: Vec<_> = std::fs::read_dir(session_path.with_extension("sub"))
|
||||
.into_iter()
|
||||
|
||||
@@ -35,6 +35,9 @@ pub struct Last {
|
||||
/// `/model auto` was on.
|
||||
#[serde(default)]
|
||||
pub auto: bool,
|
||||
/// `/fable on|off`; overrides `[auto] fable` in the config.
|
||||
#[serde(default)]
|
||||
pub fable: Option<bool>,
|
||||
}
|
||||
|
||||
impl Last {
|
||||
@@ -100,6 +103,19 @@ impl Switcher {
|
||||
self
|
||||
}
|
||||
|
||||
/// Allow (or forbid) Fable in auto mode; saved for the next start.
|
||||
pub fn set_fable(&mut self, on: bool) {
|
||||
self.auto_cfg.fable = Some(on);
|
||||
if let Some(r) = &mut self.router {
|
||||
r.cfg.fable = Some(on);
|
||||
}
|
||||
self.save(|l| l.fable = Some(on));
|
||||
}
|
||||
|
||||
pub fn fable(&self) -> bool {
|
||||
self.auto_cfg.fable == Some(true)
|
||||
}
|
||||
|
||||
pub fn is_auto(&self) -> bool {
|
||||
self.router.is_some()
|
||||
}
|
||||
@@ -234,6 +250,13 @@ impl Switcher {
|
||||
self.apply_inner(agent, pick.kind, pick.model.clone(), false, false)?
|
||||
};
|
||||
agent.set_effort(effort);
|
||||
route::log(
|
||||
agent.session().path(),
|
||||
&sig,
|
||||
&pick,
|
||||
effort,
|
||||
forced.is_some(),
|
||||
);
|
||||
Ok(Some(Routed {
|
||||
pick: route::Pick { effort, ..pick },
|
||||
sw,
|
||||
@@ -476,6 +499,7 @@ mod tests {
|
||||
model: "m".into(),
|
||||
effort: None,
|
||||
auto: false,
|
||||
fable: None,
|
||||
};
|
||||
let mut sw = sw.remember_in(f.clone(), start);
|
||||
sw.set_model(&mut a, "gpt-x").unwrap();
|
||||
@@ -485,6 +509,7 @@ mod tests {
|
||||
model: "gpt-x".into(),
|
||||
effort: Some(hx_ai::Effort::High),
|
||||
auto: false,
|
||||
fable: None,
|
||||
};
|
||||
assert_eq!(Last::load(&f), Some(want));
|
||||
std::fs::write(&f, "junk").unwrap();
|
||||
@@ -510,6 +535,8 @@ mod tests {
|
||||
("claude-haiku-x", "claude-haiku-x")
|
||||
);
|
||||
assert!(made.lock().unwrap().is_empty(), "same provider: no rebuild");
|
||||
let rep = crate::stats::route_report(a.session().path());
|
||||
assert!(rep.contains("fast: 1 prompts"), "{rep}");
|
||||
sw.set_model(&mut a, "claude-sonnet-x").unwrap();
|
||||
assert!(!sw.is_auto());
|
||||
assert!(
|
||||
|
||||
@@ -47,6 +47,7 @@ pub struct Setup {
|
||||
pub pricing: fn(&str) -> Option<hx_ai::Pricing>,
|
||||
/// `/lsp` status lines.
|
||||
pub lsp_status: LspStatus,
|
||||
pub reload: Reload,
|
||||
/// Extra slash commands (MCP prompts, `/mcp`): `(name, arg)` -> None = not mine,
|
||||
/// Some(Ok(Send(text))) = send as a user prompt, Some(Ok(Show(text))) = show, Some(Err) = error.
|
||||
pub commands: Commands,
|
||||
@@ -88,6 +89,9 @@ pub type Commands = Box<
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
/// Rebuilds `(system prompt, slash commands)` from disk for `/reload`.
|
||||
pub type Reload = Box<dyn Fn() -> Result<(String, Vec<CmdSpec>), String> + Send + Sync>;
|
||||
|
||||
pub type LspStatus = Box<
|
||||
dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<String>> + Send>> + Send,
|
||||
>;
|
||||
@@ -259,6 +263,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
switcher,
|
||||
pricing,
|
||||
lsp_status,
|
||||
reload,
|
||||
commands,
|
||||
specs,
|
||||
open_sessions,
|
||||
@@ -394,6 +399,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
tx: &tx,
|
||||
cwd: &cwd,
|
||||
lsp_status: &lsp_status,
|
||||
reload: &reload,
|
||||
commands: &commands,
|
||||
};
|
||||
let mut term = ratatui::init();
|
||||
@@ -1290,6 +1296,7 @@ struct Ctx<'a> {
|
||||
tx: &'a mpsc::UnboundedSender<Ui>,
|
||||
cwd: &'a std::path::Path,
|
||||
lsp_status: &'a LspStatus,
|
||||
reload: &'a Reload,
|
||||
commands: &'a Commands,
|
||||
}
|
||||
|
||||
@@ -1299,6 +1306,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
tx,
|
||||
cwd,
|
||||
lsp_status,
|
||||
reload,
|
||||
commands,
|
||||
} = *c;
|
||||
app.scroll.end();
|
||||
@@ -1376,6 +1384,23 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
let r = status::report(&app.st, status::now_secs());
|
||||
show(app, "usage", r);
|
||||
}
|
||||
"reload" => match reload() {
|
||||
Err(e) => app.t.push(Item::Error(format!("/reload: {e}"))),
|
||||
Ok((sys, specs)) => {
|
||||
let mut a = agent.lock().await;
|
||||
// unchanged prompt: leave it alone, a rewrite would drop the prompt cache
|
||||
let same = a.system() == sys;
|
||||
if !same {
|
||||
a.set_system(sys);
|
||||
}
|
||||
let (old, new) = (app.specs.len(), specs.len());
|
||||
app.specs = specs;
|
||||
app.t.push(Item::Info(format!(
|
||||
"reloaded: prompt {}, commands {old} → {new}",
|
||||
if same { "unchanged" } else { "updated" }
|
||||
)));
|
||||
}
|
||||
},
|
||||
"skills" => {
|
||||
let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd);
|
||||
let mut l = skills_list(&app.specs, &dirs);
|
||||
@@ -1482,6 +1507,19 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
"model: auto. Picked per prompt across logged-in providers; `@opus ...`, `@codex ...`, `@fast ...` force one turn.".into(),
|
||||
));
|
||||
}
|
||||
"fable" if arg.is_empty() => app.t.push(Item::Info(format!(
|
||||
"fable in auto mode: {}",
|
||||
if app.sw.fable() { "on" } else { "off" }
|
||||
))),
|
||||
"fable" if arg == "on" || arg == "off" => {
|
||||
app.sw.set_fable(arg == "on");
|
||||
app.t.push(Item::Info(if arg == "on" {
|
||||
"fable on: auto escalates to Fable after 2 failed turns in a row or a very hard prompt ($10/$50 per Mtok). `@fable ...` always works.".into()
|
||||
} else {
|
||||
"fable off".into()
|
||||
}));
|
||||
}
|
||||
"fable" => app.t.push(Item::Error("/fable on|off".into())),
|
||||
"model" => {
|
||||
let mut a = agent.lock().await;
|
||||
match app.sw.set_model(&mut a, arg) {
|
||||
@@ -2775,16 +2813,27 @@ mod tests {
|
||||
let (tx, _rx) = mpsc::unbounded_channel();
|
||||
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
||||
let cmds: Commands = Box::new(|_, _| None);
|
||||
let rl: Reload = Box::new(|| Ok(("sys".into(), cmd::builtins(&[]))));
|
||||
let ctx = Ctx {
|
||||
agent: &agent,
|
||||
tx: &tx,
|
||||
cwd: t.path(),
|
||||
lsp_status: &ls,
|
||||
reload: &rl,
|
||||
commands: &cmds,
|
||||
};
|
||||
let mut app = test_app();
|
||||
app.session_path = old.clone();
|
||||
app.title = Some("first".into());
|
||||
// /reload swaps prompt + commands; same prompt twice is reported unchanged
|
||||
app.specs = vec![];
|
||||
submit(&mut app, "/reload".into(), &ctx).await;
|
||||
assert_eq!(agent.lock().await.system(), "sys");
|
||||
assert!(app.specs.iter().any(|s| s.name == "reload"));
|
||||
submit(&mut app, "/reload".into(), &ctx).await;
|
||||
assert!(
|
||||
matches!(app.t.items.last(), Some(Item::Info(m)) if m.contains("prompt unchanged"))
|
||||
);
|
||||
submit(&mut app, "/clear".into(), &ctx).await;
|
||||
let new = agent.lock().await.session().path().to_path_buf();
|
||||
assert_ne!(new, old);
|
||||
@@ -2825,11 +2874,13 @@ mod tests {
|
||||
models.extend(hx_ai::models::fallback(Kind::Codex));
|
||||
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
||||
let cmds: Commands = Box::new(|_, _| None);
|
||||
let rl: Reload = Box::new(|| Ok(("sys".into(), cmd::builtins(&[]))));
|
||||
let ctx = Ctx {
|
||||
agent: &agent,
|
||||
tx: &tx,
|
||||
cwd: t.path(),
|
||||
lsp_status: &ls,
|
||||
reload: &rl,
|
||||
commands: &cmds,
|
||||
};
|
||||
let mut app = test_app();
|
||||
|
||||
@@ -6,37 +6,64 @@
|
||||
outputs =
|
||||
{ self, nixpkgs }:
|
||||
let
|
||||
systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ];
|
||||
systems = [ "x86_64-linux" "aarch64-linux" "aarch64-darwin" ];
|
||||
forAll = f: nixpkgs.lib.genAttrs systems (s: f nixpkgs.legacyPackages.${s});
|
||||
# release binaries, bin.json is rewritten by the release job in .gitea/workflows/build.yml
|
||||
bin = builtins.fromJSON (builtins.readFile ./bin.json);
|
||||
targets = {
|
||||
x86_64-linux = "x86_64-unknown-linux-musl";
|
||||
aarch64-darwin = "aarch64-apple-darwin";
|
||||
};
|
||||
in
|
||||
{
|
||||
packages = forAll (pkgs: rec {
|
||||
hx = pkgs.rustPlatform.buildRustPackage {
|
||||
pname = "hx";
|
||||
version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).workspace.package.version;
|
||||
src = pkgs.lib.cleanSource ./.;
|
||||
cargoLock.lockFile = ./Cargo.lock;
|
||||
cargoBuildFlags = [ "-p" "hx-cli" ];
|
||||
# ponytail: tests skipped (need git/network); enable when hermetic.
|
||||
doCheck = false;
|
||||
# rustls may build aws-lc-sys (cmake) depending on feature set.
|
||||
nativeBuildInputs = [ pkgs.cmake pkgs.perl ];
|
||||
dontUseCmakeConfigure = true;
|
||||
meta = {
|
||||
description = "Minimal Rust coding agent using existing subscriptions";
|
||||
license = pkgs.lib.licenses.unlicense;
|
||||
mainProgram = "hx";
|
||||
packages = forAll (
|
||||
pkgs:
|
||||
let
|
||||
target = targets.${pkgs.stdenv.hostPlatform.system} or "";
|
||||
hasBin = bin.sha256 ? ${target};
|
||||
|
||||
hx = pkgs.rustPlatform.buildRustPackage {
|
||||
pname = "hx";
|
||||
version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).workspace.package.version;
|
||||
src = pkgs.lib.cleanSource ./.;
|
||||
cargoLock.lockFile = ./Cargo.lock;
|
||||
cargoBuildFlags = [ "-p" "hx-cli" ];
|
||||
# ponytail: tests skipped (need git/network); enable when hermetic.
|
||||
doCheck = false;
|
||||
# rustls may build aws-lc-sys (cmake) depending on feature set.
|
||||
nativeBuildInputs = [ pkgs.cmake pkgs.perl ];
|
||||
dontUseCmakeConfigure = true;
|
||||
meta = {
|
||||
description = "Minimal Rust coding agent using existing subscriptions";
|
||||
license = pkgs.lib.licenses.unlicense;
|
||||
mainProgram = "hx";
|
||||
};
|
||||
};
|
||||
};
|
||||
default = hx;
|
||||
});
|
||||
|
||||
hx-bin = pkgs.runCommand "hx-${bin.version}" { meta.mainProgram = "hx"; } ''
|
||||
mkdir -p $out/bin
|
||||
tar -xzf ${
|
||||
pkgs.fetchurl {
|
||||
url = "https://git.jokresner.de/johannes/hx/releases/download/v${bin.version}/hx-${target}.tar.gz";
|
||||
sha256 = bin.sha256.${target};
|
||||
}
|
||||
} -C $out/bin hx
|
||||
'';
|
||||
in
|
||||
{
|
||||
inherit hx;
|
||||
# prebuilt binary where the release has one, source build elsewhere
|
||||
default = if hasBin then hx-bin else hx;
|
||||
}
|
||||
// pkgs.lib.optionalAttrs hasBin { inherit hx-bin; }
|
||||
);
|
||||
|
||||
apps = forAll (pkgs: rec {
|
||||
hx = { type = "app"; program = "${self.packages.${pkgs.system}.hx}/bin/hx"; };
|
||||
hx = { type = "app"; program = "${self.packages.${pkgs.system}.default}/bin/hx"; };
|
||||
default = hx;
|
||||
});
|
||||
|
||||
overlays.default = _: prev: { hx = self.packages.${prev.system}.hx; };
|
||||
overlays.default = _: prev: { hx = self.packages.${prev.system}.default; };
|
||||
|
||||
devShells = forAll (pkgs: {
|
||||
default = pkgs.mkShell {
|
||||
|
||||
Reference in new issue
Block a user