| 1 | use std::collections::HashMap; |
| 2 | use std::path::PathBuf; |
| 3 | use std::sync::Mutex; |
| 4 | use std::time::{Duration, Instant}; |
| 5 | |
| 6 | use serde::Serialize; |
| 7 | |
| 8 | use crate::extension_host::ExtensionHostOptions; |
| 9 | |
| 10 | pub const STANDARD: &str = "standard"; |
| 11 | pub const CREATOR: &str = "creator"; |
| 12 | pub const SOURCE_BUILTIN: &str = "builtin"; |
| 13 | |
| 14 | pub const CREATOR_KEY_OFF_REASON: &str = |
| 15 | "Plugin creator is off in [features] (plugin_creator = false)."; |
| 16 | |
| 17 | pub const CREATOR_TOOL_NAMES: [&str; 3] = [ |
| 18 | "plugin_manager", |
| 19 | "cordis_inspect_list", |
| 20 | "cordis_inspect_query", |
| 21 | ]; |
| 22 | |
| 23 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 24 | pub struct Loadout { |
| 25 | pub always_load: &'static [&'static str], |
| 26 | pub creator_skills: bool, |
| 27 | pub first_turn_event: bool, |
| 28 | } |
| 29 | |
| 30 | impl Loadout { |
| 31 | pub const STANDARD: Self = Self { |
| 32 | always_load: &[], |
| 33 | creator_skills: false, |
| 34 | first_turn_event: false, |
| 35 | }; |
| 36 | pub const CREATOR: Self = Self { |
| 37 | always_load: &CREATOR_TOOL_NAMES, |
| 38 | creator_skills: true, |
| 39 | first_turn_event: true, |
| 40 | }; |
| 41 | } |
| 42 | |
| 43 | #[must_use] |
| 44 | pub fn loadout(stored: Option<&str>) -> Loadout { |
| 45 | if effective_id(stored) == CREATOR { |
| 46 | Loadout::CREATOR |
| 47 | } else { |
| 48 | Loadout::STANDARD |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | #[must_use] |
| 53 | pub fn is_creator(stored: Option<&str>) -> bool { |
| 54 | effective_id(stored) == CREATOR |
| 55 | } |
| 56 | |
| 57 | const AVAILABILITY_TTL: Duration = Duration::from_secs(30); |
| 58 | |
| 59 | #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] |
| 60 | #[error("{message}")] |
| 61 | pub struct ModeRefusal { |
| 62 | pub code: &'static str, |
| 63 | pub message: String, |
| 64 | } |
| 65 | |
| 66 | impl ModeRefusal { |
| 67 | pub const UNKNOWN_MODE: &'static str = "unknown_mode"; |
| 68 | pub const MODE_UNAVAILABLE: &'static str = "mode_unavailable"; |
| 69 | pub const MODE_LOCKED: &'static str = "mode_locked"; |
| 70 | pub const MODE_NOT_SUPPORTED_WITH_EXECUTOR: &'static str = "mode_not_supported_with_executor"; |
| 71 | |
| 72 | pub fn new(code: &'static str, message: impl Into<String>) -> Self { |
| 73 | Self { |
| 74 | code, |
| 75 | message: message.into(), |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | pub fn locked() -> Self { |
| 80 | Self::new( |
| 81 | Self::MODE_LOCKED, |
| 82 | "The conversation mode is fixed once the conversation has its first turn; start a new conversation to use another mode.", |
| 83 | ) |
| 84 | } |
| 85 | |
| 86 | pub fn with_executor() -> Self { |
| 87 | Self::new( |
| 88 | Self::MODE_NOT_SUPPORTED_WITH_EXECUTOR, |
| 89 | "A session with another agent uses that agent's own tools and instructions; conversation modes are unavailable.", |
| 90 | ) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | #[derive(Debug, Clone, Serialize, PartialEq, Eq)] |
| 95 | pub struct ConversationMode { |
| 96 | pub id: String, |
| 97 | pub name: String, |
| 98 | pub description: String, |
| 99 | pub source: &'static str, |
| 100 | pub available: bool, |
| 101 | #[serde(skip_serializing_if = "Option::is_none")] |
| 102 | pub reason: Option<String>, |
| 103 | } |
| 104 | |
| 105 | #[derive(Debug, Clone, Serialize, PartialEq, Eq)] |
| 106 | pub struct ConversationModeTable { |
| 107 | pub default: &'static str, |
| 108 | pub modes: Vec<ConversationMode>, |
| 109 | } |
| 110 | |
| 111 | #[must_use] |
| 112 | pub fn effective_id(stored: Option<&str>) -> &str { |
| 113 | stored.unwrap_or(STANDARD) |
| 114 | } |
| 115 | |
| 116 | #[must_use] |
| 117 | pub fn stored_form(id: &str) -> Option<String> { |
| 118 | (id != STANDARD).then(|| id.to_string()) |
| 119 | } |
| 120 | |
| 121 | #[must_use] |
| 122 | pub fn table(creator_unavailable: Option<String>) -> ConversationModeTable { |
| 123 | ConversationModeTable { |
| 124 | default: STANDARD, |
| 125 | modes: vec![ |
| 126 | ConversationMode { |
| 127 | id: STANDARD.to_string(), |
| 128 | name: "Standard".to_string(), |
| 129 | description: "The everyday Codewhale agent with its normal tools and skills." |
| 130 | .to_string(), |
| 131 | source: SOURCE_BUILTIN, |
| 132 | available: true, |
| 133 | reason: None, |
| 134 | }, |
| 135 | ConversationMode { |
| 136 | id: CREATOR.to_string(), |
| 137 | name: "Creator".to_string(), |
| 138 | description: |
| 139 | "Build, inspect and test Codewhale plugins in this conversation, with the plugin authoring tools and guides loaded." |
| 140 | .to_string(), |
| 141 | source: SOURCE_BUILTIN, |
| 142 | available: creator_unavailable.is_none(), |
| 143 | reason: creator_unavailable, |
| 144 | }, |
| 145 | ], |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 150 | struct CreatorProbeKey { |
| 151 | runtime: &'static str, |
| 152 | node_override: Option<PathBuf>, |
| 153 | bun_override: Option<PathBuf>, |
| 154 | } |
| 155 | |
| 156 | impl CreatorProbeKey { |
| 157 | fn from_options(options: &ExtensionHostOptions) -> Self { |
| 158 | Self { |
| 159 | runtime: options.runtime.as_str(), |
| 160 | node_override: options.node_override.clone(), |
| 161 | bun_override: options.bun_override.clone(), |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | type ProbeCache = HashMap<CreatorProbeKey, (Instant, Option<String>)>; |
| 167 | |
| 168 | static CREATOR_PROBE: Mutex<Option<ProbeCache>> = Mutex::new(None); |
| 169 | |
| 170 | #[cfg(any(test, feature = "test-support"))] |
| 171 | static CREATOR_PROBE_OVERRIDE: Mutex<Option<Option<String>>> = Mutex::new(None); |
| 172 | |
| 173 | #[cfg(any(test, feature = "test-support"))] |
| 174 | static CREATOR_PROBE_LOCK: Mutex<()> = Mutex::new(()); |
| 175 | |
| 176 | #[cfg(any(test, feature = "test-support"))] |
| 177 | pub struct CreatorAvailabilityGuard { |
| 178 | _serial: std::sync::MutexGuard<'static, ()>, |
| 179 | } |
| 180 | |
| 181 | #[cfg(any(test, feature = "test-support"))] |
| 182 | impl CreatorAvailabilityGuard { |
| 183 | pub fn set(unavailable_reason: Option<&str>) -> Self { |
| 184 | Self::hold(Some(unavailable_reason.map(str::to_string))) |
| 185 | } |
| 186 | |
| 187 | pub fn unforced() -> Self { |
| 188 | Self::hold(None) |
| 189 | } |
| 190 | |
| 191 | fn hold(forced: Option<Option<String>>) -> Self { |
| 192 | let serial = CREATOR_PROBE_LOCK |
| 193 | .lock() |
| 194 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 195 | *CREATOR_PROBE_OVERRIDE |
| 196 | .lock() |
| 197 | .unwrap_or_else(std::sync::PoisonError::into_inner) = forced; |
| 198 | Self { _serial: serial } |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | #[cfg(any(test, feature = "test-support"))] |
| 203 | pub fn clear_probe_cache_for_tests() { |
| 204 | *CREATOR_PROBE |
| 205 | .lock() |
| 206 | .unwrap_or_else(std::sync::PoisonError::into_inner) = None; |
| 207 | } |
| 208 | |
| 209 | #[cfg(any(test, feature = "test-support"))] |
| 210 | impl Drop for CreatorAvailabilityGuard { |
| 211 | fn drop(&mut self) { |
| 212 | *CREATOR_PROBE_OVERRIDE |
| 213 | .lock() |
| 214 | .unwrap_or_else(std::sync::PoisonError::into_inner) = None; |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | fn probe_host_runtime(options: &ExtensionHostOptions) -> Option<String> { |
| 219 | let resolution = codewhale_dependencies::resolve_extension_host_runtime( |
| 220 | options.runtime, |
| 221 | options.node_override.as_deref(), |
| 222 | options.bun_override.as_deref(), |
| 223 | crate::extension_host::bundle_sha256(), |
| 224 | ); |
| 225 | if resolution.selected.is_some() { |
| 226 | None |
| 227 | } else { |
| 228 | Some(format!( |
| 229 | "Creator mode needs a plugin runtime (Node.js or Bun), and none was found. {}", |
| 230 | resolution.failure() |
| 231 | )) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | pub async fn creator_unavailable_reason( |
| 236 | options: ExtensionHostOptions, |
| 237 | plugin_creator_enabled: bool, |
| 238 | ) -> Option<String> { |
| 239 | if !plugin_creator_enabled { |
| 240 | return Some(CREATOR_KEY_OFF_REASON.to_string()); |
| 241 | } |
| 242 | #[cfg(any(test, feature = "test-support"))] |
| 243 | if let Some(forced) = CREATOR_PROBE_OVERRIDE |
| 244 | .lock() |
| 245 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 246 | .clone() |
| 247 | { |
| 248 | return forced; |
| 249 | } |
| 250 | let key = CreatorProbeKey::from_options(&options); |
| 251 | if let Some((at, reason)) = CREATOR_PROBE |
| 252 | .lock() |
| 253 | .expect("probe cache") |
| 254 | .as_ref() |
| 255 | .and_then(|cache| cache.get(&key).cloned()) |
| 256 | && at.elapsed() < AVAILABILITY_TTL |
| 257 | { |
| 258 | return reason; |
| 259 | } |
| 260 | let reason = tokio::task::spawn_blocking(move || probe_host_runtime(&options)) |
| 261 | .await |
| 262 | .unwrap_or_else(|_| Some("Creator mode could not check for a plugin runtime.".to_string())); |
| 263 | CREATOR_PROBE |
| 264 | .lock() |
| 265 | .expect("probe cache") |
| 266 | .get_or_insert_with(HashMap::new) |
| 267 | .insert(key, (Instant::now(), reason.clone())); |
| 268 | reason |
| 269 | } |
| 270 | |
| 271 | pub async fn current_table( |
| 272 | options: ExtensionHostOptions, |
| 273 | plugin_creator_enabled: bool, |
| 274 | ) -> ConversationModeTable { |
| 275 | table(creator_unavailable_reason(options, plugin_creator_enabled).await) |
| 276 | } |
| 277 | |
| 278 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 279 | pub struct ModeSelection { |
| 280 | pub id: String, |
| 281 | pub unavailable: Option<String>, |
| 282 | } |
| 283 | |
| 284 | impl ModeSelection { |
| 285 | pub fn require_available(&self) -> Result<(), ModeRefusal> { |
| 286 | match &self.unavailable { |
| 287 | Some(reason) => Err(ModeRefusal::new( |
| 288 | ModeRefusal::MODE_UNAVAILABLE, |
| 289 | reason.clone(), |
| 290 | )), |
| 291 | None => Ok(()), |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | pub async fn select( |
| 297 | id: &str, |
| 298 | options: ExtensionHostOptions, |
| 299 | plugin_creator_enabled: bool, |
| 300 | ) -> Result<ModeSelection, ModeRefusal> { |
| 301 | let table = current_table(options, plugin_creator_enabled).await; |
| 302 | match table.modes.into_iter().find(|mode| mode.id == id) { |
| 303 | Some(mode) => Ok(ModeSelection { |
| 304 | id: mode.id, |
| 305 | unavailable: if mode.available { |
| 306 | None |
| 307 | } else { |
| 308 | Some( |
| 309 | mode.reason |
| 310 | .unwrap_or_else(|| "This mode is unavailable.".to_string()), |
| 311 | ) |
| 312 | }, |
| 313 | }), |
| 314 | None => Err(ModeRefusal::new( |
| 315 | ModeRefusal::UNKNOWN_MODE, |
| 316 | format!("`{id}` is not a conversation mode; GET /v1/modes lists them."), |
| 317 | )), |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | #[cfg(test)] |
| 322 | mod tests { |
| 323 | use super::*; |
| 324 | |
| 325 | #[tokio::test] |
| 326 | async fn creator_unavailable_reasons_and_key_off_beats_probe_cache() { |
| 327 | let _unforced = CreatorAvailabilityGuard::unforced(); |
| 328 | clear_probe_cache_for_tests(); |
| 329 | let options = ExtensionHostOptions::default(); |
| 330 | let key = CreatorProbeKey::from_options(&options); |
| 331 | assert_eq!( |
| 332 | creator_unavailable_reason(options.clone(), false).await, |
| 333 | Some(CREATOR_KEY_OFF_REASON.to_string()) |
| 334 | ); |
| 335 | |
| 336 | let missing_runtime = ExtensionHostOptions { |
| 337 | runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node, |
| 338 | node_override: Some(PathBuf::from("/nonexistent/node-for-creator-test")), |
| 339 | ..Default::default() |
| 340 | }; |
| 341 | let reason = probe_host_runtime(&missing_runtime).expect("missing runtime reason"); |
| 342 | assert!(reason.contains("Node.js or Bun"), "{reason}"); |
| 343 | let uncached_missing = creator_unavailable_reason(missing_runtime.clone(), true) |
| 344 | .await |
| 345 | .expect("missing runtime reason"); |
| 346 | assert!( |
| 347 | uncached_missing.contains("Node.js or Bun"), |
| 348 | "{uncached_missing}" |
| 349 | ); |
| 350 | |
| 351 | { |
| 352 | let mut cache = CREATOR_PROBE.lock().expect("probe cache"); |
| 353 | cache |
| 354 | .get_or_insert_with(HashMap::new) |
| 355 | .insert(key.clone(), (Instant::now(), None)); |
| 356 | } |
| 357 | assert_eq!( |
| 358 | creator_unavailable_reason(options.clone(), true).await, |
| 359 | None |
| 360 | ); |
| 361 | assert_eq!( |
| 362 | creator_unavailable_reason(missing_runtime, true).await, |
| 363 | Some(uncached_missing) |
| 364 | ); |
| 365 | assert_eq!( |
| 366 | creator_unavailable_reason(options.clone(), false).await, |
| 367 | Some(CREATOR_KEY_OFF_REASON.to_string()) |
| 368 | ); |
| 369 | |
| 370 | { |
| 371 | let mut cache = CREATOR_PROBE.lock().expect("probe cache"); |
| 372 | cache |
| 373 | .get_or_insert_with(HashMap::new) |
| 374 | .insert(key, (Instant::now(), Some("stale probe".to_string()))); |
| 375 | } |
| 376 | assert_eq!( |
| 377 | creator_unavailable_reason(options.clone(), true).await, |
| 378 | Some("stale probe".to_string()) |
| 379 | ); |
| 380 | assert_eq!( |
| 381 | creator_unavailable_reason(options, false).await, |
| 382 | Some(CREATOR_KEY_OFF_REASON.to_string()) |
| 383 | ); |
| 384 | clear_probe_cache_for_tests(); |
| 385 | } |
| 386 | } |
| 387 |