Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(host): start an installed agent without downloading another (#203)

ForwardXu581469247404
diff --git a/host/src/agent/auth.rs b/host/src/agent/auth.rs
index c928f913..7b1eb654 100644
--- a/host/src/agent/auth.rs
+++ b/host/src/agent/auth.rs
@@ -16,7 +16,7 @@
use crate::LockExt;
use crate::agent::acp::{AUTH_REQUIRED, Acp, Incoming, RpcError};
use crate::agent::backends;
-use crate::agent::registry::{Cmd, env_prefix};
+use crate::agent::registry::{Candidate, Cmd, env_prefix};
use crate::shell::quote as shell_quote;
use crate::store::Store;
use anyhow::{Context, Result, anyhow, bail};
@@ -296,19 +296,26 @@ async fn reported_login(inbox: &mut mpsc::UnboundedReceiver<Incoming>) -> Option
type Started = (Arc<Acp>, mpsc::UnboundedReceiver<Incoming>, Value, Cmd);
async fn start(store: &Store, backend: &str) -> Result<Started> {
+ let mut candidates = backends::launch_candidates(backend)?;
// The installed CLI alone when there is one: resolving the registry build can mean a long download.
- let candidates = match backends::local_candidate(backend) {
- Some(local) => vec![local],
- None => backends::launch_candidates(backend, |_| {}).await?,
- };
+ if matches!(candidates.first(), Some(Candidate::Ready(_))) {
+ candidates.truncate(1);
+ }
let env = env(store, backend)?;
let dir = probe_dir();
tokio::fs::create_dir_all(&dir).await?;
let mut last = None;
let count = candidates.len();
- for (i, cmd) in candidates.into_iter().enumerate() {
+ for (i, candidate) in candidates.into_iter().enumerate() {
// A first `npx` run downloads the package: give the last candidate time.
let budget = Duration::from_secs(if i + 1 < count { 20 } else { 180 });
+ let cmd = match candidate.resolve(|_| {}).await {
+ Ok(cmd) => cmd,
+ Err(e) => {
+ last = Some(e);
+ continue;
+ }
+ };
let (acp, mut rx) = match Acp::spawn(&cmd.acp(), &dir.to_string_lossy(), &env) {
Ok(v) => v,
Err(e) => {
diff --git a/host/src/agent/backends.rs b/host/src/agent/backends.rs
index 5abe6bce..598159d4 100644
--- a/host/src/agent/backends.rs
+++ b/host/src/agent/backends.rs
@@ -4,7 +4,9 @@
//! shell (GUI apps and launchd get a bare PATH), add the usual install dirs
//! (Homebrew, ~/.local/bin, nvm, bun, volta, asdf, mise, pnpm…), then look for
//! each known CLI. Launching prefers the installed CLI's own ACP mode and falls
-//! back to the official ACP registry build (npx / uvx / downloaded binary).
+//! back to the official ACP registry build (npx / uvx / downloaded binary), which
+//! is resolved only when it's tried: an installed CLI that starts never downloads
+//! a second copy.
use crate::agent::{acp, node, registry};
use crate::shell;
@@ -504,19 +506,16 @@ pub fn is_known(id: &str) -> bool {
harness(id).is_some() || registry::agent(id).is_some()
}
-/// Ways to start this backend, best first. Local CLIs can be too old to speak
-/// ACP, so the registry build is kept as a fallback.
-pub async fn launch_candidates(id: &str, progress: impl Fn(&str)) -> anyhow::Result<Vec<registry::Cmd>> {
- let mut out: Vec<registry::Cmd> = local_candidate(id).into_iter().collect();
+/// Ways to start this backend, best first: the installed CLI's own ACP mode, then the
+/// registry build, for a CLI that isn't installed, has no ACP mode of its own, or is too old for it.
+pub fn launch_candidates(id: &str) -> anyhow::Result<Vec<registry::Candidate>> {
let h = harness(id);
- let reg_id = h.map_or(Some(id), |h| h.registry);
- if let Some(agent) = reg_id.and_then(registry::agent) {
- match registry::command(&agent, &progress).await {
- Ok(cmd) => out.push(cmd),
- Err(e) if out.is_empty() => return Err(e),
- Err(e) => tracing::info!(backend = id, error = format!("{e:#}"), "registry build unavailable"),
- }
- }
+ let build = h.map_or(Some(id), |h| h.registry).and_then(registry::agent);
+ let out: Vec<_> = local_candidate(id)
+ .map(registry::Candidate::Ready)
+ .into_iter()
+ .chain(build.map(registry::Candidate::Build))
+ .collect();
if out.is_empty() {
let hint = h.map_or("Check that it's installed on this computer.", |h| h.setup);
let name = h.map_or(id, |h| h.name);
@@ -563,7 +562,7 @@ pub async fn login_command(id: &str) -> anyhow::Result<String> {
}
/// The installed CLI's own ACP mode, if it has one and it's installed.
-pub fn local_candidate(id: &str) -> Option<registry::Cmd> {
+fn local_candidate(id: &str) -> Option<registry::Cmd> {
let h = harness(id)?;
let template = h.local?;
let path = h.bins.iter().find_map(|b| which(b))?;
@@ -572,20 +571,4 @@ pub fn local_candidate(id: &str) -> Option<registry::Cmd> {
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn every_harness_is_unique() {
- let ids: HashSet<_> = HARNESSES.iter().map(|h| h.id).collect();
- assert_eq!(ids.len(), HARNESSES.len());
- let bins: Vec<_> = HARNESSES.iter().flat_map(|h| h.bins).collect();
- assert_eq!(bins.iter().collect::<HashSet<_>>().len(), bins.len(), "a CLI belongs to one harness");
- }
-
- #[test]
- fn hermes_uses_native_acp() {
- let h = harness("hermes").unwrap();
- assert_eq!((h.local, h.registry, h.login), (Some("{bin} acp"), None, Some("{bin} acp --setup")));
- }
-}
+mod tests;
diff --git a/host/src/agent/backends/search_path.rs b/host/src/agent/backends/search_path.rs
index 836b338e..49d66888 100644
--- a/host/src/agent/backends/search_path.rs
+++ b/host/src/agent/backends/search_path.rs
@@ -130,6 +130,33 @@ pub fn on_path(bin: &str) -> bool {
which(bin).is_some()
}
+/// Serializes tests that replace the search path: `cargo test` runs them at once.
+#[cfg(test)]
+static TEST_LOCK: Mutex<()> = Mutex::new(());
+
+/// Holds the search path on `dir` until dropped, one test at a time.
+#[cfg(test)]
+#[must_use]
+pub(super) struct TestSearchPath {
+ _lock: std::sync::MutexGuard<'static, ()>,
+}
+
+#[cfg(test)]
+impl TestSearchPath {
+ pub(super) fn set(dir: PathBuf) -> Self {
+ let lock = TEST_LOCK.locked();
+ *SEARCH_PATH.locked() = vec![dir];
+ Self { _lock: lock }
+ }
+}
+
+#[cfg(test)]
+impl Drop for TestSearchPath {
+ fn drop(&mut self) {
+ SEARCH_PATH.locked().clear();
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -137,19 +164,15 @@ mod tests {
#[cfg(unix)]
#[test]
fn detects_executables_on_search_path() {
+ use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("codync-bin-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let bin = dir.join("fake-harness");
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
- *SEARCH_PATH.locked() = vec![dir.clone()];
+ let _path = TestSearchPath::set(dir.clone());
assert!(which("fake-harness").is_none(), "not executable yet");
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
- }
+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(which("fake-harness"), Some(bin));
- SEARCH_PATH.locked().clear();
}
#[test]
diff --git a/host/src/agent/backends/tests.rs b/host/src/agent/backends/tests.rs
new file mode 100644
index 00000000..e2240b0b
--- /dev/null
+++ b/host/src/agent/backends/tests.rs
@@ -0,0 +1,66 @@
+use super::search_path::TestSearchPath;
+use super::*;
+use std::path::PathBuf;
+
+struct TempDir(PathBuf);
+
+impl TempDir {
+ fn new() -> Self {
+ let path = std::env::temp_dir().join(format!("codync-bin-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&path).expect("create the fixture directory");
+ Self(path)
+ }
+}
+
+impl Drop for TempDir {
+ fn drop(&mut self) {
+ // Cleanup must not hide the test result when the directory is already gone.
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+/// An executable `name` the lookup can find. Windows only tries `.exe`, `.cmd`, and `.bat`.
+fn write_cli(dir: &Path, name: &str) {
+ let path = dir.join(if cfg!(windows) { format!("{name}.cmd") } else { name.to_owned() });
+ std::fs::write(&path, "#!/bin/sh\n").expect("write the fixture CLI");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("mark the fixture executable");
+ }
+}
+
+#[test]
+fn an_installed_cli_comes_before_the_registry_build() {
+ let dir = TempDir::new();
+ for name in ["codebuddy", "mcode", "cursor-agent"] {
+ write_cli(&dir.0, name);
+ }
+ let _path = TestSearchPath::set(dir.0.clone());
+ let builds = ["codebuddy-code", "minimax-code", "cursor"].map(|id| json!({"id": id}));
+ registry::set_cache(Some(json!({"agents": builds})));
+ let found = [("codebuddy", "codebuddy"), ("minimax", "mcode"), ("cursor", "cursor-agent")]
+ .map(|(id, bin)| (id, bin, launch_candidates(id)));
+ registry::set_cache(None);
+ for (id, bin, candidates) in found {
+ let candidates = candidates.expect("an installed CLI can start");
+ assert!(
+ matches!(&candidates[..], [registry::Candidate::Ready(cmd), registry::Candidate::Build(_)] if cmd.program.contains(bin)),
+ "{id}: the installed CLI first, the registry build kept for a CLI too old for ACP"
+ );
+ }
+}
+
+#[test]
+fn every_harness_is_unique() {
+ let ids: HashSet<_> = HARNESSES.iter().map(|h| h.id).collect();
+ assert_eq!(ids.len(), HARNESSES.len());
+ let bins: Vec<_> = HARNESSES.iter().flat_map(|h| h.bins).collect();
+ assert_eq!(bins.iter().collect::<HashSet<_>>().len(), bins.len(), "a CLI belongs to one harness");
+}
+
+#[test]
+fn hermes_uses_native_acp() {
+ let h = harness("hermes").unwrap();
+ assert_eq!((h.local, h.registry, h.login), (Some("{bin} acp"), None, Some("{bin} acp --setup")));
+}
diff --git a/host/src/agent/bot/launch.rs b/host/src/agent/bot/launch.rs
index f2a230d9..dc5798e9 100644
--- a/host/src/agent/bot/launch.rs
+++ b/host/src/agent/bot/launch.rs
@@ -3,6 +3,7 @@
use super::{Adapter, Conn, SessionCaps};
use crate::agent::acp::{self, Acp};
+use crate::agent::registry::{Candidate, Cmd};
use crate::store::BotConfig;
use anyhow::Result;
use serde_json::{Value, json};
@@ -35,16 +36,11 @@ fn claude_options(cfg: &BotConfig) -> Value {
json!({"options": {"settings": settings}})
}
-/// Shell commands that may start the bot's agent over ACP, best first.
-/// `progress` receives short status lines ("Downloading Cursor…").
-pub(crate) async fn launch_commands(cfg: &BotConfig, progress: impl Fn(&str)) -> Result<Vec<String>> {
+/// Ways to start the bot's agent over ACP, best first: its own command, else its backend's.
+pub(crate) fn launch_commands(cfg: &BotConfig) -> Result<Vec<Candidate>> {
Ok(match cfg.command.as_deref().map(str::trim) {
- Some(c) if !c.is_empty() => vec![c.to_owned()],
- _ => crate::agent::backends::launch_candidates(&cfg.backend, progress)
- .await?
- .iter()
- .map(crate::agent::registry::Cmd::acp)
- .collect(),
+ Some(c) if !c.is_empty() => vec![Candidate::Ready(Cmd { program: c.to_owned(), args: String::new() })],
+ _ => crate::agent::backends::launch_candidates(&cfg.backend)?,
})
}
diff --git a/host/src/agent/bot/session.rs b/host/src/agent/bot/session.rs
index 71929474..dbcd0b2a 100644
--- a/host/src/agent/bot/session.rs
+++ b/host/src/agent/bot/session.rs
@@ -5,6 +5,7 @@ use super::launch::{claude_meta, launch_commands, select_model, start_agent, sys
use super::{Actor, Conn, Instructions};
use crate::agent::acp::{self, Incoming};
use crate::agent::own_memory;
+use crate::agent::registry::Candidate;
use crate::chat::{context, memory};
use crate::store::run_session_key;
use anyhow::{Result, anyhow, bail};
@@ -105,6 +106,24 @@ impl Actor {
Ok(Value::Array(servers))
}
+ /// Starts the agent one way: resolved first (a registry build can download), with the harness's own memory set
+ /// for the bot.
+ async fn start_candidate(
+ &self,
+ candidate: Candidate,
+ env: &[(String, String)],
+ budget: Duration,
+ progress: impl Fn(&str),
+ ) -> Result<Conn> {
+ let mut command = [candidate.resolve(progress).await?.acp()];
+ self.hub.set_runtime(&self.id(), |r| r.activity = "Starting agent…".into());
+ let mut env = env.to_vec();
+ own_memory::apply(&self.cfg, &mut env, &mut command).await;
+ start_agent(&command[0], &self.cfg.cwd, &env, budget).await.inspect_err(|e| {
+ tracing::info!(command = command[0].as_str(), error = format!("{e:#}"), "agent failed to start");
+ })
+ }
+
/// Makes sure the agent runs and `slot`'s session (main, or a routine run's) is live;
/// sets `turn_session`.
pub(super) async fn ensure_session(&mut self, slot: Option<&str>) -> Result<()> {
@@ -122,34 +141,30 @@ impl Actor {
}
if self.conn.is_none() {
let (hub, id) = (self.hub.clone(), self.cfg.id.clone());
- let mut candidates = launch_commands(&self.cfg, move |msg: &str| {
+ let progress = move |msg: &str| {
let msg = msg.to_owned();
hub.set_runtime(&id, |r| r.activity = msg);
- })
- .await?;
- self.hub.set_runtime(&self.id(), |r| r.activity = "Starting agent…".into());
+ };
+ let candidates = launch_commands(&self.cfg)?;
// Keys saved from an "environment variable" sign-in.
let mut env = crate::agent::auth::env(&self.hub.store, &self.cfg.backend)?;
- own_memory::apply(&self.cfg, &mut env, &mut candidates).await;
if self.cfg.backend == "codex" && !env.iter().any(|(k, _)| k == "CODEX_CONFIG") {
// Codex's `/compact` takes no instructions: the keep-list is its config's `compact_prompt`.
let config = json!({"compact_prompt": codync_mem::compaction::KEEP});
env.push(("CODEX_CONFIG".into(), config.to_string()));
}
let mut last_err = None;
- for (i, command) in candidates.iter().enumerate() {
- let fallback_left = i + 1 < candidates.len();
+ let count = candidates.len();
+ for (i, candidate) in candidates.into_iter().enumerate() {
+ let fallback_left = i + 1 < count;
// A local CLI too old for ACP just hangs; don't make the user wait long before the fallback.
let budget = Duration::from_secs(if fallback_left { 20 } else { 180 });
- match start_agent(command, &self.cfg.cwd, &env, budget).await {
+ match self.start_candidate(candidate, &env, budget, &progress).await {
Ok(conn) => {
self.conn = Some(conn);
break;
}
- Err(e) => {
- tracing::info!(command, error = format!("{e:#}"), "agent failed to start");
- last_err = Some(e);
- }
+ Err(e) => last_err = Some(e),
}
}
if self.conn.is_none() {
diff --git a/host/src/agent/registry.rs b/host/src/agent/registry.rs
index 408334e5..364be66f 100644
--- a/host/src/agent/registry.rs
+++ b/host/src/agent/registry.rs
@@ -46,6 +46,12 @@ pub fn agent(id: &str) -> Option<Value> {
agents().into_iter().find(|a| a["id"] == id)
}
+/// Replaces the registry for a test, which serializes on `TestSearchPath` and puts `None` back.
+#[cfg(test)]
+pub(crate) fn set_cache(registry: Option<Value>) {
+ *CACHE.locked() = registry;
+}
+
pub async fn refresh_loop() {
loop {
match fetch().await {
@@ -144,7 +150,26 @@ pub struct Cmd {
impl Cmd {
/// The shell command that starts it over ACP stdio.
pub fn acp(&self) -> String {
- format!("{} {}", self.program, self.args)
+ if self.args.is_empty() { self.program.clone() } else { format!("{} {}", self.program, self.args) }
+ }
+}
+
+/// One way to start an agent. A registry build is resolved only when it's tried: that can mean a
+/// download, which an installed CLI that starts never needs.
+pub enum Candidate {
+ /// Runs as it is: an installed CLI's own ACP mode, or a bot's own command.
+ Ready(Cmd),
+ /// A registry agent, downloaded first if needed.
+ Build(Value),
+}
+
+impl Candidate {
+ /// `progress` receives short status lines ("Downloading Cursor…").
+ pub async fn resolve(self, progress: impl Fn(&str)) -> Result<Cmd> {
+ match self {
+ Self::Ready(cmd) => Ok(cmd),
+ Self::Build(agent) => command(&agent, progress).await,
+ }
}
}
diff --git a/host/src/chat/oneshot.rs b/host/src/chat/oneshot.rs
index 719cc9cc..501f83e4 100644
--- a/host/src/chat/oneshot.rs
+++ b/host/src/chat/oneshot.rs
@@ -21,13 +21,17 @@ pub async fn one_shot(hub: &Arc<Hub>, cfg: &BotConfig, system: &str, user: &str)
if hub.store.kv_read(&format!("agent-env:{}", cfg.backend))?.is_some() {
crate::market::vault::unlock(hub.clone()).await?;
}
- let mut env = crate::agent::auth::env(&hub.store, &cfg.backend)?;
- let mut commands = crate::agent::bot::launch_commands(cfg, |_| {}).await?;
- crate::agent::own_memory::turn_off(&cfg.backend, &cwd, &mut env, &mut commands).await;
+ let env = crate::agent::auth::env(&hub.store, &cfg.backend)?;
let mut conn = None;
let mut last_err = None;
- for command in commands {
- match crate::agent::bot::start_agent(&command, &cwd, &env, Duration::from_secs(60)).await {
+ for candidate in crate::agent::bot::launch_commands(cfg)? {
+ let started = async {
+ let mut command = [candidate.resolve(|_| {}).await?.acp()];
+ let mut env = env.clone();
+ crate::agent::own_memory::turn_off(&cfg.backend, &cwd, &mut env, &mut command).await;
+ crate::agent::bot::start_agent(&command[0], &cwd, &env, Duration::from_secs(60)).await
+ };
+ match started.await {
Ok(c) => {
conn = Some(c);
break;