| 1 | use std::collections::BTreeMap; |
| 2 | use std::path::Path; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use axum::Json; |
| 6 | use serde_json::{Value, json}; |
| 7 | use tokio::io::{AsyncWriteExt, BufReader}; |
| 8 | use tokio::task::JoinSet; |
| 9 | |
| 10 | const PROBE_TIMEOUT: Duration = Duration::from_secs(30); |
| 11 | const MAX_CONCURRENT_PROBES: usize = 4; |
| 12 | static PROBES: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(MAX_CONCURRENT_PROBES); |
| 13 | const MAX_PROBE_LINE_BYTES: usize = 256 * 1024; |
| 14 | const MAX_TEXT_CHARS: usize = 80; |
| 15 | const MAX_AUTH_METHODS: usize = 8; |
| 16 | const PROBE_REAP_TIMEOUT: Duration = Duration::from_secs(2); |
| 17 | const SILENT_HANDSHAKE: &str = "It did not answer the Agent Client Protocol handshake."; |
| 18 | |
| 19 | use codewhale_engine::fleet::agents::{ |
| 20 | AGENTS, AgentQuota, CustomExternalAgent, ExecutorUnavailable, ExternalAgent, QuotaGate, |
| 21 | QuotaSource, QuotaUnknown, available_direct_cli, below_minimum, cli_version_with_env, |
| 22 | custom_agents, foreign_command, local_signin_quota, not_installed, preferred_cli, resolve, |
| 23 | resolve_custom_binary, |
| 24 | }; |
| 25 | use codewhale_runtime::process_tree::ProcessTree; |
| 26 | use codewhale_runtime::settings::{AgentSettings, Settings}; |
| 27 | |
| 28 | #[derive(Debug)] |
| 29 | enum Handshake { |
| 30 | Answered(Value), |
| 31 | Refused(String), |
| 32 | Silent, |
| 33 | } |
| 34 | |
| 35 | fn clean(text: &str) -> String { |
| 36 | text.chars() |
| 37 | .filter(|ch| !ch.is_control()) |
| 38 | .take(MAX_TEXT_CHARS) |
| 39 | .collect::<String>() |
| 40 | .trim() |
| 41 | .to_string() |
| 42 | } |
| 43 | |
| 44 | async fn acp_initialize(path: &Path, args: &[&str], env: &BTreeMap<String, String>) -> Handshake { |
| 45 | let mut command = foreign_command(path, args); |
| 46 | command.envs(env); |
| 47 | #[cfg(unix)] |
| 48 | command.process_group(0); |
| 49 | let Ok(mut child) = command.spawn() else { |
| 50 | return Handshake::Silent; |
| 51 | }; |
| 52 | let Ok(tree) = ProcessTree::attach_tokio(&child) else { |
| 53 | return Handshake::Silent; |
| 54 | }; |
| 55 | let (Some(mut stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else { |
| 56 | return Handshake::Silent; |
| 57 | }; |
| 58 | let request = json!({ |
| 59 | "jsonrpc": "2.0", |
| 60 | "id": 1, |
| 61 | "method": "initialize", |
| 62 | "params": { |
| 63 | "protocolVersion": 1, |
| 64 | "clientCapabilities": { |
| 65 | "fs": { "readTextFile": false, "writeTextFile": false }, |
| 66 | "terminal": false |
| 67 | }, |
| 68 | "clientInfo": { |
| 69 | "name": "codewhale", |
| 70 | "title": "Codewhale", |
| 71 | "version": env!("CARGO_PKG_VERSION") |
| 72 | } |
| 73 | } |
| 74 | }); |
| 75 | let mut line = request.to_string(); |
| 76 | line.push('\n'); |
| 77 | let mut lines = crate::stdio::BoundedLines::new(BufReader::new(stdout)); |
| 78 | let handshake = tokio::time::timeout(PROBE_TIMEOUT, async { |
| 79 | if stdin.write_all(line.as_bytes()).await.is_err() || stdin.flush().await.is_err() { |
| 80 | return Handshake::Silent; |
| 81 | } |
| 82 | while let Ok(Some(line)) = lines.next_line().await { |
| 83 | if line.len() > MAX_PROBE_LINE_BYTES { |
| 84 | return Handshake::Refused( |
| 85 | "It answered the Agent Client Protocol handshake with a line larger than Codewhale reads." |
| 86 | .to_string(), |
| 87 | ); |
| 88 | } |
| 89 | let Ok(message) = serde_json::from_str::<Value>(&line) else { |
| 90 | continue; |
| 91 | }; |
| 92 | if message.get("jsonrpc").and_then(Value::as_str) != Some("2.0") { |
| 93 | return Handshake::Refused( |
| 94 | "It answered without JSON-RPC 2.0, which the Agent Client Protocol requires." |
| 95 | .to_string(), |
| 96 | ); |
| 97 | } |
| 98 | if message.get("id") != Some(&json!(1)) { |
| 99 | continue; |
| 100 | } |
| 101 | let Some(result) = message.get("result") else { |
| 102 | return Handshake::Refused( |
| 103 | "It refused the Agent Client Protocol handshake.".to_string(), |
| 104 | ); |
| 105 | }; |
| 106 | return match result.get("protocolVersion").and_then(Value::as_u64) { |
| 107 | Some(1) => Handshake::Answered(result.clone()), |
| 108 | Some(version) => Handshake::Refused(format!( |
| 109 | "It speaks Agent Client Protocol version {version}; Codewhale drives version 1." |
| 110 | )), |
| 111 | None => Handshake::Refused( |
| 112 | "It answered the Agent Client Protocol handshake without a protocol version." |
| 113 | .to_string(), |
| 114 | ), |
| 115 | }; |
| 116 | } |
| 117 | Handshake::Silent |
| 118 | }) |
| 119 | .await |
| 120 | .unwrap_or(Handshake::Silent); |
| 121 | drop(stdin); |
| 122 | drop(tree); |
| 123 | let _ = child.start_kill(); |
| 124 | let _ = tokio::time::timeout(PROBE_REAP_TIMEOUT, child.wait()).await; |
| 125 | handshake |
| 126 | } |
| 127 | |
| 128 | fn auth_methods(result: &Value) -> Vec<Value> { |
| 129 | result |
| 130 | .get("authMethods") |
| 131 | .and_then(Value::as_array) |
| 132 | .map(|methods| { |
| 133 | methods |
| 134 | .iter() |
| 135 | .take(MAX_AUTH_METHODS) |
| 136 | .filter_map(|method| { |
| 137 | let id = clean(method.get("id")?.as_str()?); |
| 138 | let name = method |
| 139 | .get("name") |
| 140 | .and_then(Value::as_str) |
| 141 | .map_or_else(|| id.clone(), clean); |
| 142 | let kind = method |
| 143 | .get("type") |
| 144 | .and_then(Value::as_str) |
| 145 | .map_or("agent", clean_kind); |
| 146 | Some(json!({ "id": id, "name": name, "type": kind })) |
| 147 | }) |
| 148 | .collect() |
| 149 | }) |
| 150 | .unwrap_or_default() |
| 151 | } |
| 152 | |
| 153 | fn clean_kind(kind: &str) -> &'static str { |
| 154 | if kind == "terminal" { |
| 155 | "terminal" |
| 156 | } else { |
| 157 | "agent" |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | #[derive(Clone, Copy)] |
| 162 | enum Discovery { |
| 163 | Inventory, |
| 164 | Selected, |
| 165 | } |
| 166 | |
| 167 | impl Discovery { |
| 168 | async fn native_acp( |
| 169 | self, |
| 170 | path: &Path, |
| 171 | args: &[&str], |
| 172 | env: &BTreeMap<String, String>, |
| 173 | ) -> (Option<&'static str>, Option<Value>, Option<String>) { |
| 174 | if matches!(self, Self::Inventory) { |
| 175 | return (None, None, None); |
| 176 | } |
| 177 | match acp_initialize(path, args, env).await { |
| 178 | Handshake::Answered(result) => (Some("native"), Some(result), None), |
| 179 | Handshake::Refused(reason) => (Some("unreachable"), None, Some(reason)), |
| 180 | Handshake::Silent => ( |
| 181 | Some("unreachable"), |
| 182 | None, |
| 183 | Some(SILENT_HANDSHAKE.to_string()), |
| 184 | ), |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | async fn describe_custom(agent: CustomExternalAgent, discovery: Discovery) -> Value { |
| 190 | let Some(path) = resolve_custom_binary(&agent.binary).await else { |
| 191 | return json!({ |
| 192 | "id": agent.id, |
| 193 | "name": agent.name, |
| 194 | "state": "not_installed", |
| 195 | "version": null, |
| 196 | "acp": null, |
| 197 | "transport": null, |
| 198 | "transports": [], |
| 199 | "auth_methods": [], |
| 200 | "website": agent.website, |
| 201 | "min_version": null, |
| 202 | "upgrade": null, |
| 203 | "login": null, |
| 204 | "adapter": null, |
| 205 | "adapter_installed": false, |
| 206 | "needs_update": false, |
| 207 | "runnable": false, |
| 208 | "depth": null, |
| 209 | "auth_status": "unknown", |
| 210 | "custom": true, |
| 211 | "reason_code": ExecutorUnavailable::NOT_INSTALLED, |
| 212 | "reason": format!("{} (`{}`) is not installed.", agent.name, agent.binary), |
| 213 | }); |
| 214 | }; |
| 215 | let _permit = PROBES.acquire().await; |
| 216 | if agent.transport.as_deref().map(str::trim) == Some("cli") { |
| 217 | let version = cli_version_with_env(&path, &agent.env).await; |
| 218 | return json!({ |
| 219 | "id": agent.id, |
| 220 | "name": agent.name, |
| 221 | "state": "installed", |
| 222 | "needs_update": false, |
| 223 | "min_version": null, |
| 224 | "upgrade": null, |
| 225 | "login": null, |
| 226 | "adapter": null, |
| 227 | "version": version, |
| 228 | "acp": null, |
| 229 | "transport": "cli", |
| 230 | "transports": ["cli"], |
| 231 | "auth_methods": [], |
| 232 | "website": agent.website, |
| 233 | "adapter_installed": false, |
| 234 | "runnable": true, |
| 235 | "depth": "driven", |
| 236 | "auth_status": codewhale_engine::fleet::agents::sign_in_status(&agent.id), |
| 237 | "custom": true, |
| 238 | "reason_code": null, |
| 239 | "reason": null, |
| 240 | }); |
| 241 | } |
| 242 | let arg_refs: Vec<&str> = agent.args.iter().map(String::as_str).collect(); |
| 243 | let (version, (acp, initialized, refusal)) = tokio::join!( |
| 244 | cli_version_with_env(&path, &agent.env), |
| 245 | discovery.native_acp(&path, &arg_refs, &agent.env), |
| 246 | ); |
| 247 | let reported = initialized |
| 248 | .as_ref() |
| 249 | .and_then(|result| result.pointer("/agentInfo/version")) |
| 250 | .and_then(Value::as_str) |
| 251 | .map(clean); |
| 252 | let version = version.or(reported); |
| 253 | let runnable = refusal.is_none(); |
| 254 | let transports: Vec<&'static str> = if runnable { vec!["acp"] } else { Vec::new() }; |
| 255 | let transport = transports.first().copied(); |
| 256 | let reason_code = refusal.as_ref().map(|_| ExecutorUnavailable::NO_ACP); |
| 257 | json!({ |
| 258 | "id": agent.id, |
| 259 | "name": agent.name, |
| 260 | "state": "installed", |
| 261 | "needs_update": false, |
| 262 | "min_version": null, |
| 263 | "upgrade": null, |
| 264 | "login": null, |
| 265 | "adapter": null, |
| 266 | "version": version, |
| 267 | "acp": acp, |
| 268 | "transport": transport, |
| 269 | "transports": transports, |
| 270 | "auth_methods": initialized.as_ref().map(auth_methods).unwrap_or_default(), |
| 271 | "website": agent.website, |
| 272 | "adapter_installed": false, |
| 273 | "runnable": runnable, |
| 274 | "depth": if runnable { "driven" } else { "observed" }, |
| 275 | "auth_status": codewhale_engine::fleet::agents::sign_in_status(&agent.id), |
| 276 | "custom": true, |
| 277 | "reason_code": reason_code, |
| 278 | "reason": refusal, |
| 279 | }) |
| 280 | } |
| 281 | |
| 282 | async fn describe(agent: &'static ExternalAgent, discovery: Discovery) -> Value { |
| 283 | let Some(path) = resolve(agent.binary).await else { |
| 284 | return json!({ |
| 285 | "id": agent.id, |
| 286 | "name": agent.name, |
| 287 | "state": "not_installed", |
| 288 | "version": null, |
| 289 | "acp": null, |
| 290 | "transport": null, |
| 291 | "transports": [], |
| 292 | "auth_methods": [], |
| 293 | "website": agent.website, |
| 294 | "min_version": agent.min_version, |
| 295 | "upgrade": agent.upgrade, |
| 296 | "login": agent.login, |
| 297 | "adapter": agent.adapter, |
| 298 | "adapter_installed": false, |
| 299 | "needs_update": false, |
| 300 | "runnable": false, |
| 301 | "depth": null, |
| 302 | "auth_status": "unknown", |
| 303 | "reason_code": ExecutorUnavailable::NOT_INSTALLED, |
| 304 | "reason": not_installed(agent).message, |
| 305 | }); |
| 306 | }; |
| 307 | let env = agent.process_env(); |
| 308 | let _permit = PROBES.acquire().await; |
| 309 | let ((selected, version), adapter_installed) = |
| 310 | tokio::join!(preferred_cli(agent, &path, &env), async { |
| 311 | match agent.adapter_binary { |
| 312 | Some(binary) => resolve(binary).await.is_some(), |
| 313 | None => false, |
| 314 | } |
| 315 | }); |
| 316 | let (acp, initialized, refusal) = match agent.acp_args { |
| 317 | Some(args) => discovery.native_acp(&selected, args, &env).await, |
| 318 | None => (Some("adapter"), None, None), |
| 319 | }; |
| 320 | let reported = initialized |
| 321 | .as_ref() |
| 322 | .and_then(|result| result.pointer("/agentInfo/version")) |
| 323 | .and_then(Value::as_str) |
| 324 | .map(clean); |
| 325 | let version = version.or(reported); |
| 326 | let needs_update = below_minimum(version.as_deref(), agent.min_version); |
| 327 | let acp_runnable = match agent.acp_args { |
| 328 | Some(_) => refusal.is_none(), |
| 329 | None => adapter_installed, |
| 330 | }; |
| 331 | let cli_runnable = available_direct_cli(agent); |
| 332 | let mut transports: Vec<&'static str> = Vec::new(); |
| 333 | if !needs_update { |
| 334 | if acp_runnable { |
| 335 | transports.push("acp"); |
| 336 | } |
| 337 | if cli_runnable { |
| 338 | transports.push("cli"); |
| 339 | } |
| 340 | } |
| 341 | let transport = transports.first().copied(); |
| 342 | let runnable = !needs_update && (acp_runnable || cli_runnable); |
| 343 | let (reason_code, reason) = if needs_update { |
| 344 | ( |
| 345 | Some(ExecutorUnavailable::BELOW_MIN_VERSION), |
| 346 | Some(format!( |
| 347 | "Version {} is installed; Codewhale needs {} or newer to drive it.", |
| 348 | version.as_deref().unwrap_or("unknown"), |
| 349 | agent.min_version.unwrap_or("a newer one") |
| 350 | )), |
| 351 | ) |
| 352 | } else if runnable { |
| 353 | (None, None) |
| 354 | } else if version.is_none() && agent.min_version.is_some() && acp == Some("unreachable") { |
| 355 | ( |
| 356 | Some(ExecutorUnavailable::VERSION_UNKNOWN), |
| 357 | Some(format!( |
| 358 | "Codewhale could not read its version, so it cannot check the {} minimum. {}", |
| 359 | agent.min_version.unwrap_or_default(), |
| 360 | refusal.unwrap_or_else(|| SILENT_HANDSHAKE.to_string()) |
| 361 | )), |
| 362 | ) |
| 363 | } else if acp == Some("unreachable") { |
| 364 | (Some(ExecutorUnavailable::NO_ACP), refusal) |
| 365 | } else if acp == Some("adapter") && !adapter_installed { |
| 366 | let adapter = agent.adapter.unwrap_or("its ACP adapter"); |
| 367 | ( |
| 368 | Some(ExecutorUnavailable::ADAPTER_MISSING), |
| 369 | Some(format!( |
| 370 | "It runs through the ACP adapter {adapter}, which is not installed. Install it with `npm i -g {adapter}`." |
| 371 | )), |
| 372 | ) |
| 373 | } else { |
| 374 | (None, None) |
| 375 | }; |
| 376 | json!({ |
| 377 | "id": agent.id, |
| 378 | "name": agent.name, |
| 379 | "state": "installed", |
| 380 | "needs_update": needs_update, |
| 381 | "min_version": agent.min_version, |
| 382 | "upgrade": agent.upgrade, |
| 383 | "login": agent.login, |
| 384 | "adapter": agent.adapter, |
| 385 | "version": version, |
| 386 | "acp": acp, |
| 387 | "transport": transport, |
| 388 | "transports": transports, |
| 389 | "auth_methods": initialized.as_ref().map(auth_methods).unwrap_or_default(), |
| 390 | "website": agent.website, |
| 391 | "adapter_installed": adapter_installed, |
| 392 | "runnable": runnable, |
| 393 | "depth": if runnable { "driven" } else { "observed" }, |
| 394 | "auth_status": codewhale_engine::fleet::agents::sign_in_status(agent.id), |
| 395 | "reason_code": reason_code, |
| 396 | "reason": reason, |
| 397 | }) |
| 398 | } |
| 399 | |
| 400 | #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 401 | pub struct ExternalAgentDiscoveryRow { |
| 402 | pub id: String, |
| 403 | pub name: String, |
| 404 | pub state: String, |
| 405 | #[serde(default)] |
| 406 | pub version: Option<String>, |
| 407 | #[serde(default)] |
| 408 | pub acp: Option<String>, |
| 409 | #[serde(default)] |
| 410 | pub transport: Option<String>, |
| 411 | #[serde(default)] |
| 412 | pub transports: Vec<String>, |
| 413 | #[serde(default)] |
| 414 | pub website: String, |
| 415 | #[serde(default)] |
| 416 | pub min_version: Option<String>, |
| 417 | #[serde(default)] |
| 418 | pub upgrade: Option<String>, |
| 419 | #[serde(default)] |
| 420 | pub login: Option<String>, |
| 421 | #[serde(default)] |
| 422 | pub adapter: Option<String>, |
| 423 | #[serde(default)] |
| 424 | pub adapter_installed: bool, |
| 425 | #[serde(default)] |
| 426 | pub needs_update: bool, |
| 427 | #[serde(default)] |
| 428 | pub runnable: bool, |
| 429 | #[serde(default)] |
| 430 | pub custom: bool, |
| 431 | #[serde(default)] |
| 432 | pub reason_code: Option<String>, |
| 433 | #[serde(default)] |
| 434 | pub reason: Option<String>, |
| 435 | } |
| 436 | |
| 437 | pub async fn discover_external_agents() -> Vec<ExternalAgentDiscoveryRow> { |
| 438 | let Json(value) = list_external_agents().await; |
| 439 | value |
| 440 | .get("agents") |
| 441 | .cloned() |
| 442 | .and_then(|agents| serde_json::from_value(agents).ok()) |
| 443 | .unwrap_or_default() |
| 444 | } |
| 445 | |
| 446 | pub async fn discover_external_agent(id: &str) -> Option<ExternalAgentDiscoveryRow> { |
| 447 | let id = id.trim(); |
| 448 | if id == codewhale_engine::fleet::agents::FIXTURE_AGENT_ID { |
| 449 | let agent = codewhale_engine::fleet::agents::find(id)?; |
| 450 | let row = match codewhale_engine::fleet::agents::launch(id).await { |
| 451 | Ok(launch) => ExternalAgentDiscoveryRow { |
| 452 | id: agent.id.to_string(), |
| 453 | name: agent.name.to_string(), |
| 454 | state: "installed".to_string(), |
| 455 | version: None, |
| 456 | acp: Some("native".to_string()), |
| 457 | transport: Some(launch.transport.as_str().to_string()), |
| 458 | transports: vec![launch.transport.as_str().to_string()], |
| 459 | website: agent.website.to_string(), |
| 460 | min_version: None, |
| 461 | upgrade: None, |
| 462 | login: None, |
| 463 | adapter: None, |
| 464 | adapter_installed: false, |
| 465 | needs_update: false, |
| 466 | runnable: true, |
| 467 | custom: false, |
| 468 | reason_code: None, |
| 469 | reason: None, |
| 470 | }, |
| 471 | Err(unavailable) => ExternalAgentDiscoveryRow { |
| 472 | id: agent.id.to_string(), |
| 473 | name: agent.name.to_string(), |
| 474 | state: "not_installed".to_string(), |
| 475 | version: None, |
| 476 | acp: None, |
| 477 | transport: None, |
| 478 | transports: Vec::new(), |
| 479 | website: agent.website.to_string(), |
| 480 | min_version: None, |
| 481 | upgrade: None, |
| 482 | login: None, |
| 483 | adapter: None, |
| 484 | adapter_installed: false, |
| 485 | needs_update: false, |
| 486 | runnable: false, |
| 487 | custom: false, |
| 488 | reason_code: Some(unavailable.code.to_string()), |
| 489 | reason: Some(unavailable.message), |
| 490 | }, |
| 491 | }; |
| 492 | return Some(row); |
| 493 | } |
| 494 | if let Some(agent) = AGENTS.iter().find(|agent| agent.id == id) { |
| 495 | return serde_json::from_value(describe(agent, Discovery::Selected).await).ok(); |
| 496 | } |
| 497 | if let Some(custom) = codewhale_engine::fleet::agents::find_custom(id) { |
| 498 | return serde_json::from_value(describe_custom(custom, Discovery::Selected).await).ok(); |
| 499 | } |
| 500 | None |
| 501 | } |
| 502 | |
| 503 | pub(super) async fn list_external_agents() -> Json<Value> { |
| 504 | let customs = custom_agents(); |
| 505 | let custom_ids: Vec<String> = customs.iter().map(|c| c.id.clone()).collect(); |
| 506 | let mut tasks = JoinSet::new(); |
| 507 | for agent in AGENTS { |
| 508 | tasks.spawn(describe(agent, Discovery::Inventory)); |
| 509 | } |
| 510 | for custom in customs { |
| 511 | tasks.spawn(describe_custom(custom, Discovery::Inventory)); |
| 512 | } |
| 513 | let mut found = Vec::with_capacity(AGENTS.len() + custom_ids.len()); |
| 514 | while let Some(result) = tasks.join_next().await { |
| 515 | if let Ok(entry) = result { |
| 516 | found.push(entry); |
| 517 | } |
| 518 | } |
| 519 | found.sort_by_key(|entry| { |
| 520 | let id = entry.get("id").and_then(Value::as_str).unwrap_or_default(); |
| 521 | AGENTS |
| 522 | .iter() |
| 523 | .position(|agent| agent.id == id) |
| 524 | .or_else(|| { |
| 525 | custom_ids |
| 526 | .iter() |
| 527 | .position(|cid| cid == id) |
| 528 | .map(|idx| AGENTS.len() + idx) |
| 529 | }) |
| 530 | .unwrap_or(usize::MAX) |
| 531 | }); |
| 532 | Json(json!({ "agents": found })) |
| 533 | } |
| 534 | |
| 535 | fn quota_json(quota: &AgentQuota) -> Value { |
| 536 | match quota { |
| 537 | AgentQuota::Known { source, windows } => json!({ |
| 538 | "status": "known", |
| 539 | "source": source.as_str(), |
| 540 | "windows": windows |
| 541 | .iter() |
| 542 | .map(|window| json!({ |
| 543 | "name": window.name, |
| 544 | "used_percent": window.used_percent, |
| 545 | "resets_at": window.resets_at, |
| 546 | })) |
| 547 | .collect::<Vec<_>>(), |
| 548 | }), |
| 549 | AgentQuota::Unknown(reason) => json!({ |
| 550 | "status": "unknown", |
| 551 | "reason": reason.as_str(), |
| 552 | }), |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | async fn agent_quota_report(agents: &AgentSettings) -> Value { |
| 557 | let mut entries = Vec::with_capacity(AGENTS.len()); |
| 558 | for agent in AGENTS { |
| 559 | let choice = agents.quota(agent.id); |
| 560 | let gate = QuotaGate { |
| 561 | enabled: choice.enabled, |
| 562 | consented: choice.consented_at.is_some(), |
| 563 | }; |
| 564 | let quota = local_signin_quota(agent, gate).await; |
| 565 | entries.push(json!({ |
| 566 | "id": agent.id, |
| 567 | "name": agent.name, |
| 568 | "quota": quota_json("a), |
| 569 | })); |
| 570 | } |
| 571 | for id in agents |
| 572 | .quota |
| 573 | .keys() |
| 574 | .filter(|id| !AGENTS.iter().any(|agent| agent.id == id.as_str())) |
| 575 | { |
| 576 | entries.push(json!({ |
| 577 | "id": id, |
| 578 | "name": null, |
| 579 | "quota": quota_json(&AgentQuota::Unknown(QuotaUnknown::UnknownAgent)), |
| 580 | })); |
| 581 | } |
| 582 | json!({ |
| 583 | "default_source": QuotaSource::AgentReported.as_str(), |
| 584 | "agents": entries, |
| 585 | }) |
| 586 | } |
| 587 | |
| 588 | pub(super) async fn get_external_agent_quota() -> Json<Value> { |
| 589 | #[cfg(any(test, feature = "test-support"))] |
| 590 | let env_ticket = codewhale_engine::test_support::env_scope_ticket(); |
| 591 | let agents = tokio::task::spawn_blocking(move || { |
| 592 | #[cfg(any(test, feature = "test-support"))] |
| 593 | let _membership = codewhale_engine::test_support::join_env_scope(env_ticket); |
| 594 | Settings::load_read_only() |
| 595 | }) |
| 596 | .await |
| 597 | .ok() |
| 598 | .and_then(Result::ok) |
| 599 | .map(|settings| settings.agents) |
| 600 | .unwrap_or_default(); |
| 601 | Json(agent_quota_report(&agents).await) |
| 602 | } |
| 603 | |
| 604 | #[cfg(all(test, unix))] |
| 605 | mod tests { |
| 606 | use super::*; |
| 607 | use std::time::Instant; |
| 608 | |
| 609 | fn script(dir: &Path, name: &str, body: &str) -> std::path::PathBuf { |
| 610 | use std::os::unix::fs::PermissionsExt; |
| 611 | let path = dir.join(name); |
| 612 | std::fs::write(&path, format!("#!/bin/sh\nread request\n{body}\n")).unwrap(); |
| 613 | std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 614 | path |
| 615 | } |
| 616 | |
| 617 | #[tokio::test] |
| 618 | async fn selected_agent_passes_registered_env_to_version_and_initialize() { |
| 619 | let root = tempfile::tempdir().unwrap(); |
| 620 | let path = script( |
| 621 | root.path(), |
| 622 | "agent", |
| 623 | r#" |
| 624 | test "$AUGMENT_DISABLE_AUTO_UPDATE" = 1 || exit 3 |
| 625 | test "$DROID_DISABLE_AUTO_UPDATE" = true || exit 4 |
| 626 | test "$FACTORY_DROID_AUTO_UPDATE_ENABLED" = false || exit 5 |
| 627 | if [ "$1" = --version ]; then echo "agent 1.2.3"; exit; fi |
| 628 | test "$1" = acp || exit 6 |
| 629 | echo '{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1}}' |
| 630 | "#, |
| 631 | ); |
| 632 | let mut env = codewhale_engine::fleet::agents::find("auggie") |
| 633 | .unwrap() |
| 634 | .process_env(); |
| 635 | env.extend( |
| 636 | codewhale_engine::fleet::agents::find("factory-droid") |
| 637 | .unwrap() |
| 638 | .process_env(), |
| 639 | ); |
| 640 | let row = describe_custom( |
| 641 | CustomExternalAgent { |
| 642 | id: "local".into(), |
| 643 | name: "Local".into(), |
| 644 | binary: path.display().to_string(), |
| 645 | args: vec!["acp".into()], |
| 646 | transport: None, |
| 647 | website: String::new(), |
| 648 | env, |
| 649 | }, |
| 650 | Discovery::Selected, |
| 651 | ) |
| 652 | .await; |
| 653 | assert_eq!(row["version"], "1.2.3"); |
| 654 | assert_eq!(row["runnable"], true); |
| 655 | assert_eq!(row["transport"], "acp"); |
| 656 | assert_eq!(row["transports"], json!(["acp"])); |
| 657 | } |
| 658 | |
| 659 | #[tokio::test] |
| 660 | async fn listing_only_checks_versions_then_selection_verifies_one_agent() { |
| 661 | use codewhale_engine::test_support::{EnvVarGuard, lock_test_env}; |
| 662 | |
| 663 | let _env = lock_test_env(); |
| 664 | let root = tempfile::tempdir().unwrap(); |
| 665 | let bin = root.path(); |
| 666 | let body = r#" |
| 667 | echo "$*" >> "$0.calls" |
| 668 | if [ "$1" = --version ]; then echo 999.0.0; exit; fi |
| 669 | echo '{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1}}' |
| 670 | "#; |
| 671 | for agent in AGENTS { |
| 672 | script(bin, agent.binary, body); |
| 673 | } |
| 674 | let custom_path = script(bin, "test-custom", body); |
| 675 | let custom = json!([{ |
| 676 | "id": "test-custom", "name": "Custom agent", "binary": custom_path, "args": ["acp"] |
| 677 | }]); |
| 678 | let _path = EnvVarGuard::set("PATH", bin.to_str().unwrap()); |
| 679 | let _home = EnvVarGuard::set("HOME", bin.to_str().unwrap()); |
| 680 | let _cw_home = EnvVarGuard::set("CODEWHALE_HOME", bin.to_str().unwrap()); |
| 681 | let _custom = EnvVarGuard::set("CODEWHALE_CUSTOM_ACP_AGENTS", custom.to_string()); |
| 682 | |
| 683 | let Json(list) = list_external_agents().await; |
| 684 | let calls = |id: &str| std::fs::read_to_string(bin.join(format!("{id}.calls"))).unwrap(); |
| 685 | for id in ["opencode", "test-custom"] { |
| 686 | let row = list["agents"] |
| 687 | .as_array() |
| 688 | .unwrap() |
| 689 | .iter() |
| 690 | .find(|row| row["id"] == id) |
| 691 | .unwrap(); |
| 692 | assert_eq!(row["runnable"], true); |
| 693 | assert_eq!(row["transport"], "acp"); |
| 694 | assert_eq!(row["acp"], Value::Null); |
| 695 | assert_eq!(row["auth_methods"], json!([])); |
| 696 | assert_eq!(calls(id), "--version\n"); |
| 697 | } |
| 698 | for id in ["opencode", "test-custom"] { |
| 699 | let row = discover_external_agent(id).await.unwrap(); |
| 700 | assert_eq!(row.acp.as_deref(), Some("native")); |
| 701 | assert_eq!(calls(id).lines().filter(|args| *args == "acp").count(), 1); |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | #[tokio::test] |
| 706 | async fn installed_claude_without_adapter_is_runnable_via_cli_transport() { |
| 707 | let _env = codewhale_engine::test_support::lock_test_env(); |
| 708 | let root = tempfile::tempdir().unwrap(); |
| 709 | let bin_dir = root.path().join("bin"); |
| 710 | std::fs::create_dir_all(&bin_dir).unwrap(); |
| 711 | let claude_path = bin_dir.join("claude"); |
| 712 | std::fs::write(&claude_path, "#!/bin/sh\necho '2.5.0'\n").unwrap(); |
| 713 | use std::os::unix::fs::PermissionsExt; |
| 714 | std::fs::set_permissions(&claude_path, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 715 | let _path = |
| 716 | codewhale_engine::test_support::EnvVarGuard::set("PATH", bin_dir.to_str().unwrap()); |
| 717 | let _home = |
| 718 | codewhale_engine::test_support::EnvVarGuard::set("HOME", root.path().to_str().unwrap()); |
| 719 | |
| 720 | let claude = codewhale_engine::fleet::agents::find("claude").unwrap(); |
| 721 | let row = describe(claude, Discovery::Inventory).await; |
| 722 | assert_eq!(row["state"], "installed"); |
| 723 | assert_eq!(row["acp"], "adapter"); |
| 724 | assert_eq!(row["adapter"], "@agentclientprotocol/claude-agent-acp"); |
| 725 | assert_eq!(row["adapter_installed"], false); |
| 726 | assert_eq!(row["runnable"], true); |
| 727 | assert_eq!(row["depth"], "driven"); |
| 728 | assert_eq!(row["transport"], "cli"); |
| 729 | assert_eq!(row["transports"], json!(["cli"])); |
| 730 | assert_eq!(row["reason_code"], Value::Null); |
| 731 | assert_eq!(row["reason"], Value::Null); |
| 732 | |
| 733 | let cli_custom = describe_custom( |
| 734 | CustomExternalAgent { |
| 735 | id: "my-cli".into(), |
| 736 | name: "My CLI".into(), |
| 737 | binary: claude_path.display().to_string(), |
| 738 | args: vec!["--flag".into()], |
| 739 | transport: Some("cli".into()), |
| 740 | website: String::new(), |
| 741 | env: BTreeMap::new(), |
| 742 | }, |
| 743 | Discovery::Inventory, |
| 744 | ) |
| 745 | .await; |
| 746 | assert_eq!(cli_custom["runnable"], true); |
| 747 | assert_eq!(cli_custom["depth"], "driven"); |
| 748 | assert_eq!(cli_custom["transport"], "cli"); |
| 749 | assert_eq!(cli_custom["transports"], json!(["cli"])); |
| 750 | assert_eq!(cli_custom["reason_code"], Value::Null); |
| 751 | } |
| 752 | |
| 753 | #[tokio::test] |
| 754 | async fn handshake_keeps_answered_unsupported_and_silent_agents_distinct() { |
| 755 | let root = tempfile::tempdir().unwrap(); |
| 756 | let dir = root.path().join("agent dir ünï"); |
| 757 | std::fs::create_dir_all(&dir).unwrap(); |
| 758 | let answer = |reply: &str| format!("echo 'log line'; echo '{reply}'; sleep 30"); |
| 759 | let native = script( |
| 760 | &dir, |
| 761 | "native", |
| 762 | &answer( |
| 763 | r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"version":"2.0.0"},"authMethods":[{"id":"login","name":"Log in","type":"terminal"}]}}"#, |
| 764 | ), |
| 765 | ); |
| 766 | let Handshake::Answered(result) = acp_initialize(&native, &["acp"], &BTreeMap::new()).await |
| 767 | else { |
| 768 | panic!("a v1 answer must count as native ACP"); |
| 769 | }; |
| 770 | assert_eq!(auth_methods(&result)[0]["type"], "terminal"); |
| 771 | |
| 772 | let cases = [ |
| 773 | ( |
| 774 | r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":2}}"#, |
| 775 | "It speaks Agent Client Protocol version 2; Codewhale drives version 1.", |
| 776 | ), |
| 777 | ( |
| 778 | r#"{"id":1,"result":{"protocolVersion":1}}"#, |
| 779 | "It answered without JSON-RPC 2.0, which the Agent Client Protocol requires.", |
| 780 | ), |
| 781 | ( |
| 782 | r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"no"}}"#, |
| 783 | "It refused the Agent Client Protocol handshake.", |
| 784 | ), |
| 785 | ]; |
| 786 | for (index, (reply, expected)) in cases.into_iter().enumerate() { |
| 787 | let agent = script(&dir, &format!("refusing {index}"), &answer(reply)); |
| 788 | match acp_initialize(&agent, &[], &BTreeMap::new()).await { |
| 789 | Handshake::Refused(reason) => assert_eq!(reason, expected), |
| 790 | other => panic!("{reply}: {other:?}"), |
| 791 | } |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | #[tokio::test] |
| 796 | async fn silent_handshake_is_bounded_and_kills_the_agent_tree() { |
| 797 | let root = tempfile::tempdir().unwrap(); |
| 798 | let pid_file = root.path().join("grandchild.pid"); |
| 799 | let silent = script( |
| 800 | root.path(), |
| 801 | "silent", |
| 802 | &format!("sleep 300 & echo $! > '{}'; sleep 300", pid_file.display()), |
| 803 | ); |
| 804 | let started = Instant::now(); |
| 805 | assert!(matches!( |
| 806 | acp_initialize(&silent, &[], &BTreeMap::new()).await, |
| 807 | Handshake::Silent |
| 808 | )); |
| 809 | assert!(started.elapsed() < PROBE_TIMEOUT + PROBE_REAP_TIMEOUT + Duration::from_secs(2)); |
| 810 | let grandchild = |
| 811 | codewhale_runtime::process_tree::read_pid_file(&pid_file, Duration::from_secs(5)); |
| 812 | assert!(codewhale_runtime::process_tree::wait_for_pid_exit( |
| 813 | grandchild, |
| 814 | Duration::from_secs(5) |
| 815 | )); |
| 816 | } |
| 817 | } |
| 818 |