Faster startup: parallel catalog (stale-while-revalidate), MCP overlaps catalog, parallel extensions, single prompt scan, 10s MCP connect timeout, HX_TRACE_STARTUP

This commit is contained in:
hermes committed 2026-10-08 16:53:56 +00:00
1 parent 7a238e0e51
commit 6c8d492ca5
6 files changed
+83 -33

No files matched your search

+62 -31
View File
@@ -215,25 +215,46 @@ fn logged_in() -> Vec<Kind> {
/// Model catalog of every logged-in provider (live list cached a day, else the built-in list).
async fn catalog(kinds: &[Kind]) -> Vec<ModelInfo> {
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::time::Instant> = 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,