From 2f1ce2c072eee9947480d7f757f36840443094ca Mon Sep 17 00:00:00 2001 From: hermes Date: Tue, 6 Oct 2026 11:43:51 +0000 Subject: [PATCH 1/2] Remember last chosen provider/model in HX_HOME/last.json --- crates/hx-cli/src/main.rs | 23 ++++++++++++++---- crates/hx-core/src/switch.rs | 46 ++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index f5d76c2..2c96c8e 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -99,6 +99,8 @@ struct Config { explore_model: Option, /// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift). mouse: Option, + /// Reuse the last model chosen with /model or /provider (default true). + remember_model: Option, /// "ask" (default) or "yolo": whether bash/write/edit prompt in the TUI. permissions: Option, /// Replaces the built-in system prompt (AGENTS.md etc. are still appended). @@ -146,6 +148,7 @@ impl Config { max_tokens: o.max_tokens.or(c.max_tokens), explore_model: o.explore_model.or(c.explore_model), mouse: o.mouse.or(c.mouse), + remember_model: o.remember_model.or(c.remember_model), permissions: o.permissions.or(c.permissions), system_prompt: o.system_prompt.or(c.system_prompt), lsp: o.lsp.or(c.lsp), @@ -478,10 +481,18 @@ async fn main() -> Result<()> { let cwd = std::env::current_dir()?; let cfg = Config::load(&cwd)?; let kinds = logged_in(); - // default provider: configured, else the first one logged in + let last_path = context::hx_home().join("last.json"); + let remember = cfg.remember_model != Some(false); + // last /model choice, only while its provider is still logged in + let last = remember + .then(|| hx_core::switch::Last::load(&last_path)) + .flatten() + .filter(|l| kinds.contains(&l.provider)); + // default provider: flag, config, last choice, else the first one logged in let kind = cli .provider .or(cfg.provider) + .or(last.as_ref().map(|l| l.provider)) .or(kinds.first().copied()) .unwrap_or(Kind::Claude); let models = catalog(&kinds).await; @@ -490,7 +501,9 @@ async fn main() -> Result<()> { (None, Some(m)) => hx_ai::models::kind_of(&models, m).unwrap_or(kind), _ => kind, }; - let model = cli.model.or(cfg.model).unwrap_or_else(|| { + // the remembered model applies only to the provider it was chosen on + let last_model = last.filter(|l| l.provider == kind).map(|l| l.model); + let model = cli.model.or(cfg.model).or(last_model).unwrap_or_else(|| { match kind { Kind::Claude => cfg.claude_model.clone(), Kind::Codex => cfg.codex_model.clone(), @@ -667,7 +680,8 @@ async fn main() -> Result<()> { models.clone(), Box::new(provider), cfg.compact_at.is_none(), - ), + ) + .remember_in(last_path.clone()), }, ) .await; @@ -685,7 +699,8 @@ async fn main() -> Result<()> { models.clone(), Box::new(provider), cfg.compact_at.is_none(), - ), + ) + .remember_in(last_path), pricing, specs, open_sessions, diff --git a/crates/hx-core/src/switch.rs b/crates/hx-core/src/switch.rs index 0734a92..6e2c0f4 100644 --- a/crates/hx-core/src/switch.rs +++ b/crates/hx-core/src/switch.rs @@ -23,7 +23,22 @@ pub struct Switched { pub window: u64, } +/// Last chosen provider + model, kept in `$HX_HOME/last.json` so the next start reuses it. +#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)] +pub struct Last { + pub provider: Kind, + pub model: String, +} + +impl Last { + /// `None` when the file is missing or unreadable. + pub fn load(path: &std::path::Path) -> Option { + serde_json::from_slice(&std::fs::read(path).ok()?).ok() + } +} + pub struct Switcher { + remember: Option, kind: Kind, models: Vec, make_provider: MakeProvider, @@ -40,6 +55,7 @@ impl Switcher { auto_compact: bool, ) -> Self { Self { + remember: None, kind, models, make_provider, @@ -47,6 +63,12 @@ impl Switcher { } } + /// Write every successful switch to `path` (best effort). + pub fn remember_in(mut self, path: std::path::PathBuf) -> Self { + self.remember = Some(path); + self + } + /// The provider the agent currently uses. pub fn kind(&self) -> Kind { self.kind @@ -81,6 +103,14 @@ impl Switcher { } else { agent.set_model(model.as_str()); } + if let Some(p) = &self.remember { + let last = Last { + provider: kind, + model: model.clone(), + }; + // ponytail: failing to save must not fail the switch + let _ = serde_json::to_vec(&last).map(|b| std::fs::write(p, b)); + } let window = models::window(&self.models, &model); if self.auto_compact { agent.fit_window(window); @@ -219,6 +249,22 @@ mod tests { ); } + #[test] + fn switches_are_remembered() { + let (sw, mut a, _m, d) = setup(true, false); + let f = d.path().join("last.json"); + assert_eq!(Last::load(&f), None); + let mut sw = sw.remember_in(f.clone()); + sw.set_model(&mut a, "gpt-x").unwrap(); + let want = Last { + provider: Kind::Codex, + model: "gpt-x".into(), + }; + assert_eq!(Last::load(&f), Some(want)); + std::fs::write(&f, "junk").unwrap(); + assert_eq!(Last::load(&f), None); + } + #[test] fn configured_threshold_is_left_alone() { let (mut sw, mut a, _m, _d) = setup(false, false); -- 2.54.1 From ab2af421a4674cafb26c01ac5fea814583da40a5 Mon Sep 17 00:00:00 2001 From: hermes Date: Tue, 6 Oct 2026 12:05:29 +0000 Subject: [PATCH 2/2] Thinking levels: Tab cycles off/low/medium/high, /effort --- crates/hx-ai/src/anthropic.rs | 23 +++++++++ crates/hx-ai/src/codex.rs | 19 +++---- crates/hx-ai/src/lib.rs | 94 +++++++++++++++++++++++++++++++++++ crates/hx-cli/src/main.rs | 1 + crates/hx-core/src/agent.rs | 12 +++++ crates/hx-core/src/command.rs | 5 ++ crates/hx-core/src/compact.rs | 1 + crates/hx-tui/src/lib.rs | 36 +++++++++++--- crates/hx-tui/src/status.rs | 5 ++ 9 files changed, 180 insertions(+), 16 deletions(-) diff --git a/crates/hx-ai/src/anthropic.rs b/crates/hx-ai/src/anthropic.rs index c61b7fb..678b8b8 100644 --- a/crates/hx-ai/src/anthropic.rs +++ b/crates/hx-ai/src/anthropic.rs @@ -120,6 +120,18 @@ pub fn body(req: &Request) -> Value { if !tools.is_empty() { b["tools"] = tools.into(); } + // ponytail: fixed token budgets; newer models may prefer adaptive thinking, add when needed + let budget = match req.effort { + crate::Effort::Off => 0, + crate::Effort::Low => 4_000, + crate::Effort::Medium => 10_000, + crate::Effort::High => 24_000, + }; + if budget > 0 { + b["thinking"] = json!({"type": "enabled", "budget_tokens": budget}); + // the budget counts against max_tokens, which must leave room for the reply + b["max_tokens"] = req.max_tokens.max(budget + 4_096).into(); + } b } @@ -377,6 +389,16 @@ mod tests { use super::*; use crate::ToolSpec; + #[test] + fn effort_sets_thinking_budget() { + let mut r = req(); + assert!(body(&r).get("thinking").is_none()); + r.effort = crate::Effort::High; + let b = body(&r); + assert_eq!(b["thinking"]["budget_tokens"], 24_000); + assert!(b["max_tokens"].as_u64().unwrap() > 24_000); + } + #[test] fn quota_and_models() { let mut h = reqwest::header::HeaderMap::new(); @@ -427,6 +449,7 @@ mod tests { input_schema: json!({"type": "object"}), }], max_tokens: 1024, + effort: crate::Effort::Off, } } diff --git a/crates/hx-ai/src/codex.rs b/crates/hx-ai/src/codex.rs index bbbda8f..31ea913 100644 --- a/crates/hx-ai/src/codex.rs +++ b/crates/hx-ai/src/codex.rs @@ -12,8 +12,6 @@ pub struct Codex { auth: Auth, base_url: String, http: reqwest::Client, - /// "none" | "minimal" | "low" | "medium" | "high" - pub reasoning_effort: Option, } impl Codex { @@ -22,7 +20,6 @@ impl Codex { auth, base_url: "https://chatgpt.com/backend-api/codex".into(), http: reqwest::Client::new(), - reasoning_effort: Some("medium".into()), } } pub fn login_default() -> Result { @@ -42,7 +39,7 @@ fn split_id(id: &str) -> (&str, Option<&str>) { } } -pub fn body(req: &Request, effort: Option<&str>) -> Value { +pub fn body(req: &Request) -> Value { let mut input = vec![]; for m in &req.messages { for b in &m.content { @@ -109,9 +106,12 @@ pub fn body(req: &Request, effort: Option<&str>) -> Value { "text": {"verbosity": "low"}, "include": ["reasoning.encrypted_content"], }); - if let Some(e) = effort { - b["reasoning"] = json!({"effort": e, "summary": "auto"}); - } + // Off has no Codex equivalent (see Effort::levels); send the lowest level instead + let e = match req.effort { + crate::Effort::Off | crate::Effort::Low => "low", + e => e.name(), + }; + b["reasoning"] = json!({"effort": e, "summary": "auto"}); b } @@ -368,7 +368,7 @@ impl Provider for Codex { .header("OpenAI-Beta", "responses=experimental") .header("accept", "text/event-stream") .header("user-agent", concat!("hx/", env!("CARGO_PKG_VERSION"))) - .json(&body(&req, self.reasoning_effort.as_deref())) + .json(&body(&req)) .send() .await .map_err(|e| Error::Http(e.to_string()))?; @@ -528,8 +528,9 @@ mod tests { input_schema: json!({"type":"object"}), }], max_tokens: 100, + effort: crate::Effort::Low, }; - let b = body(&req, Some("low")); + let b = body(&req); let inp = b["input"].as_array().unwrap(); assert_eq!(inp[0]["content"][0]["type"], "input_text"); assert_eq!(inp[1]["type"], "reasoning"); diff --git a/crates/hx-ai/src/lib.rs b/crates/hx-ai/src/lib.rs index 07c0421..ae10dd7 100644 --- a/crates/hx-ai/src/lib.rs +++ b/crates/hx-ai/src/lib.rs @@ -138,6 +138,99 @@ pub enum StopReason { Other, } +/// How hard the model thinks before answering. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Effort { + Off, + Low, + #[default] + Medium, + High, +} + +impl Effort { + pub const ALL: [Effort; 4] = [Effort::Off, Effort::Low, Effort::Medium, Effort::High]; + + /// Start level per provider: Claude thinks only when asked (token cost), Codex always reasons. + pub fn default_for(k: auth::Kind) -> Self { + match k { + auth::Kind::Claude => Effort::Off, + auth::Kind::Codex => Effort::Medium, + } + } + + /// Levels the provider supports (Codex models can't switch reasoning off). + pub fn levels(k: auth::Kind) -> &'static [Effort] { + match k { + auth::Kind::Claude => &Self::ALL, + auth::Kind::Codex => &Self::ALL[1..], + } + } + + /// Next level in `levels(k)`, wrapping; a level the provider lacks maps to its first. + pub fn next(self, k: auth::Kind) -> Self { + let l = Self::levels(k); + l.iter() + .position(|&e| e == self) + .map_or(l[0], |i| l[(i + 1) % l.len()]) + } + + pub fn name(self) -> &'static str { + match self { + Effort::Off => "off", + Effort::Low => "low", + Effort::Medium => "medium", + Effort::High => "high", + } + } +} + +#[cfg(test)] +mod effort_tests { + use super::*; + use auth::Kind; + + #[test] + fn cycle_wraps_and_codex_skips_off() { + let mut e = Effort::Off; + let seen: Vec<_> = (0..5) + .map(|_| { + e = e.next(Kind::Claude); + e + }) + .collect(); + assert_eq!( + seen, + [ + Effort::Low, + Effort::Medium, + Effort::High, + Effort::Off, + Effort::Low + ] + ); + assert_eq!(Effort::High.next(Kind::Codex), Effort::Low); + assert_eq!( + Effort::Off.next(Kind::Codex), + Effort::Low, + "unsupported level" + ); + assert_eq!("high".parse::(), Ok(Effort::High)); + assert!("max".parse::().is_err()); + } +} + +impl std::str::FromStr for Effort { + type Err = String; + fn from_str(s: &str) -> std::result::Result { + Self::ALL + .into_iter() + .find(|e| e.name() == s) + .ok_or_else(|| format!("unknown level {s:?} (off, low, medium, high)")) + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Request { pub model: String, @@ -145,6 +238,7 @@ pub struct Request { pub messages: Vec, pub tools: Vec, pub max_tokens: u32, + pub effort: Effort, } /// Incremental stream events. Providers must emit `Done` last with the full assembled message. diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 2c96c8e..3ac7731 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -544,6 +544,7 @@ async fn main() -> Result<()> { cx, ); agent.set_model(model); + agent.set_effort(hx_ai::Effort::default_for(kind)); agent.set_system(context::system_prompt( cfg.system_prompt.as_deref(), &context::hx_home(), diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 20ff894..22b6b70 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -32,6 +32,7 @@ pub struct Agent { model: String, system: String, max_tokens: u32, + effort: hx_ai::Effort, max_turns: u32, usage: Usage, session: Session, @@ -71,6 +72,7 @@ impl Agent { model: String::new(), system: String::new(), max_tokens: 16_384, + effort: hx_ai::Effort::Off, max_turns: 200, usage: Usage::default(), session, @@ -107,6 +109,15 @@ impl Agent { self.model = model.into(); } + pub fn effort(&self) -> hx_ai::Effort { + self.effort + } + + /// Thinking level for the following requests. + pub fn set_effort(&mut self, e: hx_ai::Effort) { + self.effort = e; + } + pub fn set_system(&mut self, system: impl Into) { self.system = system.into(); } @@ -239,6 +250,7 @@ impl Agent { messages: view.messages, tools: self.tools.specs(), max_tokens: self.max_tokens, + effort: self.effort, }; let mut s = self.provider.stream(req).await?; let mut done = None; diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs index bdff3f9..b8b1d68 100644 --- a/crates/hx-core/src/command.rs +++ b/crates/hx-core/src/command.rs @@ -56,6 +56,11 @@ pub fn builtins(models: &[&str]) -> Vec { "switch provider", Enum(vec!["claude".into(), "codex".into()]), ), + b( + "effort", + "thinking level (tab on an empty line cycles)", + Enum(["off", "low", "medium", "high"].map(String::from).into()), + ), b("compact", "summarize old context", None), b("new", "start a new session (old one stays resumable)", None), b("clear", "alias of /new", None), diff --git a/crates/hx-core/src/compact.rs b/crates/hx-core/src/compact.rs index 2231623..7fcbcd6 100644 --- a/crates/hx-core/src/compact.rs +++ b/crates/hx-core/src/compact.rs @@ -43,6 +43,7 @@ impl Plan { messages: vec![Message::user(self.transcript.clone())], tools: vec![], max_tokens: 4096, + effort: hx_ai::Effort::Off, } } diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index a2abbe3..681b1c3 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -183,6 +183,10 @@ impl App { fn apply_switch(&mut self, sw: &hx_core::switch::Switched) { self.st.kind = sw.kind; self.st.model = sw.model.clone(); + // keep the level when the new provider has it, else its first (Codex has no "off") + if !hx_ai::Effort::levels(sw.kind).contains(&self.st.effort) { + self.st.effort = hx_ai::Effort::levels(sw.kind)[0]; + } if sw.provider_changed { self.st.quota = None; } @@ -298,6 +302,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { st: status::Status { kind: switcher.kind(), model: agent.model().to_string(), + effort: agent.effort(), usage: Usage::default(), ctx_tokens: agent.context_tokens(), ctx_max: agent.compact_at(), @@ -906,6 +911,10 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { KeyCode::End => app.ed.end(), KeyCode::Up => app.ed.up(), KeyCode::Down => app.ed.down(), + KeyCode::Tab if app.ed.buf.is_empty() => { + app.st.effort = app.st.effort.next(app.st.kind); + app.hint = format!("thinking: {}", app.st.effort.name()); + } KeyCode::Tab => { let c = completion(app); let labels: Vec<&str> = c.items.iter().map(|i| i.label.as_str()).collect(); @@ -1054,6 +1063,21 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { Err(e) => app.t.push(Item::Error(format!("/new: {e}"))), } } + "effort" if arg.is_empty() => app.t.push(Item::Info(format!( + "thinking: {} (off, low, medium, high)", + app.st.effort.name() + ))), + "effort" => match arg.parse::() { + Ok(e) if hx_ai::Effort::levels(app.st.kind).contains(&e) => { + app.st.effort = e; + app.t.push(Item::Info(format!("thinking → {}", e.name()))); + } + Ok(_) => app.t.push(Item::Error(format!( + "{:?} cannot turn thinking off", + app.st.kind + ))), + Err(e) => app.t.push(Item::Error(e)), + }, "model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.st.model))), "model" => { let mut a = agent.lock().await; @@ -1147,14 +1171,11 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { app.since = Instant::now(); let prompt = expand_mentions(&line, cwd); let (agent, tx) = (agent.clone(), tx.clone()); + let effort = app.st.effort; tokio::spawn(async move { - let r = agent - .lock() - .await - .run(prompt) - .await - .map(|_| ()) - .map_err(|e| e.to_string()); + let mut a = agent.lock().await; + a.set_effort(effort); + let r = a.run(prompt).await.map(|_| ()).map_err(|e| e.to_string()); let _ = tx.send(Ui::Done(r)); }); } @@ -1799,6 +1820,7 @@ mod tests { st: status::Status { kind: Kind::Claude, model: "m1".into(), + effort: hx_ai::Effort::Off, usage: Usage::default(), ctx_tokens: 0, ctx_max: 150_000, diff --git a/crates/hx-tui/src/status.rs b/crates/hx-tui/src/status.rs index 6bd960c..1453cab 100644 --- a/crates/hx-tui/src/status.rs +++ b/crates/hx-tui/src/status.rs @@ -13,6 +13,7 @@ use ratatui::text::{Line, Span}; pub struct Status { pub kind: Kind, pub model: String, + pub effort: hx_ai::Effort, pub usage: Usage, pub ctx_tokens: usize, /// auto-compact threshold: the context bar's 100% @@ -226,6 +227,9 @@ pub fn footer(st: &Status, c: &Chrome, width: u16, now: u64) -> Line<'static> { fn tail(st: &Status, c: &Chrome) -> Vec { let mut t = vec![format!("{:?}", st.kind), st.model.clone()]; + if st.effort != hx_ai::Effort::Off { + t.push(format!("think {}", st.effort.name())); + } if c.queued > 0 { t.push(format!("{} queued", c.queued)); } @@ -322,6 +326,7 @@ mod tests { Status { kind: Kind::Claude, model: "m1".into(), + effort: hx_ai::Effort::Off, usage: Usage::default(), ctx_tokens: 0, ctx_max: 150_000, -- 2.54.1