| 1 | use std::collections::BTreeMap; |
| 2 | use std::ffi::OsStr; |
| 3 | use std::path::{Component, Path, PathBuf}; |
| 4 | use std::process::Stdio; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | use tokio::process::Command; |
| 8 | |
| 9 | pub const FIXTURE_AGENT_ENV: &str = "CODEWHALE_ACP_FIXTURE_AGENT"; |
| 10 | pub const FIXTURE_AGENT_ID: &str = "fixture"; |
| 11 | pub const CUSTOM_AGENTS_ENV: &str = "CODEWHALE_CUSTOM_ACP_AGENTS"; |
| 12 | pub const EXTERNAL_AGENT_TRANSPORT_ENV: &str = "CODEWHALE_EXTERNAL_AGENT_TRANSPORT"; |
| 13 | const VERSION_TIMEOUT: Duration = Duration::from_secs(30); |
| 14 | const MAX_VERSION_CHARS: usize = 80; |
| 15 | const MAX_VERSION_BYTES: usize = 8192; |
| 16 | const MAX_VERSION_STDERR_BYTES: usize = 64 * 1024; |
| 17 | const WINDOWS_SPAWNABLE_EXTENSIONS: &[&str] = &[".com", ".exe", ".bat", ".cmd"]; |
| 18 | #[cfg(any(windows, test))] |
| 19 | const WINDOWS_DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD"; |
| 20 | |
| 21 | #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] |
| 22 | #[error("{message}")] |
| 23 | pub struct ExecutorUnavailable { |
| 24 | pub code: &'static str, |
| 25 | pub message: String, |
| 26 | } |
| 27 | |
| 28 | impl ExecutorUnavailable { |
| 29 | pub const UNKNOWN_AGENT: &'static str = "unknown_agent"; |
| 30 | pub const NOT_INSTALLED: &'static str = "not_installed"; |
| 31 | pub const ADAPTER_MISSING: &'static str = "adapter_missing"; |
| 32 | pub const BELOW_MIN_VERSION: &'static str = "below_min_version"; |
| 33 | pub const NEEDS_SIGN_IN: &'static str = "needs_sign_in"; |
| 34 | pub const NO_ACP: &'static str = "no_acp"; |
| 35 | pub const VERSION_UNKNOWN: &'static str = "version_unknown"; |
| 36 | pub const EXECUTOR_NOT_SUPPORTED: &'static str = "executor_not_supported"; |
| 37 | pub const ENVIRONMENT_NOT_SUPPORTED: &'static str = "environment_not_supported"; |
| 38 | |
| 39 | pub fn new(code: &'static str, message: impl Into<String>) -> Self { |
| 40 | Self { |
| 41 | code, |
| 42 | message: message.into(), |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | pub use crate::external_agents::DirectCliKind; |
| 48 | |
| 49 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 50 | pub enum ExternalAgentTransport { |
| 51 | Acp, |
| 52 | DirectCli(DirectCliKind), |
| 53 | } |
| 54 | |
| 55 | impl ExternalAgentTransport { |
| 56 | pub const fn as_str(self) -> &'static str { |
| 57 | match self { |
| 58 | Self::Acp => "acp", |
| 59 | Self::DirectCli(_) => "cli", |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | #[derive(Debug)] |
| 65 | pub struct ExternalAgent { |
| 66 | pub id: &'static str, |
| 67 | pub name: &'static str, |
| 68 | pub binary: &'static str, |
| 69 | pub acp_args: Option<&'static [&'static str]>, |
| 70 | pub direct_cli: Option<DirectCliKind>, |
| 71 | pub website: &'static str, |
| 72 | pub min_version: Option<&'static str>, |
| 73 | pub upgrade: Option<&'static str>, |
| 74 | pub login: Option<&'static str>, |
| 75 | pub adapter: Option<&'static str>, |
| 76 | pub adapter_binary: Option<&'static str>, |
| 77 | pub adapter_cli_env: Option<&'static str>, |
| 78 | } |
| 79 | |
| 80 | pub fn available_direct_cli(agent: &ExternalAgent) -> bool { |
| 81 | agent.direct_cli.is_some() |
| 82 | } |
| 83 | |
| 84 | impl ExternalAgent { |
| 85 | pub fn process_env(&self) -> BTreeMap<String, String> { |
| 86 | let vars: &[(&str, &str)] = match self.id { |
| 87 | "auggie" => &[("AUGMENT_DISABLE_AUTO_UPDATE", "1")], |
| 88 | "factory-droid" => &[ |
| 89 | ("DROID_DISABLE_AUTO_UPDATE", "true"), |
| 90 | ("FACTORY_DROID_AUTO_UPDATE_ENABLED", "false"), |
| 91 | ], |
| 92 | _ => &[], |
| 93 | }; |
| 94 | vars.iter() |
| 95 | .map(|&(key, value)| (key.into(), value.into())) |
| 96 | .collect() |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)] |
| 101 | pub struct CustomExternalAgent { |
| 102 | pub id: String, |
| 103 | pub name: String, |
| 104 | pub binary: String, |
| 105 | #[serde(default)] |
| 106 | pub args: Vec<String>, |
| 107 | #[serde(default)] |
| 108 | pub transport: Option<String>, |
| 109 | #[serde(default)] |
| 110 | pub website: String, |
| 111 | #[serde(default)] |
| 112 | pub env: BTreeMap<String, String>, |
| 113 | } |
| 114 | |
| 115 | pub const AGENTS: &[ExternalAgent] = &[ |
| 116 | ExternalAgent { |
| 117 | id: "claude", |
| 118 | name: "Claude Agent", |
| 119 | binary: "claude", |
| 120 | acp_args: None, |
| 121 | direct_cli: Some(DirectCliKind::Claude), |
| 122 | website: "https://github.com/agentclientprotocol/claude-agent-acp", |
| 123 | min_version: Some("2.1.226"), |
| 124 | upgrade: Some("npm i -g @anthropic-ai/claude-code@latest"), |
| 125 | login: Some("claude auth login"), |
| 126 | adapter: Some("@agentclientprotocol/claude-agent-acp"), |
| 127 | adapter_binary: Some("claude-agent-acp"), |
| 128 | adapter_cli_env: Some("CLAUDE_CODE_EXECUTABLE"), |
| 129 | }, |
| 130 | ExternalAgent { |
| 131 | id: "codex", |
| 132 | name: "Codex", |
| 133 | binary: "codex", |
| 134 | acp_args: None, |
| 135 | direct_cli: Some(DirectCliKind::Codex), |
| 136 | website: "https://github.com/agentclientprotocol/codex-acp", |
| 137 | min_version: Some("0.160.0"), |
| 138 | upgrade: Some("npm i -g @openai/codex@latest"), |
| 139 | login: Some("codex login"), |
| 140 | adapter: Some("@agentclientprotocol/codex-acp"), |
| 141 | adapter_binary: Some("codex-acp"), |
| 142 | adapter_cli_env: Some("CODEX_PATH"), |
| 143 | }, |
| 144 | ExternalAgent { |
| 145 | id: "dsh", |
| 146 | name: "DeepSeek Harness", |
| 147 | binary: "dsh", |
| 148 | acp_args: Some(&["acp"]), |
| 149 | direct_cli: None, |
| 150 | website: "https://github.com/deepseek-ai/deepseek-harness", |
| 151 | min_version: None, |
| 152 | upgrade: Some("npm i -g @deepseek-ai/dsh@latest"), |
| 153 | login: None, |
| 154 | adapter: None, |
| 155 | adapter_binary: None, |
| 156 | adapter_cli_env: None, |
| 157 | }, |
| 158 | ExternalAgent { |
| 159 | id: "antigravity", |
| 160 | name: "Antigravity", |
| 161 | binary: "agy", |
| 162 | acp_args: Some(&["acp"]), |
| 163 | direct_cli: Some(DirectCliKind::Antigravity), |
| 164 | website: "https://antigravity.google/docs/cli/acp/", |
| 165 | min_version: Some("1.5.0"), |
| 166 | upgrade: Some("agy update"), |
| 167 | login: Some("agy acp --login"), |
| 168 | adapter: None, |
| 169 | adapter_binary: None, |
| 170 | adapter_cli_env: None, |
| 171 | }, |
| 172 | ExternalAgent { |
| 173 | id: "cursor", |
| 174 | name: "Cursor", |
| 175 | binary: "cursor-agent", |
| 176 | acp_args: Some(&["acp"]), |
| 177 | direct_cli: None, |
| 178 | website: "https://cursor.com/docs/cli/acp", |
| 179 | min_version: None, |
| 180 | upgrade: None, |
| 181 | login: Some("cursor-agent login"), |
| 182 | adapter: None, |
| 183 | adapter_binary: None, |
| 184 | adapter_cli_env: None, |
| 185 | }, |
| 186 | ExternalAgent { |
| 187 | id: "cline", |
| 188 | name: "Cline", |
| 189 | binary: "cline", |
| 190 | acp_args: Some(&["--acp"]), |
| 191 | direct_cli: None, |
| 192 | website: "https://cline.bot/cli", |
| 193 | min_version: Some("3.0.73"), |
| 194 | upgrade: Some("npm i -g cline@latest"), |
| 195 | login: Some("cline auth"), |
| 196 | adapter: None, |
| 197 | adapter_binary: None, |
| 198 | adapter_cli_env: None, |
| 199 | }, |
| 200 | ExternalAgent { |
| 201 | id: "devin", |
| 202 | name: "Devin", |
| 203 | binary: "devin", |
| 204 | acp_args: Some(&["acp"]), |
| 205 | direct_cli: None, |
| 206 | website: "https://docs.devin.ai/cli", |
| 207 | min_version: None, |
| 208 | upgrade: None, |
| 209 | login: Some("devin login"), |
| 210 | adapter: None, |
| 211 | adapter_binary: None, |
| 212 | adapter_cli_env: None, |
| 213 | }, |
| 214 | ExternalAgent { |
| 215 | id: "opencode", |
| 216 | name: "OpenCode", |
| 217 | binary: "opencode", |
| 218 | acp_args: Some(&["acp"]), |
| 219 | direct_cli: None, |
| 220 | website: "https://opencode.ai", |
| 221 | min_version: Some("1.15.5"), |
| 222 | upgrade: Some("npm i -g opencode-ai@latest"), |
| 223 | login: Some("opencode auth login"), |
| 224 | adapter: None, |
| 225 | adapter_binary: None, |
| 226 | adapter_cli_env: None, |
| 227 | }, |
| 228 | ExternalAgent { |
| 229 | id: "goose", |
| 230 | name: "Goose", |
| 231 | binary: "goose", |
| 232 | acp_args: Some(&["acp"]), |
| 233 | direct_cli: None, |
| 234 | website: "https://block.github.io/goose/", |
| 235 | min_version: Some("1.56.0"), |
| 236 | upgrade: None, |
| 237 | login: Some("goose configure"), |
| 238 | adapter: None, |
| 239 | adapter_binary: None, |
| 240 | adapter_cli_env: None, |
| 241 | }, |
| 242 | ExternalAgent { |
| 243 | id: "junie", |
| 244 | name: "Junie", |
| 245 | binary: "junie", |
| 246 | acp_args: Some(&["--acp=true"]), |
| 247 | direct_cli: None, |
| 248 | website: "https://junie.jetbrains.com", |
| 249 | min_version: None, |
| 250 | upgrade: None, |
| 251 | login: Some("junie login"), |
| 252 | adapter: None, |
| 253 | adapter_binary: None, |
| 254 | adapter_cli_env: None, |
| 255 | }, |
| 256 | ExternalAgent { |
| 257 | id: "amp", |
| 258 | name: "Amp", |
| 259 | binary: "amp-acp", |
| 260 | acp_args: Some(&[]), |
| 261 | direct_cli: None, |
| 262 | website: "https://github.com/tao12345666333/amp-acp", |
| 263 | min_version: None, |
| 264 | upgrade: None, |
| 265 | login: Some("amp login"), |
| 266 | adapter: None, |
| 267 | adapter_binary: None, |
| 268 | adapter_cli_env: None, |
| 269 | }, |
| 270 | ExternalAgent { |
| 271 | id: "auggie", |
| 272 | name: "Auggie CLI", |
| 273 | binary: "auggie", |
| 274 | acp_args: Some(&["--acp"]), |
| 275 | direct_cli: None, |
| 276 | website: "https://www.augmentcode.com/", |
| 277 | min_version: Some("0.36.0"), |
| 278 | upgrade: Some("npm i -g @augmentcode/auggie@latest"), |
| 279 | login: Some("auggie login"), |
| 280 | adapter: None, |
| 281 | adapter_binary: None, |
| 282 | adapter_cli_env: None, |
| 283 | }, |
| 284 | ExternalAgent { |
| 285 | id: "kimi", |
| 286 | name: "Kimi Code", |
| 287 | binary: "kimi", |
| 288 | acp_args: Some(&["acp"]), |
| 289 | direct_cli: None, |
| 290 | website: "https://moonshotai.github.io/kimi-code/", |
| 291 | min_version: None, |
| 292 | upgrade: Some("kimi upgrade"), |
| 293 | login: Some("kimi login"), |
| 294 | adapter: None, |
| 295 | adapter_binary: None, |
| 296 | adapter_cli_env: None, |
| 297 | }, |
| 298 | ExternalAgent { |
| 299 | id: "mistral-vibe", |
| 300 | name: "Mistral Vibe", |
| 301 | binary: "vibe-acp", |
| 302 | acp_args: Some(&[]), |
| 303 | direct_cli: None, |
| 304 | website: "https://mistral.ai/products/vibe", |
| 305 | min_version: None, |
| 306 | upgrade: None, |
| 307 | login: None, |
| 308 | adapter: None, |
| 309 | adapter_binary: None, |
| 310 | adapter_cli_env: None, |
| 311 | }, |
| 312 | ExternalAgent { |
| 313 | id: "qoder", |
| 314 | name: "Qoder", |
| 315 | binary: "qodercli", |
| 316 | acp_args: Some(&["--acp"]), |
| 317 | direct_cli: None, |
| 318 | website: "https://qoder.com", |
| 319 | min_version: None, |
| 320 | upgrade: Some("qodercli update"), |
| 321 | login: Some("qodercli login"), |
| 322 | adapter: None, |
| 323 | adapter_binary: None, |
| 324 | adapter_cli_env: None, |
| 325 | }, |
| 326 | ExternalAgent { |
| 327 | id: "codebuddy", |
| 328 | name: "CodeBuddy", |
| 329 | binary: "codebuddy", |
| 330 | acp_args: Some(&["--acp"]), |
| 331 | direct_cli: None, |
| 332 | website: "https://www.codebuddy.cn/cli/", |
| 333 | min_version: None, |
| 334 | upgrade: None, |
| 335 | login: None, |
| 336 | adapter: None, |
| 337 | adapter_binary: None, |
| 338 | adapter_cli_env: None, |
| 339 | }, |
| 340 | ExternalAgent { |
| 341 | id: "grok", |
| 342 | name: "Grok", |
| 343 | binary: "grok", |
| 344 | acp_args: Some(&["agent", "stdio"]), |
| 345 | direct_cli: Some(DirectCliKind::Grok), |
| 346 | website: "https://x.ai/cli", |
| 347 | min_version: None, |
| 348 | upgrade: Some("grok update"), |
| 349 | login: Some("grok login"), |
| 350 | adapter: None, |
| 351 | adapter_binary: None, |
| 352 | adapter_cli_env: None, |
| 353 | }, |
| 354 | ExternalAgent { |
| 355 | id: "qwen-code", |
| 356 | name: "Qwen Code", |
| 357 | binary: "qwen", |
| 358 | acp_args: Some(&["--acp"]), |
| 359 | direct_cli: None, |
| 360 | website: "https://github.com/QwenLM/qwen-code", |
| 361 | min_version: Some("0.6.1"), |
| 362 | upgrade: Some("npm i -g @qwen-code/qwen-code@latest"), |
| 363 | login: None, |
| 364 | adapter: None, |
| 365 | adapter_binary: None, |
| 366 | adapter_cli_env: None, |
| 367 | }, |
| 368 | ExternalAgent { |
| 369 | id: "copilot", |
| 370 | name: "GitHub Copilot CLI", |
| 371 | binary: "copilot", |
| 372 | acp_args: Some(&["--acp", "--stdio"]), |
| 373 | direct_cli: None, |
| 374 | website: "https://docs.github.com/copilot/reference/copilot-cli-reference/acp-server", |
| 375 | min_version: None, |
| 376 | upgrade: Some("copilot update"), |
| 377 | login: Some("copilot login"), |
| 378 | adapter: None, |
| 379 | adapter_binary: None, |
| 380 | adapter_cli_env: None, |
| 381 | }, |
| 382 | ExternalAgent { |
| 383 | id: "muse", |
| 384 | name: "Muse Code", |
| 385 | binary: "muse", |
| 386 | acp_args: Some(&["acp"]), |
| 387 | direct_cli: None, |
| 388 | website: "https://dev.meta.ai/products/muse-code", |
| 389 | min_version: None, |
| 390 | upgrade: None, |
| 391 | login: Some("muse login"), |
| 392 | adapter: None, |
| 393 | adapter_binary: None, |
| 394 | adapter_cli_env: None, |
| 395 | }, |
| 396 | ExternalAgent { |
| 397 | id: "minimax-code", |
| 398 | name: "MiniMax Code", |
| 399 | binary: "minimax-code", |
| 400 | acp_args: Some(&["acp"]), |
| 401 | direct_cli: None, |
| 402 | website: "https://agent.minimax.io", |
| 403 | min_version: Some("0.2.7"), |
| 404 | upgrade: Some("npm i -g @minimax-ai/code@latest"), |
| 405 | login: None, |
| 406 | adapter: None, |
| 407 | adapter_binary: None, |
| 408 | adapter_cli_env: None, |
| 409 | }, |
| 410 | ExternalAgent { |
| 411 | id: "deepagents", |
| 412 | name: "DeepAgents", |
| 413 | binary: "deepagents-acp", |
| 414 | acp_args: Some(&[]), |
| 415 | direct_cli: None, |
| 416 | website: "https://docs.langchain.com/oss/javascript/deepagents/overview", |
| 417 | min_version: Some("0.1.7"), |
| 418 | upgrade: Some("npm i -g deepagents-acp@latest"), |
| 419 | login: None, |
| 420 | adapter: None, |
| 421 | adapter_binary: None, |
| 422 | adapter_cli_env: None, |
| 423 | }, |
| 424 | ExternalAgent { |
| 425 | id: "factory-droid", |
| 426 | name: "Factory Droid", |
| 427 | binary: "droid", |
| 428 | acp_args: Some(&["exec", "--output-format", "acp-daemon"]), |
| 429 | direct_cli: None, |
| 430 | website: "https://factory.ai/product/cli", |
| 431 | min_version: Some("0.249.0"), |
| 432 | upgrade: Some("npm update -g @factory/cli"), |
| 433 | login: Some("droid login"), |
| 434 | adapter: None, |
| 435 | adapter_binary: None, |
| 436 | adapter_cli_env: None, |
| 437 | }, |
| 438 | ExternalAgent { |
| 439 | id: "pi-acp", |
| 440 | name: "Pi", |
| 441 | binary: "pi", |
| 442 | acp_args: None, |
| 443 | direct_cli: None, |
| 444 | website: "https://github.com/svkozak/pi-acp", |
| 445 | min_version: None, |
| 446 | upgrade: None, |
| 447 | login: None, |
| 448 | adapter: Some("pi-acp"), |
| 449 | adapter_binary: Some("pi-acp"), |
| 450 | adapter_cli_env: None, |
| 451 | }, |
| 452 | ]; |
| 453 | |
| 454 | const FIXTURE_AGENT: ExternalAgent = ExternalAgent { |
| 455 | id: FIXTURE_AGENT_ID, |
| 456 | name: "ACP fixture agent", |
| 457 | binary: "node", |
| 458 | acp_args: None, |
| 459 | direct_cli: None, |
| 460 | website: "", |
| 461 | min_version: None, |
| 462 | upgrade: None, |
| 463 | login: None, |
| 464 | adapter: None, |
| 465 | adapter_binary: None, |
| 466 | adapter_cli_env: None, |
| 467 | }; |
| 468 | |
| 469 | pub fn custom_agents() -> Vec<CustomExternalAgent> { |
| 470 | let mut combined = std::env::var(CUSTOM_AGENTS_ENV) |
| 471 | .ok() |
| 472 | .map_or_else(Vec::new, |raw| parse_custom_agents_raw(&raw)); |
| 473 | combined.extend(config_custom_agents()); |
| 474 | filter_custom_agents(combined) |
| 475 | } |
| 476 | |
| 477 | fn config_custom_agents() -> Vec<CustomExternalAgent> { |
| 478 | let Ok(config) = codewhale_runtime::config::Config::load_with( |
| 479 | None, |
| 480 | None, |
| 481 | codewhale_runtime::config::ConfigEnvironmentPolicy::StructuralDiagnostic, |
| 482 | &mut |_| Ok(()), |
| 483 | ) else { |
| 484 | return Vec::new(); |
| 485 | }; |
| 486 | config |
| 487 | .external_agents |
| 488 | .into_iter() |
| 489 | .map(|entry| CustomExternalAgent { |
| 490 | id: entry.id, |
| 491 | name: entry.name, |
| 492 | binary: entry.binary, |
| 493 | args: entry.args, |
| 494 | transport: entry.transport, |
| 495 | website: entry.website, |
| 496 | env: entry.env, |
| 497 | }) |
| 498 | .collect() |
| 499 | } |
| 500 | |
| 501 | fn parse_custom_agents_raw(raw: &str) -> Vec<CustomExternalAgent> { |
| 502 | if raw.len() > 64 * 1024 { |
| 503 | return Vec::new(); |
| 504 | } |
| 505 | serde_json::from_str::<Vec<CustomExternalAgent>>(raw).unwrap_or_default() |
| 506 | } |
| 507 | |
| 508 | #[cfg(test)] |
| 509 | fn parse_custom_agents(raw: &str) -> Vec<CustomExternalAgent> { |
| 510 | filter_custom_agents(parse_custom_agents_raw(raw)) |
| 511 | } |
| 512 | |
| 513 | fn filter_custom_agents(entries: Vec<CustomExternalAgent>) -> Vec<CustomExternalAgent> { |
| 514 | let mut seen = std::collections::BTreeSet::new(); |
| 515 | for builtin in AGENTS { |
| 516 | seen.insert(builtin.id.to_string()); |
| 517 | } |
| 518 | seen.insert(FIXTURE_AGENT_ID.to_string()); |
| 519 | entries |
| 520 | .into_iter() |
| 521 | .filter(|entry| { |
| 522 | let id = entry.id.as_str(); |
| 523 | !id.is_empty() |
| 524 | && id.len() <= 64 |
| 525 | && id |
| 526 | .chars() |
| 527 | .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_')) |
| 528 | && !entry.name.trim().is_empty() |
| 529 | && !entry.binary.trim().is_empty() |
| 530 | && !entry.name.chars().any(char::is_control) |
| 531 | && !entry.binary.chars().any(char::is_control) |
| 532 | && entry.args.iter().all(|arg| !arg.contains('\0')) |
| 533 | && entry |
| 534 | .transport |
| 535 | .as_deref() |
| 536 | .is_none_or(|transport| matches!(transport.trim(), "acp" | "cli")) |
| 537 | && (entry.website.is_empty() |
| 538 | || url::Url::parse(&entry.website).is_ok_and(|url| { |
| 539 | url.scheme() == "https" |
| 540 | && url.has_host() |
| 541 | && url.username().is_empty() |
| 542 | && url.password().is_none() |
| 543 | })) |
| 544 | && entry.env.iter().all(|(key, value)| { |
| 545 | !key.is_empty() |
| 546 | && key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') |
| 547 | && !key.to_ascii_uppercase().starts_with("CODEWHALE_") |
| 548 | && super::host::is_safe_env_key(key) |
| 549 | && !value.contains('\0') |
| 550 | }) |
| 551 | && seen.insert(id.to_string()) |
| 552 | }) |
| 553 | .take(32) |
| 554 | .collect() |
| 555 | } |
| 556 | |
| 557 | pub fn find_custom(id: &str) -> Option<CustomExternalAgent> { |
| 558 | custom_agents().into_iter().find(|entry| entry.id == id) |
| 559 | } |
| 560 | |
| 561 | pub fn find(id: &str) -> Option<&'static ExternalAgent> { |
| 562 | if id == FIXTURE_AGENT_ID { |
| 563 | return fixture_script().map(|_| &FIXTURE_AGENT); |
| 564 | } |
| 565 | AGENTS.iter().find(|agent| agent.id == id) |
| 566 | } |
| 567 | |
| 568 | pub fn agent_meta(id: &str) -> Option<(String, Option<&'static str>)> { |
| 569 | if let Some(agent) = find(id) { |
| 570 | return Some((agent.name.to_string(), agent.login)); |
| 571 | } |
| 572 | find_custom(id).map(|custom| (custom.name, None)) |
| 573 | } |
| 574 | |
| 575 | fn fixture_script() -> Option<PathBuf> { |
| 576 | std::env::var_os(FIXTURE_AGENT_ENV) |
| 577 | .map(PathBuf::from) |
| 578 | .filter(|path| path.is_absolute()) |
| 579 | } |
| 580 | |
| 581 | const USER_BIN_DIRS: &[&str] = &[ |
| 582 | ".local/bin", |
| 583 | ".npm-global/bin", |
| 584 | ".opencode/bin", |
| 585 | ".kimi-code/bin", |
| 586 | ".cursor/bin", |
| 587 | ".devin/bin", |
| 588 | ".bun/bin", |
| 589 | ".cargo/bin", |
| 590 | ]; |
| 591 | #[cfg(not(windows))] |
| 592 | const SYSTEM_BIN_DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/bin"]; |
| 593 | |
| 594 | fn search_dirs() -> Vec<PathBuf> { |
| 595 | let mut dirs: Vec<PathBuf> = std::env::var_os("PATH") |
| 596 | .map(|path| std::env::split_paths(&path).collect()) |
| 597 | .unwrap_or_default(); |
| 598 | let home = std::env::var_os("HOME"); |
| 599 | #[cfg(windows)] |
| 600 | let home = home.or_else(|| std::env::var_os("USERPROFILE")); |
| 601 | if let Some(home) = home.map(PathBuf::from) { |
| 602 | dirs.extend(USER_BIN_DIRS.iter().map(|dir| home.join(dir))); |
| 603 | } |
| 604 | #[cfg(windows)] |
| 605 | if let Some(appdata) = std::env::var_os("APPDATA") { |
| 606 | dirs.push(PathBuf::from(appdata).join("npm")); |
| 607 | } |
| 608 | #[cfg(not(windows))] |
| 609 | dirs.extend(SYSTEM_BIN_DIRS.iter().map(PathBuf::from)); |
| 610 | dirs.retain(|dir| dir.is_absolute()); |
| 611 | dirs |
| 612 | } |
| 613 | |
| 614 | fn candidates(dir: &Path, binary: &str, windows_pathext: Option<&OsStr>) -> Vec<PathBuf> { |
| 615 | let Some(pathext) = windows_pathext else { |
| 616 | return vec![dir.join(binary)]; |
| 617 | }; |
| 618 | let spawnable = |ext: &str| { |
| 619 | WINDOWS_SPAWNABLE_EXTENSIONS |
| 620 | .iter() |
| 621 | .any(|known| known.eq_ignore_ascii_case(ext)) |
| 622 | }; |
| 623 | if let Some(ext) = Path::new(binary).extension().and_then(OsStr::to_str) { |
| 624 | return if spawnable(&format!(".{ext}")) { |
| 625 | vec![dir.join(binary)] |
| 626 | } else { |
| 627 | Vec::new() |
| 628 | }; |
| 629 | } |
| 630 | let mut extensions: Vec<String> = Vec::new(); |
| 631 | for ext in pathext.to_string_lossy().split(';').map(str::trim) { |
| 632 | if spawnable(ext) && !extensions.iter().any(|seen| seen.eq_ignore_ascii_case(ext)) { |
| 633 | extensions.push(ext.to_string()); |
| 634 | } |
| 635 | } |
| 636 | extensions |
| 637 | .iter() |
| 638 | .map(|ext| dir.join(format!("{binary}{ext}"))) |
| 639 | .collect() |
| 640 | } |
| 641 | |
| 642 | fn windows_pathext() -> Option<std::ffi::OsString> { |
| 643 | #[cfg(windows)] |
| 644 | { |
| 645 | Some(std::env::var_os("PATHEXT").unwrap_or_else(|| WINDOWS_DEFAULT_PATHEXT.into())) |
| 646 | } |
| 647 | #[cfg(not(windows))] |
| 648 | { |
| 649 | None |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | async fn resolve_in( |
| 654 | dirs: Vec<PathBuf>, |
| 655 | binary: &str, |
| 656 | windows_pathext: Option<&OsStr>, |
| 657 | ) -> Option<PathBuf> { |
| 658 | let mut components = Path::new(binary).components(); |
| 659 | if !matches!( |
| 660 | (components.next(), components.next()), |
| 661 | (Some(Component::Normal(_)), None) |
| 662 | ) { |
| 663 | return None; |
| 664 | } |
| 665 | for dir in dirs { |
| 666 | for candidate in candidates(&dir, binary, windows_pathext) { |
| 667 | if is_executable(&candidate).await { |
| 668 | return Some(candidate); |
| 669 | } |
| 670 | } |
| 671 | } |
| 672 | None |
| 673 | } |
| 674 | |
| 675 | pub async fn resolve(binary: &str) -> Option<PathBuf> { |
| 676 | let pathext = windows_pathext(); |
| 677 | resolve_in(search_dirs(), binary, pathext.as_deref()).await |
| 678 | } |
| 679 | |
| 680 | pub async fn resolve_custom_binary(binary: &str) -> Option<PathBuf> { |
| 681 | let path = Path::new(binary); |
| 682 | if path.is_absolute() { |
| 683 | return is_executable(path).await.then(|| path.to_path_buf()); |
| 684 | } |
| 685 | resolve(binary).await |
| 686 | } |
| 687 | |
| 688 | pub fn is_batch_shim(path: &Path) -> bool { |
| 689 | path.extension() |
| 690 | .and_then(OsStr::to_str) |
| 691 | .is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) |
| 692 | } |
| 693 | |
| 694 | #[cfg(unix)] |
| 695 | async fn is_executable(path: &Path) -> bool { |
| 696 | use std::os::unix::fs::PermissionsExt; |
| 697 | tokio::fs::metadata(path) |
| 698 | .await |
| 699 | .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0) |
| 700 | } |
| 701 | |
| 702 | #[cfg(not(unix))] |
| 703 | async fn is_executable(path: &Path) -> bool { |
| 704 | tokio::fs::metadata(path) |
| 705 | .await |
| 706 | .is_ok_and(|meta| meta.is_file()) |
| 707 | } |
| 708 | |
| 709 | pub fn install_hint(agent: &ExternalAgent) -> String { |
| 710 | let runs_itself = |command: &str| command.split_whitespace().next() == Some(agent.binary); |
| 711 | match agent.upgrade { |
| 712 | Some(command) if !runs_itself(command) => format!(" Install it with `{command}`."), |
| 713 | _ if !agent.website.is_empty() => format!(" See {} to install it.", agent.website), |
| 714 | _ => String::new(), |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | pub fn not_installed(agent: &ExternalAgent) -> ExecutorUnavailable { |
| 719 | ExecutorUnavailable::new( |
| 720 | ExecutorUnavailable::NOT_INSTALLED, |
| 721 | format!("{} is not installed.{}", agent.name, install_hint(agent)), |
| 722 | ) |
| 723 | } |
| 724 | |
| 725 | pub fn foreign_command(path: &Path, args: &[&str]) -> Command { |
| 726 | let mut command = Command::new(path); |
| 727 | command |
| 728 | .args(args) |
| 729 | .current_dir(std::env::temp_dir()) |
| 730 | .stdin(Stdio::piped()) |
| 731 | .stdout(Stdio::piped()) |
| 732 | .stderr(Stdio::null()) |
| 733 | .kill_on_drop(true); |
| 734 | command.env_clear().envs( |
| 735 | codewhale_runtime::child_env::sanitized_runtime_env_from(std::env::vars_os()) |
| 736 | .into_iter() |
| 737 | .filter(|(name, _)| { |
| 738 | !name |
| 739 | .to_string_lossy() |
| 740 | .to_ascii_uppercase() |
| 741 | .starts_with("CODEWHALE_") |
| 742 | }), |
| 743 | ); |
| 744 | command |
| 745 | } |
| 746 | |
| 747 | pub fn version_token(text: &str) -> Option<String> { |
| 748 | text.split(|ch: char| ch.is_whitespace() || ch == '(' || ch == ')' || ch == ',') |
| 749 | .map(|token| token.trim_start_matches('v')) |
| 750 | .find(|token| { |
| 751 | token.chars().next().is_some_and(|ch| ch.is_ascii_digit()) && token.contains('.') |
| 752 | }) |
| 753 | .map(|token| { |
| 754 | token |
| 755 | .chars() |
| 756 | .filter(|ch| !ch.is_control()) |
| 757 | .take(MAX_VERSION_CHARS) |
| 758 | .collect::<String>() |
| 759 | .trim() |
| 760 | .trim_end_matches('.') |
| 761 | .to_string() |
| 762 | }) |
| 763 | } |
| 764 | |
| 765 | pub async fn preferred_cli( |
| 766 | agent: &ExternalAgent, |
| 767 | first: &Path, |
| 768 | env: &BTreeMap<String, String>, |
| 769 | ) -> (PathBuf, Option<String>) { |
| 770 | preferred_cli_in(agent, first, env, search_dirs()).await |
| 771 | } |
| 772 | |
| 773 | async fn preferred_cli_in( |
| 774 | agent: &ExternalAgent, |
| 775 | first: &Path, |
| 776 | env: &BTreeMap<String, String>, |
| 777 | dirs: Vec<PathBuf>, |
| 778 | ) -> (PathBuf, Option<String>) { |
| 779 | let version = cli_version_with_env(first, env).await; |
| 780 | if below_minimum(version.as_deref(), agent.min_version) { |
| 781 | let pathext = windows_pathext(); |
| 782 | let mut seen = std::collections::HashSet::from([first.to_path_buf()]); |
| 783 | for path in dirs |
| 784 | .iter() |
| 785 | .flat_map(|dir| candidates(dir, agent.binary, pathext.as_deref())) |
| 786 | { |
| 787 | if !seen.insert(path.clone()) |
| 788 | || (agent.adapter_cli_env.is_some() && is_batch_shim(&path)) |
| 789 | || !is_executable(&path).await |
| 790 | { |
| 791 | continue; |
| 792 | } |
| 793 | if let Some(found) = cli_version_with_env(&path, env).await |
| 794 | && version_core(&found).is_some() |
| 795 | && !below_minimum(Some(&found), agent.min_version) |
| 796 | { |
| 797 | return (path, Some(found)); |
| 798 | } |
| 799 | } |
| 800 | } |
| 801 | (first.to_owned(), version) |
| 802 | } |
| 803 | |
| 804 | pub async fn cli_version(path: &Path) -> Option<String> { |
| 805 | cli_version_with_env(path, &BTreeMap::new()).await |
| 806 | } |
| 807 | |
| 808 | pub async fn cli_version_with_env(path: &Path, env: &BTreeMap<String, String>) -> Option<String> { |
| 809 | let mut command = foreign_command(path, &["--version"]); |
| 810 | command.envs(env); |
| 811 | let run = codewhale_runtime::process_tree::contained_output_with_input_bounded( |
| 812 | &mut command, |
| 813 | Vec::new(), |
| 814 | MAX_VERSION_BYTES, |
| 815 | MAX_VERSION_STDERR_BYTES, |
| 816 | tokio::time::sleep(VERSION_TIMEOUT), |
| 817 | ) |
| 818 | .await |
| 819 | .ok()?; |
| 820 | if run.stopped { |
| 821 | return None; |
| 822 | } |
| 823 | let text = String::from_utf8_lossy(&run.output.stdout); |
| 824 | version_token(text.lines().next().unwrap_or_default()) |
| 825 | } |
| 826 | |
| 827 | fn version_core(text: &str) -> Option<(u64, u64, u64)> { |
| 828 | let core: String = text |
| 829 | .trim_start_matches('v') |
| 830 | .chars() |
| 831 | .take_while(|ch| ch.is_ascii_digit() || *ch == '.') |
| 832 | .collect(); |
| 833 | let mut parts = core.trim_end_matches('.').split('.'); |
| 834 | let major = parts.next()?.parse().ok()?; |
| 835 | let minor = parts.next()?.parse().ok()?; |
| 836 | let patch = parts.next()?.parse().ok()?; |
| 837 | parts.next().is_none().then_some((major, minor, patch)) |
| 838 | } |
| 839 | |
| 840 | pub fn below_minimum(version: Option<&str>, minimum: Option<&str>) -> bool { |
| 841 | match ( |
| 842 | version.and_then(version_core), |
| 843 | minimum.and_then(version_core), |
| 844 | ) { |
| 845 | (Some(found), Some(floor)) => found < floor, |
| 846 | _ => false, |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 851 | pub struct ExternalAgentLaunch { |
| 852 | pub agent_id: String, |
| 853 | pub agent_name: String, |
| 854 | pub program: PathBuf, |
| 855 | pub args: Vec<String>, |
| 856 | pub env: BTreeMap<String, String>, |
| 857 | pub transport: ExternalAgentTransport, |
| 858 | } |
| 859 | |
| 860 | static SIGN_IN: std::sync::LazyLock<std::sync::Mutex<BTreeMap<String, bool>>> = |
| 861 | std::sync::LazyLock::new(Default::default); |
| 862 | |
| 863 | pub fn record_sign_in(agent_id: &str, signed_in: bool) { |
| 864 | if let Ok(mut known) = SIGN_IN.lock() { |
| 865 | known.insert(agent_id.to_string(), signed_in); |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | pub fn sign_in_status(agent_id: &str) -> &'static str { |
| 870 | match SIGN_IN |
| 871 | .lock() |
| 872 | .ok() |
| 873 | .and_then(|known| known.get(agent_id).copied()) |
| 874 | { |
| 875 | Some(true) => "signed_in", |
| 876 | Some(false) => ExecutorUnavailable::NEEDS_SIGN_IN, |
| 877 | None => "unknown", |
| 878 | } |
| 879 | } |
| 880 | |
| 881 | pub async fn launch(id: &str) -> Result<ExternalAgentLaunch, ExecutorUnavailable> { |
| 882 | let preferred = std::env::var(EXTERNAL_AGENT_TRANSPORT_ENV) |
| 883 | .ok() |
| 884 | .map(|value| value.trim().to_string()) |
| 885 | .filter(|value| !value.is_empty()); |
| 886 | launch_with_transport(id, preferred.as_deref()).await |
| 887 | } |
| 888 | |
| 889 | pub async fn launch_with_transport( |
| 890 | id: &str, |
| 891 | preferred_transport: Option<&str>, |
| 892 | ) -> Result<ExternalAgentLaunch, ExecutorUnavailable> { |
| 893 | let preferred = preferred_transport |
| 894 | .map(str::trim) |
| 895 | .filter(|value| !value.is_empty()); |
| 896 | if let Some(other) = preferred |
| 897 | && !matches!(other, "acp" | "cli") |
| 898 | { |
| 899 | return Err(ExecutorUnavailable::new( |
| 900 | ExecutorUnavailable::EXECUTOR_NOT_SUPPORTED, |
| 901 | format!("Unsupported external agent transport `{other}`; expected `acp` or `cli`."), |
| 902 | )); |
| 903 | } |
| 904 | let Some(agent) = find(id) else { |
| 905 | if let Some(custom) = find_custom(id) { |
| 906 | let program = resolve_custom_binary(&custom.binary).await.ok_or_else(|| { |
| 907 | ExecutorUnavailable::new( |
| 908 | ExecutorUnavailable::NOT_INSTALLED, |
| 909 | format!("{} (`{}`) is not installed.", custom.name, custom.binary), |
| 910 | ) |
| 911 | })?; |
| 912 | let transport = match preferred.or(custom.transport.as_deref().map(str::trim)) { |
| 913 | Some("cli") => ExternalAgentTransport::DirectCli(DirectCliKind::Generic), |
| 914 | _ => ExternalAgentTransport::Acp, |
| 915 | }; |
| 916 | return Ok(ExternalAgentLaunch { |
| 917 | agent_id: custom.id, |
| 918 | agent_name: custom.name, |
| 919 | program, |
| 920 | args: custom.args, |
| 921 | env: custom.env, |
| 922 | transport, |
| 923 | }); |
| 924 | } |
| 925 | return Err(ExecutorUnavailable::new( |
| 926 | ExecutorUnavailable::UNKNOWN_AGENT, |
| 927 | format!("No external agent is named `{id}`."), |
| 928 | )); |
| 929 | }; |
| 930 | if agent.id == FIXTURE_AGENT_ID { |
| 931 | if preferred == Some("cli") { |
| 932 | return Err(ExecutorUnavailable::new( |
| 933 | ExecutorUnavailable::EXECUTOR_NOT_SUPPORTED, |
| 934 | "The fixture agent does not support direct CLI mode.", |
| 935 | )); |
| 936 | } |
| 937 | let script = fixture_script().ok_or_else(|| { |
| 938 | ExecutorUnavailable::new( |
| 939 | ExecutorUnavailable::UNKNOWN_AGENT, |
| 940 | "The fixture agent is not configured.", |
| 941 | ) |
| 942 | })?; |
| 943 | let node = resolve("node").await.ok_or_else(|| { |
| 944 | ExecutorUnavailable::new( |
| 945 | ExecutorUnavailable::NOT_INSTALLED, |
| 946 | "The fixture agent needs `node` on PATH.", |
| 947 | ) |
| 948 | })?; |
| 949 | return Ok(ExternalAgentLaunch { |
| 950 | agent_id: agent.id.to_string(), |
| 951 | agent_name: agent.name.to_string(), |
| 952 | program: node, |
| 953 | args: vec![script.display().to_string()], |
| 954 | env: BTreeMap::new(), |
| 955 | transport: ExternalAgentTransport::Acp, |
| 956 | }); |
| 957 | } |
| 958 | let mut cli = resolve(agent.binary) |
| 959 | .await |
| 960 | .ok_or_else(|| not_installed(agent))?; |
| 961 | let mut env = agent.process_env(); |
| 962 | if agent.min_version.is_some() { |
| 963 | let (selected, version) = preferred_cli(agent, &cli, &env).await; |
| 964 | cli = selected; |
| 965 | if below_minimum(version.as_deref(), agent.min_version) { |
| 966 | let update = agent |
| 967 | .upgrade |
| 968 | .map(|command| format!(" Update it with `{command}`.")) |
| 969 | .unwrap_or_default(); |
| 970 | return Err(ExecutorUnavailable::new( |
| 971 | ExecutorUnavailable::BELOW_MIN_VERSION, |
| 972 | format!( |
| 973 | "{} {} is installed; Codewhale needs {} or newer to drive it.{update}", |
| 974 | agent.name, |
| 975 | version.as_deref().unwrap_or("unknown"), |
| 976 | agent.min_version.unwrap_or("a newer one"), |
| 977 | ), |
| 978 | )); |
| 979 | } |
| 980 | } |
| 981 | if preferred == Some("cli") { |
| 982 | let Some(kind) = agent.direct_cli else { |
| 983 | return Err(ExecutorUnavailable::new( |
| 984 | ExecutorUnavailable::EXECUTOR_NOT_SUPPORTED, |
| 985 | format!("{} does not support direct CLI mode.", agent.name), |
| 986 | )); |
| 987 | }; |
| 988 | return Ok(ExternalAgentLaunch { |
| 989 | agent_id: agent.id.to_string(), |
| 990 | agent_name: agent.name.to_string(), |
| 991 | program: cli, |
| 992 | args: Vec::new(), |
| 993 | env, |
| 994 | transport: ExternalAgentTransport::DirectCli(kind), |
| 995 | }); |
| 996 | } |
| 997 | match (agent.acp_args, agent.adapter_binary) { |
| 998 | (Some(args), _) => Ok(ExternalAgentLaunch { |
| 999 | agent_id: agent.id.to_string(), |
| 1000 | agent_name: agent.name.to_string(), |
| 1001 | program: cli, |
| 1002 | args: args.iter().map(|arg| (*arg).to_string()).collect(), |
| 1003 | env, |
| 1004 | transport: ExternalAgentTransport::Acp, |
| 1005 | }), |
| 1006 | (None, Some(adapter_binary)) => match resolve(adapter_binary).await { |
| 1007 | Some(adapter) => { |
| 1008 | if let Some(key) = agent.adapter_cli_env.filter(|_| !is_batch_shim(&cli)) { |
| 1009 | env.insert(key.to_string(), cli.display().to_string()); |
| 1010 | } |
| 1011 | Ok(ExternalAgentLaunch { |
| 1012 | agent_id: agent.id.to_string(), |
| 1013 | agent_name: agent.name.to_string(), |
| 1014 | program: adapter, |
| 1015 | args: Vec::new(), |
| 1016 | env, |
| 1017 | transport: ExternalAgentTransport::Acp, |
| 1018 | }) |
| 1019 | } |
| 1020 | None => { |
| 1021 | if preferred.is_none() |
| 1022 | && let Some(kind) = agent.direct_cli |
| 1023 | { |
| 1024 | return Ok(ExternalAgentLaunch { |
| 1025 | agent_id: agent.id.to_string(), |
| 1026 | agent_name: agent.name.to_string(), |
| 1027 | program: cli, |
| 1028 | args: Vec::new(), |
| 1029 | env, |
| 1030 | transport: ExternalAgentTransport::DirectCli(kind), |
| 1031 | }); |
| 1032 | } |
| 1033 | Err(ExecutorUnavailable::new( |
| 1034 | ExecutorUnavailable::ADAPTER_MISSING, |
| 1035 | format!( |
| 1036 | "{} runs through the ACP adapter {}, which is not installed. Install it with `npm i -g {}`; Codewhale never downloads it for you.", |
| 1037 | agent.name, |
| 1038 | agent.adapter.unwrap_or(adapter_binary), |
| 1039 | agent.adapter.unwrap_or(adapter_binary), |
| 1040 | ), |
| 1041 | )) |
| 1042 | } |
| 1043 | }, |
| 1044 | (None, None) => { |
| 1045 | if preferred.is_none() |
| 1046 | && let Some(kind) = agent.direct_cli |
| 1047 | { |
| 1048 | return Ok(ExternalAgentLaunch { |
| 1049 | agent_id: agent.id.to_string(), |
| 1050 | agent_name: agent.name.to_string(), |
| 1051 | program: cli, |
| 1052 | args: Vec::new(), |
| 1053 | env, |
| 1054 | transport: ExternalAgentTransport::DirectCli(kind), |
| 1055 | }); |
| 1056 | } |
| 1057 | Err(ExecutorUnavailable::new( |
| 1058 | ExecutorUnavailable::NO_ACP, |
| 1059 | format!("{} has no ACP mode Codewhale can run.", agent.name), |
| 1060 | )) |
| 1061 | } |
| 1062 | } |
| 1063 | } |
| 1064 | |
| 1065 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 1066 | pub struct QuotaGate { |
| 1067 | pub enabled: bool, |
| 1068 | pub consented: bool, |
| 1069 | } |
| 1070 | |
| 1071 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1072 | pub enum QuotaSource { |
| 1073 | AgentReported, |
| 1074 | LocalSignin, |
| 1075 | } |
| 1076 | |
| 1077 | impl QuotaSource { |
| 1078 | pub fn as_str(self) -> &'static str { |
| 1079 | match self { |
| 1080 | Self::AgentReported => "agent_reported", |
| 1081 | Self::LocalSignin => "local_signin", |
| 1082 | } |
| 1083 | } |
| 1084 | } |
| 1085 | |
| 1086 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1087 | pub enum QuotaUnknown { |
| 1088 | FlagOff, |
| 1089 | ConsentMissing, |
| 1090 | NotImplemented, |
| 1091 | UnknownAgent, |
| 1092 | } |
| 1093 | |
| 1094 | impl QuotaUnknown { |
| 1095 | pub fn as_str(self) -> &'static str { |
| 1096 | match self { |
| 1097 | Self::FlagOff => "flag_off", |
| 1098 | Self::ConsentMissing => "consent_missing", |
| 1099 | Self::NotImplemented => "not_implemented", |
| 1100 | Self::UnknownAgent => "unknown_agent", |
| 1101 | } |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | #[derive(Debug, Clone, PartialEq)] |
| 1106 | pub struct QuotaWindow { |
| 1107 | pub name: String, |
| 1108 | pub used_percent: Option<f64>, |
| 1109 | pub resets_at: Option<String>, |
| 1110 | } |
| 1111 | |
| 1112 | #[derive(Debug, Clone, PartialEq)] |
| 1113 | pub enum AgentQuota { |
| 1114 | Known { |
| 1115 | source: QuotaSource, |
| 1116 | windows: Vec<QuotaWindow>, |
| 1117 | }, |
| 1118 | Unknown(QuotaUnknown), |
| 1119 | } |
| 1120 | |
| 1121 | pub enum LocalSigninReader {} |
| 1122 | |
| 1123 | fn local_signin_reader(_agent: &ExternalAgent) -> Option<LocalSigninReader> { |
| 1124 | None |
| 1125 | } |
| 1126 | |
| 1127 | pub async fn local_signin_quota(agent: &ExternalAgent, gate: QuotaGate) -> AgentQuota { |
| 1128 | if !gate.enabled { |
| 1129 | return AgentQuota::Unknown(QuotaUnknown::FlagOff); |
| 1130 | } |
| 1131 | if !gate.consented { |
| 1132 | return AgentQuota::Unknown(QuotaUnknown::ConsentMissing); |
| 1133 | } |
| 1134 | match local_signin_reader(agent) { |
| 1135 | None => AgentQuota::Unknown(QuotaUnknown::NotImplemented), |
| 1136 | Some(reader) => match reader {}, |
| 1137 | } |
| 1138 | } |
| 1139 | |
| 1140 | #[cfg(test)] |
| 1141 | mod tests { |
| 1142 | use super::*; |
| 1143 | |
| 1144 | #[tokio::test(flavor = "current_thread")] |
| 1145 | async fn quota_gate_reads_nothing_without_flag_and_consent_and_logs_nothing() { |
| 1146 | let buffer = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new())); |
| 1147 | let writer = buffer.clone(); |
| 1148 | let subscriber = tracing_subscriber::fmt() |
| 1149 | .with_max_level(tracing::Level::TRACE) |
| 1150 | .with_writer(move || CaptureWriter(writer.clone())) |
| 1151 | .finish(); |
| 1152 | let _guard = tracing::subscriber::set_default(subscriber); |
| 1153 | let cases = [ |
| 1154 | (QuotaGate::default(), QuotaUnknown::FlagOff), |
| 1155 | ( |
| 1156 | QuotaGate { |
| 1157 | enabled: false, |
| 1158 | consented: true, |
| 1159 | }, |
| 1160 | QuotaUnknown::FlagOff, |
| 1161 | ), |
| 1162 | ( |
| 1163 | QuotaGate { |
| 1164 | enabled: true, |
| 1165 | consented: false, |
| 1166 | }, |
| 1167 | QuotaUnknown::ConsentMissing, |
| 1168 | ), |
| 1169 | ( |
| 1170 | QuotaGate { |
| 1171 | enabled: true, |
| 1172 | consented: true, |
| 1173 | }, |
| 1174 | QuotaUnknown::NotImplemented, |
| 1175 | ), |
| 1176 | ]; |
| 1177 | for agent in AGENTS { |
| 1178 | assert!(local_signin_reader(agent).is_none(), "{}", agent.id); |
| 1179 | for (gate, reason) in cases { |
| 1180 | assert_eq!( |
| 1181 | local_signin_quota(agent, gate).await, |
| 1182 | AgentQuota::Unknown(reason), |
| 1183 | "{} {gate:?}", |
| 1184 | agent.id |
| 1185 | ); |
| 1186 | } |
| 1187 | } |
| 1188 | assert!(buffer.lock().unwrap().is_empty()); |
| 1189 | } |
| 1190 | |
| 1191 | struct CaptureWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>); |
| 1192 | |
| 1193 | impl std::io::Write for CaptureWriter { |
| 1194 | fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { |
| 1195 | self.0.lock().unwrap().extend_from_slice(bytes); |
| 1196 | Ok(bytes.len()) |
| 1197 | } |
| 1198 | |
| 1199 | fn flush(&mut self) -> std::io::Result<()> { |
| 1200 | Ok(()) |
| 1201 | } |
| 1202 | } |
| 1203 | |
| 1204 | fn names(paths: &[PathBuf]) -> Vec<String> { |
| 1205 | paths |
| 1206 | .iter() |
| 1207 | .map(|path| path.file_name().unwrap().to_string_lossy().into_owned()) |
| 1208 | .collect() |
| 1209 | } |
| 1210 | |
| 1211 | #[test] |
| 1212 | fn windows_lookup_tries_only_spawnable_pathext_suffixes_in_order() { |
| 1213 | let dir = Path::new("C:/Users/Ünï Person/AppData/Roaming/npm"); |
| 1214 | let pathext = OsStr::new(".COM;.EXE;.BAT;.CMD;.VBS;.JS;.PS1;.exe;;"); |
| 1215 | assert_eq!( |
| 1216 | names(&candidates(dir, "claude", Some(pathext))), |
| 1217 | ["claude.COM", "claude.EXE", "claude.BAT", "claude.CMD"] |
| 1218 | ); |
| 1219 | assert_eq!( |
| 1220 | names(&candidates( |
| 1221 | dir, |
| 1222 | "node", |
| 1223 | Some(OsStr::new(WINDOWS_DEFAULT_PATHEXT)) |
| 1224 | )), |
| 1225 | ["node.COM", "node.EXE", "node.BAT", "node.CMD"] |
| 1226 | ); |
| 1227 | assert_eq!( |
| 1228 | names(&candidates(dir, "node.exe", Some(pathext))), |
| 1229 | ["node.exe"] |
| 1230 | ); |
| 1231 | assert!(candidates(dir, "cli.js", Some(pathext)).is_empty()); |
| 1232 | assert!(candidates(dir, "claude", Some(OsStr::new(".PS1;.JS"))).is_empty()); |
| 1233 | assert_eq!(names(&candidates(dir, "claude", None)), ["claude"]); |
| 1234 | } |
| 1235 | |
| 1236 | #[test] |
| 1237 | fn install_hint_never_offers_a_self_update_as_the_install() { |
| 1238 | let agy = find("antigravity").unwrap(); |
| 1239 | assert_eq!( |
| 1240 | not_installed(agy).message, |
| 1241 | "Antigravity is not installed. See https://antigravity.google/docs/cli/acp/ to install it." |
| 1242 | ); |
| 1243 | let claude = find("claude").unwrap(); |
| 1244 | assert_eq!( |
| 1245 | install_hint(claude), |
| 1246 | " Install it with `npm i -g @anthropic-ai/claude-code@latest`." |
| 1247 | ); |
| 1248 | assert_eq!( |
| 1249 | not_installed(claude).code, |
| 1250 | ExecutorUnavailable::NOT_INSTALLED |
| 1251 | ); |
| 1252 | } |
| 1253 | |
| 1254 | #[cfg(unix)] |
| 1255 | fn script(dir: &Path, name: &str, body: &str) -> PathBuf { |
| 1256 | use std::os::unix::fs::PermissionsExt; |
| 1257 | let path = dir.join(name); |
| 1258 | std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); |
| 1259 | std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 1260 | path |
| 1261 | } |
| 1262 | |
| 1263 | #[cfg(unix)] |
| 1264 | #[tokio::test] |
| 1265 | async fn resolve_skips_unspawnable_files_and_handles_spaces_and_unicode() { |
| 1266 | let root = tempfile::tempdir().unwrap(); |
| 1267 | let plain = root.path().join("not executable"); |
| 1268 | let shims = root.path().join("dir with space/ünïcode bin"); |
| 1269 | std::fs::create_dir_all(&plain).unwrap(); |
| 1270 | std::fs::create_dir_all(&shims).unwrap(); |
| 1271 | std::fs::write(plain.join("claude"), "").unwrap(); |
| 1272 | let unix = script(&shims, "claude", "exit 0"); |
| 1273 | let windows = script(&shims, "claude.CMD", "exit 0"); |
| 1274 | let dirs = vec![plain.clone(), shims.clone()]; |
| 1275 | assert_eq!(resolve_in(dirs.clone(), "claude", None).await, Some(unix)); |
| 1276 | let found = resolve_in( |
| 1277 | dirs.clone(), |
| 1278 | "claude", |
| 1279 | Some(OsStr::new(WINDOWS_DEFAULT_PATHEXT)), |
| 1280 | ) |
| 1281 | .await |
| 1282 | .unwrap(); |
| 1283 | assert!( |
| 1284 | found |
| 1285 | .to_string_lossy() |
| 1286 | .eq_ignore_ascii_case(&windows.to_string_lossy()), |
| 1287 | "{}", |
| 1288 | found.display() |
| 1289 | ); |
| 1290 | for hostile in ["", ".", "..", "../claude", "bin/claude", "/bin/sh"] { |
| 1291 | assert_eq!( |
| 1292 | resolve_in(dirs.clone(), hostile, None).await, |
| 1293 | None, |
| 1294 | "{hostile}" |
| 1295 | ); |
| 1296 | } |
| 1297 | } |
| 1298 | |
| 1299 | #[cfg(unix)] |
| 1300 | #[tokio::test] |
| 1301 | async fn preferred_cli_preserves_search_order_among_compatible_installations() { |
| 1302 | let root = tempfile::tempdir().unwrap(); |
| 1303 | let dirs: Vec<_> = ["old", "unknown", "supported", "newer"] |
| 1304 | .map(|name| root.path().join(name)) |
| 1305 | .into(); |
| 1306 | let mut paths = Vec::new(); |
| 1307 | for (dir, version) in dirs.iter().zip(["0.46.0", "unknown", "0.165.0", "0.172.0"]) { |
| 1308 | std::fs::create_dir(dir).unwrap(); |
| 1309 | paths.push(script(dir, "codex", &format!("echo {version}"))); |
| 1310 | } |
| 1311 | let agent = AGENTS.iter().find(|agent| agent.id == "codex").unwrap(); |
| 1312 | let env = agent.process_env(); |
| 1313 | for first in [0, 2] { |
| 1314 | assert_eq!( |
| 1315 | preferred_cli_in(agent, &paths[first], &env, dirs[first..].to_vec()).await, |
| 1316 | (paths[2].clone(), Some("0.165.0".into())) |
| 1317 | ); |
| 1318 | } |
| 1319 | assert_eq!( |
| 1320 | preferred_cli_in(agent, &paths[0], &env, dirs[..2].to_vec()).await, |
| 1321 | (paths[0].clone(), Some("0.46.0".into())) |
| 1322 | ); |
| 1323 | } |
| 1324 | |
| 1325 | #[cfg(unix)] |
| 1326 | #[tokio::test] |
| 1327 | async fn cli_version_reads_a_bounded_answer_from_paths_with_spaces() { |
| 1328 | let root = tempfile::tempdir().unwrap(); |
| 1329 | let dir = root.path().join("spaced ünï dir"); |
| 1330 | std::fs::create_dir_all(&dir).unwrap(); |
| 1331 | let good = script( |
| 1332 | &dir, |
| 1333 | "agent one", |
| 1334 | "echo \"agent v1.5.2 (build)\"; echo noise >&2", |
| 1335 | ); |
| 1336 | assert_eq!(cli_version(&good).await.as_deref(), Some("1.5.2")); |
| 1337 | let sentence = script(&dir, "sentence", "echo \"GitHub Copilot CLI 1.0.82.\""); |
| 1338 | assert_eq!(cli_version(&sentence).await.as_deref(), Some("1.0.82")); |
| 1339 | let flood = script( |
| 1340 | &dir, |
| 1341 | "flood", |
| 1342 | "echo 9.9.9; head -c 20000 /dev/zero | tr '\\0' '1'; echo", |
| 1343 | ); |
| 1344 | assert_eq!(cli_version(&flood).await, None); |
| 1345 | let failed = script(&dir, "failed", "exit 3"); |
| 1346 | assert_eq!(cli_version(&failed).await, None); |
| 1347 | } |
| 1348 | |
| 1349 | #[cfg(unix)] |
| 1350 | #[tokio::test] |
| 1351 | async fn cli_version_stops_a_hung_cli_and_everything_it_started() { |
| 1352 | let root = tempfile::tempdir().unwrap(); |
| 1353 | let pid_file = root.path().join("grandchild.pid"); |
| 1354 | let hung = script( |
| 1355 | root.path(), |
| 1356 | "hung", |
| 1357 | &format!("sleep 300 & echo $! > '{}'; sleep 300", pid_file.display()), |
| 1358 | ); |
| 1359 | let started = std::time::Instant::now(); |
| 1360 | assert_eq!(cli_version(&hung).await, None); |
| 1361 | assert!(started.elapsed() < VERSION_TIMEOUT + Duration::from_secs(4)); |
| 1362 | let grandchild = |
| 1363 | codewhale_runtime::process_tree::read_pid_file(&pid_file, Duration::from_secs(5)); |
| 1364 | assert!(codewhale_runtime::process_tree::wait_for_pid_exit( |
| 1365 | grandchild, |
| 1366 | Duration::from_secs(5) |
| 1367 | )); |
| 1368 | } |
| 1369 | |
| 1370 | #[test] |
| 1371 | fn custom_registry_keeps_the_first_valid_id_and_reserves_builtins() { |
| 1372 | let entries = serde_json::json!([ |
| 1373 | {"id":"opencode","name":"Replacement","binary":"replacement"}, |
| 1374 | {"id":"fixture","name":"Fixture","binary":"fixture"}, |
| 1375 | {"id":" trim ","name":"Whitespace","binary":"agent"}, |
| 1376 | {"id":"bad","name":"Bad link","binary":"agent","website":"file:///local"}, |
| 1377 | {"id":"bad","name":"Secret override","binary":"agent","env":{"API_TOKEN":"fixture"}}, |
| 1378 | {"id":"bad","name":"Internal override","binary":"agent","env":{"codewhale_home":"local"}}, |
| 1379 | {"id":"desk","name":"Desk","binary":"local-acp","args":["acp"],"env":{"AGENT_PROFILE":"desk"}}, |
| 1380 | {"id":"desk","name":"Duplicate","binary":"other"} |
| 1381 | ]); |
| 1382 | let parsed = parse_custom_agents(&entries.to_string()); |
| 1383 | assert_eq!(parsed.len(), 1); |
| 1384 | assert_eq!(parsed[0].id, "desk"); |
| 1385 | assert_eq!(parsed[0].args, ["acp"]); |
| 1386 | assert_eq!(parsed[0].env["AGENT_PROFILE"], "desk"); |
| 1387 | } |
| 1388 | |
| 1389 | #[test] |
| 1390 | fn sign_in_status_follows_what_the_agent_last_showed() { |
| 1391 | assert_eq!(sign_in_status("sign-in-probe"), "unknown"); |
| 1392 | record_sign_in("sign-in-probe", false); |
| 1393 | assert_eq!(sign_in_status("sign-in-probe"), "needs_sign_in"); |
| 1394 | record_sign_in("sign-in-probe", true); |
| 1395 | assert_eq!(sign_in_status("sign-in-probe"), "signed_in"); |
| 1396 | } |
| 1397 | |
| 1398 | #[test] |
| 1399 | fn registry_rows_are_unique_with_verified_commands() { |
| 1400 | assert_eq!(AGENTS.len(), 24); |
| 1401 | let mut ids: Vec<&str> = AGENTS.iter().map(|agent| agent.id).collect(); |
| 1402 | ids.sort_unstable(); |
| 1403 | ids.dedup(); |
| 1404 | assert_eq!(ids.len(), AGENTS.len()); |
| 1405 | for agent in AGENTS { |
| 1406 | assert!( |
| 1407 | agent.acp_args.is_some() || agent.adapter_binary.is_some(), |
| 1408 | "{}", |
| 1409 | agent.id |
| 1410 | ); |
| 1411 | assert_eq!( |
| 1412 | Path::new(agent.binary).components().count(), |
| 1413 | 1, |
| 1414 | "{}", |
| 1415 | agent.id |
| 1416 | ); |
| 1417 | } |
| 1418 | for required in [ |
| 1419 | "claude", |
| 1420 | "codex", |
| 1421 | "dsh", |
| 1422 | "antigravity", |
| 1423 | "cursor", |
| 1424 | "cline", |
| 1425 | "devin", |
| 1426 | "opencode", |
| 1427 | "goose", |
| 1428 | "junie", |
| 1429 | "amp", |
| 1430 | "auggie", |
| 1431 | "kimi", |
| 1432 | "mistral-vibe", |
| 1433 | "qoder", |
| 1434 | "codebuddy", |
| 1435 | "grok", |
| 1436 | "qwen-code", |
| 1437 | "copilot", |
| 1438 | "muse", |
| 1439 | "minimax-code", |
| 1440 | "deepagents", |
| 1441 | "factory-droid", |
| 1442 | "pi-acp", |
| 1443 | ] { |
| 1444 | assert!(find(required).is_some(), "missing {required}"); |
| 1445 | } |
| 1446 | let grok = find("grok").unwrap(); |
| 1447 | assert_eq!( |
| 1448 | (grok.login, grok.upgrade), |
| 1449 | (Some("grok login"), Some("grok update")) |
| 1450 | ); |
| 1451 | let muse = find("muse").unwrap(); |
| 1452 | assert_eq!( |
| 1453 | ( |
| 1454 | muse.binary, |
| 1455 | muse.acp_args, |
| 1456 | muse.adapter, |
| 1457 | muse.adapter_binary, |
| 1458 | muse.adapter_cli_env, |
| 1459 | muse.login |
| 1460 | ), |
| 1461 | ( |
| 1462 | "muse", |
| 1463 | Some(["acp"].as_slice()), |
| 1464 | None, |
| 1465 | None, |
| 1466 | None, |
| 1467 | Some("muse login"), |
| 1468 | ) |
| 1469 | ); |
| 1470 | assert_eq!( |
| 1471 | find("antigravity").unwrap().direct_cli, |
| 1472 | Some(DirectCliKind::Antigravity) |
| 1473 | ); |
| 1474 | assert_eq!( |
| 1475 | find("claude").unwrap().direct_cli, |
| 1476 | Some(DirectCliKind::Claude) |
| 1477 | ); |
| 1478 | assert_eq!( |
| 1479 | find("codex").unwrap().direct_cli, |
| 1480 | Some(DirectCliKind::Codex) |
| 1481 | ); |
| 1482 | assert_eq!(find("grok").unwrap().direct_cli, Some(DirectCliKind::Grok)); |
| 1483 | assert!(available_direct_cli(find("claude").unwrap())); |
| 1484 | assert!(!available_direct_cli(find("opencode").unwrap())); |
| 1485 | } |
| 1486 | |
| 1487 | #[test] |
| 1488 | fn custom_agents_merges_config_and_env_overrides_duplicate_ids() { |
| 1489 | let _env = crate::test_support::lock_test_env(); |
| 1490 | let root = tempfile::tempdir().unwrap(); |
| 1491 | let config_path = root.path().join("config.toml"); |
| 1492 | std::fs::write( |
| 1493 | &config_path, |
| 1494 | r#" |
| 1495 | [[external_agents]] |
| 1496 | id = "from-config" |
| 1497 | name = "From Config" |
| 1498 | binary = "my-cli" |
| 1499 | args = ["--json"] |
| 1500 | transport = "cli" |
| 1501 | |
| 1502 | [[external_agents]] |
| 1503 | id = "shared-id" |
| 1504 | name = "Config Version" |
| 1505 | binary = "cfg-bin" |
| 1506 | transport = "acp" |
| 1507 | "#, |
| 1508 | ) |
| 1509 | .unwrap(); |
| 1510 | let _cfg = crate::test_support::EnvVarGuard::set( |
| 1511 | "CODEWHALE_CONFIG_PATH", |
| 1512 | config_path.to_str().unwrap(), |
| 1513 | ); |
| 1514 | let env_json = serde_json::json!([ |
| 1515 | {"id":"shared-id","name":"Env Version","binary":"env-bin","transport":"cli"} |
| 1516 | ]); |
| 1517 | let _custom = |
| 1518 | crate::test_support::EnvVarGuard::set(CUSTOM_AGENTS_ENV, env_json.to_string()); |
| 1519 | |
| 1520 | let agents = custom_agents(); |
| 1521 | let shared = agents.iter().find(|a| a.id == "shared-id").unwrap(); |
| 1522 | assert_eq!(shared.name, "Env Version"); |
| 1523 | assert_eq!(shared.binary, "env-bin"); |
| 1524 | assert_eq!(shared.transport.as_deref(), Some("cli")); |
| 1525 | let from_config = agents.iter().find(|a| a.id == "from-config").unwrap(); |
| 1526 | assert_eq!(from_config.name, "From Config"); |
| 1527 | assert_eq!(from_config.args, vec!["--json"]); |
| 1528 | assert_eq!(from_config.transport.as_deref(), Some("cli")); |
| 1529 | } |
| 1530 | |
| 1531 | #[cfg(unix)] |
| 1532 | #[tokio::test] |
| 1533 | async fn launch_with_transport_falls_back_to_direct_cli_when_adapter_missing() { |
| 1534 | let _env = crate::test_support::lock_test_env(); |
| 1535 | let root = tempfile::tempdir().unwrap(); |
| 1536 | let bin_dir = root.path().join("bin"); |
| 1537 | std::fs::create_dir_all(&bin_dir).unwrap(); |
| 1538 | let claude = script(&bin_dir, "claude", "echo '2.5.0'"); |
| 1539 | let _path = crate::test_support::EnvVarGuard::set("PATH", bin_dir.to_str().unwrap()); |
| 1540 | let _home = crate::test_support::EnvVarGuard::set("HOME", root.path().to_str().unwrap()); |
| 1541 | let _override = crate::test_support::EnvVarGuard::remove(EXTERNAL_AGENT_TRANSPORT_ENV); |
| 1542 | |
| 1543 | let fallback = launch_with_transport("claude", None).await.unwrap(); |
| 1544 | assert_eq!(fallback.program, claude); |
| 1545 | assert_eq!( |
| 1546 | fallback.transport, |
| 1547 | ExternalAgentTransport::DirectCli(DirectCliKind::Claude) |
| 1548 | ); |
| 1549 | assert_eq!(fallback.transport.as_str(), "cli"); |
| 1550 | |
| 1551 | let forced_acp = launch_with_transport("claude", Some("acp")) |
| 1552 | .await |
| 1553 | .unwrap_err(); |
| 1554 | assert_eq!(forced_acp.code, ExecutorUnavailable::ADAPTER_MISSING); |
| 1555 | |
| 1556 | let forced_cli = launch_with_transport("claude", Some("cli")).await.unwrap(); |
| 1557 | assert_eq!( |
| 1558 | forced_cli.transport, |
| 1559 | ExternalAgentTransport::DirectCli(DirectCliKind::Claude) |
| 1560 | ); |
| 1561 | } |
| 1562 | } |
| 1563 |