8 Commits
Author SHA1 Message Date
gitea-actions 63b286efaf ci: bin.json v0.1.5 2026-11-10 22:22:39 +00:00
hermes 6222fcab17 Merge pull request 'auto: optional Fable tier, sharper signals, newest model per tier' (#178) from feat/auto-fable into main
build / version (push) Successful in 56s
build / build (aarch64-apple-darwin) (push) Successful in 6m22s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m16s
build / release (push) Successful in 21s
2026-11-10 22:09:44 +00:00
hermes c6c4add124 stats: log auto routing per prompt, hx stats routing report 2026-11-10 22:08:55 +00:00
hermes 478c007271 auto: optional Fable tier (/fable), sharper signals, newest model per tier 2026-11-10 21:58:11 +00:00
gitea-actions 410385dcfb ci: bin.json v0.1.4 2026-11-05 19:40:41 +00:00
hermes 39a4e0c625 Merge pull request 'claude_cli: AskUserQuestion shows hx popup' (#177) from fix/claude-ask-question into main
build / version (push) Successful in 10s
build / build (aarch64-apple-darwin) (push) Successful in 5m45s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m55s
build / release (push) Successful in 21s
2026-11-05 19:29:30 +00:00
hermes dc0a329ae1 claude_cli: route AskUserQuestion to hx popup, no permission prompt 2026-11-05 19:27:44 +00:00
gitea-actions ca6b917b17 ci: bin.json v0.1.3 2026-11-03 22:47:35 +00:00
10 changed files with 401 additions and 46 deletions

No files matched your search

+7 -2
View File
@@ -84,17 +84,22 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off
## Auto model ## 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). 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 ```toml
[auto] # all optional [auto] # all optional
fast = "claude-haiku-4-5" fast = "claude-haiku-4-5"
deep = "gpt-5.6-sol" # pins can name another provider's model deep = "gpt-5.6-sol" # pins can name another provider's model
down_after = 3 down_after = 3
fable = false # same as /fable on|off
``` ```
## Subagents ## Subagents
+3 -3
View File
@@ -1,7 +1,7 @@
{ {
"version": "0.1.2", "version": "0.1.5",
"sha256": { "sha256": {
"aarch64-apple-darwin": "ae5ffd46d793c437d06f0f695201f5cbb768681b23f130080b4ba7cb1ef3e99c", "aarch64-apple-darwin": "106d0f4156b687a7a5e1ef8cdd9fcf5f00408afdb320f93e885acdd892b353a1",
"x86_64-unknown-linux-musl": "f44cc2a70032c9f458df8a1cf1716bd3e9e43597b4daeb9223de387cf1c8ba0a" "x86_64-unknown-linux-musl": "2a86641064692c52c4455b327856be772ff75f93572bdad5836e2a5124f6c3ba"
} }
} }
+29 -6
View File
@@ -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. /// Default model for a provider: Sonnet for Claude, the provider's first-listed model otherwise.
pub fn default_for(k: Kind, models: &[ModelInfo]) -> String { pub fn default_for(k: Kind, models: &[ModelInfo]) -> String {
let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect(); let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect();
let pick = match k { 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, Kind::Codex | Kind::Custom => None,
}; };
pick.or(mine.first()) pick.or(mine.first().copied())
.map(|m| m.id.clone()) .map(|m| m.id.clone())
.or_else(|| fallback(k).first().map(|m| m.id.clone())) .or_else(|| fallback(k).first().map(|m| m.id.clone()))
.unwrap_or_default() .unwrap_or_default()
@@ -59,10 +85,7 @@ pub fn cheap_for(k: Kind, models: &[ModelInfo]) -> Option<String> {
Kind::Codex => "luna", Kind::Codex => "luna",
Kind::Custom => return None, Kind::Custom => return None,
}; };
models newest(models.iter().filter(|m| m.kind == k && m.id.contains(tag))).map(|m| m.id.clone())
.iter()
.find(|m| m.kind == k && m.id.contains(tag))
.map(|m| m.id.clone())
} }
/// Context window for `id`: exact match, then dated-snapshot prefix match, then a family guess. /// Context window for `id`: exact match, then dated-snapshot prefix match, then a family guess.
+5 -1
View File
@@ -579,6 +579,7 @@ async fn main() -> Result<()> {
hx_core::stats::model_report(&Session::open(&session)?) 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::route_report(&session));
print!("{}", hx_core::stats::sub_report(&session)); print!("{}", hx_core::stats::sub_report(&session));
return Ok(()); return Ok(());
} }
@@ -830,6 +831,7 @@ async fn main() -> Result<()> {
_ => kind, _ => kind,
}; };
// 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_fable = last.as_ref().and_then(|l| l.fable);
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 // auto mode: `--model auto` / `model = "auto"`, else whatever was on last time
@@ -889,8 +891,10 @@ async fn main() -> Result<()> {
model: model.clone(), model: model.clone(),
effort: Some(effort), effort: Some(effort),
auto: want_auto, 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() { 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);
+55 -8
View File
@@ -78,7 +78,12 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
} }
let v: Value = serde_json::from_str(&line).unwrap_or_default(); let v: Value = serde_json::from_str(&line).unwrap_or_default();
// hx tools run by `codemode` inside mcp-serve ask for their own permission // 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(); let s = |k: &str| q[k].as_str().unwrap_or_default().to_string();
gate( gate(
&cx, &cx,
@@ -96,13 +101,40 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
} }
}; };
let _ = w let _ = w
.write_all(format!("{}\n", json!({"allow": ok})).as_bytes()) .write_all(format!("{}\n", json!({"allow": ok, "input": input})).as_bytes())
.await; .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 ask = async {
let mut c = UnixStream::connect(path).await?; let mut c = UnixStream::connect(path).await?;
c.write_all(format!("{msg}\n").as_bytes()).await?; c.write_all(format!("{msg}\n").as_bytes()).await?;
@@ -113,7 +145,7 @@ async fn roundtrip(path: &Path, msg: Value) -> bool {
ask.await ask.await
.ok() .ok()
.and_then(|l| serde_json::from_str::<Value>(&l).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. /// 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 { Box::pin(async move {
let m = json!({"permit": {"tool": r.tool, "detail": r.detail, "rule": r.rule}}); 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 // 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 Decision::Once
} else { } else {
Decision::Deny Decision::Deny
@@ -149,9 +181,10 @@ impl Tool for Approve {
} }
} }
async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult { async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult {
let ok = roundtrip(&self.0, args.clone()).await; let r = roundtrip(&self.0, args.clone()).await;
ToolResult::ok(if ok { ToolResult::ok(if let Some(r) = r {
json!({"behavior": "allow", "updatedInput": args["input"]}) let input = if r["input"].is_null() { &args["input"] } else { &r["input"] };
json!({"behavior": "allow", "updatedInput": input})
} else { } else {
json!({"behavior": "deny", "message": "denied by the user; do not retry, ask what to do instead"}) 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"); 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] #[tokio::test]
async fn socket_round_trip_allows_and_denies() { async fn socket_round_trip_allows_and_denies() {
use crate::permit::Decision; use crate::permit::Decision;
+5
View File
@@ -58,6 +58,11 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
.collect(), .collect(),
), ),
), ),
b(
"fable",
"let auto mode escalate to Fable (costly)",
Enum(vec!["on".into(), "off".into()]),
),
b( b(
"provider", "provider",
"switch provider", "switch provider",
+204 -26
View File
@@ -15,6 +15,8 @@ pub enum Tier {
Fast, Fast,
Balanced, Balanced,
Deep, Deep,
/// Fable: only with `[auto] fable` / `/fable on`, for repeated failures and the hardest prompts.
Max,
} }
impl Tier { impl Tier {
@@ -23,6 +25,7 @@ impl Tier {
Tier::Fast => "fast", Tier::Fast => "fast",
Tier::Balanced => "balanced", Tier::Balanced => "balanced",
Tier::Deep => "deep", Tier::Deep => "deep",
Tier::Max => "max",
} }
} }
@@ -35,17 +38,20 @@ impl Tier {
Some(Tier::Balanced) Some(Tier::Balanced)
} else if has(&["opus", "sol"]) { } else if has(&["opus", "sol"]) {
Some(Tier::Deep) Some(Tier::Deep)
} else if has(&["fable"]) {
Some(Tier::Max)
} else { } else {
None None
} }
} }
/// Tiers to try for a provider lacking this one: the closest first. /// Tiers to try for a provider lacking this one: the closest first.
fn nearest(self) -> [Tier; 3] { fn nearest(self) -> &'static [Tier] {
match self { match self {
Tier::Fast => [Tier::Fast, Tier::Balanced, Tier::Deep], Tier::Fast => &[Tier::Fast, Tier::Balanced, Tier::Deep],
Tier::Balanced => [Tier::Balanced, Tier::Deep, Tier::Fast], Tier::Balanced => &[Tier::Balanced, Tier::Deep, Tier::Fast],
Tier::Deep => [Tier::Deep, Tier::Balanced, 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>, pub deep: Option<String>,
/// Light prompts in a row before dropping to a cheaper tier (default 3). Stepping up is immediate. /// Light prompts in a row before dropping to a cheaper tier (default 3). Stepping up is immediate.
pub down_after: Option<u32>, 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 { impl Cfg {
@@ -67,6 +76,7 @@ impl Cfg {
Tier::Fast => &self.fast, Tier::Fast => &self.fast,
Tier::Balanced => &self.balanced, Tier::Balanced => &self.balanced,
Tier::Deep => &self.deep, Tier::Deep => &self.deep,
Tier::Max => &None,
} }
.as_deref() .as_deref()
} }
@@ -80,6 +90,10 @@ pub struct Signals {
/// Too short and plain ("continue", "ja") to say anything: keep the current tier. /// Too short and plain ("continue", "ja") to say anything: keep the current tier.
pub keep: bool, pub keep: bool,
pub hits: Vec<String>, 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] = &[ const DEEP: &[&str] = &[
@@ -99,11 +113,9 @@ const DEEP: &[&str] = &[
"rewrite", "rewrite",
"from scratch", "from scratch",
"entwirf", "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] = &[ const LIGHT: &[&str] = &[
"typo", "typo",
"rename", "rename",
@@ -149,6 +161,13 @@ pub fn signals(prompt: &str, history: &[Message]) -> Signals {
score += 2 * deep.len().min(2) as i32; score += 2 * deep.len().min(2) as i32;
hits.push(deep.join(",")); 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(); let light: Vec<&str> = LIGHT.iter().copied().filter(|k| p.contains(k)).collect();
if !light.is_empty() { if !light.is_empty() {
score -= 2; score -= 2;
@@ -158,19 +177,42 @@ pub fn signals(prompt: &str, history: &[Message]) -> Signals {
score += 1; score += 1;
hits.push("trace".into()); hits.push("trace".into());
} }
let failed = history.iter().rev().take(2).any(|m| { // consecutive turns (tool-result messages) that failed, newest first
m.content let streak = history
.iter() .iter()
.any(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. })) .rev()
}); .filter(|m| {
if failed { m.content
score += 2; .iter()
hits.push("last turn failed".into()); .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 { if history.len() > 40 {
score += 1; score += 1;
hits.push("long session".into()); 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 keep = hits.is_empty() && prompt.split_whitespace().count() <= 3;
let tier = match score { let tier = match score {
i32::MIN..=-1 => Tier::Fast, i32::MIN..=-1 => Tier::Fast,
@@ -182,6 +224,8 @@ pub fn signals(prompt: &str, history: &[Message]) -> Signals {
tier, tier,
keep, keep,
hits, 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(); let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect();
t.nearest() t.nearest()
.iter() .iter()
.find_map(|t| mine.iter().find(|m| Tier::of(&m.id) == Some(*t))) .find_map(|t| {
.or(mine.first()) hx_ai::models::newest(mine.iter().copied().filter(|m| Tier::of(&m.id) == Some(*t)))
})
.or(mine.first().copied())
.map(|m| m.id.clone()) .map(|m| m.id.clone())
} }
@@ -297,28 +343,44 @@ impl Router {
avoid: Option<Kind>, avoid: Option<Kind>,
models: &[ModelInfo], models: &[ModelInfo],
) -> Option<Pick> { ) -> 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 { let tier = match self.cur {
Some((_, c)) if sig.keep => c, Some((_, c)) if sig.keep => c,
Some((_, c)) if sig.tier < c => { Some((_, c)) if want < c => {
self.down += 1; self.down += 1;
if self.down >= n { if self.down >= if c == Tier::Max { 1 } else { n } {
self.down = 0; self.down = 0;
sig.tier want
} else { } else {
c c
} }
} }
_ => { _ => {
self.down = 0; self.down = 0;
sig.tier want
} }
}; };
let prefer = self.cur.map_or(start, |(k, _)| k); let prefer = self.cur.map_or(start, |(k, _)| k);
let (kind, model) = pick_for(tier, prefer, avoid, models, &self.cfg)?; 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)); self.cur = Some((kind, tier));
let held = if tier != sig.tier && !sig.keep { let held = if tier != want && !sig.keep {
format!(", holding (wanted {})", sig.tier.name()) format!(", holding (wanted {})", want.name())
} else { } else {
String::new() 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. /// What `@word` at the start of a prompt asks for.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum Target { pub enum Target {
@@ -363,6 +448,7 @@ pub fn parse_override(
"fast" => Target::Tier(Tier::Fast), "fast" => Target::Tier(Tier::Fast),
"balanced" => Target::Tier(Tier::Balanced), "balanced" => Target::Tier(Tier::Balanced),
"deep" => Target::Tier(Tier::Deep), "deep" => Target::Tier(Tier::Deep),
"max" => Target::Tier(Tier::Max),
_ => { _ => {
if let Some(m) = models.iter().find(|m| m.id.to_lowercase() == lw) { if let Some(m) = models.iter().find(|m| m.id.to_lowercase() == lw) {
Target::Model(m.id.clone()) Target::Model(m.id.clone())
@@ -454,7 +540,99 @@ mod tests {
}]; }];
let s = signals("try again with a different approach", &h); let s = signals("try again with a different approach", &h);
assert_eq!(s.score, 2); 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] #[test]
+53
View File
@@ -47,6 +47,59 @@ pub fn task_report(s: &Session) -> String {
} }
/// One line per subagent log in `<session>.sub/` (empty when there are none). /// 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 { pub fn sub_report(session_path: &std::path::Path) -> String {
let mut files: Vec<_> = std::fs::read_dir(session_path.with_extension("sub")) let mut files: Vec<_> = std::fs::read_dir(session_path.with_extension("sub"))
.into_iter() .into_iter()
+27
View File
@@ -35,6 +35,9 @@ pub struct Last {
/// `/model auto` was on. /// `/model auto` was on.
#[serde(default)] #[serde(default)]
pub auto: bool, pub auto: bool,
/// `/fable on|off`; overrides `[auto] fable` in the config.
#[serde(default)]
pub fable: Option<bool>,
} }
impl Last { impl Last {
@@ -100,6 +103,19 @@ impl Switcher {
self 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 { pub fn is_auto(&self) -> bool {
self.router.is_some() self.router.is_some()
} }
@@ -234,6 +250,13 @@ impl Switcher {
self.apply_inner(agent, pick.kind, pick.model.clone(), false, false)? self.apply_inner(agent, pick.kind, pick.model.clone(), false, false)?
}; };
agent.set_effort(effort); agent.set_effort(effort);
route::log(
agent.session().path(),
&sig,
&pick,
effort,
forced.is_some(),
);
Ok(Some(Routed { Ok(Some(Routed {
pick: route::Pick { effort, ..pick }, pick: route::Pick { effort, ..pick },
sw, sw,
@@ -476,6 +499,7 @@ mod tests {
model: "m".into(), model: "m".into(),
effort: None, effort: None,
auto: false, auto: false,
fable: None,
}; };
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();
@@ -485,6 +509,7 @@ mod tests {
model: "gpt-x".into(), model: "gpt-x".into(),
effort: Some(hx_ai::Effort::High), effort: Some(hx_ai::Effort::High),
auto: false, auto: false,
fable: None,
}; };
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();
@@ -510,6 +535,8 @@ mod tests {
("claude-haiku-x", "claude-haiku-x") ("claude-haiku-x", "claude-haiku-x")
); );
assert!(made.lock().unwrap().is_empty(), "same provider: no rebuild"); 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(); sw.set_model(&mut a, "claude-sonnet-x").unwrap();
assert!(!sw.is_auto()); assert!(!sw.is_auto());
assert!( assert!(
+13
View File
@@ -1507,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(), "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" => { "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) {