| 1 | use std::collections::BTreeSet; |
| 2 | |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use sha2::{Digest, Sha256}; |
| 5 | |
| 6 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] |
| 7 | #[serde(rename_all = "snake_case")] |
| 8 | pub enum HostService { |
| 9 | Workspace, |
| 10 | Llm, |
| 11 | Network, |
| 12 | Settings, |
| 13 | Catalog, |
| 14 | Terminal, |
| 15 | Remote, |
| 16 | Attachments, |
| 17 | } |
| 18 | |
| 19 | impl HostService { |
| 20 | pub const ALL: [Self; 8] = [ |
| 21 | Self::Workspace, |
| 22 | Self::Llm, |
| 23 | Self::Network, |
| 24 | Self::Settings, |
| 25 | Self::Catalog, |
| 26 | Self::Terminal, |
| 27 | Self::Remote, |
| 28 | Self::Attachments, |
| 29 | ]; |
| 30 | |
| 31 | #[must_use] |
| 32 | pub fn name(self) -> &'static str { |
| 33 | match self { |
| 34 | Self::Workspace => "workspace", |
| 35 | Self::Llm => "llm", |
| 36 | Self::Network => "network", |
| 37 | Self::Settings => "settings", |
| 38 | Self::Catalog => "catalog", |
| 39 | Self::Terminal => "terminal", |
| 40 | Self::Remote => "remote", |
| 41 | Self::Attachments => "attachments", |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | #[must_use] |
| 46 | pub fn parse(name: &str) -> Option<Self> { |
| 47 | Self::ALL.into_iter().find(|service| service.name() == name) |
| 48 | } |
| 49 | |
| 50 | #[must_use] |
| 51 | pub fn label(self) -> &'static str { |
| 52 | match self { |
| 53 | Self::Workspace => "Workspace files and commands", |
| 54 | Self::Llm => "Your model provider", |
| 55 | Self::Network => "Network requests", |
| 56 | Self::Settings => "Codewhale settings", |
| 57 | Self::Catalog => "Plugins and provider routes", |
| 58 | Self::Terminal => "Terminal sessions", |
| 59 | Self::Remote => "Remote pairing", |
| 60 | Self::Attachments => "Images in the conversation", |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | #[must_use] |
| 65 | pub fn plain(self) -> &'static str { |
| 66 | match self { |
| 67 | Self::Workspace => { |
| 68 | "read and change files and run commands in the session's workspace, under Codewhale's approval rules" |
| 69 | } |
| 70 | Self::Llm => "send requests to the model provider you approved, on your account", |
| 71 | Self::Network => { |
| 72 | "send requests to the hosts in its review, with credentials it stores in Codewhale" |
| 73 | } |
| 74 | Self::Settings => "read and change the Codewhale settings in its review", |
| 75 | Self::Catalog => { |
| 76 | "list your provider routes, read your balance and plan plugin installs" |
| 77 | } |
| 78 | Self::Terminal => "start and drive terminal sessions in the session's workspace", |
| 79 | Self::Remote => "pair another device with the session", |
| 80 | Self::Attachments => { |
| 81 | "read and add images in this conversation, within Codewhale's image limits" |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | pub const HOST_SERVICE_INJECTS: &[(&str, HostService)] = &[ |
| 88 | ("workspace", HostService::Workspace), |
| 89 | ("llm", HostService::Llm), |
| 90 | ("credentials", HostService::Network), |
| 91 | ("settings", HostService::Settings), |
| 92 | ("pluginManager", HostService::Catalog), |
| 93 | ("deepseekAccount", HostService::Catalog), |
| 94 | ("terminal", HostService::Terminal), |
| 95 | ("remote", HostService::Remote), |
| 96 | ("attachments", HostService::Attachments), |
| 97 | ]; |
| 98 | |
| 99 | #[cfg(any(test, feature = "test-support"))] |
| 100 | thread_local! { |
| 101 | static TEST_OFFER: std::cell::RefCell<Option<Vec<HostService>>> = |
| 102 | const { std::cell::RefCell::new(None) }; |
| 103 | } |
| 104 | |
| 105 | #[cfg(any(test, feature = "test-support"))] |
| 106 | pub struct TestOffer(Option<Vec<HostService>>); |
| 107 | |
| 108 | #[cfg(any(test, feature = "test-support"))] |
| 109 | impl TestOffer { |
| 110 | pub fn only(services: &[HostService]) -> Self { |
| 111 | Self(TEST_OFFER.with(|offer| offer.replace(Some(services.to_vec())))) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | #[cfg(any(test, feature = "test-support"))] |
| 116 | impl Drop for TestOffer { |
| 117 | fn drop(&mut self) { |
| 118 | let previous = self.0.take(); |
| 119 | TEST_OFFER.with(|offer| *offer.borrow_mut() = previous); |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | #[must_use] |
| 124 | pub fn offered(service: HostService) -> bool { |
| 125 | #[cfg(any(test, feature = "test-support"))] |
| 126 | if let Some(offer) = TEST_OFFER.with(|offer| offer.borrow().clone()) { |
| 127 | return offer.contains(&service); |
| 128 | } |
| 129 | HOST_SERVICE_INJECTS |
| 130 | .iter() |
| 131 | .any(|(_, candidate)| *candidate == service) |
| 132 | } |
| 133 | |
| 134 | #[must_use] |
| 135 | pub fn declared_injects(source: &str) -> BTreeSet<String> { |
| 136 | static DECLARATION: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new(); |
| 137 | static NAME: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new(); |
| 138 | let declaration = DECLARATION.get_or_init(|| { |
| 139 | regex::Regex::new(r"\binject\b\s*[:=]\s*(\[[^\]]*\]|\{[^;]*?\}\s*(?:[;,\n)]|$))") |
| 140 | .expect("inject declaration pattern") |
| 141 | }); |
| 142 | let name = NAME.get_or_init(|| { |
| 143 | regex::Regex::new( |
| 144 | r#""([A-Za-z_$][\w$]{0,63})"|'([A-Za-z_$][\w$]{0,63})'|([A-Za-z_$][\w$]{0,63})\s*:"#, |
| 145 | ) |
| 146 | .expect("inject name pattern") |
| 147 | }); |
| 148 | let mut names = BTreeSet::new(); |
| 149 | for found in declaration.captures_iter(source) { |
| 150 | let body = found.get(1).map_or("", |body| body.as_str()); |
| 151 | for capture in name.captures_iter(body) { |
| 152 | if let Some(matched) = capture.get(1).or(capture.get(2)).or(capture.get(3)) { |
| 153 | names.insert(matched.as_str().to_string()); |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | names |
| 158 | } |
| 159 | |
| 160 | #[must_use] |
| 161 | pub fn services_for_injects<'a>( |
| 162 | injects: impl IntoIterator<Item = &'a str>, |
| 163 | table: &[(&str, HostService)], |
| 164 | ) -> Vec<HostService> { |
| 165 | let services: BTreeSet<HostService> = injects |
| 166 | .into_iter() |
| 167 | .flat_map(|inject| { |
| 168 | table |
| 169 | .iter() |
| 170 | .filter(move |(name, _)| *name == inject) |
| 171 | .map(|(_, service)| *service) |
| 172 | }) |
| 173 | .collect(); |
| 174 | services.into_iter().collect() |
| 175 | } |
| 176 | |
| 177 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 178 | #[serde(rename_all = "snake_case")] |
| 179 | pub enum PersonVia { |
| 180 | Terminal, |
| 181 | App, |
| 182 | ApprovalCard, |
| 183 | } |
| 184 | |
| 185 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 186 | #[serde(rename_all = "snake_case")] |
| 187 | pub enum AgentPosture { |
| 188 | FullAccess, |
| 189 | AutoReview, |
| 190 | CommandLine, |
| 191 | } |
| 192 | |
| 193 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 194 | pub struct AgentApproval { |
| 195 | pub posture: AgentPosture, |
| 196 | pub workspace: String, |
| 197 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 198 | pub thread_id: Option<String>, |
| 199 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 200 | pub turn_id: Option<String>, |
| 201 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 202 | pub tool_call_id: Option<String>, |
| 203 | } |
| 204 | |
| 205 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 206 | #[serde(tag = "kind", rename_all = "snake_case")] |
| 207 | pub enum PluginApprover { |
| 208 | Person { via: PersonVia }, |
| 209 | Agent(AgentApproval), |
| 210 | CommandLine, |
| 211 | } |
| 212 | |
| 213 | #[derive(Debug, Clone, Serialize)] |
| 214 | #[serde(tag = "kind", rename_all = "snake_case")] |
| 215 | pub enum PluginCohort { |
| 216 | Reviewed, |
| 217 | Agent { workspace: String }, |
| 218 | } |
| 219 | |
| 220 | impl PluginCohort { |
| 221 | #[must_use] |
| 222 | pub fn agent(workspace: impl AsRef<std::path::Path>) -> Self { |
| 223 | let normalized = codewhale_config::normalize_project_workspace(workspace.as_ref()) |
| 224 | .unwrap_or_else(|_| workspace.as_ref().components().collect()); |
| 225 | Self::Agent { |
| 226 | workspace: normalized.to_string_lossy().into_owned(), |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | impl PartialEq for PluginCohort { |
| 232 | fn eq(&self, other: &Self) -> bool { |
| 233 | match (self, other) { |
| 234 | (Self::Reviewed, Self::Reviewed) => true, |
| 235 | (Self::Agent { workspace: a }, Self::Agent { workspace: b }) => { |
| 236 | let norm_a = codewhale_config::normalize_project_workspace(std::path::Path::new(a)) |
| 237 | .unwrap_or_else(|_| std::path::Path::new(a).components().collect()); |
| 238 | let norm_b = codewhale_config::normalize_project_workspace(std::path::Path::new(b)) |
| 239 | .unwrap_or_else(|_| std::path::Path::new(b).components().collect()); |
| 240 | norm_a == norm_b |
| 241 | } |
| 242 | _ => false, |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | impl Eq for PluginCohort {} |
| 248 | |
| 249 | impl PartialOrd for PluginCohort { |
| 250 | fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { |
| 251 | Some(self.cmp(other)) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | impl Ord for PluginCohort { |
| 256 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
| 257 | let key = |cohort: &Self| match cohort { |
| 258 | Self::Reviewed => (0u8, None), |
| 259 | Self::Agent { workspace } => { |
| 260 | let norm = |
| 261 | codewhale_config::normalize_project_workspace(std::path::Path::new(workspace)) |
| 262 | .unwrap_or_else(|_| std::path::Path::new(workspace).components().collect()); |
| 263 | (1u8, Some(norm)) |
| 264 | } |
| 265 | }; |
| 266 | key(self).cmp(&key(other)) |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | impl std::hash::Hash for PluginCohort { |
| 271 | fn hash<H: std::hash::Hasher>(&self, state: &mut H) { |
| 272 | match self { |
| 273 | Self::Reviewed => 0u8.hash(state), |
| 274 | Self::Agent { workspace } => { |
| 275 | 1u8.hash(state); |
| 276 | let norm = |
| 277 | codewhale_config::normalize_project_workspace(std::path::Path::new(workspace)) |
| 278 | .unwrap_or_else(|_| std::path::Path::new(workspace).components().collect()); |
| 279 | norm.hash(state); |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | impl PluginApprover { |
| 286 | #[must_use] |
| 287 | pub fn person(via: PersonVia) -> Self { |
| 288 | Self::Person { via } |
| 289 | } |
| 290 | |
| 291 | #[must_use] |
| 292 | pub fn command_line(agent_workspace: Option<&std::path::Path>) -> Self { |
| 293 | match agent_workspace { |
| 294 | Some(workspace) => Self::Agent(AgentApproval { |
| 295 | posture: AgentPosture::CommandLine, |
| 296 | workspace: workspace.to_string_lossy().into_owned(), |
| 297 | thread_id: None, |
| 298 | turn_id: None, |
| 299 | tool_call_id: None, |
| 300 | }), |
| 301 | None => Self::CommandLine, |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | #[must_use] |
| 306 | pub fn auto_review( |
| 307 | agent_workspace: &std::path::Path, |
| 308 | thread_id: Option<String>, |
| 309 | turn_id: Option<String>, |
| 310 | tool_call_id: Option<String>, |
| 311 | ) -> Self { |
| 312 | Self::Agent(AgentApproval { |
| 313 | posture: AgentPosture::AutoReview, |
| 314 | workspace: agent_workspace.to_string_lossy().into_owned(), |
| 315 | thread_id, |
| 316 | turn_id, |
| 317 | tool_call_id, |
| 318 | }) |
| 319 | } |
| 320 | |
| 321 | #[must_use] |
| 322 | pub fn kind(&self) -> &'static str { |
| 323 | match self { |
| 324 | Self::Person { .. } => "person", |
| 325 | Self::Agent(_) => "agent", |
| 326 | Self::CommandLine => "command_line", |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | #[must_use] |
| 331 | pub fn cohort(&self) -> PluginCohort { |
| 332 | match self { |
| 333 | Self::Agent(agent) => PluginCohort::agent(&agent.workspace), |
| 334 | Self::Person { .. } | Self::CommandLine => PluginCohort::Reviewed, |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | #[must_use] |
| 339 | pub fn agent_workspace(&self) -> Option<&str> { |
| 340 | match self { |
| 341 | Self::Agent(agent) => Some(agent.workspace.as_str()), |
| 342 | Self::Person { .. } | Self::CommandLine => None, |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | #[must_use] |
| 348 | pub fn cohort_of(approver: Option<&PluginApprover>) -> PluginCohort { |
| 349 | approver.map_or(PluginCohort::Reviewed, PluginApprover::cohort) |
| 350 | } |
| 351 | |
| 352 | #[must_use] |
| 353 | pub fn approver_label(approver: Option<&PluginApprover>) -> &'static str { |
| 354 | match approver { |
| 355 | Some(PluginApprover::Person { .. }) => "approved by you", |
| 356 | Some(PluginApprover::Agent(agent)) => match agent.posture { |
| 357 | AgentPosture::FullAccess => "approved by the agent in Full Access", |
| 358 | AgentPosture::AutoReview => "approved by the agent in Auto-Review", |
| 359 | AgentPosture::CommandLine => "approved by the agent from a shell command", |
| 360 | }, |
| 361 | Some(PluginApprover::CommandLine) => { |
| 362 | "trusted from the command line with --yes; no review was shown there" |
| 363 | } |
| 364 | None => "approver not recorded (reviewed before 0.10.3)", |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | #[must_use] |
| 369 | pub fn recorded_approver_label( |
| 370 | approver: Option<&str>, |
| 371 | posture: Option<&str>, |
| 372 | ) -> Option<&'static str> { |
| 373 | match (approver, posture) { |
| 374 | (Some("person"), _) => Some("approved by you"), |
| 375 | (Some("agent"), Some("full_access")) => Some("approved by the agent in Full Access"), |
| 376 | (Some("agent"), Some("auto_review")) => Some("approved by the agent in Auto-Review"), |
| 377 | (Some("agent"), Some("command_line")) => Some("approved by the agent from a shell command"), |
| 378 | (Some("command_line"), _) => { |
| 379 | Some("trusted from the command line with --yes; no review was shown there") |
| 380 | } |
| 381 | (Some("none"), _) => Some("approver not recorded (reviewed before 0.10.3)"), |
| 382 | _ => None, |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | pub const AGENT_PROCESS_NOTE: &str = "runs apart from your reviewed plugins until you review it"; |
| 387 | |
| 388 | #[must_use] |
| 389 | pub fn short_review_date(timestamp: &str) -> &str { |
| 390 | let bytes = timestamp.as_bytes(); |
| 391 | if bytes.len() >= 10 |
| 392 | && bytes[0..4].iter().all(u8::is_ascii_digit) |
| 393 | && bytes[4] == b'-' |
| 394 | && bytes[5..7].iter().all(u8::is_ascii_digit) |
| 395 | && bytes[7] == b'-' |
| 396 | && bytes[8..10].iter().all(u8::is_ascii_digit) |
| 397 | && timestamp.is_char_boundary(10) |
| 398 | { |
| 399 | ×tamp[..10] |
| 400 | } else { |
| 401 | timestamp |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | #[must_use] |
| 406 | pub fn workspace_folder_name(workspace: &str) -> &str { |
| 407 | std::path::Path::new(workspace) |
| 408 | .file_name() |
| 409 | .and_then(|name| name.to_str()) |
| 410 | .filter(|name| !name.is_empty()) |
| 411 | .unwrap_or(workspace) |
| 412 | } |
| 413 | |
| 414 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 415 | #[serde(rename_all = "snake_case")] |
| 416 | pub enum HostServiceWireState { |
| 417 | CanUse, |
| 418 | NotOffered, |
| 419 | } |
| 420 | |
| 421 | #[must_use] |
| 422 | pub fn host_service_wire_state( |
| 423 | granted: &[HostService], |
| 424 | line: &HostServiceLine, |
| 425 | ) -> HostServiceWireState { |
| 426 | if line.offered && granted.contains(&line.service) { |
| 427 | HostServiceWireState::CanUse |
| 428 | } else { |
| 429 | HostServiceWireState::NotOffered |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 434 | pub struct ReviewApproval { |
| 435 | pub approved_by: PluginApprover, |
| 436 | pub host_services: Option<String>, |
| 437 | } |
| 438 | |
| 439 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 440 | pub struct ReviewPeer { |
| 441 | pub id: String, |
| 442 | pub name: String, |
| 443 | } |
| 444 | |
| 445 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 446 | pub struct HostServiceLine { |
| 447 | pub service: HostService, |
| 448 | pub offered: bool, |
| 449 | pub shared_with: Vec<ReviewPeer>, |
| 450 | pub withheld_by: Vec<ReviewPeer>, |
| 451 | } |
| 452 | |
| 453 | pub const REVIEW_LEAD: &str = "This plugin asks to use services of the Codewhale host. Plugins share one process: a service works only while every plugin that is turned on holds it, and each of those plugins can use it while another's tool runs."; |
| 454 | |
| 455 | fn quoted(peers: &[ReviewPeer]) -> String { |
| 456 | peers |
| 457 | .iter() |
| 458 | .map(|peer| format!("`{}`", peer.name)) |
| 459 | .collect::<Vec<_>>() |
| 460 | .join(", ") |
| 461 | } |
| 462 | |
| 463 | impl HostServiceLine { |
| 464 | #[must_use] |
| 465 | pub fn sentence(&self) -> String { |
| 466 | let label = self.service.label(); |
| 467 | if !self.offered { |
| 468 | return format!( |
| 469 | "{label}: this version of Codewhale does not offer it to plugins. Approving grants nothing for it." |
| 470 | ); |
| 471 | } |
| 472 | let mut sentence = format!("{label}: {}.", self.service.plain()); |
| 473 | if self.shared_with.is_empty() { |
| 474 | sentence.push_str(" No other reviewed plugin holds it."); |
| 475 | } else { |
| 476 | sentence.push_str(&format!( |
| 477 | " Shared with {}: each can use it as this plugin while this plugin's tool runs, and this plugin can use it as them.", |
| 478 | quoted(&self.shared_with) |
| 479 | )); |
| 480 | } |
| 481 | if !self.withheld_by.is_empty() { |
| 482 | sentence.push_str(&format!( |
| 483 | " Off for now: {} {} turned on and {} review does not include it.", |
| 484 | quoted(&self.withheld_by), |
| 485 | if self.withheld_by.len() == 1 { |
| 486 | "is" |
| 487 | } else { |
| 488 | "are" |
| 489 | }, |
| 490 | if self.withheld_by.len() == 1 { |
| 491 | "its" |
| 492 | } else { |
| 493 | "their" |
| 494 | }, |
| 495 | )); |
| 496 | } |
| 497 | sentence |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 502 | pub struct HostServiceReview { |
| 503 | pub lines: Vec<HostServiceLine>, |
| 504 | pub token: String, |
| 505 | } |
| 506 | |
| 507 | impl HostServiceReview { |
| 508 | #[must_use] |
| 509 | pub fn new( |
| 510 | plugin_id: &str, |
| 511 | content_hash: &str, |
| 512 | capability_hash: &str, |
| 513 | cohort: &PluginCohort, |
| 514 | lines: Vec<HostServiceLine>, |
| 515 | ) -> Self { |
| 516 | let mut hasher = Sha256::new(); |
| 517 | let mut field = |label: &str, value: &str| { |
| 518 | hasher.update(label.as_bytes()); |
| 519 | hasher.update(b"\0"); |
| 520 | hasher.update((value.len() as u64).to_le_bytes()); |
| 521 | hasher.update(value.as_bytes()); |
| 522 | }; |
| 523 | field("codewhale-host-service-review-v1", plugin_id); |
| 524 | field("content", content_hash); |
| 525 | field("capability", capability_hash); |
| 526 | match cohort { |
| 527 | PluginCohort::Reviewed => field("cohort", "reviewed"), |
| 528 | PluginCohort::Agent { workspace } => field("cohort-agent", workspace), |
| 529 | } |
| 530 | for line in &lines { |
| 531 | field("service", line.service.name()); |
| 532 | field("offered", if line.offered { "yes" } else { "no" }); |
| 533 | for peer in &line.shared_with { |
| 534 | field("shared", &peer.id); |
| 535 | } |
| 536 | for peer in &line.withheld_by { |
| 537 | field("withheld", &peer.id); |
| 538 | } |
| 539 | } |
| 540 | let token = crate::manifest::hex_digest(hasher.finalize()); |
| 541 | Self { lines, token } |
| 542 | } |
| 543 | |
| 544 | #[must_use] |
| 545 | pub fn grants(&self) -> Vec<HostService> { |
| 546 | self.lines |
| 547 | .iter() |
| 548 | .filter(|line| line.offered) |
| 549 | .map(|line| line.service) |
| 550 | .collect() |
| 551 | } |
| 552 | |
| 553 | #[must_use] |
| 554 | pub fn text(&self) -> Vec<String> { |
| 555 | if self.lines.is_empty() { |
| 556 | return Vec::new(); |
| 557 | } |
| 558 | std::iter::once(REVIEW_LEAD.to_string()) |
| 559 | .chain(self.lines.iter().map(HostServiceLine::sentence)) |
| 560 | .collect() |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | #[cfg(test)] |
| 565 | mod tests { |
| 566 | use super::*; |
| 567 | |
| 568 | fn peer(name: &str) -> ReviewPeer { |
| 569 | ReviewPeer { |
| 570 | id: format!("user/0/{name}"), |
| 571 | name: name.to_string(), |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | fn line(shared: &[&str], withheld: &[&str], offered: bool) -> HostServiceLine { |
| 576 | HostServiceLine { |
| 577 | service: HostService::Network, |
| 578 | offered, |
| 579 | shared_with: shared.iter().map(|name| peer(name)).collect(), |
| 580 | withheld_by: withheld.iter().map(|name| peer(name)).collect(), |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | #[test] |
| 585 | fn every_host_service_is_offered_and_the_table_names_only_advertised_injects() { |
| 586 | assert!(!HOST_SERVICE_INJECTS.is_empty()); |
| 587 | assert!(HostService::ALL.into_iter().all(offered)); |
| 588 | let table: serde_json::Value = |
| 589 | serde_json::from_slice(crate::activation::DSH_COMPATIBILITY).unwrap(); |
| 590 | let advertised: BTreeSet<&str> = table["provided_services"] |
| 591 | .as_object() |
| 592 | .unwrap() |
| 593 | .values() |
| 594 | .flat_map(|group| group.as_array().unwrap()) |
| 595 | .map(|name| name.as_str().unwrap()) |
| 596 | .collect(); |
| 597 | for (inject, _) in HOST_SERVICE_INJECTS { |
| 598 | assert!(advertised.contains(inject), "{inject} is not advertised"); |
| 599 | } |
| 600 | for service in HostService::ALL { |
| 601 | assert_eq!(HostService::parse(service.name()), Some(service)); |
| 602 | assert_eq!( |
| 603 | serde_json::to_value(service).unwrap(), |
| 604 | serde_json::Value::String(service.name().into()) |
| 605 | ); |
| 606 | } |
| 607 | let _offer = TestOffer::only(&[HostService::Llm]); |
| 608 | assert!(offered(HostService::Llm)); |
| 609 | assert!(!offered(HostService::Network)); |
| 610 | } |
| 611 | |
| 612 | #[test] |
| 613 | fn the_review_says_whether_a_service_is_held_alone_shared_withheld_or_not_offered() { |
| 614 | assert_eq!( |
| 615 | line(&[], &[], true).sentence(), |
| 616 | "Network requests: send requests to the hosts in its review, with credentials it stores in Codewhale. No other reviewed plugin holds it." |
| 617 | ); |
| 618 | assert_eq!( |
| 619 | line(&["alpha", "beta"], &[], true).sentence(), |
| 620 | "Network requests: send requests to the hosts in its review, with credentials it stores in Codewhale. Shared with `alpha`, `beta`: each can use it as this plugin while this plugin's tool runs, and this plugin can use it as them." |
| 621 | ); |
| 622 | assert_eq!( |
| 623 | line(&[], &["gamma"], true).sentence(), |
| 624 | "Network requests: send requests to the hosts in its review, with credentials it stores in Codewhale. No other reviewed plugin holds it. Off for now: `gamma` is turned on and its review does not include it." |
| 625 | ); |
| 626 | assert!( |
| 627 | line(&["alpha"], &["gamma", "delta"], true) |
| 628 | .sentence() |
| 629 | .ends_with("Off for now: `gamma`, `delta` are turned on and their review does not include it.") |
| 630 | ); |
| 631 | assert_eq!( |
| 632 | line(&["alpha"], &["gamma"], false).sentence(), |
| 633 | "Network requests: this version of Codewhale does not offer it to plugins. Approving grants nothing for it." |
| 634 | ); |
| 635 | let review = HostServiceReview::new( |
| 636 | "id", |
| 637 | "c", |
| 638 | "k", |
| 639 | &PluginCohort::Reviewed, |
| 640 | vec![line(&["alpha"], &[], true)], |
| 641 | ); |
| 642 | assert_eq!(review.text()[0], REVIEW_LEAD); |
| 643 | assert_eq!(review.text().len(), 2); |
| 644 | assert_eq!(review.grants(), vec![HostService::Network]); |
| 645 | assert!( |
| 646 | HostServiceReview::new( |
| 647 | "id", |
| 648 | "c", |
| 649 | "k", |
| 650 | &PluginCohort::Reviewed, |
| 651 | vec![line(&[], &[], false)] |
| 652 | ) |
| 653 | .grants() |
| 654 | .is_empty() |
| 655 | ); |
| 656 | let token = |
| 657 | |lines| HostServiceReview::new("id", "c", "k", &PluginCohort::Reviewed, lines).token; |
| 658 | let base = token(vec![line(&["alpha"], &[], true)]); |
| 659 | assert_eq!(base.len(), 64); |
| 660 | assert_ne!(base, token(vec![line(&["beta"], &[], true)])); |
| 661 | assert_ne!(base, token(vec![line(&[], &["alpha"], true)])); |
| 662 | assert_ne!(base, token(vec![line(&["alpha"], &[], false)])); |
| 663 | assert_ne!( |
| 664 | base, |
| 665 | HostServiceReview::new( |
| 666 | "other", |
| 667 | "c", |
| 668 | "k", |
| 669 | &PluginCohort::Reviewed, |
| 670 | vec![line(&["alpha"], &[], true)] |
| 671 | ) |
| 672 | .token |
| 673 | ); |
| 674 | assert_ne!( |
| 675 | base, |
| 676 | HostServiceReview::new( |
| 677 | "id", |
| 678 | "c2", |
| 679 | "k", |
| 680 | &PluginCohort::Reviewed, |
| 681 | vec![line(&["alpha"], &[], true)] |
| 682 | ) |
| 683 | .token |
| 684 | ); |
| 685 | assert_ne!( |
| 686 | base, |
| 687 | HostServiceReview::new( |
| 688 | "id", |
| 689 | "c", |
| 690 | "k", |
| 691 | &PluginCohort::Agent { |
| 692 | workspace: "/w".into() |
| 693 | }, |
| 694 | vec![line(&["alpha"], &[], true)] |
| 695 | ) |
| 696 | .token |
| 697 | ); |
| 698 | assert!( |
| 699 | HostServiceReview::new("id", "c", "k", &PluginCohort::Reviewed, Vec::new()) |
| 700 | .text() |
| 701 | .is_empty() |
| 702 | ); |
| 703 | } |
| 704 | |
| 705 | #[test] |
| 706 | fn the_record_says_who_approved_in_one_shape_and_the_label_says_it_in_words() { |
| 707 | let agent = PluginApprover::Agent(AgentApproval { |
| 708 | posture: AgentPosture::AutoReview, |
| 709 | workspace: "/w".into(), |
| 710 | thread_id: Some("t".into()), |
| 711 | turn_id: Some("u".into()), |
| 712 | tool_call_id: Some("c".into()), |
| 713 | }); |
| 714 | let cases = [ |
| 715 | ( |
| 716 | PluginApprover::person(PersonVia::ApprovalCard), |
| 717 | serde_json::json!({"kind": "person", "via": "approval_card"}), |
| 718 | "approved by you", |
| 719 | ), |
| 720 | ( |
| 721 | agent.clone(), |
| 722 | serde_json::json!({"kind": "agent", "posture": "auto_review", "workspace": "/w", "thread_id": "t", "turn_id": "u", "tool_call_id": "c"}), |
| 723 | "approved by the agent in Auto-Review", |
| 724 | ), |
| 725 | ( |
| 726 | PluginApprover::command_line(None), |
| 727 | serde_json::json!({"kind": "command_line"}), |
| 728 | "trusted from the command line with --yes; no review was shown there", |
| 729 | ), |
| 730 | ( |
| 731 | PluginApprover::command_line(Some(std::path::Path::new("/w"))), |
| 732 | serde_json::json!({"kind": "agent", "posture": "command_line", "workspace": "/w"}), |
| 733 | "approved by the agent from a shell command", |
| 734 | ), |
| 735 | ]; |
| 736 | for (approver, json, label) in cases { |
| 737 | assert_eq!(serde_json::to_value(&approver).unwrap(), json); |
| 738 | assert_eq!( |
| 739 | serde_json::from_value::<PluginApprover>(json).unwrap(), |
| 740 | approver |
| 741 | ); |
| 742 | assert_eq!(approver_label(Some(&approver)), label); |
| 743 | } |
| 744 | assert_eq!( |
| 745 | approver_label(None), |
| 746 | "approver not recorded (reviewed before 0.10.3)" |
| 747 | ); |
| 748 | assert_eq!(cohort_of(None), PluginCohort::Reviewed); |
| 749 | assert_eq!( |
| 750 | PluginApprover::command_line(None).cohort(), |
| 751 | PluginCohort::Reviewed |
| 752 | ); |
| 753 | assert_eq!( |
| 754 | agent.cohort(), |
| 755 | PluginCohort::Agent { |
| 756 | workspace: "/w".into() |
| 757 | } |
| 758 | ); |
| 759 | assert!(serde_json::from_value::<PluginApprover>(serde_json::json!("person")).is_err()); |
| 760 | assert!( |
| 761 | serde_json::from_value::<PluginApprover>(serde_json::json!({"kind": "agent"})).is_err() |
| 762 | ); |
| 763 | } |
| 764 | |
| 765 | #[test] |
| 766 | fn inject_declarations_map_to_host_services_through_one_table() { |
| 767 | let table = [ |
| 768 | ("llm", HostService::Llm), |
| 769 | ("credentials", HostService::Network), |
| 770 | ("pluginManager", HostService::Catalog), |
| 771 | ("deepseekAccount", HostService::Catalog), |
| 772 | ]; |
| 773 | let array = |
| 774 | "export const inject = ['tools', 'llm', \"subagents\"]\nconst other = ['credentials']"; |
| 775 | assert_eq!( |
| 776 | declared_injects(array), |
| 777 | ["llm", "subagents", "tools"].map(String::from).into() |
| 778 | ); |
| 779 | assert_eq!( |
| 780 | services_for_injects(declared_injects(array).iter().map(String::as_str), &table), |
| 781 | vec![HostService::Llm] |
| 782 | ); |
| 783 | let property = |
| 784 | "var plugin={name:'w',inject:['webServer','credentials','connection'],apply(){}}"; |
| 785 | assert_eq!( |
| 786 | services_for_injects( |
| 787 | declared_injects(property).iter().map(String::as_str), |
| 788 | &table |
| 789 | ), |
| 790 | vec![HostService::Network] |
| 791 | ); |
| 792 | let object = "class P { static inject = { required: ['pluginManager'], optional: [\"llm\"] }; }\nPlugin.inject = { deepseekAccount: { required: false } };"; |
| 793 | assert_eq!( |
| 794 | services_for_injects(declared_injects(object).iter().map(String::as_str), &table), |
| 795 | vec![HostService::Llm, HostService::Catalog] |
| 796 | ); |
| 797 | assert!(declared_injects("const injected = ['llm']; reinject('llm')").is_empty()); |
| 798 | assert!( |
| 799 | services_for_injects(declared_injects(array).iter().map(String::as_str), &[]) |
| 800 | .is_empty() |
| 801 | ); |
| 802 | } |
| 803 | } |
| 804 |