Craft Anything: understand how any software works, and craft your own.
Rust
Find an agent's chosen program again after an update moves it (#729)
BFlat0c79f957fadd
diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rsindex 81a603f1..d5d02036 100644--- a/crates/ai/src/cli_agents/mod.rs+++ b/crates/ai/src/cli_agents/mod.rs@@ -55,6 +55,36 @@ pub fn program_for(agent: &str) -> String {KNOWN.iter().find(|(id, _, _)| *id == agent).map(|(_, p, _)| p.to_string()).unwrap_or_else(|| agent.to_string())}+/// The program a backend runs: the one chosen for it, else the agent's usual name. A chosen path+/// that's gone from this computer is looked for again (#721): an agent that installs each version+/// in a folder of its own (Codex's `bin/<build>/codex.exe`) moves on every update, so the same file+/// in the newest folder beside the old one is used, else the usual name on PATH. On another+/// computer (ssh) the chosen command is used as it is.+pub fn program_of(config: &BackendConfig, options: &BackendOptions) -> String {+ let usual = program_for(&config.model);+ let Some(chosen) = options.command.as_deref().map(str::trim).filter(|c| !c.is_empty()) else { return usual };+ let local = config.ssh_host.as_deref().is_none_or(|h| h.trim().is_empty());+ let path = Path::new(chosen);+ if !local || path.parent().is_none_or(|p| p.as_os_str().is_empty()) || path.exists() {+ return chosen.to_string();+ }+ moved_program(path).or_else(|| craft_anything_platform::which(&usual).map(|_| usual)).unwrap_or_else(|| chosen.to_string())+}++/// The same file in the most recently changed sibling of its missing folder, if there is one.+fn moved_program(missing: &Path) -> Option<String> {+ let file = missing.file_name()?;+ let versions = missing.parent()?.parent()?;+ std::fs::read_dir(versions)+ .ok()?+ .flatten()+ .take(256)+ .map(|e| e.path().join(file))+ .filter(|p| p.is_file())+ .max_by_key(|p| p.metadata().and_then(|m| m.modified()).ok())+ .map(|p| p.display().to_string())+}+pub fn display_for(agent: &str) -> String {KNOWN.iter().find(|(id, _, _)| *id == agent).map(|(_, _, d)| d.to_string()).unwrap_or_else(|| agent.to_string())}@@ -510,7 +540,7 @@ fn acp_for(spec: &CliSpec) -> Option<AcpConversation> {}let local = spec.config.ssh_host.as_deref().is_none_or(|h| h.trim().is_empty());let acp_args = selected_acp_args(adapter.as_ref(), &agent, &spec.options).filter(|_| local)?;- let program = spec.options.command.clone().unwrap_or_else(|| program_for(&agent));+ let program = program_of(&spec.config, &spec.options);let access = match (spec.question, spec.deep, spec.builder.is_some()) {(true, true, _) => Access::Question,(true, false, _) => Access::CleanRoomQuestion,@@ -713,7 +743,7 @@ fn run_cli(spec: &CliSpec, text: &str, retry: bool, tx: &Sender<AgentEvent>, stolet RunState { session, verified, lost, failure } = state;let name = spec.config.name.clone();let agent = spec.config.model.clone();- let program = spec.options.command.clone().unwrap_or_else(|| program_for(&agent));+ let program = program_of(&spec.config, &spec.options);let remote = spec.config.ssh_host.clone().filter(|h| !h.trim().is_empty());// A folder chosen for it is on the computer it runs on: on another one, it's set below.let mut adapter = match remote {@@ -1065,6 +1095,33 @@ impl Drop for CliConversation {mod tests {use super::*;+ /// #721: Codex's desktop app keeps its CLI in `bin/<build>/codex.exe` and moves it on every+ /// update; a backend set to the old path kept failing on a file that was gone.+ #[test]+ fn a_chosen_program_that_moved_with_an_update_is_found_again() {+ let d = tempfile::tempdir().unwrap();+ let bin = d.path().join("Codex/bin");+ let new = bin.join("build-2").join("codex.exe");+ std::fs::create_dir_all(new.parent().unwrap()).unwrap();+ std::fs::write(&new, b"").unwrap();+ let gone = bin.join("build-1").join("codex.exe");+ let config = |ssh: Option<&str>| BackendConfig {+ name: "Codex".into(),+ kind: crate::BackendKind::AgentCli,+ model: "codex".into(),+ base_url: None,+ ssh_host: ssh.map(str::to_string),+ enabled: true,+ };+ let chosen = |p: &Path| BackendOptions { command: Some(p.display().to_string()), ..Default::default() };+ assert_eq!(program_of(&config(None), &chosen(&gone)), new.display().to_string(), "the same file in the newer build folder");+ assert_eq!(program_of(&config(None), &chosen(&new)), new.display().to_string(), "a path that's there is used as it is");+ assert_eq!(program_of(&config(Some("box")), &chosen(&gone)), gone.display().to_string(), "another computer's path isn't checked here");+ assert_eq!(program_of(&config(None), &BackendOptions::default()), "codex", "nothing chosen: the usual name");+ let bare = BackendOptions { command: Some("my-codex".into()), ..Default::default() };+ assert_eq!(program_of(&config(None), &bare), "my-codex", "a bare name is left to PATH");+ }+#[test]fn failed_craft_tool_server_is_reported_from_its_init_status() {let mut p = StreamParser::new(adapter_for("claude-code"));diff --git a/crates/ai/src/cli_agents/models.rs b/crates/ai/src/cli_agents/models.rsindex 16b700a4..5706cd9d 100644--- a/crates/ai/src/cli_agents/models.rs+++ b/crates/ai/src/cli_agents/models.rs@@ -106,7 +106,7 @@ pub(crate) fn query_args(options: &BackendOptions) -> Result<Vec<String>, ToolEr/// Select the configured executable and catalogue location, quoting SSH arguments for the remote shell./// Local queries use the supplied directory or current directory; SSH queries expand remote `$PWD`.fn query_command(config: &BackendConfig, options: &BackendOptions, directory: Option<&Path>) -> Result<(String, Vec<String>), ToolError> {- let program = options.command.clone().unwrap_or_else(|| super::program_for(&config.model));+ let program = super::program_of(config, options);let mut args = query_args(options)?;match config.ssh_host.as_deref().filter(|h| !h.trim().is_empty()) {Some(host) => {diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rsindex 08586712..d4a6b231 100644--- a/crates/ai/src/lib.rs+++ b/crates/ai/src/lib.rs@@ -909,7 +909,7 @@ impl AiHub {let e = self.entry(name)?;let start = Instant::now();if e.config.kind == BackendKind::AgentCli {- let program = e.options.command.clone().unwrap_or_else(|| cli_agents::program_for(&e.config.model));+ let program = cli_agents::program_of(&e.config, &e.options);let p = match e.config.ssh_host.as_deref().filter(|h| !h.trim().is_empty()) {Some(h) => craft_anything_platform::Process::new("ssh").args(ssh::ssh_args(h, &[program.clone(), "--version".into()])),None => craft_anything_platform::Process::new(&program).arg("--version"),@@ -1020,7 +1020,7 @@ fn reach(e: &BackendEntry, key: Option<String>) -> Result<u64, String> {}}BackendKind::AgentCli => {- let program = e.options.command.clone().unwrap_or_else(|| cli_agents::program_for(&e.config.model));+ let program = cli_agents::program_of(&e.config, &e.options);craft_anything_platform::which(&program).map(|_| ()).ok_or_else(|| format!("{program} isn't on PATH"))}};diff --git a/crates/ai/src/rebuild/mod.rs b/crates/ai/src/rebuild/mod.rsindex 1a0edecf..0a9afcd4 100644--- a/crates/ai/src/rebuild/mod.rs+++ b/crates/ai/src/rebuild/mod.rs@@ -613,7 +613,7 @@ impl Worker {if !remote && api.is_none() {let adapter = opts.adapters.for_backend(&entry.config.model, &entry.options);crate::cli_agents::check_builder_tools(adapter.as_ref(), &entry.config.model, &entry.options, &self.stop)?;- let program = entry.options.command.clone().unwrap_or_else(|| crate::cli_agents::program_for(&entry.config.model));+ let program = crate::cli_agents::program_of(&entry.config, &entry.options);if adapter.signed_in(&program) == Some(false) {return Err(ToolError::new(ErrorCode::BadSettings, not_signed_in(&entry.config.model, adapter.signed_in_before())).with_remediation(adapter.sign_in_fix().unwrap_or_default()));