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:
1 parent
7a238e0e51
commit
6c8d492ca5
6 files changed
+83
-33
No files matched your search
Generated
+1
@@ -983,6 +983,7 @@ dependencies = [
|
|||||||
"anyhow",
|
"anyhow",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"clap",
|
"clap",
|
||||||
|
"futures",
|
||||||
"hx-ai",
|
"hx-ai",
|
||||||
"hx-core",
|
"hx-core",
|
||||||
"hx-lens",
|
"hx-lens",
|
||||||
|
|||||||
@@ -146,6 +146,14 @@ fn read_cache(k: Kind) -> Option<Cache> {
|
|||||||
.filter(|c| !c.models.is_empty())
|
.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<ModelInfo>, 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).
|
/// 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.
|
/// On fetch failure: the expired cache if any, else the built-in list; `Source::Failed` says which.
|
||||||
pub async fn load_with(
|
pub async fn load_with(
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ path = "src/main.rs"
|
|||||||
anyhow = "1.0.104"
|
anyhow = "1.0.104"
|
||||||
async-trait = "0.1.92"
|
async-trait = "0.1.92"
|
||||||
clap = { version = "4.6.7", features = ["derive", "env"] }
|
clap = { version = "4.6.7", features = ["derive", "env"] }
|
||||||
|
futures = "0.3.34"
|
||||||
hx-ai = { version = "0.1.0", path = "../hx-ai" }
|
hx-ai = { version = "0.1.0", path = "../hx-ai" }
|
||||||
hx-core = { version = "0.1.0", path = "../hx-core" }
|
hx-core = { version = "0.1.0", path = "../hx-core" }
|
||||||
hx-lens = { version = "0.1.0", path = "../hx-lens" }
|
hx-lens = { version = "0.1.0", path = "../hx-lens" }
|
||||||
|
|||||||
+62
-31
@@ -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).
|
/// Model catalog of every logged-in provider (live list cached a day, else the built-in list).
|
||||||
async fn catalog(kinds: &[Kind]) -> Vec<ModelInfo> {
|
async fn catalog(kinds: &[Kind]) -> Vec<ModelInfo> {
|
||||||
let mut v = vec![];
|
let one = |k: Kind| async move {
|
||||||
for k in kinds {
|
let Ok(p) = provider(k) else {
|
||||||
match provider(*k) {
|
return hx_ai::models::fallback(k);
|
||||||
Ok(p) => {
|
};
|
||||||
let (m, src) = hx_ai::models::load_with(*k, p.as_ref(), false).await;
|
// stale-while-revalidate: any cached list starts us now; an expired one refreshes in the background
|
||||||
if let hx_ai::models::Source::Failed(e, stale) = src {
|
if k != Kind::Custom
|
||||||
let what = if stale {
|
&& let Some((m, fresh)) = hx_ai::models::cached(k)
|
||||||
"expired cache"
|
{
|
||||||
} else {
|
if !fresh {
|
||||||
"built-in list"
|
tokio::spawn(async move {
|
||||||
};
|
hx_ai::models::load_with(k, p.as_ref(), true).await;
|
||||||
eprintln!("[{k:?}: live model list failed ({e}); using {what}]");
|
});
|
||||||
}
|
|
||||||
v.extend(m)
|
|
||||||
}
|
}
|
||||||
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.
|
/// `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]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
|
trace("main");
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
match cli.cmd {
|
match cli.cmd {
|
||||||
Some(Cmd::Login { provider }) => {
|
Some(Cmd::Login { provider }) => {
|
||||||
@@ -507,9 +529,13 @@ async fn main() -> Result<()> {
|
|||||||
}
|
}
|
||||||
let cwd = std::env::current_dir()?;
|
let cwd = std::env::current_dir()?;
|
||||||
let cfg = Config::load(&cwd)?;
|
let cfg = Config::load(&cwd)?;
|
||||||
|
trace("config");
|
||||||
if let Some(oc) = cfg.openai_compat.clone() {
|
if let Some(oc) = cfg.openai_compat.clone() {
|
||||||
let _ = COMPAT.set(oc);
|
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 kinds = logged_in();
|
||||||
let last_path = context::hx_home().join("last.json");
|
let last_path = context::hx_home().join("last.json");
|
||||||
let remember = cfg.remember_model != Some(false);
|
let remember = cfg.remember_model != Some(false);
|
||||||
@@ -526,6 +552,7 @@ async fn main() -> Result<()> {
|
|||||||
.or(kinds.first().copied())
|
.or(kinds.first().copied())
|
||||||
.unwrap_or(Kind::Claude);
|
.unwrap_or(Kind::Claude);
|
||||||
let models = catalog(&kinds).await;
|
let models = catalog(&kinds).await;
|
||||||
|
trace("catalog");
|
||||||
// an explicit model picks its provider unless --provider says otherwise
|
// an explicit model picks its provider unless --provider says otherwise
|
||||||
let kind = match (&cli.provider, cli.model.as_deref().or(cfg.model.as_deref())) {
|
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),
|
(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_model(model);
|
||||||
agent.set_effort(effort);
|
agent.set_effort(effort);
|
||||||
agent.set_system(context::system_prompt(
|
let tail = context::prompt_tail(&context::hx_home(), &cwd);
|
||||||
cfg.system_prompt.as_deref(),
|
agent.set_system(format!(
|
||||||
&context::hx_home(),
|
"{}{tail}",
|
||||||
&cwd,
|
cfg.system_prompt
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or(context::DEFAULT_PROMPT)
|
||||||
));
|
));
|
||||||
let mcp = Arc::new(
|
trace("prompt");
|
||||||
hx_mcp::Hub::start(
|
let mcp = Arc::new(mcp_task.await?);
|
||||||
hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?,
|
trace("mcp");
|
||||||
)
|
|
||||||
.await,
|
|
||||||
);
|
|
||||||
mcp.register(&mut agent.tools);
|
mcp.register(&mut agent.tools);
|
||||||
let idx = mcp.system_prompt();
|
let idx = mcp.system_prompt();
|
||||||
if !idx.is_empty() {
|
if !idx.is_empty() {
|
||||||
@@ -618,10 +644,14 @@ async fn main() -> Result<()> {
|
|||||||
Some(n) => agent.set_compact_at(n),
|
Some(n) => agent.set_compact_at(n),
|
||||||
None => agent.fit_window(hx_ai::models::window(&models, agent.model())),
|
None => agent.fit_window(hx_ai::models::window(&models, agent.model())),
|
||||||
}
|
}
|
||||||
for e in &cfg.extensions {
|
let exts = futures::future::join_all(cfg.extensions.iter().map(|e| async {
|
||||||
let x = hx_core::ext::Extension::start(e, &cwd)
|
hx_core::ext::Extension::start(e, &cwd)
|
||||||
.await
|
.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() {
|
for t in x.tools() {
|
||||||
agent.tools.add(t);
|
agent.tools.add(t);
|
||||||
}
|
}
|
||||||
@@ -679,18 +709,18 @@ async fn main() -> Result<()> {
|
|||||||
.collect();
|
.collect();
|
||||||
mgr.warm(probe).await;
|
mgr.warm(probe).await;
|
||||||
}
|
}
|
||||||
|
trace("lens");
|
||||||
{
|
{
|
||||||
// children get the parent's tools as of now (no `task`, so no recursion)
|
// children get the parent's tools as of now (no `task`, so no recursion)
|
||||||
let mut general = agent.tools.clone();
|
let mut general = agent.tools.clone();
|
||||||
general.retain(|n| n != "ask_user");
|
general.retain(|n| n != "ask_user");
|
||||||
let mut explore = agent.tools.clone();
|
let mut explore = agent.tools.clone();
|
||||||
explore.retain(|n| hx_core::subagent::EXPLORE_TOOLS.contains(&n));
|
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 {
|
let role = |model: String, tools, base: &str| hx_core::subagent::Role {
|
||||||
provider: provider(kind).expect("provider worked above"),
|
provider: provider(kind).expect("provider worked above"),
|
||||||
model,
|
model,
|
||||||
tools,
|
tools,
|
||||||
system: context::system_prompt(Some(base), &home, &cwd),
|
system: format!("{base}{tail}"),
|
||||||
};
|
};
|
||||||
let cheap = cfg
|
let cheap = cfg
|
||||||
.explore_model
|
.explore_model
|
||||||
@@ -713,6 +743,7 @@ async fn main() -> Result<()> {
|
|||||||
agent.tools.add(task);
|
agent.tools.add(task);
|
||||||
}
|
}
|
||||||
let specs = command_specs(&mcp, &cwd, &models, &kinds);
|
let specs = command_specs(&mcp, &cwd, &models, &kinds);
|
||||||
|
trace("ready");
|
||||||
if cli.mode == Mode::Rpc {
|
if cli.mode == Mode::Rpc {
|
||||||
let r = rpc::serve(
|
let r = rpc::serve(
|
||||||
agent,
|
agent,
|
||||||
|
|||||||
@@ -162,7 +162,16 @@ pub fn skill_index_line(k: &Skill) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn system_prompt(base: Option<&str>, home: &Path, cwd: &Path) -> 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()));
|
s.push_str(&format!("\n\nWorking directory: {}", cwd.display()));
|
||||||
let sk = skills(home, cwd);
|
let sk = skills(home, cwd);
|
||||||
for k in sk.iter().filter(|k| k.load == Load::Always) {
|
for k in sk.iter().filter(|k| k.load == Load::Always) {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ use tokio::sync::Mutex;
|
|||||||
pub const EAGER_MAX_TOKENS: usize = 400;
|
pub const EAGER_MAX_TOKENS: usize = 400;
|
||||||
/// Max characters of tool output returned to the model.
|
/// Max characters of tool output returned to the model.
|
||||||
pub const OUTPUT_CAP: usize = 30_000;
|
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;
|
const MAX_RESTARTS: u32 = 3;
|
||||||
|
|
||||||
pub struct Slot {
|
pub struct Slot {
|
||||||
|
|||||||
Reference in new issue
Block a user