diff --git a/Cargo.lock b/Cargo.lock index a2177c1..4f0a671 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -983,6 +983,7 @@ dependencies = [ "anyhow", "async-trait", "clap", + "futures", "hx-ai", "hx-core", "hx-lens", diff --git a/crates/hx-ai/src/models.rs b/crates/hx-ai/src/models.rs index e421b51..4fc4f45 100644 --- a/crates/hx-ai/src/models.rs +++ b/crates/hx-ai/src/models.rs @@ -146,6 +146,14 @@ fn read_cache(k: Kind) -> Option { .filter(|c| !c.models.is_empty()) } +/// Cached list for `k` at any age, and whether it is still fresh. +pub fn cached(k: Kind) -> Option<(Vec, bool)> { + read_cache(k).map(|c| { + let fresh = now().saturating_sub(c.fetched) < CACHE_SECS; + (c.models, fresh) + }) +} + /// Live model list for `k` via `p`, cached for an hour (`refresh` skips the cache). /// On fetch failure: the expired cache if any, else the built-in list; `Source::Failed` says which. pub async fn load_with( diff --git a/crates/hx-cli/Cargo.toml b/crates/hx-cli/Cargo.toml index 543f40e..e61b51d 100644 --- a/crates/hx-cli/Cargo.toml +++ b/crates/hx-cli/Cargo.toml @@ -12,6 +12,7 @@ path = "src/main.rs" anyhow = "1.0.104" async-trait = "0.1.92" clap = { version = "4.6.7", features = ["derive", "env"] } +futures = "0.3.34" hx-ai = { version = "0.1.0", path = "../hx-ai" } hx-core = { version = "0.1.0", path = "../hx-core" } hx-lens = { version = "0.1.0", path = "../hx-lens" } diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index aad761c..de854c4 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -215,25 +215,46 @@ fn logged_in() -> Vec { /// Model catalog of every logged-in provider (live list cached a day, else the built-in list). async fn catalog(kinds: &[Kind]) -> Vec { - let mut v = vec![]; - for k in kinds { - match provider(*k) { - Ok(p) => { - let (m, src) = hx_ai::models::load_with(*k, p.as_ref(), false).await; - if let hx_ai::models::Source::Failed(e, stale) = src { - let what = if stale { - "expired cache" - } else { - "built-in list" - }; - eprintln!("[{k:?}: live model list failed ({e}); using {what}]"); - } - v.extend(m) + let one = |k: Kind| async move { + let Ok(p) = provider(k) else { + return hx_ai::models::fallback(k); + }; + // stale-while-revalidate: any cached list starts us now; an expired one refreshes in the background + if k != Kind::Custom + && let Some((m, fresh)) = hx_ai::models::cached(k) + { + if !fresh { + tokio::spawn(async move { + hx_ai::models::load_with(k, p.as_ref(), true).await; + }); } - Err(_) => v.extend(hx_ai::models::fallback(*k)), + return m; } + let (m, src) = hx_ai::models::load_with(k, p.as_ref(), false).await; + if let hx_ai::models::Source::Failed(e, stale) = src { + let what = if stale { + "expired cache" + } else { + "built-in list" + }; + eprintln!("[{k:?}: live model list failed ({e}); using {what}]"); + } + m + }; + futures::future::join_all(kinds.iter().map(|k| one(*k))) + .await + .into_iter() + .flatten() + .collect() +} + +/// `HX_TRACE_STARTUP=1`: print time since process start at each phase. +fn trace(phase: &str) { + static T0: std::sync::OnceLock = std::sync::OnceLock::new(); + let t0 = T0.get_or_init(std::time::Instant::now); + if std::env::var_os("HX_TRACE_STARTUP").is_some() { + eprintln!("[startup] {:>6}ms {phase}", t0.elapsed().as_millis()); } - v } /// `hx models`: what each provider's `/models` returns, and where the list came from. @@ -350,6 +371,7 @@ fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf { #[tokio::main] async fn main() -> Result<()> { + trace("main"); let cli = Cli::parse(); match cli.cmd { Some(Cmd::Login { provider }) => { @@ -507,9 +529,13 @@ async fn main() -> Result<()> { } let cwd = std::env::current_dir()?; let cfg = Config::load(&cwd)?; + trace("config"); if let Some(oc) = cfg.openai_compat.clone() { let _ = COMPAT.set(oc); } + // MCP servers connect while the model catalog loads + let mcp_cfg = hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?; + let mcp_task = tokio::spawn(hx_mcp::Hub::start(mcp_cfg)); let kinds = logged_in(); let last_path = context::hx_home().join("last.json"); let remember = cfg.remember_model != Some(false); @@ -526,6 +552,7 @@ async fn main() -> Result<()> { .or(kinds.first().copied()) .unwrap_or(Kind::Claude); let models = catalog(&kinds).await; + trace("catalog"); // an explicit model picks its provider unless --provider says otherwise let kind = match (&cli.provider, cli.model.as_deref().or(cfg.model.as_deref())) { (None, Some(m)) => hx_ai::models::kind_of(&models, m).unwrap_or(kind), @@ -590,17 +617,16 @@ async fn main() -> Result<()> { } agent.set_model(model); agent.set_effort(effort); - agent.set_system(context::system_prompt( - cfg.system_prompt.as_deref(), - &context::hx_home(), - &cwd, + let tail = context::prompt_tail(&context::hx_home(), &cwd); + agent.set_system(format!( + "{}{tail}", + cfg.system_prompt + .as_deref() + .unwrap_or(context::DEFAULT_PROMPT) )); - let mcp = Arc::new( - hx_mcp::Hub::start( - hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?, - ) - .await, - ); + trace("prompt"); + let mcp = Arc::new(mcp_task.await?); + trace("mcp"); mcp.register(&mut agent.tools); let idx = mcp.system_prompt(); if !idx.is_empty() { @@ -618,10 +644,14 @@ async fn main() -> Result<()> { Some(n) => agent.set_compact_at(n), None => agent.fit_window(hx_ai::models::window(&models, agent.model())), } - for e in &cfg.extensions { - let x = hx_core::ext::Extension::start(e, &cwd) + let exts = futures::future::join_all(cfg.extensions.iter().map(|e| async { + hx_core::ext::Extension::start(e, &cwd) .await - .map_err(|err| anyhow::anyhow!("extension {:?}: {err}", e.command))?; + .map_err(|err| anyhow::anyhow!("extension {:?}: {err}", e.command)) + })) + .await; + for x in exts { + let x = x?; for t in x.tools() { agent.tools.add(t); } @@ -679,18 +709,18 @@ async fn main() -> Result<()> { .collect(); mgr.warm(probe).await; } + trace("lens"); { // children get the parent's tools as of now (no `task`, so no recursion) let mut general = agent.tools.clone(); general.retain(|n| n != "ask_user"); let mut explore = agent.tools.clone(); explore.retain(|n| hx_core::subagent::EXPLORE_TOOLS.contains(&n)); - let home = context::hx_home(); let role = |model: String, tools, base: &str| hx_core::subagent::Role { provider: provider(kind).expect("provider worked above"), model, tools, - system: context::system_prompt(Some(base), &home, &cwd), + system: format!("{base}{tail}"), }; let cheap = cfg .explore_model @@ -713,6 +743,7 @@ async fn main() -> Result<()> { agent.tools.add(task); } let specs = command_specs(&mcp, &cwd, &models, &kinds); + trace("ready"); if cli.mode == Mode::Rpc { let r = rpc::serve( agent, diff --git a/crates/hx-core/src/context.rs b/crates/hx-core/src/context.rs index 804a3fb..67793c0 100644 --- a/crates/hx-core/src/context.rs +++ b/crates/hx-core/src/context.rs @@ -162,7 +162,16 @@ pub fn skill_index_line(k: &Skill) -> String { } pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> String { - let mut s = base.unwrap_or(DEFAULT_PROMPT).to_string(); + format!( + "{}{}", + base.unwrap_or(DEFAULT_PROMPT), + prompt_tail(home, cwd) + ) +} + +/// Everything after the base prompt (cwd, skills, context files, memory). Scans the disk: compute once, reuse per role. +pub fn prompt_tail(home: &Path, cwd: &Path) -> String { + let mut s = String::new(); s.push_str(&format!("\n\nWorking directory: {}", cwd.display())); let sk = skills(home, cwd); for k in sk.iter().filter(|k| k.load == Load::Always) { diff --git a/crates/hx-mcp/src/lib.rs b/crates/hx-mcp/src/lib.rs index e34bfe6..a0f869a 100644 --- a/crates/hx-mcp/src/lib.rs +++ b/crates/hx-mcp/src/lib.rs @@ -25,7 +25,7 @@ use tokio::sync::Mutex; pub const EAGER_MAX_TOKENS: usize = 400; /// Max characters of tool output returned to the model. pub const OUTPUT_CAP: usize = 30_000; -const CONNECT_TIMEOUT: Duration = Duration::from_secs(30); +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); const MAX_RESTARTS: u32 = 3; pub struct Slot {