| 1 | use std::collections::{BTreeSet, HashMap}; |
| 2 | use std::path::{Path as FsPath, PathBuf}; |
| 3 | |
| 4 | use axum::Json; |
| 5 | use axum::extract::{Query, State}; |
| 6 | use serde::Serialize; |
| 7 | use serde_json::Value; |
| 8 | |
| 9 | use super::plugins::{self, PluginSummaryEntry}; |
| 10 | use super::{ApiError, CommandsQuery, HooksQuery, RuntimeApiState}; |
| 11 | |
| 12 | const MAX_ADDED_NAMES: usize = 512; |
| 13 | |
| 14 | #[derive(Debug, Serialize)] |
| 15 | pub(super) struct PluginIndexResponse { |
| 16 | workspace: String, |
| 17 | items: Vec<IndexItem>, |
| 18 | unavailable: Vec<IndexNote>, |
| 19 | problems: Vec<IndexNote>, |
| 20 | } |
| 21 | |
| 22 | #[derive(Debug, Serialize)] |
| 23 | struct IndexNote { |
| 24 | kind: &'static str, |
| 25 | message: String, |
| 26 | } |
| 27 | |
| 28 | #[derive(Debug, Serialize)] |
| 29 | struct IndexItem { |
| 30 | id: String, |
| 31 | kind: &'static str, |
| 32 | name: String, |
| 33 | description: Option<String>, |
| 34 | source: &'static str, |
| 35 | state: &'static str, |
| 36 | labels: Vec<&'static str>, |
| 37 | #[serde(skip_serializing_if = "Option::is_none")] |
| 38 | plugin: Option<String>, |
| 39 | #[serde(skip_serializing_if = "Option::is_none")] |
| 40 | adds: Option<PluginAdds>, |
| 41 | #[serde(skip_serializing_if = "Option::is_none")] |
| 42 | tier: Option<&'static str>, |
| 43 | owner: &'static str, |
| 44 | row: Value, |
| 45 | } |
| 46 | |
| 47 | #[derive(Debug, Default, Serialize)] |
| 48 | struct PluginAdds { |
| 49 | skills: Vec<String>, |
| 50 | connectors: Vec<String>, |
| 51 | hooks: Vec<String>, |
| 52 | commands: Vec<String>, |
| 53 | profiles: Vec<String>, |
| 54 | } |
| 55 | |
| 56 | impl PluginAdds { |
| 57 | fn labels(&self, entry: &PluginSummaryEntry) -> Vec<&'static str> { |
| 58 | [ |
| 59 | ("skill", !self.skills.is_empty()), |
| 60 | ("connector", !self.connectors.is_empty()), |
| 61 | ("hook", !self.hooks.is_empty()), |
| 62 | ("command", !self.commands.is_empty()), |
| 63 | ( |
| 64 | "tool", |
| 65 | entry.inventory.native > 0 || entry.inventory.lsp > 0, |
| 66 | ), |
| 67 | ("profile", !self.profiles.is_empty()), |
| 68 | ] |
| 69 | .into_iter() |
| 70 | .filter_map(|(label, present)| present.then_some(label)) |
| 71 | .collect() |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | fn row_value<T: Serialize>(row: &T) -> Value { |
| 76 | serde_json::to_value(row).unwrap_or(Value::Null) |
| 77 | } |
| 78 | |
| 79 | fn note_failure(unavailable: &mut Vec<IndexNote>, kind: &'static str, error: &ApiError) { |
| 80 | unavailable.push(IndexNote { |
| 81 | kind, |
| 82 | message: error.message.clone(), |
| 83 | }); |
| 84 | } |
| 85 | |
| 86 | fn plugin_source(origin: &str) -> &'static str { |
| 87 | match origin { |
| 88 | "codewhale-builtin" => "built_in", |
| 89 | "workspace-codewhale" => "project", |
| 90 | _ => "user", |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | fn plugin_state(entry: &PluginSummaryEntry) -> &'static str { |
| 95 | if matches!( |
| 96 | entry.trust_status, |
| 97 | "content-changed" | "capabilities-changed" |
| 98 | ) || entry.state == "enabled-untrusted" |
| 99 | { |
| 100 | return "needs_review"; |
| 101 | } |
| 102 | match entry.state { |
| 103 | "active" => "enabled", |
| 104 | "disabled" => "disabled", |
| 105 | _ => "unavailable", |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | async fn component_names( |
| 110 | paths: &[PathBuf], |
| 111 | extension: Option<&'static str>, |
| 112 | lowercase: bool, |
| 113 | omitted: &mut bool, |
| 114 | ) -> Vec<String> { |
| 115 | let (names, cut) = codewhale_plugins::runtime::component_file_names( |
| 116 | paths, |
| 117 | extension, |
| 118 | lowercase, |
| 119 | MAX_ADDED_NAMES, |
| 120 | ) |
| 121 | .await; |
| 122 | *omitted |= cut; |
| 123 | names |
| 124 | } |
| 125 | |
| 126 | async fn plugin_adds( |
| 127 | plugin: &codewhale_plugins::types::LoadedPlugin, |
| 128 | omitted: &mut bool, |
| 129 | ) -> PluginAdds { |
| 130 | let mut skills: Vec<String> = plugin |
| 131 | .skill_snapshots |
| 132 | .iter() |
| 133 | .map(|skill| skill.name.clone()) |
| 134 | .collect(); |
| 135 | skills.sort(); |
| 136 | let mut connectors: Vec<String> = plugin |
| 137 | .manifest |
| 138 | .mcp_servers |
| 139 | .as_ref() |
| 140 | .map(|servers| servers.keys().cloned().collect()) |
| 141 | .unwrap_or_default(); |
| 142 | connectors.sort(); |
| 143 | PluginAdds { |
| 144 | skills, |
| 145 | connectors, |
| 146 | hooks: component_names(&plugin.components.hooks, None, false, omitted).await, |
| 147 | commands: component_names(&plugin.components.commands, Some("md"), true, omitted).await, |
| 148 | profiles: component_names(&plugin.components.agents, Some("toml"), false, omitted).await, |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | async fn plugin_adds_by_id( |
| 153 | state: &RuntimeApiState, |
| 154 | omitted: &mut BTreeSet<String>, |
| 155 | ) -> HashMap<String, PluginAdds> { |
| 156 | let registry = state |
| 157 | .plugin_discovery |
| 158 | .registry_for_workspace(&state.workspace); |
| 159 | let mut adds = HashMap::new(); |
| 160 | for plugin in registry.list() { |
| 161 | let mut cut = false; |
| 162 | adds.insert( |
| 163 | plugin.id.as_str().to_string(), |
| 164 | plugin_adds(plugin, &mut cut).await, |
| 165 | ); |
| 166 | if cut { |
| 167 | omitted.insert(plugin.name().to_string()); |
| 168 | } |
| 169 | } |
| 170 | adds |
| 171 | } |
| 172 | |
| 173 | fn skill_source( |
| 174 | path: Option<&PathBuf>, |
| 175 | is_bundled: bool, |
| 176 | skills_dir: &FsPath, |
| 177 | directory_scope: codewhale_skills::SkillScope, |
| 178 | workspace: &FsPath, |
| 179 | ) -> &'static str { |
| 180 | if is_bundled { |
| 181 | return "built_in"; |
| 182 | } |
| 183 | match path { |
| 184 | Some(path) if path.starts_with(skills_dir) => { |
| 185 | if directory_scope == codewhale_skills::SkillScope::Project { |
| 186 | "project" |
| 187 | } else { |
| 188 | "user" |
| 189 | } |
| 190 | } |
| 191 | Some(path) if path.starts_with(workspace) => "project", |
| 192 | Some(_) => "other_app", |
| 193 | None => "plugin", |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | pub(super) async fn get_plugin_index( |
| 198 | State(state): State<RuntimeApiState>, |
| 199 | ) -> Result<Json<PluginIndexResponse>, ApiError> { |
| 200 | let mut items = Vec::new(); |
| 201 | let mut unavailable = Vec::new(); |
| 202 | let mut problems = Vec::new(); |
| 203 | |
| 204 | let commands = super::list_commands( |
| 205 | State(state.clone()), |
| 206 | Query(CommandsQuery { thread_id: None }), |
| 207 | ) |
| 208 | .await; |
| 209 | let mut plugin_commands: HashMap<String, BTreeSet<String>> = HashMap::new(); |
| 210 | if let Ok(Json(response)) = &commands { |
| 211 | for command in &response.commands { |
| 212 | if let (Some(plugin_id), "user") = (command.plugin_id.as_ref(), command.kind) { |
| 213 | plugin_commands |
| 214 | .entry(plugin_id.clone()) |
| 215 | .or_default() |
| 216 | .insert(command.name.clone()); |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | match plugins::list_plugins(State(state.clone())).await { |
| 222 | Ok(Json(response)) => { |
| 223 | let mut omitted = BTreeSet::new(); |
| 224 | let mut adds_by_id = plugin_adds_by_id(&state, &mut omitted).await; |
| 225 | for name in &omitted { |
| 226 | problems.push(IndexNote { |
| 227 | kind: "plugin", |
| 228 | message: format!( |
| 229 | "plugin '{name}' adds more files than are listed, or a file name with control characters; some names are left out of `adds`" |
| 230 | ), |
| 231 | }); |
| 232 | } |
| 233 | for diagnostic in &response.registry_diagnostics { |
| 234 | problems.push(IndexNote { |
| 235 | kind: "plugin", |
| 236 | message: diagnostic.message.clone(), |
| 237 | }); |
| 238 | } |
| 239 | for entry in &response.plugins { |
| 240 | let mut adds = adds_by_id.remove(&entry.id); |
| 241 | if entry.state == "active" |
| 242 | && commands.is_ok() |
| 243 | && let Some(adds) = adds.as_mut() |
| 244 | { |
| 245 | adds.commands = plugin_commands |
| 246 | .remove(&entry.id) |
| 247 | .map(|names| names.into_iter().collect()) |
| 248 | .unwrap_or_default(); |
| 249 | } |
| 250 | items.push(IndexItem { |
| 251 | id: format!("plugin:{}", entry.id), |
| 252 | kind: "plugin", |
| 253 | name: entry |
| 254 | .display_name |
| 255 | .clone() |
| 256 | .unwrap_or_else(|| entry.name.clone()), |
| 257 | description: entry.description.clone(), |
| 258 | source: plugin_source(entry.origin), |
| 259 | state: plugin_state(entry), |
| 260 | labels: adds |
| 261 | .as_ref() |
| 262 | .map(|adds| adds.labels(entry)) |
| 263 | .unwrap_or_default(), |
| 264 | plugin: None, |
| 265 | adds, |
| 266 | tier: None, |
| 267 | owner: "/v1/apps/plugins", |
| 268 | row: row_value(entry), |
| 269 | }); |
| 270 | } |
| 271 | } |
| 272 | Err(error) => note_failure(&mut unavailable, "plugin", &error), |
| 273 | } |
| 274 | |
| 275 | match plugins::list_plugin_catalog(State(state.clone())).await { |
| 276 | Ok(Json(catalog)) => { |
| 277 | for (tier, rows) in [ |
| 278 | ("builtin", &catalog.builtin), |
| 279 | ("experimental", &catalog.experimental), |
| 280 | ("more", &catalog.more), |
| 281 | ] { |
| 282 | for row in rows { |
| 283 | items.push(IndexItem { |
| 284 | id: format!("plugin:catalog:{}", row.id), |
| 285 | kind: "plugin", |
| 286 | name: row.title.clone(), |
| 287 | description: row.description.clone(), |
| 288 | source: "built_in", |
| 289 | state: if !row.available { |
| 290 | "unavailable" |
| 291 | } else if row.enabled { |
| 292 | "enabled" |
| 293 | } else { |
| 294 | "disabled" |
| 295 | }, |
| 296 | labels: Vec::new(), |
| 297 | plugin: None, |
| 298 | adds: None, |
| 299 | tier: Some(tier), |
| 300 | owner: "/v1/apps/plugins/catalog", |
| 301 | row: row_value(row), |
| 302 | }); |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | Err(error) => note_failure(&mut unavailable, "plugin", &error), |
| 307 | } |
| 308 | |
| 309 | match super::list_skills(State(state.clone())).await { |
| 310 | Ok(Json(response)) => { |
| 311 | for warning in &response.warnings { |
| 312 | problems.push(IndexNote { |
| 313 | kind: "skill", |
| 314 | message: warning.clone(), |
| 315 | }); |
| 316 | } |
| 317 | for skill in &response.skills { |
| 318 | if skill.plugin_id.is_some() { |
| 319 | continue; |
| 320 | } |
| 321 | items.push(IndexItem { |
| 322 | id: format!("skill:{}", skill.name), |
| 323 | kind: "skill", |
| 324 | name: skill.name.clone(), |
| 325 | description: Some(skill.description.clone()), |
| 326 | source: skill_source( |
| 327 | skill.path.as_ref(), |
| 328 | skill.is_bundled, |
| 329 | &response.directory, |
| 330 | response.directory_scope, |
| 331 | &state.workspace, |
| 332 | ), |
| 333 | state: if skill.enabled { "enabled" } else { "disabled" }, |
| 334 | labels: vec!["skill"], |
| 335 | plugin: None, |
| 336 | adds: None, |
| 337 | tier: None, |
| 338 | owner: "/v1/skills", |
| 339 | row: row_value(skill), |
| 340 | }); |
| 341 | } |
| 342 | } |
| 343 | Err(error) => note_failure(&mut unavailable, "skill", &error), |
| 344 | } |
| 345 | |
| 346 | match super::list_mcp_servers(State(state.clone())).await { |
| 347 | Ok(Json(response)) => { |
| 348 | for server in &response.servers { |
| 349 | let source = match server.origin { |
| 350 | "plugin" => continue, |
| 351 | "project" => "project", |
| 352 | "runtime" => "runtime", |
| 353 | _ => "user", |
| 354 | }; |
| 355 | items.push(IndexItem { |
| 356 | id: format!("connector:{}", server.name), |
| 357 | kind: "connector", |
| 358 | name: server.name.clone(), |
| 359 | description: None, |
| 360 | source, |
| 361 | state: if !server.enabled { |
| 362 | "disabled" |
| 363 | } else if server.auth_required { |
| 364 | "needs_sign_in" |
| 365 | } else { |
| 366 | "enabled" |
| 367 | }, |
| 368 | labels: vec!["connector"], |
| 369 | plugin: None, |
| 370 | adds: None, |
| 371 | tier: None, |
| 372 | owner: "/v1/apps/mcp/servers", |
| 373 | row: row_value(server), |
| 374 | }); |
| 375 | } |
| 376 | } |
| 377 | Err(error) => note_failure(&mut unavailable, "connector", &error), |
| 378 | } |
| 379 | |
| 380 | match super::list_hooks(State(state.clone()), Query(HooksQuery { thread_id: None })).await { |
| 381 | Ok(Json(response)) => { |
| 382 | for problem in &response.problems { |
| 383 | problems.push(IndexNote { |
| 384 | kind: "hook", |
| 385 | message: problem.clone(), |
| 386 | }); |
| 387 | } |
| 388 | let mut ordinals: HashMap<&'static str, usize> = HashMap::new(); |
| 389 | for hook in &response.hooks { |
| 390 | let ordinal = ordinals.entry(hook.event).or_default(); |
| 391 | *ordinal += 1; |
| 392 | let source = match hook.source { |
| 393 | "plugin" => continue, |
| 394 | "project" => "project", |
| 395 | _ => "user", |
| 396 | }; |
| 397 | let name = hook |
| 398 | .name |
| 399 | .clone() |
| 400 | .unwrap_or_else(|| format!("{} {}", hook.event, ordinal)); |
| 401 | items.push(IndexItem { |
| 402 | id: format!("hook:{source}:{}:{ordinal}", hook.event), |
| 403 | kind: "hook", |
| 404 | name, |
| 405 | description: None, |
| 406 | source, |
| 407 | state: if response.enabled { |
| 408 | "enabled" |
| 409 | } else { |
| 410 | "disabled" |
| 411 | }, |
| 412 | labels: vec!["hook"], |
| 413 | plugin: None, |
| 414 | adds: None, |
| 415 | tier: None, |
| 416 | owner: "/v1/hooks", |
| 417 | row: row_value(hook), |
| 418 | }); |
| 419 | } |
| 420 | } |
| 421 | Err(error) => note_failure(&mut unavailable, "hook", &error), |
| 422 | } |
| 423 | |
| 424 | match commands { |
| 425 | Ok(Json(response)) => { |
| 426 | for command in &response.commands { |
| 427 | let (source, plugin) = match (command.kind, command.plugin_id.as_ref()) { |
| 428 | ("builtin", _) => continue, |
| 429 | ("user", Some(_)) => continue, |
| 430 | ("extension", plugin_id) => ("plugin", plugin_id.cloned()), |
| 431 | _ if command.workspace_sourced => ("project", None), |
| 432 | _ => ("user", None), |
| 433 | }; |
| 434 | items.push(IndexItem { |
| 435 | id: format!("command:{}", command.name), |
| 436 | kind: "command", |
| 437 | name: command.name.clone(), |
| 438 | description: command.summary.clone(), |
| 439 | source, |
| 440 | state: "enabled", |
| 441 | labels: vec!["command"], |
| 442 | plugin, |
| 443 | adds: None, |
| 444 | tier: None, |
| 445 | owner: "/v1/commands", |
| 446 | row: row_value(command), |
| 447 | }); |
| 448 | } |
| 449 | } |
| 450 | Err(error) => note_failure(&mut unavailable, "command", &error), |
| 451 | } |
| 452 | |
| 453 | Ok(Json(PluginIndexResponse { |
| 454 | workspace: state.workspace.display().to_string(), |
| 455 | items, |
| 456 | unavailable, |
| 457 | problems, |
| 458 | })) |
| 459 | } |
| 460 | |
| 461 | #[cfg(test)] |
| 462 | mod tests { |
| 463 | use super::*; |
| 464 | |
| 465 | #[test] |
| 466 | fn configured_project_and_personal_roots_retain_their_discovered_scope() -> std::io::Result<()> |
| 467 | { |
| 468 | let temp = tempfile::tempdir()?; |
| 469 | let workspace = temp.path().join("project"); |
| 470 | let home = temp.path().join("home"); |
| 471 | let project_dir = workspace.join(".agents/skills"); |
| 472 | let personal_dir = home.join(".agents/skills"); |
| 473 | for (directory, workspace, expected) in [ |
| 474 | (&project_dir, workspace.as_path(), "project"), |
| 475 | (&personal_dir, workspace.as_path(), "user"), |
| 476 | (&personal_dir, temp.path(), "user"), |
| 477 | ] { |
| 478 | let entry = directory.join("readback/SKILL.md"); |
| 479 | std::fs::create_dir_all(entry.parent().unwrap())?; |
| 480 | std::fs::write(&entry, "# Readback")?; |
| 481 | let (_, _, scope) = |
| 482 | codewhale_skills::classify_configured_skills_dir(workspace, Some(&home), directory); |
| 483 | assert_eq!( |
| 484 | skill_source(Some(&entry), false, directory, scope, workspace), |
| 485 | expected |
| 486 | ); |
| 487 | } |
| 488 | Ok(()) |
| 489 | } |
| 490 | } |
| 491 |