diff --git a/crates/hx-cli/src/config.sample.toml b/crates/hx-cli/src/config.sample.toml index 2aee308..2ca7c50 100644 --- a/crates/hx-cli/src/config.sample.toml +++ b/crates/hx-cli/src/config.sample.toml @@ -12,7 +12,9 @@ # subagent_max_turns = 40 # turn limit per subagent (an agent file's max_turns wins) # subagent_max_tokens = 500000 # stop a subagent that spends more tokens than this; default: no limit # subagent_timeout_secs = 600 # stop a subagent run after this long; default: no limit -# remember_model = true # reuse the last model picked with /model or /provider +# consultant = "claude-fable-5-2" # stronger model behind the `consult` tool (off when unset; each call asks first) +# consultant_max_calls = 5 # calls allowed per session (resets on /new) +# remember_model = true # reuse the last model picked with /model or /provider # compact_at = 900000 # auto-compact at this many tokens; default: 90% of the context window # max_tokens = 16384 # permissions = "ask" # ask | auto (refuse dangerous calls, run safe ones) | yolo (nothing asks) diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index e750c2a..b14ba0e 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -178,6 +178,8 @@ struct Config { subagent_max_turns: Option, subagent_max_tokens: Option, subagent_timeout_secs: Option, + consultant: Option, + consultant_max_calls: Option, codemode: Option, mouse: Option, sessions_dir: Option, @@ -247,6 +249,8 @@ impl Config { subagent_max_turns: o.subagent_max_turns.or(c.subagent_max_turns), subagent_max_tokens: o.subagent_max_tokens.or(c.subagent_max_tokens), subagent_timeout_secs: o.subagent_timeout_secs.or(c.subagent_timeout_secs), + consultant: o.consultant.or(c.consultant), + consultant_max_calls: o.consultant_max_calls.or(c.consultant_max_calls), codemode: o.codemode.or(c.codemode), mouse: o.mouse.or(c.mouse), sessions_dir: o.sessions_dir.or(c.sessions_dir), @@ -1144,6 +1148,27 @@ async fn main() -> Result<()> { .bus .add(hx_core::subagent::Notify(agent.cx.state.clone())); } + if let Some(model) = cfg.consultant.clone() + && let Ok(p) = provider(kind) + { + let stats = hx_core::consult::Stats::new( + model, + cfg.consultant_max_calls + .unwrap_or(hx_core::consult::DEFAULT_MAX), + &[ + hx_core::consult::PLAN, + hx_core::consult::DONE, + hx_core::consult::STUCK_NAME, + ], + ); + agent + .tools + .add(hx_core::consult::Consult::new(p, stats.clone())); + agent + .bus + .add(hx_core::consult::ConsultNudge::new(stats.clone())); + let _ = agent.cx.state.consult.set(stats); + } if CLAUDE_CLI.get().is_none() && let (Ok(p), Some(model)) = ( provider(kind), diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 5b27530..84d24b2 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -271,6 +271,9 @@ impl Agent { crate::herdr::set_session(session.path()); self.session = session; self.window.reset(); + if let Some(c) = self.cx.state.consult.get() { + c.reset(); + } self.publish(); } diff --git a/crates/hx-core/src/consult.rs b/crates/hx-core/src/consult.rs new file mode 100644 index 0000000..943bc35 --- /dev/null +++ b/crates/hx-core/src/consult.rs @@ -0,0 +1,359 @@ +use crate::hook::{Event, Hook, HookAction}; +use crate::tool::{Tool, ToolCtx, ToolResult}; +use async_trait::async_trait; +use futures::StreamExt; +use hx_ai::{Effort, Message, Provider, Request, StreamEvent, ToolSpec}; +use serde_json::{Value, json}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +pub const DEFAULT_MAX: u32 = 5; +const STUCK: u32 = 3; +const MAX_TOKENS: u32 = 4096; +const TIMEOUT: Duration = Duration::from_secs(180); +const SYSTEM: &str = "You are a senior consultant to a coding agent. You cannot run tools and see only what the caller wrote. Give a direct answer: the recommended approach, the risks it missed, and what to check. Short, no preamble."; + +pub const PLAN: &str = "before a plan"; +pub const DONE: &str = "before done"; +pub const STUCK_NAME: &str = "when stuck"; + +struct Inner { + advising: bool, + count: u32, + last: Option<(Instant, Duration)>, + triggers: Vec<(&'static str, bool)>, +} + +pub struct Stats { + pub model: String, + pub max: u32, + inner: Mutex, +} + +pub struct Snapshot { + pub model: String, + pub max: u32, + pub advising: bool, + pub count: u32, + pub last: Option<(Duration, Duration)>, + pub triggers: Vec<(String, bool)>, +} + +impl Stats { + pub fn new(model: String, max: u32, triggers: &[&'static str]) -> Arc { + Arc::new(Self { + model, + max, + inner: Mutex::new(Inner { + advising: false, + count: 0, + last: None, + triggers: triggers.iter().map(|t| (*t, false)).collect(), + }), + }) + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { + self.inner.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub fn reset(&self) { + let mut i = self.lock(); + i.advising = false; + i.count = 0; + i.last = None; + i.triggers.iter_mut().for_each(|t| t.1 = false); + } + + pub fn left(&self) -> u32 { + self.max.saturating_sub(self.lock().count) + } + + fn enabled(&self, name: &str) -> bool { + self.lock().triggers.iter().any(|t| t.0 == name) + } + + fn mark(&self, name: &str, on: bool) { + for t in self.lock().triggers.iter_mut().filter(|t| t.0 == name) { + t.1 = on; + } + } + + fn begin(&self) -> Result<(), String> { + let mut i = self.lock(); + if i.count >= self.max { + return Err(format!( + "consultant limit reached ({}/{}) for this session; decide yourself or ask the user", + i.count, self.max + )); + } + i.count += 1; + i.advising = true; + i.triggers.iter_mut().for_each(|t| t.1 = false); + Ok(()) + } + + fn end(&self, took: Duration) { + let mut i = self.lock(); + i.advising = false; + i.last = Some((Instant::now(), took)); + } + + pub fn snapshot(&self) -> Snapshot { + let i = self.lock(); + Snapshot { + model: self.model.clone(), + max: self.max, + advising: i.advising, + count: i.count, + last: i.last.map(|(at, took)| (at.elapsed(), took)), + triggers: i.triggers.iter().map(|t| (t.0.to_string(), t.1)).collect(), + } + } +} + +pub fn spec() -> ToolSpec { + ToolSpec { + name: "consult".into(), + description: "Ask a stronger consultant model for advice. It sees only `question` and `context`, no tools, no conversation. Use it before committing to a plan, when stuck after repeated failures, and before declaring a hard task done. The number of calls per session is limited; the user is asked to approve each call. Make the question specific and put the relevant code, errors and constraints in `context`.".into(), + input_schema: json!({"type":"object","properties":{ + "question":{"type":"string"}, + "context":{"type":"string","description":"relevant facts, code, error output, what you already tried"}}, + "required":["question"]}), + } +} + +pub struct Consult { + provider: Arc, + stats: Arc, +} + +impl Consult { + pub fn new(provider: Arc, stats: Arc) -> Self { + Self { provider, stats } + } + + async fn ask(&self, prompt: String) -> Result<(String, hx_ai::Usage), String> { + let req = Request { + model: self.stats.model.clone(), + system: SYSTEM.into(), + messages: vec![Message::user(prompt)], + tools: vec![], + max_tokens: MAX_TOKENS, + effort: Effort::Off, + }; + let run = async { + let mut s = self.provider.stream(req).await.map_err(|e| e.to_string())?; + while let Some(ev) = s.next().await { + if let StreamEvent::Done { message, usage, .. } = ev.map_err(|e| e.to_string())? { + return Ok((message.text(), usage)); + } + } + Err("stream ended without an answer".to_string()) + }; + let (text, usage) = tokio::time::timeout(TIMEOUT, run) + .await + .map_err(|_| "timed out".to_string())??; + Ok((text, usage)) + } +} + +#[async_trait] +impl Tool for Consult { + fn spec(&self) -> ToolSpec { + spec() + } + async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { + let q = a["question"].as_str().unwrap_or_default().trim(); + if q.is_empty() { + return ToolResult::err("question is required"); + } + if cx.state.abort.get().is_some_and(|r| *r.borrow()) { + return ToolResult::err("aborted"); + } + if let Err(e) = self.stats.begin() { + return ToolResult::err(e); + } + let ctx = a["context"].as_str().unwrap_or_default(); + let prompt = format!("\n{ctx}\n\n\n{q}"); + let t0 = Instant::now(); + let r = self.ask(prompt).await; + self.stats.end(t0.elapsed()); + match r { + Ok((text, usage)) => { + cx.state + .sub_usage + .lock() + .unwrap_or_else(|e| e.into_inner()) + .add(&usage); + ToolResult::ok(format!( + "{}\n[consult · {} · {}/{} calls · {}s]", + text.trim(), + self.stats.model, + self.stats.snapshot().count, + self.stats.max, + t0.elapsed().as_secs() + )) + } + Err(e) => ToolResult::err(format!("consultant failed: {e}")), + } + } +} + +#[derive(Default)] +struct Seen { + edited: bool, + errors: u32, + done_nudged: bool, + stuck_nudged: bool, +} + +pub struct ConsultNudge { + stats: Arc, + s: Mutex, +} + +impl ConsultNudge { + pub fn new(stats: Arc) -> Self { + Self { + stats, + s: Mutex::default(), + } + } + + fn hint(&self, name: &str, text: &str) -> HookAction { + if self.stats.left() == 0 || !self.stats.enabled(name) { + return HookAction::Continue; + } + self.stats.mark(name, true); + HookAction::Inject(format!( + "hint: {text} Consider the `consult` tool ({} calls left).", + self.stats.left() + )) + } +} + +#[async_trait] +impl Hook for ConsultNudge { + async fn on(&self, ev: &Event) -> HookAction { + let mut s = self.s.lock().unwrap_or_else(|e| e.into_inner()); + match ev { + Event::ToolCall { name, .. } => match name.as_str() { + "exit_plan" => return self.hint(PLAN, "You are about to submit a plan."), + "edit" | "write" => s.edited = true, + "consult" => *s = Seen::default(), + _ => {} + }, + Event::ToolResult { is_error, name, .. } if name != "consult" => { + s.errors = if *is_error { s.errors + 1 } else { 0 }; + if s.errors >= STUCK && !s.stuck_nudged { + s.stuck_nudged = true; + return self.hint(STUCK_NAME, "Several tool calls in a row failed."); + } + if !*is_error { + s.stuck_nudged = false; + } + } + Event::AgentEnd if s.edited && !s.done_nudged => { + s.done_nudged = true; + return self.hint(DONE, "You made edits and are about to finish."); + } + Event::AgentEnd => s.done_nudged = false, + _ => {} + } + HookAction::Continue + } +} + +#[cfg(test)] +mod tests { + use super::*; + use futures::stream::BoxStream; + use hx_ai::{StopReason, Usage}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Fake(AtomicUsize); + #[async_trait] + impl Provider for Fake { + async fn stream( + &self, + _req: Request, + ) -> hx_ai::Result>> { + self.0.fetch_add(1, Ordering::Relaxed); + let done = StreamEvent::Done { + message: Message { + role: hx_ai::Role::Assistant, + content: vec![hx_ai::ContentBlock::Text { + text: "use a trait".into(), + }], + }, + stop: StopReason::EndTurn, + usage: Usage { + input_tokens: 10, + ..Default::default() + }, + }; + Ok(futures::stream::iter(vec![Ok(done)]).boxed()) + } + } + + fn cx() -> ToolCtx { + ToolCtx { + cwd: ".".into(), + state: Arc::new(crate::State::default()), + } + } + + fn all() -> Arc { + Stats::new("m".into(), 2, &[PLAN, DONE, STUCK_NAME]) + } + + #[tokio::test] + async fn caps_calls_without_invoking_the_provider() { + let p = Arc::new(Fake(AtomicUsize::new(0))); + let st = all(); + let t = Consult::new(p.clone(), st.clone()); + let cx = cx(); + for _ in 0..2 { + let r = t.call(json!({"question": "q"}), &cx).await; + assert!(!r.is_error && r.content.contains("use a trait"), "{}", r.content); + } + let r = t.call(json!({"question": "q"}), &cx).await; + assert!(r.is_error && r.content.contains("limit reached (2/2)")); + assert_eq!(p.0.load(Ordering::Relaxed), 2); + assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 20); + let snap = st.snapshot(); + assert_eq!((snap.count, snap.advising, snap.last.is_some()), (2, false, true)); + st.reset(); + assert_eq!(st.snapshot().count, 0); + } + + #[tokio::test] + async fn nudges_on_triggers_and_stops_at_cap() { + let st = all(); + let h = ConsultNudge::new(st.clone()); + let call = |n: &str| Event::ToolCall { + id: "i".into(), + name: n.into(), + args: json!({}), + }; + let res = |e: bool| Event::ToolResult { + id: "i".into(), + name: "bash".into(), + args: json!({}), + content: String::new(), + is_error: e, + }; + assert_eq!(h.on(&call("edit")).await, HookAction::Continue); + assert!(matches!(h.on(&Event::AgentEnd).await, HookAction::Inject(m) if m.contains("2 calls"))); + assert!(st.snapshot().triggers.iter().any(|t| t.0 == DONE && t.1)); + assert_eq!(h.on(&Event::AgentEnd).await, HookAction::Continue); + h.on(&res(true)).await; + h.on(&res(true)).await; + assert!(matches!(h.on(&res(true)).await, HookAction::Inject(_))); + assert!(matches!(h.on(&call("exit_plan")).await, HookAction::Inject(_))); + st.begin().unwrap(); + st.begin().unwrap(); + assert_eq!(h.on(&call("exit_plan")).await, HookAction::Continue); + } +} diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index 6483e6f..7213f88 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -2,6 +2,7 @@ pub mod agent; pub mod approve; pub mod command; pub mod compact; +pub mod consult; pub mod context; pub mod danger; pub mod ext; @@ -62,6 +63,7 @@ pub struct State { pub abort: std::sync::OnceLock>, pub sub_usage: Mutex, pub subs: subagent::Subs, + pub consult: std::sync::OnceLock>, pub live: Mutex>, pub claude_seen: Mutex>, pub lens: Mutex, diff --git a/crates/hx-core/src/permit.rs b/crates/hx-core/src/permit.rs index 1d25c42..7153f4a 100644 --- a/crates/hx-core/src/permit.rs +++ b/crates/hx-core/src/permit.rs @@ -184,7 +184,7 @@ pub fn needs_permit(tool: &str, args: &serde_json::Value) -> bool { "task" => { !(args["wait"].is_array() && args["prompt"].is_null() && args["prompts"].is_null()) } - "web_fetch" => true, + "web_fetch" | "consult" => true, _ => gated(tool), } } @@ -235,6 +235,13 @@ pub fn request(tool: &str, args: &serde_json::Value) -> Request { rule: format!("web:{host}"), }; } + if tool == "consult" { + return Request { + tool: tool.into(), + detail: s("question").chars().take(200).collect(), + rule: "consult".into(), + }; + } if tool == "task" { let kind = args["kind"].as_str().unwrap_or("explore"); let ps: Vec<&str> = match args["prompts"].as_array() { diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 1ee39f5..c173082 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -1904,6 +1904,17 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { .unwrap_or_else(|e| e.into_inner()) .clone(); let subs = app.state.subs.list(); + app.consult = app.state.consult.get().map(|c| { + let s = c.snapshot(); + side::Consult { + model: s.model, + advising: s.advising, + consults: s.count, + max: s.max, + last: s.last, + triggers: s.triggers, + } + }); ls.extend(side::lines(&side::View { st: &app.st, mode: app.mode, diff --git a/crates/hx-tui/src/side.rs b/crates/hx-tui/src/side.rs index 0fb4b8e..e60ec2c 100644 --- a/crates/hx-tui/src/side.rs +++ b/crates/hx-tui/src/side.rs @@ -36,6 +36,7 @@ pub struct Consult { pub model: String, pub advising: bool, pub consults: u32, + pub max: u32, pub last: Option<(Duration, Duration)>, pub triggers: Vec<(String, bool)>, } @@ -289,7 +290,7 @@ fn consult_card(c: &View) -> Option>> { }; Some(card( "CONSULTANT", - &format!("{state} {} {}", th.sym.info, k.consults), + &format!("{state} {} {}/{}", th.sym.info, k.consults, k.max), border, b, c.w, @@ -665,6 +666,7 @@ mod tests { model: "claude-fable-5-2".into(), advising: true, consults: 2, + max: 5, last: Some((Duration::from_secs(7), Duration::from_secs(27))), triggers: vec![ ("before a plan".into(), false), @@ -673,7 +675,10 @@ mod tests { }; v.consult = Some(&k); let s = text(&lines(&v)); - assert!(s.contains("CONSULTANT") && s.contains("advising"), "{s}"); + assert!( + s.contains("CONSULTANT") && s.contains("advising") && s.contains("2/5"), + "{s}" + ); assert!( s.contains("● before done") && s.contains("○ before a plan"), "{s}"