| 1 | //! Core admission, preview, scope, and carried-decision enforcement for the |
| 2 | //! built-in creator `plugin_manager` tool (`CR-05a`). |
| 3 | |
| 4 | use std::io::Read as _; |
| 5 | use std::path::{Component, Path, PathBuf}; |
| 6 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 7 | use std::sync::{Arc, OnceLock}; |
| 8 | use std::time::Duration; |
| 9 | |
| 10 | use codewhale_execpolicy::ApprovalMode; |
| 11 | use codewhale_paths::{codewhale_home_override, user_home}; |
| 12 | use codewhale_plugins::activation::{PolicyScope, extension_host_policy_enabled}; |
| 13 | use codewhale_plugins::agent_plugin::resolve_manifest_path; |
| 14 | #[cfg(any(test, feature = "test-support"))] |
| 15 | use codewhale_plugins::host_services::TestOffer; |
| 16 | use codewhale_plugins::host_services::{ |
| 17 | AgentApproval, AgentPosture, HostService, HostServiceLine, HostServiceReview, PersonVia, |
| 18 | PluginApprover, PluginCohort, ReviewPeer, cohort_of, offered, |
| 19 | }; |
| 20 | use codewhale_plugins::install::{ |
| 21 | DEFAULT_MAX_SIZE_BYTES, PluginInstallSource, clean_dir_is_strictly_inside, dsh, |
| 22 | has_regular_install_marker, installed_by_the_agent, path_is_within, |
| 23 | }; |
| 24 | use codewhale_plugins::manifest::{PluginInventory, PluginManifest}; |
| 25 | use codewhale_plugins::registry::PluginRegistry; |
| 26 | use codewhale_plugins::types::{LoadedPlugin, PluginScope}; |
| 27 | use codewhale_sanitize::redact::redact_model_bound_secrets; |
| 28 | use codewhale_sanitize::sanitize::{is_bidi_control, sanitize_text, strip_ansi_into}; |
| 29 | use codewhale_skill_install::install::{INSTALLED_FROM_MARKER, InstallSource, InstalledFromMarker}; |
| 30 | use codewhale_util::path_identity::metadata_is_link_or_reparse; |
| 31 | use regex::Regex; |
| 32 | use serde::Serialize; |
| 33 | use serde_json::{Value, json}; |
| 34 | use tokio_util::sync::CancellationToken; |
| 35 | |
| 36 | use super::dsh_broker::BrokerEffect; |
| 37 | use crate::core::engine::LiveRuntimeAuthority; |
| 38 | use crate::tools::spec::{ToolContext, ToolError, ToolSpec}; |
| 39 | |
| 40 | /// Model-visible tool name owned by the tier-0 creator host module. |
| 41 | pub const PLUGIN_MANAGER_TOOL_NAME: &str = "plugin_manager"; |
| 42 | |
| 43 | /// Tier-0 owner id for the built-in creator host module. |
| 44 | pub const CREATOR_PLUGIN_ID: &str = "host:creator"; |
| 45 | |
| 46 | /// Maximum accepted character/byte bounds for validated creator arguments and summaries. |
| 47 | pub const MAX_ACTION_BYTES: usize = 32; |
| 48 | pub const MAX_TARGET_BYTES: usize = 512; |
| 49 | pub const MAX_VERSION_BYTES: usize = 128; |
| 50 | pub const MAX_REGISTRY_BYTES: usize = 512; |
| 51 | pub const MAX_APPROVED_BUILDS: usize = 16; |
| 52 | pub const MAX_TEXT_BYTES: usize = 256; |
| 53 | pub const MAX_DIAGNOSTIC_BYTES: usize = 2048; |
| 54 | pub const MAX_WARNING_ENTRIES: usize = 12; |
| 55 | pub const MAX_PREVIEW_TREE_BYTES: u64 = DEFAULT_MAX_SIZE_BYTES; |
| 56 | pub const MAX_PREVIEW_TREE_ENTRIES: usize = 4_096; |
| 57 | pub const PREVIEW_TIMEOUT: Duration = Duration::from_secs(60); |
| 58 | |
| 59 | const CREATOR_SCOPE_PREFIX: &str = "ext:host:creator@"; |
| 60 | |
| 61 | /// Return true when `input` requests a read-only `plugin_manager` list action. |
| 62 | #[must_use] |
| 63 | pub fn is_list_action(input: &Value) -> bool { |
| 64 | matches!( |
| 65 | input.get("action").and_then(Value::as_str).map(str::trim), |
| 66 | Some("list_plugins" | "list_bundles" | "list_version_exemptions") |
| 67 | ) |
| 68 | } |
| 69 | |
| 70 | /// Return true when `name` identifies the built-in `plugin_manager` tool. |
| 71 | #[must_use] |
| 72 | pub fn is_creator_plugin_manager_name(name: &str) -> bool { |
| 73 | name.eq_ignore_ascii_case(PLUGIN_MANAGER_TOOL_NAME) |
| 74 | } |
| 75 | |
| 76 | /// Return true when `spec` identifies the built-in `host:creator` `plugin_manager` tool. |
| 77 | #[must_use] |
| 78 | pub fn is_creator_plugin_manager_spec(spec: &dyn ToolSpec) -> bool { |
| 79 | spec.name() == PLUGIN_MANAGER_TOOL_NAME |
| 80 | && spec |
| 81 | .approval_scope() |
| 82 | .is_some_and(|scope| scope.starts_with(CREATOR_SCOPE_PREFIX)) |
| 83 | } |
| 84 | |
| 85 | /// Return true when a call to `spec` with `input` targets a changing `plugin_manager` action. |
| 86 | #[must_use] |
| 87 | pub fn is_creator_changing_spec_call(spec: &dyn ToolSpec, input: &Value) -> bool { |
| 88 | is_creator_plugin_manager_spec(spec) && !is_list_action(input) |
| 89 | } |
| 90 | |
| 91 | /// Initial Rust-authored approval card fallback description before async preview completes. |
| 92 | #[must_use] |
| 93 | pub(super) fn initial_prepared_description(input: &Value) -> String { |
| 94 | if is_list_action(input) { |
| 95 | return "List installed plugins and bundle status (read-only)".to_string(); |
| 96 | } |
| 97 | let action = input |
| 98 | .get("action") |
| 99 | .and_then(Value::as_str) |
| 100 | .map(str::trim) |
| 101 | .unwrap_or("change"); |
| 102 | let mut truncated = false; |
| 103 | let clean_action = sanitize_inline(action, MAX_ACTION_BYTES, &mut truncated); |
| 104 | match input.get("target").and_then(Value::as_str).map(str::trim) { |
| 105 | Some(target) if !target.is_empty() => { |
| 106 | let clean_target = sanitize_inline(target, MAX_TEXT_BYTES, &mut truncated); |
| 107 | format!("Change plugin state ({clean_action}) for `{clean_target}`") |
| 108 | } |
| 109 | _ => format!("Change plugin state ({clean_action})"), |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// Mutating action requested on `plugin_manager`. |
| 114 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 115 | pub enum CreatorAction { |
| 116 | Install, |
| 117 | Remove, |
| 118 | Enable, |
| 119 | Disable, |
| 120 | } |
| 121 | |
| 122 | impl CreatorAction { |
| 123 | /// Wire method name handled by the `plugins` broker arm. |
| 124 | #[must_use] |
| 125 | pub const fn as_str(self) -> &'static str { |
| 126 | match self { |
| 127 | Self::Install => "install", |
| 128 | Self::Remove => "remove", |
| 129 | Self::Enable => "enable", |
| 130 | Self::Disable => "disable", |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | /// Authority that admitted a `plugin_manager` change. |
| 136 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 137 | pub enum CreatorDecider { |
| 138 | Person, |
| 139 | Agent(AgentPosture), |
| 140 | } |
| 141 | |
| 142 | /// Structured plugin preview summary passed to Auto-Review (`plugin_review`). |
| 143 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 144 | pub struct CreatorReviewSummary { |
| 145 | pub action: String, |
| 146 | pub name: String, |
| 147 | pub target: String, |
| 148 | pub scope: String, |
| 149 | #[serde(skip_serializing_if = "Option::is_none")] |
| 150 | pub version: Option<String>, |
| 151 | pub source: String, |
| 152 | pub content_hash: String, |
| 153 | pub capability_hash: String, |
| 154 | #[serde(skip_serializing_if = "Option::is_none")] |
| 155 | pub enabled: Option<bool>, |
| 156 | #[serde(skip_serializing_if = "Option::is_none")] |
| 157 | pub dsh_package: Option<String>, |
| 158 | pub capabilities: Value, |
| 159 | pub host_services: Vec<String>, |
| 160 | #[serde(skip_serializing_if = "Vec::is_empty")] |
| 161 | pub warnings: Vec<String>, |
| 162 | } |
| 163 | |
| 164 | /// Target lookup result against the discovered plugin registry. |
| 165 | pub(crate) enum TargetLookup<'a> { |
| 166 | Found(&'a LoadedPlugin), |
| 167 | Missing, |
| 168 | Ambiguous { |
| 169 | message: String, |
| 170 | first: &'a LoadedPlugin, |
| 171 | }, |
| 172 | } |
| 173 | |
| 174 | /// Paths held only by Rust for stripping host-private prefixes from messages. |
| 175 | pub(crate) struct ScrubContext<'a> { |
| 176 | pub workspace: &'a Path, |
| 177 | pub canon_workspace: Option<&'a Path>, |
| 178 | pub plugin_root: Option<&'a Path>, |
| 179 | pub user_plugins_dir: Option<&'a Path>, |
| 180 | pub state_path: Option<&'a Path>, |
| 181 | } |
| 182 | |
| 183 | /// Pre-gate preview of one valid `plugin_manager` change call. |
| 184 | #[derive(Debug, Clone)] |
| 185 | pub enum PlannedChangePreview { |
| 186 | LocalInstall { |
| 187 | raw_target: String, |
| 188 | canon_source: PathBuf, |
| 189 | is_dsh: bool, |
| 190 | plugin_name: String, |
| 191 | want_enabled: bool, |
| 192 | pre_hash: String, |
| 193 | capability_hash: String, |
| 194 | expected_gate_target: String, |
| 195 | person_review_lines: Vec<String>, |
| 196 | agent_review_lines: Vec<String>, |
| 197 | warnings: Vec<String>, |
| 198 | }, |
| 199 | UnseenFetchInstall { |
| 200 | raw_target: String, |
| 201 | is_remote: bool, |
| 202 | canon_source: Option<PathBuf>, |
| 203 | remote_label: String, |
| 204 | remote_host: String, |
| 205 | }, |
| 206 | ExistingRemove { |
| 207 | plugin_id: String, |
| 208 | plugin_name: String, |
| 209 | expected_gate_target: String, |
| 210 | }, |
| 211 | ExistingToggle { |
| 212 | enabled: bool, |
| 213 | plugin_id: String, |
| 214 | plugin_name: String, |
| 215 | content_hash: String, |
| 216 | capability_hash: String, |
| 217 | expected_gate_target: String, |
| 218 | person_review_lines: Vec<String>, |
| 219 | person_review_token: Option<String>, |
| 220 | agent_review_lines: Vec<String>, |
| 221 | agent_review_token: Option<String>, |
| 222 | }, |
| 223 | } |
| 224 | |
| 225 | /// Pre-approval plan carried on `ToolExecutionPlan::creator_gate`. |
| 226 | #[derive(Debug, Clone)] |
| 227 | pub struct CreatorGatePlan { |
| 228 | pub action: CreatorAction, |
| 229 | pub in_agent_scope: bool, |
| 230 | pub unseen_network_fetch: bool, |
| 231 | pub outside_scope_reason: Option<String>, |
| 232 | pub card_description: String, |
| 233 | pub auto_review_summary: Option<CreatorReviewSummary>, |
| 234 | pub preview: PlannedChangePreview, |
| 235 | } |
| 236 | |
| 237 | impl CreatorGatePlan { |
| 238 | /// Construct the single-use carried decision attached to `ToolContext` on admission. |
| 239 | pub fn build_carrier( |
| 240 | &self, |
| 241 | decider: CreatorDecider, |
| 242 | admitted_authority: LiveRuntimeAuthority, |
| 243 | ) -> Result<CreatorDecisionCarrier, ToolError> { |
| 244 | if admitted_authority.is_read_only_sandbox() { |
| 245 | return Err(ToolError::permission_denied( |
| 246 | "plugin changes are not permitted while sandbox_mode is read-only", |
| 247 | )); |
| 248 | } |
| 249 | if matches!(decider, CreatorDecider::Agent(_)) |
| 250 | && (!self.in_agent_scope || self.unseen_network_fetch) |
| 251 | { |
| 252 | return Err(ToolError::permission_denied( |
| 253 | self.outside_scope_reason.clone().unwrap_or_else(|| { |
| 254 | "this plugin change is outside agent scope and requires a person's approval" |
| 255 | .to_string() |
| 256 | }), |
| 257 | )); |
| 258 | } |
| 259 | |
| 260 | let is_agent = matches!(decider, CreatorDecider::Agent(_)); |
| 261 | let change = match &self.preview { |
| 262 | PlannedChangePreview::LocalInstall { |
| 263 | raw_target, |
| 264 | canon_source, |
| 265 | is_dsh, |
| 266 | plugin_name, |
| 267 | pre_hash, |
| 268 | capability_hash, |
| 269 | want_enabled, |
| 270 | expected_gate_target, |
| 271 | person_review_lines, |
| 272 | agent_review_lines, |
| 273 | warnings, |
| 274 | .. |
| 275 | } => AdmittedChangeKind::LocalInstall { |
| 276 | raw_target: raw_target.clone(), |
| 277 | canon_source: canon_source.clone(), |
| 278 | is_dsh: *is_dsh, |
| 279 | plugin_name: plugin_name.clone(), |
| 280 | pre_hash: pre_hash.clone(), |
| 281 | capability_hash: capability_hash.clone(), |
| 282 | want_enabled: *want_enabled, |
| 283 | expected_gate_target: expected_gate_target.clone(), |
| 284 | shown_service_lines: if is_agent { |
| 285 | agent_review_lines.clone() |
| 286 | } else { |
| 287 | person_review_lines.clone() |
| 288 | }, |
| 289 | preview_warnings: warnings.clone(), |
| 290 | remaining_writes: Arc::new(AtomicUsize::new(1)), |
| 291 | }, |
| 292 | PlannedChangePreview::UnseenFetchInstall { |
| 293 | raw_target, |
| 294 | is_remote, |
| 295 | canon_source, |
| 296 | remote_label, |
| 297 | remote_host, |
| 298 | } => { |
| 299 | let reach_slots = if *is_remote { 2 } else { 1 }; |
| 300 | AdmittedChangeKind::UnseenFetchInstall { |
| 301 | raw_target: raw_target.clone(), |
| 302 | is_remote: *is_remote, |
| 303 | canon_source: canon_source.clone(), |
| 304 | remote_label: remote_label.clone(), |
| 305 | remote_host: remote_host.clone(), |
| 306 | remaining_reach: Arc::new(AtomicUsize::new(reach_slots)), |
| 307 | used_reach: Arc::new(AtomicUsize::new(0)), |
| 308 | remaining_writes: Arc::new(AtomicUsize::new(1)), |
| 309 | } |
| 310 | } |
| 311 | PlannedChangePreview::ExistingRemove { |
| 312 | plugin_id, |
| 313 | plugin_name, |
| 314 | expected_gate_target, |
| 315 | } => AdmittedChangeKind::Remove { |
| 316 | plugin_id: plugin_id.clone(), |
| 317 | plugin_name: plugin_name.clone(), |
| 318 | expected_gate_target: expected_gate_target.clone(), |
| 319 | remaining_writes: Arc::new(AtomicUsize::new(1)), |
| 320 | }, |
| 321 | PlannedChangePreview::ExistingToggle { |
| 322 | enabled, |
| 323 | plugin_id, |
| 324 | plugin_name, |
| 325 | content_hash, |
| 326 | capability_hash, |
| 327 | expected_gate_target, |
| 328 | person_review_lines, |
| 329 | person_review_token, |
| 330 | agent_review_lines, |
| 331 | agent_review_token, |
| 332 | } => AdmittedChangeKind::Toggle { |
| 333 | enabled: *enabled, |
| 334 | plugin_id: plugin_id.clone(), |
| 335 | plugin_name: plugin_name.clone(), |
| 336 | content_hash: content_hash.clone(), |
| 337 | capability_hash: capability_hash.clone(), |
| 338 | expected_gate_target: expected_gate_target.clone(), |
| 339 | shown_service_lines: if is_agent { |
| 340 | agent_review_lines.clone() |
| 341 | } else { |
| 342 | person_review_lines.clone() |
| 343 | }, |
| 344 | shown_service_token: if is_agent { |
| 345 | agent_review_token.clone() |
| 346 | } else { |
| 347 | person_review_token.clone() |
| 348 | }, |
| 349 | remaining_writes: Arc::new(AtomicUsize::new(1)), |
| 350 | }, |
| 351 | }; |
| 352 | |
| 353 | Ok(CreatorDecisionCarrier { |
| 354 | decider, |
| 355 | admitted_authority, |
| 356 | in_agent_scope: self.in_agent_scope, |
| 357 | change, |
| 358 | }) |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | /// Exact operation scope permitted by an admitted [`CreatorDecisionCarrier`]. |
| 363 | #[derive(Debug, Clone)] |
| 364 | pub enum AdmittedChangeKind { |
| 365 | LocalInstall { |
| 366 | raw_target: String, |
| 367 | canon_source: PathBuf, |
| 368 | is_dsh: bool, |
| 369 | plugin_name: String, |
| 370 | pre_hash: String, |
| 371 | capability_hash: String, |
| 372 | want_enabled: bool, |
| 373 | expected_gate_target: String, |
| 374 | shown_service_lines: Vec<String>, |
| 375 | preview_warnings: Vec<String>, |
| 376 | remaining_writes: Arc<AtomicUsize>, |
| 377 | }, |
| 378 | UnseenFetchInstall { |
| 379 | raw_target: String, |
| 380 | is_remote: bool, |
| 381 | canon_source: Option<PathBuf>, |
| 382 | remote_label: String, |
| 383 | remote_host: String, |
| 384 | remaining_reach: Arc<AtomicUsize>, |
| 385 | used_reach: Arc<AtomicUsize>, |
| 386 | remaining_writes: Arc<AtomicUsize>, |
| 387 | }, |
| 388 | Remove { |
| 389 | plugin_id: String, |
| 390 | plugin_name: String, |
| 391 | expected_gate_target: String, |
| 392 | remaining_writes: Arc<AtomicUsize>, |
| 393 | }, |
| 394 | Toggle { |
| 395 | enabled: bool, |
| 396 | plugin_id: String, |
| 397 | plugin_name: String, |
| 398 | content_hash: String, |
| 399 | capability_hash: String, |
| 400 | expected_gate_target: String, |
| 401 | shown_service_lines: Vec<String>, |
| 402 | shown_service_token: Option<String>, |
| 403 | remaining_writes: Arc<AtomicUsize>, |
| 404 | }, |
| 405 | } |
| 406 | |
| 407 | /// Carried admission placed by the Engine gate on `ToolExecutionState::creator_decision`. |
| 408 | #[derive(Debug, Clone)] |
| 409 | pub struct CreatorDecisionCarrier { |
| 410 | pub decider: CreatorDecider, |
| 411 | pub admitted_authority: LiveRuntimeAuthority, |
| 412 | pub in_agent_scope: bool, |
| 413 | pub change: AdmittedChangeKind, |
| 414 | } |
| 415 | |
| 416 | impl CreatorDecisionCarrier { |
| 417 | /// Return true when this admission covers unseen network bytes (Option A). |
| 418 | #[must_use] |
| 419 | pub fn is_unseen_fetch(&self) -> bool { |
| 420 | matches!(self.change, AdmittedChangeKind::UnseenFetchInstall { .. }) |
| 421 | } |
| 422 | |
| 423 | /// Audit wire value identifying who admitted the action. |
| 424 | #[must_use] |
| 425 | pub const fn decider_wire(&self) -> &'static str { |
| 426 | match self.decider { |
| 427 | CreatorDecider::Person => "person", |
| 428 | CreatorDecider::Agent(_) => "agent", |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | /// Convert the carried decision into a [`PluginApprover`] for persistence, refusing Option A unseen-byte admissions. |
| 433 | pub fn trust_approver( |
| 434 | &self, |
| 435 | canon_workspace: &Path, |
| 436 | thread_id: String, |
| 437 | turn_id: Option<String>, |
| 438 | tool_call_id: Option<String>, |
| 439 | ) -> Result<PluginApprover, String> { |
| 440 | if self.is_unseen_fetch() { |
| 441 | return Err( |
| 442 | "unseen network bytes cannot receive a trust receipt before review".to_string(), |
| 443 | ); |
| 444 | } |
| 445 | match self.decider { |
| 446 | CreatorDecider::Person => Ok(PluginApprover::person(PersonVia::ApprovalCard)), |
| 447 | CreatorDecider::Agent(posture) => Ok(PluginApprover::Agent(AgentApproval { |
| 448 | posture, |
| 449 | workspace: canon_workspace.to_string_lossy().into_owned(), |
| 450 | thread_id: Some(thread_id), |
| 451 | turn_id, |
| 452 | tool_call_id, |
| 453 | })), |
| 454 | } |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | fn take_slot(counter: &AtomicUsize, label: &str) -> Result<(), String> { |
| 459 | let mut current = counter.load(Ordering::SeqCst); |
| 460 | loop { |
| 461 | let Some(next) = current.checked_sub(1) else { |
| 462 | return Err(format!( |
| 463 | "plugin change decision has already spent its {label} slot" |
| 464 | )); |
| 465 | }; |
| 466 | match counter.compare_exchange_weak(current, next, Ordering::SeqCst, Ordering::SeqCst) { |
| 467 | Ok(_) => return Ok(()), |
| 468 | Err(observed) => current = observed, |
| 469 | } |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | fn is_write_target_with_suffix(target: &str, suffix: &str) -> bool { |
| 474 | let Some(prefix) = target |
| 475 | .strip_suffix(suffix) |
| 476 | .and_then(|s| s.strip_suffix(' ')) |
| 477 | else { |
| 478 | return false; |
| 479 | }; |
| 480 | let Some((name, hash)) = prefix.rsplit_once(' ') else { |
| 481 | return false; |
| 482 | }; |
| 483 | !name.trim().is_empty() |
| 484 | && hash.len() == 64 |
| 485 | && hash |
| 486 | .bytes() |
| 487 | .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) |
| 488 | } |
| 489 | |
| 490 | /// Consume one broker `Write` or `Reach` act against the carried Engine admission. |
| 491 | pub(crate) fn admit_broker_act( |
| 492 | tool: &ToolContext, |
| 493 | live_authority: Option<&LiveRuntimeAuthority>, |
| 494 | method: &str, |
| 495 | effect: BrokerEffect, |
| 496 | raw_target: Option<&str>, |
| 497 | ) -> Result<(&'static str, &'static str), String> { |
| 498 | if tool.execution.owner_agent_id.is_some() || tool.execution.child_host.is_some() { |
| 499 | return Err("a sub-agent cannot change plugins".to_string()); |
| 500 | } |
| 501 | let Some(carrier) = tool.execution.creator_decision.as_ref() else { |
| 502 | return Err("plugin changes require an admitted engine decision".to_string()); |
| 503 | }; |
| 504 | let Some(live) = live_authority else { |
| 505 | return Err("runtime authority is unavailable for this plugin change".to_string()); |
| 506 | }; |
| 507 | if live.is_read_only_sandbox() || live.approval_mode() == ApprovalMode::Never { |
| 508 | return Err("cannot change plugins in this mode".to_string()); |
| 509 | } |
| 510 | if live.narrows(&carrier.admitted_authority) { |
| 511 | return Err("cannot continue after session permissions were narrowed".to_string()); |
| 512 | } |
| 513 | if matches!(carrier.decider, CreatorDecider::Agent(_)) |
| 514 | && (!carrier.in_agent_scope || carrier.is_unseen_fetch()) |
| 515 | { |
| 516 | return Err("agent decision cannot authorize an outside-scope plugin change".to_string()); |
| 517 | } |
| 518 | |
| 519 | match &carrier.change { |
| 520 | AdmittedChangeKind::LocalInstall { |
| 521 | expected_gate_target, |
| 522 | remaining_writes, |
| 523 | .. |
| 524 | } => { |
| 525 | if method != "install" || effect != BrokerEffect::Write { |
| 526 | return Err( |
| 527 | "plugin change decision only permits installing this bundle".to_string() |
| 528 | ); |
| 529 | } |
| 530 | if raw_target != Some(expected_gate_target.as_str()) { |
| 531 | return Err("plugin bundle changed after approval".to_string()); |
| 532 | } |
| 533 | take_slot(remaining_writes, "write")?; |
| 534 | } |
| 535 | AdmittedChangeKind::UnseenFetchInstall { |
| 536 | raw_target: approved_spec, |
| 537 | is_remote, |
| 538 | canon_source, |
| 539 | remote_label, |
| 540 | remote_host, |
| 541 | remaining_reach, |
| 542 | used_reach, |
| 543 | remaining_writes, |
| 544 | } => { |
| 545 | if carrier.decider != CreatorDecider::Person { |
| 546 | return Err("unseen network fetches require a person's approval card".to_string()); |
| 547 | } |
| 548 | if method != "install" { |
| 549 | return Err("plugin install decision cannot run another action".to_string()); |
| 550 | } |
| 551 | match effect { |
| 552 | BrokerEffect::Reach => { |
| 553 | let allowed = if *is_remote { |
| 554 | raw_target == Some(format!("{remote_label} from {remote_host}").as_str()) |
| 555 | || raw_target |
| 556 | == Some( |
| 557 | format!( |
| 558 | "{remote_label} npm dependencies from registry.npmjs.org" |
| 559 | ) |
| 560 | .as_str(), |
| 561 | ) |
| 562 | } else { |
| 563 | raw_target |
| 564 | == Some( |
| 565 | format!("{approved_spec} npm dependencies from registry.npmjs.org") |
| 566 | .as_str(), |
| 567 | ) |
| 568 | || canon_source.as_ref().is_some_and(|dir| { |
| 569 | raw_target |
| 570 | == Some( |
| 571 | format!( |
| 572 | "{} npm dependencies from registry.npmjs.org", |
| 573 | dir.display() |
| 574 | ) |
| 575 | .as_str(), |
| 576 | ) |
| 577 | }) |
| 578 | }; |
| 579 | if !allowed { |
| 580 | return Err( |
| 581 | "network fetch target does not match the approved plugin spec" |
| 582 | .to_string(), |
| 583 | ); |
| 584 | } |
| 585 | take_slot(remaining_reach, "reach")?; |
| 586 | used_reach.fetch_add(1, Ordering::SeqCst); |
| 587 | } |
| 588 | BrokerEffect::Write => { |
| 589 | if used_reach.load(Ordering::SeqCst) == 0 { |
| 590 | return Err( |
| 591 | "unseen-fetch install must perform its admitted fetch before writing" |
| 592 | .to_string(), |
| 593 | ); |
| 594 | } |
| 595 | let allowed = if *is_remote { |
| 596 | raw_target.is_some_and(|t| is_write_target_with_suffix(t, approved_spec)) |
| 597 | } else { |
| 598 | raw_target.is_some_and(|t| { |
| 599 | t == approved_spec |
| 600 | || is_write_target_with_suffix(t, approved_spec) |
| 601 | || canon_source.as_ref().is_some_and(|dir| { |
| 602 | let dir_str = dir.to_string_lossy(); |
| 603 | t == dir_str.as_ref() |
| 604 | || is_write_target_with_suffix(t, dir_str.as_ref()) |
| 605 | }) |
| 606 | }) |
| 607 | }; |
| 608 | if !allowed { |
| 609 | return Err( |
| 610 | "write target does not match the approved unseen-fetch install" |
| 611 | .to_string(), |
| 612 | ); |
| 613 | } |
| 614 | take_slot(remaining_writes, "write")?; |
| 615 | } |
| 616 | BrokerEffect::Read => {} |
| 617 | } |
| 618 | } |
| 619 | AdmittedChangeKind::Remove { |
| 620 | expected_gate_target, |
| 621 | remaining_writes, |
| 622 | .. |
| 623 | } => { |
| 624 | if method != "remove" || effect != BrokerEffect::Write { |
| 625 | return Err("plugin remove decision cannot run another action".to_string()); |
| 626 | } |
| 627 | if raw_target != Some(expected_gate_target.as_str()) { |
| 628 | return Err("plugin remove target does not match the approved plugin".to_string()); |
| 629 | } |
| 630 | take_slot(remaining_writes, "write")?; |
| 631 | } |
| 632 | AdmittedChangeKind::Toggle { |
| 633 | enabled, |
| 634 | expected_gate_target, |
| 635 | remaining_writes, |
| 636 | .. |
| 637 | } => { |
| 638 | let expected_method = if *enabled { "enable" } else { "disable" }; |
| 639 | if method != expected_method || effect != BrokerEffect::Write { |
| 640 | return Err( |
| 641 | "plugin toggle decision does not match the requested method".to_string() |
| 642 | ); |
| 643 | } |
| 644 | if raw_target != Some(expected_gate_target.as_str()) { |
| 645 | return Err("plugin state changed after approval".to_string()); |
| 646 | } |
| 647 | take_slot(remaining_writes, "write")?; |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | let posture = match carrier.decider { |
| 652 | CreatorDecider::Person => person_via_wire(PersonVia::ApprovalCard), |
| 653 | CreatorDecider::Agent(posture) => agent_posture_wire(posture), |
| 654 | }; |
| 655 | Ok((carrier.decider_wire(), posture)) |
| 656 | } |
| 657 | |
| 658 | struct ParsedChangeInput { |
| 659 | action: CreatorAction, |
| 660 | target: String, |
| 661 | want_enabled: bool, |
| 662 | registry_ignored: bool, |
| 663 | } |
| 664 | |
| 665 | fn validate_control_free_str(raw: &str, field: &str, max_bytes: usize) -> Result<String, String> { |
| 666 | let trimmed = raw.trim(); |
| 667 | if trimmed.is_empty() { |
| 668 | return Err(format!("{field} must not be empty")); |
| 669 | } |
| 670 | if trimmed.len() > max_bytes { |
| 671 | return Err(format!("{field} is longer than {max_bytes} bytes")); |
| 672 | } |
| 673 | if trimmed |
| 674 | .chars() |
| 675 | .any(|ch| ch == '\0' || ch.is_control() || is_bidi_control(ch)) |
| 676 | { |
| 677 | return Err(format!("{field} contains disallowed control characters")); |
| 678 | } |
| 679 | Ok(trimmed.to_string()) |
| 680 | } |
| 681 | |
| 682 | fn validate_optional_control_free_str( |
| 683 | value: Option<&Value>, |
| 684 | field: &str, |
| 685 | max_bytes: usize, |
| 686 | ) -> Result<Option<String>, String> { |
| 687 | let Some(value) = value else { |
| 688 | return Ok(None); |
| 689 | }; |
| 690 | if value.is_null() { |
| 691 | return Ok(None); |
| 692 | } |
| 693 | let Some(raw) = value.as_str() else { |
| 694 | return Err(format!("{field} must be a string")); |
| 695 | }; |
| 696 | if raw.trim().is_empty() { |
| 697 | return Ok(None); |
| 698 | } |
| 699 | validate_control_free_str(raw, field, max_bytes).map(Some) |
| 700 | } |
| 701 | |
| 702 | fn parse_change_input(input: &Value) -> Result<ParsedChangeInput, ToolError> { |
| 703 | let raw_action = input |
| 704 | .get("action") |
| 705 | .and_then(Value::as_str) |
| 706 | .ok_or_else(|| ToolError::invalid_input("plugin_manager requires a string `action`"))?; |
| 707 | let clean_action = validate_control_free_str(raw_action, "action", MAX_ACTION_BYTES) |
| 708 | .map_err(ToolError::invalid_input)?; |
| 709 | let explicit_enabled = match input.get("enabled") { |
| 710 | None | Some(Value::Null) => None, |
| 711 | Some(Value::Bool(value)) => Some(*value), |
| 712 | Some(_) => { |
| 713 | return Err(ToolError::invalid_input("`enabled` must be a boolean")); |
| 714 | } |
| 715 | }; |
| 716 | let action = match clean_action.as_str() { |
| 717 | "install" | "install_bundle" => CreatorAction::Install, |
| 718 | "remove" | "remove_bundle" => CreatorAction::Remove, |
| 719 | "enable" => CreatorAction::Enable, |
| 720 | "disable" => CreatorAction::Disable, |
| 721 | "set_bundle" | "set_plugin" => match explicit_enabled { |
| 722 | Some(true) => CreatorAction::Enable, |
| 723 | Some(false) => CreatorAction::Disable, |
| 724 | None => { |
| 725 | return Err(ToolError::invalid_input(format!( |
| 726 | "`{clean_action}` requires a boolean `enabled`" |
| 727 | ))); |
| 728 | } |
| 729 | }, |
| 730 | "set_version_exemption" => { |
| 731 | return Err(ToolError::invalid_input( |
| 732 | "Codewhale does not exempt plugins from the host compatibility contract", |
| 733 | )); |
| 734 | } |
| 735 | other => { |
| 736 | return Err(ToolError::invalid_input(format!( |
| 737 | "unsupported plugin_manager action `{other}`" |
| 738 | ))); |
| 739 | } |
| 740 | }; |
| 741 | |
| 742 | let raw_target = input.get("target").and_then(Value::as_str).ok_or_else(|| { |
| 743 | ToolError::invalid_input(format!( |
| 744 | "`{}` requires a non-empty `target`", |
| 745 | action.as_str() |
| 746 | )) |
| 747 | })?; |
| 748 | let target = validate_control_free_str(raw_target, "target", MAX_TARGET_BYTES) |
| 749 | .map_err(ToolError::invalid_input)?; |
| 750 | |
| 751 | let want_enabled = explicit_enabled.unwrap_or(true); |
| 752 | |
| 753 | let registry_ignored = |
| 754 | validate_optional_control_free_str(input.get("registry"), "registry", MAX_REGISTRY_BYTES) |
| 755 | .map_err(ToolError::invalid_input)? |
| 756 | .is_some(); |
| 757 | |
| 758 | let _ = validate_optional_control_free_str( |
| 759 | input.get("runtimeVersion"), |
| 760 | "runtimeVersion", |
| 761 | MAX_VERSION_BYTES, |
| 762 | ) |
| 763 | .map_err(ToolError::invalid_input)?; |
| 764 | |
| 765 | match input.get("acceptRisk") { |
| 766 | None | Some(Value::Null) | Some(Value::Bool(_)) => {} |
| 767 | Some(_) => { |
| 768 | return Err(ToolError::invalid_input("`acceptRisk` must be a boolean")); |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | if let Some(builds_val) = input |
| 773 | .get("approvedBuilds") |
| 774 | .or_else(|| input.get("approved_builds")) |
| 775 | .filter(|v| !v.is_null()) |
| 776 | { |
| 777 | let Some(arr) = builds_val.as_array() else { |
| 778 | return Err(ToolError::invalid_input( |
| 779 | "`approvedBuilds` must be an array of strings", |
| 780 | )); |
| 781 | }; |
| 782 | if arr.len() > MAX_APPROVED_BUILDS { |
| 783 | return Err(ToolError::invalid_input(format!( |
| 784 | "`approvedBuilds` accepts at most {MAX_APPROVED_BUILDS} entries" |
| 785 | ))); |
| 786 | } |
| 787 | for item in arr { |
| 788 | let Some(text) = item.as_str() else { |
| 789 | return Err(ToolError::invalid_input( |
| 790 | "`approvedBuilds` entries must be strings", |
| 791 | )); |
| 792 | }; |
| 793 | validate_control_free_str(text, "approvedBuilds entry", MAX_TEXT_BYTES) |
| 794 | .map_err(ToolError::invalid_input)?; |
| 795 | } |
| 796 | } |
| 797 | |
| 798 | Ok(ParsedChangeInput { |
| 799 | action, |
| 800 | target, |
| 801 | want_enabled, |
| 802 | registry_ignored, |
| 803 | }) |
| 804 | } |
| 805 | |
| 806 | /// Preview and scope check a mutating `plugin_manager` call before Auto-Review or a person card. |
| 807 | #[cfg(test)] |
| 808 | pub async fn plan_change_async( |
| 809 | tool: &ToolContext, |
| 810 | input: &Value, |
| 811 | cancel: &CancellationToken, |
| 812 | ) -> Result<CreatorGatePlan, ToolError> { |
| 813 | plan_change_for_turn_async(tool, input, true, tool.shell_policy.allows_shell(), cancel).await |
| 814 | } |
| 815 | |
| 816 | pub async fn plan_change_for_turn_async( |
| 817 | tool: &ToolContext, |
| 818 | input: &Value, |
| 819 | can_prompt_outside_scope: bool, |
| 820 | allow_shell: bool, |
| 821 | cancel: &CancellationToken, |
| 822 | ) -> Result<CreatorGatePlan, ToolError> { |
| 823 | let parsed = parse_change_input(input)?; |
| 824 | let Some(base_registry) = tool.plugin_registry.as_ref().cloned() else { |
| 825 | return Err(ToolError::not_available( |
| 826 | "plugin manager is not available in this session", |
| 827 | )); |
| 828 | }; |
| 829 | |
| 830 | if parsed.action == CreatorAction::Install { |
| 831 | let source = parse_install_target_syntax(&parsed.target) |
| 832 | .map_err(|(_, msg)| ToolError::invalid_input(msg))?; |
| 833 | if let PluginInstallSource::Remote(_) = source { |
| 834 | let (remote_label, remote_host) = remote_target_display(&source, &parsed.target); |
| 835 | let mut truncated = false; |
| 836 | let safe_spec = sanitize_inline(&parsed.target, MAX_TEXT_BYTES, &mut truncated); |
| 837 | let safe_host = sanitize_inline(&remote_host, MAX_TEXT_BYTES, &mut truncated); |
| 838 | let card_description = format!( |
| 839 | "Action: install\n\ |
| 840 | Source: {safe_spec}\n\ |
| 841 | Remote host: {safe_host}\n\ |
| 842 | Outside agent scope: fetches unseen bytes over the network (bytes are never fetched or inspected before you confirm).\n\ |
| 843 | Fetched bytes will land disabled and untrusted until you review and enable the plugin on the Plugins page or via `/plugin trust <name>`." |
| 844 | ); |
| 845 | return Ok(CreatorGatePlan { |
| 846 | action: CreatorAction::Install, |
| 847 | in_agent_scope: false, |
| 848 | unseen_network_fetch: true, |
| 849 | outside_scope_reason: Some(format!( |
| 850 | "fetches unseen plugin bytes from `{safe_host}`" |
| 851 | )), |
| 852 | card_description, |
| 853 | auto_review_summary: None, |
| 854 | preview: PlannedChangePreview::UnseenFetchInstall { |
| 855 | raw_target: parsed.target, |
| 856 | is_remote: true, |
| 857 | canon_source: None, |
| 858 | remote_label, |
| 859 | remote_host, |
| 860 | }, |
| 861 | }); |
| 862 | } |
| 863 | } |
| 864 | |
| 865 | let workspace = tool.workspace.clone(); |
| 866 | let policy = extension_host_policy_enabled(); |
| 867 | #[cfg(any(test, feature = "test-support"))] |
| 868 | let env_scope = crate::test_support::env_scope_ticket(); |
| 869 | #[cfg(any(test, feature = "test-support"))] |
| 870 | let test_offered: Vec<HostService> = HostService::ALL |
| 871 | .into_iter() |
| 872 | .filter(|service| offered(*service)) |
| 873 | .collect(); |
| 874 | |
| 875 | let blocking = spawn_blocking_policy_job(BlockingPolicyJob::PlanChange { |
| 876 | parsed, |
| 877 | workspace, |
| 878 | base_registry, |
| 879 | can_prompt_outside_scope, |
| 880 | allow_shell, |
| 881 | policy, |
| 882 | #[cfg(any(test, feature = "test-support"))] |
| 883 | env_scope, |
| 884 | #[cfg(any(test, feature = "test-support"))] |
| 885 | test_offered, |
| 886 | }); |
| 887 | |
| 888 | let joined = tokio::select! { |
| 889 | biased; |
| 890 | () = cancel.cancelled() => { |
| 891 | return Err(ToolError::Cancelled { |
| 892 | message: "cancelled while inspecting plugin change".to_string(), |
| 893 | }); |
| 894 | } |
| 895 | res = tokio::time::timeout(PREVIEW_TIMEOUT, blocking) => res, |
| 896 | }; |
| 897 | |
| 898 | match joined { |
| 899 | Ok(Ok(BlockingPolicyResult::Plan(result))) => *result, |
| 900 | Ok(Ok(_)) => Err(ToolError::execution_failed( |
| 901 | "unexpected plugin preview task result".to_string(), |
| 902 | )), |
| 903 | Ok(Err(join_err)) => Err(ToolError::execution_failed(format!( |
| 904 | "plugin preview task failed: {join_err}" |
| 905 | ))), |
| 906 | Err(_) => Err(ToolError::execution_failed( |
| 907 | "timed out inspecting plugin bundle for review".to_string(), |
| 908 | )), |
| 909 | } |
| 910 | } |
| 911 | |
| 912 | fn scope_label(scope: PluginScope) -> &'static str { |
| 913 | match scope { |
| 914 | PluginScope::Builtin => "builtin", |
| 915 | PluginScope::User => "user_from_project", |
| 916 | PluginScope::Workspace => "workspace", |
| 917 | } |
| 918 | } |
| 919 | |
| 920 | fn format_capabilities_summary(inv: &PluginInventory) -> Vec<String> { |
| 921 | let mut parts = Vec::new(); |
| 922 | if inv.skills > 0 { |
| 923 | parts.push(format!("{} skill(s)", inv.skills)); |
| 924 | } |
| 925 | if inv.mcp_servers > 0 { |
| 926 | parts.push(format!( |
| 927 | "{} MCP server(s) ({} stdio, {} remote)", |
| 928 | inv.mcp_servers, inv.stdio_mcp_servers, inv.remote_mcp_servers |
| 929 | )); |
| 930 | } |
| 931 | if inv.commands > 0 { |
| 932 | parts.push(format!("{} command(s)", inv.commands)); |
| 933 | } |
| 934 | if inv.agents > 0 { |
| 935 | parts.push(format!("{} agent(s)", inv.agents)); |
| 936 | } |
| 937 | if inv.hooks > 0 { |
| 938 | parts.push(format!("{} hook(s)", inv.hooks)); |
| 939 | } |
| 940 | if inv.lsp > 0 { |
| 941 | parts.push(format!("{} LSP server(s)", inv.lsp)); |
| 942 | } |
| 943 | if inv.native > 0 { |
| 944 | parts.push(format!("{} native module(s)", inv.native)); |
| 945 | } |
| 946 | if inv.providers > 0 { |
| 947 | parts.push(format!("{} provider(s)", inv.providers)); |
| 948 | } |
| 949 | if !inv.filesystem_roots.is_empty() { |
| 950 | parts.push(format!("{} filesystem root(s)", inv.filesystem_roots.len())); |
| 951 | } |
| 952 | if !inv.network_hosts.is_empty() { |
| 953 | parts.push(format!("{} network host(s)", inv.network_hosts.len())); |
| 954 | } |
| 955 | if inv.lifecycle_mutation { |
| 956 | parts.push("lifecycle mutation".to_string()); |
| 957 | } |
| 958 | if parts.is_empty() { |
| 959 | parts.push("none declared".to_string()); |
| 960 | } |
| 961 | parts |
| 962 | } |
| 963 | |
| 964 | fn build_auto_review_summary( |
| 965 | action: &str, |
| 966 | name: &str, |
| 967 | target: &str, |
| 968 | scope: &str, |
| 969 | version: Option<&str>, |
| 970 | source: &str, |
| 971 | content_hash: &str, |
| 972 | capability_hash: &str, |
| 973 | enabled: Option<bool>, |
| 974 | dsh_package: Option<&str>, |
| 975 | inv: &PluginInventory, |
| 976 | host_services: &[String], |
| 977 | warnings: &[String], |
| 978 | ) -> CreatorReviewSummary { |
| 979 | let mut truncated = false; |
| 980 | CreatorReviewSummary { |
| 981 | action: action.to_string(), |
| 982 | name: name.to_string(), |
| 983 | target: sanitize_inline(target, MAX_TEXT_BYTES, &mut truncated), |
| 984 | scope: scope.to_string(), |
| 985 | version: version.map(str::to_string), |
| 986 | source: sanitize_inline(source, MAX_TEXT_BYTES, &mut truncated), |
| 987 | content_hash: content_hash.to_string(), |
| 988 | capability_hash: capability_hash.to_string(), |
| 989 | enabled, |
| 990 | dsh_package: dsh_package.map(str::to_string), |
| 991 | capabilities: json!({ |
| 992 | "skills": inv.skills, |
| 993 | "mcp_servers": inv.mcp_servers, |
| 994 | "stdio_mcp_servers": inv.stdio_mcp_servers, |
| 995 | "remote_mcp_servers": inv.remote_mcp_servers, |
| 996 | "commands": inv.commands, |
| 997 | "agents": inv.agents, |
| 998 | "hooks": inv.hooks, |
| 999 | "lsp": inv.lsp, |
| 1000 | "native": inv.native, |
| 1001 | "providers": inv.providers, |
| 1002 | "filesystem_roots": inv.filesystem_roots, |
| 1003 | "network_hosts": inv.network_hosts, |
| 1004 | "lifecycle_mutation": inv.lifecycle_mutation, |
| 1005 | }), |
| 1006 | host_services: host_services.to_vec(), |
| 1007 | warnings: warnings.to_vec(), |
| 1008 | } |
| 1009 | } |
| 1010 | |
| 1011 | fn format_local_install_card( |
| 1012 | name: &str, |
| 1013 | version: Option<&str>, |
| 1014 | want_enabled: bool, |
| 1015 | source_label: &str, |
| 1016 | content_hash: &str, |
| 1017 | capability_hash: &str, |
| 1018 | in_agent_scope: bool, |
| 1019 | outside_reason: Option<&str>, |
| 1020 | inventory: &PluginInventory, |
| 1021 | review_lines: &[String], |
| 1022 | warnings: &[String], |
| 1023 | ) -> String { |
| 1024 | let mut lines = Vec::new(); |
| 1025 | let verb = if want_enabled { |
| 1026 | "install and enable" |
| 1027 | } else { |
| 1028 | "install (disabled)" |
| 1029 | }; |
| 1030 | lines.push(format!("Action: {verb}")); |
| 1031 | match version { |
| 1032 | Some(v) => lines.push(format!("Plugin: {name} v{v}")), |
| 1033 | None => lines.push(format!("Plugin: {name}")), |
| 1034 | } |
| 1035 | lines.push(format!("Source: {source_label}")); |
| 1036 | lines.push(format!("Content hash: {content_hash}")); |
| 1037 | lines.push(format!("Capability hash: {capability_hash}")); |
| 1038 | if in_agent_scope { |
| 1039 | lines.push("Scope: inside this project".to_string()); |
| 1040 | } else { |
| 1041 | lines.push(format!( |
| 1042 | "Outside agent scope: {}", |
| 1043 | outside_reason.unwrap_or("requires a person's approval") |
| 1044 | )); |
| 1045 | } |
| 1046 | if want_enabled { |
| 1047 | lines.push("If enabled, this user-level bundle applies for every project.".to_string()); |
| 1048 | } |
| 1049 | lines.push(format!( |
| 1050 | "Capabilities: {}", |
| 1051 | format_capabilities_summary(inventory).join(", ") |
| 1052 | )); |
| 1053 | if !review_lines.is_empty() { |
| 1054 | lines.extend(review_lines.iter().cloned()); |
| 1055 | } |
| 1056 | if !warnings.is_empty() { |
| 1057 | lines.push(format!("Warnings: {}", warnings.join("; "))); |
| 1058 | } |
| 1059 | lines.join("\n") |
| 1060 | } |
| 1061 | |
| 1062 | fn format_toggle_card( |
| 1063 | enabled: bool, |
| 1064 | name: &str, |
| 1065 | plugin_id: &str, |
| 1066 | version: Option<&str>, |
| 1067 | scope: PluginScope, |
| 1068 | content_hash: &str, |
| 1069 | capability_hash: &str, |
| 1070 | in_agent_scope: bool, |
| 1071 | outside_reason: Option<&str>, |
| 1072 | inventory: &PluginInventory, |
| 1073 | review_lines: &[String], |
| 1074 | ) -> String { |
| 1075 | let mut lines = Vec::new(); |
| 1076 | lines.push(format!( |
| 1077 | "Action: {}", |
| 1078 | if enabled { "enable" } else { "disable" } |
| 1079 | )); |
| 1080 | match version { |
| 1081 | Some(v) => lines.push(format!("Plugin: {name} v{v} ({plugin_id})")), |
| 1082 | None => lines.push(format!("Plugin: {name} ({plugin_id})")), |
| 1083 | } |
| 1084 | lines.push(format!("Bundle scope: {}", scope.as_str())); |
| 1085 | lines.push(format!("Content hash: {content_hash}")); |
| 1086 | lines.push(format!("Capability hash: {capability_hash}")); |
| 1087 | if !in_agent_scope { |
| 1088 | lines.push(format!( |
| 1089 | "Outside agent scope: {}", |
| 1090 | outside_reason.unwrap_or("requires a person's approval") |
| 1091 | )); |
| 1092 | } else { |
| 1093 | lines.push("Scope: installed by agent from this project".to_string()); |
| 1094 | } |
| 1095 | if enabled { |
| 1096 | lines.push(format!( |
| 1097 | "Capabilities: {}", |
| 1098 | format_capabilities_summary(inventory).join(", ") |
| 1099 | )); |
| 1100 | if !review_lines.is_empty() { |
| 1101 | lines.extend(review_lines.iter().cloned()); |
| 1102 | } |
| 1103 | } |
| 1104 | lines.join("\n") |
| 1105 | } |
| 1106 | |
| 1107 | fn source_display_for_review( |
| 1108 | canon_src: &Path, |
| 1109 | canon_workspace: Option<&Path>, |
| 1110 | is_dsh: bool, |
| 1111 | ) -> String { |
| 1112 | let label = canon_workspace |
| 1113 | .and_then(|ws| canon_src.strip_prefix(ws).ok().map(Path::to_path_buf)) |
| 1114 | .map(|rel| rel.to_string_lossy().into_owned()) |
| 1115 | .unwrap_or_else(|| canon_src.to_string_lossy().into_owned()); |
| 1116 | if is_dsh { |
| 1117 | format!("dsh:{label}") |
| 1118 | } else { |
| 1119 | label |
| 1120 | } |
| 1121 | } |
| 1122 | |
| 1123 | fn source_display_for_card( |
| 1124 | raw_target: &str, |
| 1125 | canon_src: &Path, |
| 1126 | canon_workspace: Option<&Path>, |
| 1127 | is_dsh: bool, |
| 1128 | dsh_package: Option<&str>, |
| 1129 | ) -> String { |
| 1130 | let mut truncated = false; |
| 1131 | let rel_or_raw = canon_workspace |
| 1132 | .and_then(|ws| { |
| 1133 | canon_src |
| 1134 | .strip_prefix(ws) |
| 1135 | .ok() |
| 1136 | .map(Path::to_path_buf) |
| 1137 | .filter(|rel| !rel.as_os_str().is_empty()) |
| 1138 | }) |
| 1139 | .map(|rel| format!("project/{}", rel.to_string_lossy())) |
| 1140 | .unwrap_or_else(|| raw_target.to_string()); |
| 1141 | let clean = sanitize_inline(&rel_or_raw, MAX_TEXT_BYTES, &mut truncated); |
| 1142 | match (is_dsh, dsh_package) { |
| 1143 | (true, Some(pkg)) => format!("{clean} (DSH package {pkg})"), |
| 1144 | (true, None) => format!("{clean} (DSH package)"), |
| 1145 | (false, _) => clean, |
| 1146 | } |
| 1147 | } |
| 1148 | |
| 1149 | fn path_has_dot_git_component(path: &Path) -> bool { |
| 1150 | path.components().any(|component| match component { |
| 1151 | Component::Normal(part) => part.to_string_lossy().eq_ignore_ascii_case(".git"), |
| 1152 | _ => false, |
| 1153 | }) |
| 1154 | } |
| 1155 | |
| 1156 | enum BlockingPolicyJob { |
| 1157 | PlanChange { |
| 1158 | parsed: ParsedChangeInput, |
| 1159 | workspace: PathBuf, |
| 1160 | base_registry: Arc<PluginRegistry>, |
| 1161 | can_prompt_outside_scope: bool, |
| 1162 | allow_shell: bool, |
| 1163 | policy: bool, |
| 1164 | #[cfg(any(test, feature = "test-support"))] |
| 1165 | env_scope: Option<crate::test_support::EnvScopeTicket>, |
| 1166 | #[cfg(any(test, feature = "test-support"))] |
| 1167 | test_offered: Vec<HostService>, |
| 1168 | }, |
| 1169 | EnsureNoLinks { |
| 1170 | root: PathBuf, |
| 1171 | }, |
| 1172 | CheckSymlinkAncestors { |
| 1173 | path: PathBuf, |
| 1174 | }, |
| 1175 | DirInUserPlugins { |
| 1176 | dir: PathBuf, |
| 1177 | user_plugins_dir: PathBuf, |
| 1178 | }, |
| 1179 | } |
| 1180 | |
| 1181 | enum BlockingPolicyResult { |
| 1182 | Plan(Box<Result<CreatorGatePlan, ToolError>>), |
| 1183 | Unit(Result<(), String>), |
| 1184 | BoolIo(Result<bool, std::io::Error>), |
| 1185 | Bool(bool), |
| 1186 | } |
| 1187 | |
| 1188 | async fn run_blocking_policy_job(job: BlockingPolicyJob) -> Result<BlockingPolicyResult, String> { |
| 1189 | spawn_blocking_policy_job(job) |
| 1190 | .await |
| 1191 | .map_err(|_| "blocking plugin policy task failed".to_string()) |
| 1192 | } |
| 1193 | |
| 1194 | fn spawn_blocking_policy_job( |
| 1195 | job: BlockingPolicyJob, |
| 1196 | ) -> tokio::task::JoinHandle<BlockingPolicyResult> { |
| 1197 | tokio::task::spawn_blocking(move || { |
| 1198 | fn plan_local_install_blocking( |
| 1199 | parsed: ParsedChangeInput, |
| 1200 | workspace: &Path, |
| 1201 | base_registry: &PluginRegistry, |
| 1202 | can_prompt_outside_scope: bool, |
| 1203 | allow_shell: bool, |
| 1204 | ) -> Result<CreatorGatePlan, ToolError> { |
| 1205 | let source = parse_install_target_syntax(&parsed.target) |
| 1206 | .map_err(|(_, msg)| ToolError::invalid_input(msg))?; |
| 1207 | let (raw_path, explicit_dsh) = match source { |
| 1208 | PluginInstallSource::LocalPath(dir) => (dir, false), |
| 1209 | PluginInstallSource::Dsh(dir) => (dir, true), |
| 1210 | PluginInstallSource::Remote(_) => { |
| 1211 | return Err(ToolError::invalid_input("unexpected remote install source")); |
| 1212 | } |
| 1213 | }; |
| 1214 | |
| 1215 | let fresh = base_registry.rediscover_for_workspace(workspace); |
| 1216 | let canon_ws = std::fs::canonicalize(workspace).ok(); |
| 1217 | let canon_user_plugins = fresh |
| 1218 | .user_plugins_dir() |
| 1219 | .map(|p| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())); |
| 1220 | |
| 1221 | if !can_prompt_outside_scope { |
| 1222 | let inside_ws_lexically = canon_ws.is_some() |
| 1223 | && !canon_ws |
| 1224 | .as_deref() |
| 1225 | .is_some_and(workspace_is_root_or_home_sync) |
| 1226 | && !canon_ws.as_deref().is_some_and(path_has_dot_git_component) |
| 1227 | && !raw_path |
| 1228 | .components() |
| 1229 | .any(|c| matches!(c, Component::ParentDir)) |
| 1230 | && !path_has_dot_git_component(&raw_path) |
| 1231 | && (path_is_within(workspace, &raw_path, false) |
| 1232 | || canon_ws |
| 1233 | .as_deref() |
| 1234 | .is_some_and(|cw| path_is_within(cw, &raw_path, false))) |
| 1235 | && !fresh |
| 1236 | .user_plugins_dir() |
| 1237 | .is_some_and(|dir| path_is_within(dir, &raw_path, true)) |
| 1238 | && !canon_user_plugins |
| 1239 | .as_deref() |
| 1240 | .is_some_and(|dir| path_is_within(dir, &raw_path, true)); |
| 1241 | if !inside_ws_lexically { |
| 1242 | return Err(ToolError::permission_denied( |
| 1243 | "folder is outside this project".to_string(), |
| 1244 | )); |
| 1245 | } |
| 1246 | } |
| 1247 | |
| 1248 | match check_symlink_ancestors_sync(&raw_path) { |
| 1249 | Ok(true) => { |
| 1250 | return Err(ToolError::invalid_input( |
| 1251 | "local plugin install path cannot traverse symbolic links", |
| 1252 | )); |
| 1253 | } |
| 1254 | Ok(false) => {} |
| 1255 | Err(error) => { |
| 1256 | let scrubbed = scrub_path_error( |
| 1257 | &error.to_string(), |
| 1258 | workspace, |
| 1259 | canon_ws.as_deref(), |
| 1260 | None, |
| 1261 | fresh.user_plugins_dir(), |
| 1262 | fresh.state_path(), |
| 1263 | ); |
| 1264 | return Err(ToolError::invalid_input(format!( |
| 1265 | "cannot inspect local install folder: {scrubbed}" |
| 1266 | ))); |
| 1267 | } |
| 1268 | } |
| 1269 | |
| 1270 | let src_meta = std::fs::metadata(&raw_path).map_err(|error| { |
| 1271 | let scrubbed = scrub_path_error( |
| 1272 | &error.to_string(), |
| 1273 | workspace, |
| 1274 | canon_ws.as_deref(), |
| 1275 | None, |
| 1276 | fresh.user_plugins_dir(), |
| 1277 | fresh.state_path(), |
| 1278 | ); |
| 1279 | ToolError::invalid_input(format!("cannot inspect local install folder: {scrubbed}")) |
| 1280 | })?; |
| 1281 | if !src_meta.is_dir() { |
| 1282 | return Err(ToolError::invalid_input( |
| 1283 | "local plugin install target must be a directory", |
| 1284 | )); |
| 1285 | } |
| 1286 | |
| 1287 | let canon_src = std::fs::canonicalize(&raw_path).map_err(|error| { |
| 1288 | let scrubbed = scrub_path_error( |
| 1289 | &error.to_string(), |
| 1290 | workspace, |
| 1291 | canon_ws.as_deref(), |
| 1292 | None, |
| 1293 | fresh.user_plugins_dir(), |
| 1294 | fresh.state_path(), |
| 1295 | ); |
| 1296 | ToolError::invalid_input(format!("cannot resolve local install folder: {scrubbed}")) |
| 1297 | })?; |
| 1298 | |
| 1299 | scan_no_links_bounded(&canon_src, MAX_PREVIEW_TREE_BYTES, MAX_PREVIEW_TREE_ENTRIES) |
| 1300 | .map_err(ToolError::invalid_input)?; |
| 1301 | |
| 1302 | let has_native_manifest = clean_root_manifest_sync(&canon_src).is_some(); |
| 1303 | let is_dsh = if explicit_dsh { |
| 1304 | true |
| 1305 | } else { |
| 1306 | match dsh::try_is_dsh_package(&canon_src) { |
| 1307 | Ok(true) => true, |
| 1308 | Ok(false) if has_native_manifest => false, |
| 1309 | Ok(false) => { |
| 1310 | return Err(ToolError::invalid_input( |
| 1311 | "source directory has no plugin.json, .claude-plugin/plugin.json, kimi.plugin.json, plugin.toml, or DSH package.json", |
| 1312 | )); |
| 1313 | } |
| 1314 | Err(error) => { |
| 1315 | let scrubbed = scrub_path_error( |
| 1316 | &error.to_string(), |
| 1317 | workspace, |
| 1318 | canon_ws.as_deref(), |
| 1319 | None, |
| 1320 | fresh.user_plugins_dir(), |
| 1321 | fresh.state_path(), |
| 1322 | ); |
| 1323 | return Err(ToolError::invalid_input(scrubbed)); |
| 1324 | } |
| 1325 | } |
| 1326 | }; |
| 1327 | |
| 1328 | let scrub = ScrubContext { |
| 1329 | workspace: fresh.workspace(), |
| 1330 | canon_workspace: canon_ws.as_deref(), |
| 1331 | plugin_root: Some(&canon_src), |
| 1332 | user_plugins_dir: fresh.user_plugins_dir(), |
| 1333 | state_path: fresh.state_path(), |
| 1334 | }; |
| 1335 | |
| 1336 | if is_dsh { |
| 1337 | let has_npm_deps = |
| 1338 | dsh::has_unresolved_npm_dependencies(&canon_src).map_err(|err| { |
| 1339 | ToolError::invalid_input(scrub_message(&err.to_string(), &scrub)) |
| 1340 | })?; |
| 1341 | if has_npm_deps { |
| 1342 | let mut truncated = false; |
| 1343 | let safe_target = |
| 1344 | sanitize_inline(&parsed.target, MAX_TEXT_BYTES, &mut truncated); |
| 1345 | let pkg_note = read_dsh_source_package_sync(&canon_src) |
| 1346 | .map(|pkg| { |
| 1347 | format!( |
| 1348 | "\nPackage: {}", |
| 1349 | sanitize_inline(&pkg, MAX_TEXT_BYTES, &mut truncated) |
| 1350 | ) |
| 1351 | }) |
| 1352 | .unwrap_or_default(); |
| 1353 | let card_description = format!( |
| 1354 | "Action: install\n\ |
| 1355 | Folder: {safe_target}{pkg_note}\n\ |
| 1356 | Remote host: registry.npmjs.org\n\ |
| 1357 | Outside agent scope: unresolved npm dependencies will fetch unseen bytes from registry.npmjs.org (no network fetch or conversion runs before you confirm).\n\ |
| 1358 | Fetched bytes will land disabled and untrusted until you review and enable the plugin on the Plugins page or via `/plugin trust <name>`." |
| 1359 | ); |
| 1360 | return Ok(CreatorGatePlan { |
| 1361 | action: CreatorAction::Install, |
| 1362 | in_agent_scope: false, |
| 1363 | unseen_network_fetch: true, |
| 1364 | outside_scope_reason: Some( |
| 1365 | "DSH bundle has unresolved npm dependencies from registry.npmjs.org" |
| 1366 | .to_string(), |
| 1367 | ), |
| 1368 | card_description, |
| 1369 | auto_review_summary: None, |
| 1370 | preview: PlannedChangePreview::UnseenFetchInstall { |
| 1371 | raw_target: parsed.target, |
| 1372 | is_remote: false, |
| 1373 | canon_source: Some(canon_src), |
| 1374 | remote_label: safe_target, |
| 1375 | remote_host: "registry.npmjs.org".to_string(), |
| 1376 | }, |
| 1377 | }); |
| 1378 | } |
| 1379 | } |
| 1380 | |
| 1381 | let (validated, dsh_package, extra_warnings) = if is_dsh { |
| 1382 | let (_scratch, bundle, conversion) = |
| 1383 | dsh::convert_to_scratch(&canon_src).map_err(|err| { |
| 1384 | ToolError::invalid_input(scrub_message(&err.to_string(), &scrub)) |
| 1385 | })?; |
| 1386 | let manifest_path = resolve_manifest_path(&bundle).ok_or_else(|| { |
| 1387 | ToolError::invalid_input( |
| 1388 | "converted DSH bundle has no supported plugin manifest", |
| 1389 | ) |
| 1390 | })?; |
| 1391 | let validated = PluginManifest::validate_from_path(&manifest_path) |
| 1392 | .map_err(|err| ToolError::invalid_input(scrub_message(&err, &scrub)))?; |
| 1393 | let mut diag_warnings = Vec::new(); |
| 1394 | for note in conversion.diagnostics { |
| 1395 | diag_warnings.push(scrub_warning(¬e, &scrub)); |
| 1396 | } |
| 1397 | (validated, conversion.source_package, diag_warnings) |
| 1398 | } else { |
| 1399 | let manifest_path = clean_root_manifest_sync(&canon_src).ok_or_else(|| { |
| 1400 | ToolError::invalid_input("source directory has no valid plugin manifest") |
| 1401 | })?; |
| 1402 | let validated = PluginManifest::validate_from_path(&manifest_path) |
| 1403 | .map_err(|err| ToolError::invalid_input(scrub_message(&err, &scrub)))?; |
| 1404 | (validated, None, Vec::new()) |
| 1405 | }; |
| 1406 | |
| 1407 | let (mut in_agent_scope, mut outside_scope_reason) = check_local_install_scope( |
| 1408 | &raw_path, |
| 1409 | &canon_src, |
| 1410 | canon_ws.as_deref(), |
| 1411 | fresh.user_plugins_dir(), |
| 1412 | canon_user_plugins.as_deref(), |
| 1413 | ); |
| 1414 | if in_agent_scope |
| 1415 | && !allow_shell |
| 1416 | && (validated.inventory.stdio_mcp_servers > 0 || validated.inventory.hooks > 0) |
| 1417 | { |
| 1418 | in_agent_scope = false; |
| 1419 | outside_scope_reason = Some( |
| 1420 | "bundle declares stdio MCP connectors or hooks while shell execution is disabled" |
| 1421 | .to_string(), |
| 1422 | ); |
| 1423 | } |
| 1424 | |
| 1425 | let mut truncated = false; |
| 1426 | let raw_name = validated.manifest.plugin.name.clone(); |
| 1427 | let safe_name = sanitize_inline(&raw_name, MAX_VERSION_BYTES, &mut truncated); |
| 1428 | let version = non_empty_version(&validated.manifest.plugin.version) |
| 1429 | .map(|v| sanitize_inline(&v, MAX_VERSION_BYTES, &mut truncated)); |
| 1430 | let safe_dsh_pkg = dsh_package |
| 1431 | .as_deref() |
| 1432 | .map(|p| sanitize_inline(p, MAX_TEXT_BYTES, &mut truncated)); |
| 1433 | |
| 1434 | let mut warnings = Vec::new(); |
| 1435 | for w in validated.warnings.into_iter().chain(extra_warnings) { |
| 1436 | if warnings.len() >= MAX_WARNING_ENTRIES { |
| 1437 | break; |
| 1438 | } |
| 1439 | let cleaned = scrub_warning(&w, &scrub); |
| 1440 | if !cleaned.is_empty() && !warnings.contains(&cleaned) { |
| 1441 | warnings.push(cleaned); |
| 1442 | } |
| 1443 | } |
| 1444 | if parsed.registry_ignored && warnings.len() < MAX_WARNING_ENTRIES { |
| 1445 | warnings.push( |
| 1446 | "registry was ignored; Codewhale installs from the configured source" |
| 1447 | .to_string(), |
| 1448 | ); |
| 1449 | } |
| 1450 | |
| 1451 | let person_review = host_service_review_from_inventory( |
| 1452 | &fresh, |
| 1453 | "", |
| 1454 | &raw_name, |
| 1455 | &validated.content_hash, |
| 1456 | &validated.capability_hash, |
| 1457 | &validated.inventory, |
| 1458 | &PluginCohort::Reviewed, |
| 1459 | ); |
| 1460 | let person_review_lines = person_review.text(); |
| 1461 | |
| 1462 | let (agent_review_lines, auto_review_summary) = if in_agent_scope { |
| 1463 | let ws = canon_ws.as_deref().unwrap_or_else(|| fresh.workspace()); |
| 1464 | let agent_cohort = PluginCohort::agent(ws); |
| 1465 | let agent_review = host_service_review_from_inventory( |
| 1466 | &fresh, |
| 1467 | "", |
| 1468 | &raw_name, |
| 1469 | &validated.content_hash, |
| 1470 | &validated.capability_hash, |
| 1471 | &validated.inventory, |
| 1472 | &agent_cohort, |
| 1473 | ); |
| 1474 | let agent_lines = agent_review.text(); |
| 1475 | let summary = build_auto_review_summary( |
| 1476 | "install", |
| 1477 | &safe_name, |
| 1478 | &parsed.target, |
| 1479 | "local_project", |
| 1480 | version.as_deref(), |
| 1481 | &source_display_for_review(&canon_src, canon_ws.as_deref(), is_dsh), |
| 1482 | &validated.content_hash, |
| 1483 | &validated.capability_hash, |
| 1484 | Some(parsed.want_enabled), |
| 1485 | safe_dsh_pkg.as_deref(), |
| 1486 | &validated.inventory, |
| 1487 | &agent_lines, |
| 1488 | &warnings, |
| 1489 | ); |
| 1490 | (agent_lines, Some(summary)) |
| 1491 | } else { |
| 1492 | (Vec::new(), None) |
| 1493 | }; |
| 1494 | |
| 1495 | let source_label = source_display_for_card( |
| 1496 | &parsed.target, |
| 1497 | &canon_src, |
| 1498 | canon_ws.as_deref(), |
| 1499 | is_dsh, |
| 1500 | safe_dsh_pkg.as_deref(), |
| 1501 | ); |
| 1502 | let card_description = format_local_install_card( |
| 1503 | &safe_name, |
| 1504 | version.as_deref(), |
| 1505 | parsed.want_enabled, |
| 1506 | &source_label, |
| 1507 | &validated.content_hash, |
| 1508 | &validated.capability_hash, |
| 1509 | in_agent_scope, |
| 1510 | outside_scope_reason.as_deref(), |
| 1511 | &validated.inventory, |
| 1512 | &person_review_lines, |
| 1513 | &warnings, |
| 1514 | ); |
| 1515 | let expected_gate_target = |
| 1516 | format!("{raw_name} {} {}", validated.content_hash, parsed.target); |
| 1517 | |
| 1518 | Ok(CreatorGatePlan { |
| 1519 | action: CreatorAction::Install, |
| 1520 | in_agent_scope, |
| 1521 | unseen_network_fetch: false, |
| 1522 | outside_scope_reason, |
| 1523 | card_description, |
| 1524 | auto_review_summary, |
| 1525 | preview: PlannedChangePreview::LocalInstall { |
| 1526 | raw_target: parsed.target, |
| 1527 | canon_source: canon_src, |
| 1528 | is_dsh, |
| 1529 | plugin_name: raw_name, |
| 1530 | want_enabled: parsed.want_enabled, |
| 1531 | pre_hash: validated.content_hash, |
| 1532 | capability_hash: validated.capability_hash, |
| 1533 | expected_gate_target, |
| 1534 | person_review_lines, |
| 1535 | agent_review_lines, |
| 1536 | warnings, |
| 1537 | }, |
| 1538 | }) |
| 1539 | } |
| 1540 | |
| 1541 | fn plan_existing_blocking( |
| 1542 | parsed: ParsedChangeInput, |
| 1543 | workspace: &Path, |
| 1544 | base_registry: &PluginRegistry, |
| 1545 | allow_shell: bool, |
| 1546 | ) -> Result<CreatorGatePlan, ToolError> { |
| 1547 | let fresh = base_registry.rediscover_for_workspace(workspace); |
| 1548 | let canon_ws = std::fs::canonicalize(workspace).ok(); |
| 1549 | let canon_user_plugins = fresh |
| 1550 | .user_plugins_dir() |
| 1551 | .map(|p| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())); |
| 1552 | let mut truncated = false; |
| 1553 | let clean_target = sanitize_inline(&parsed.target, MAX_TEXT_BYTES, &mut truncated); |
| 1554 | |
| 1555 | let plugin = match resolve_plugin_by_target(&fresh, &parsed.target) { |
| 1556 | TargetLookup::Missing => { |
| 1557 | return Err(ToolError::invalid_input(format!( |
| 1558 | "Plugin bundle `{clean_target}` was not found" |
| 1559 | ))); |
| 1560 | } |
| 1561 | TargetLookup::Ambiguous { message, .. } => { |
| 1562 | return Err(ToolError::invalid_input(message)); |
| 1563 | } |
| 1564 | TargetLookup::Found(plugin) => plugin, |
| 1565 | }; |
| 1566 | |
| 1567 | let raw_name = plugin.name().to_string(); |
| 1568 | let safe_name = sanitize_inline(&raw_name, MAX_VERSION_BYTES, &mut truncated); |
| 1569 | let plugin_id = plugin.id.as_str().to_string(); |
| 1570 | let version = non_empty_version(&plugin.manifest.plugin.version) |
| 1571 | .map(|v| sanitize_inline(&v, MAX_VERSION_BYTES, &mut truncated)); |
| 1572 | |
| 1573 | if parsed.action == CreatorAction::Remove { |
| 1574 | match plugin.scope { |
| 1575 | PluginScope::Builtin => { |
| 1576 | return Err(ToolError::invalid_input(format!( |
| 1577 | "Built-in plugin `{safe_name}` cannot be removed; use disable instead" |
| 1578 | ))); |
| 1579 | } |
| 1580 | PluginScope::Workspace => { |
| 1581 | return Err(ToolError::invalid_input(format!( |
| 1582 | "Project plugin `{safe_name}` is a workspace file and cannot be removed with plugin_manager" |
| 1583 | ))); |
| 1584 | } |
| 1585 | PluginScope::User => { |
| 1586 | if !has_regular_install_marker(&plugin.canonical_root) { |
| 1587 | return Err(ToolError::invalid_input(format!( |
| 1588 | "Plugin `{safe_name}` was not installed via plugin install and cannot be removed here" |
| 1589 | ))); |
| 1590 | } |
| 1591 | } |
| 1592 | } |
| 1593 | } |
| 1594 | |
| 1595 | let (mut in_agent_scope, mut outside_scope_reason) = check_existing_scope( |
| 1596 | &fresh, |
| 1597 | plugin, |
| 1598 | canon_ws.as_deref(), |
| 1599 | canon_user_plugins.as_deref(), |
| 1600 | ); |
| 1601 | if in_agent_scope |
| 1602 | && parsed.action == CreatorAction::Enable |
| 1603 | && !allow_shell |
| 1604 | && (plugin.inventory.stdio_mcp_servers > 0 || plugin.inventory.hooks > 0) |
| 1605 | { |
| 1606 | in_agent_scope = false; |
| 1607 | outside_scope_reason = Some( |
| 1608 | "bundle declares stdio MCP connectors or hooks while shell execution is disabled" |
| 1609 | .to_string(), |
| 1610 | ); |
| 1611 | } |
| 1612 | |
| 1613 | if parsed.action == CreatorAction::Remove { |
| 1614 | let expected_gate_target = format!("{raw_name} {plugin_id}"); |
| 1615 | let scope_note = if in_agent_scope { |
| 1616 | "Scope: installed by agent from this project".to_string() |
| 1617 | } else { |
| 1618 | format!( |
| 1619 | "Outside agent scope: {}", |
| 1620 | outside_scope_reason |
| 1621 | .as_deref() |
| 1622 | .unwrap_or("requires a person's approval") |
| 1623 | ) |
| 1624 | }; |
| 1625 | let version_line = version |
| 1626 | .as_deref() |
| 1627 | .map(|v| format!("\nVersion: {v}")) |
| 1628 | .unwrap_or_default(); |
| 1629 | let card_description = format!( |
| 1630 | "Action: remove\n\ |
| 1631 | Plugin: {safe_name} ({plugin_id}){version_line}\n\ |
| 1632 | Content hash: {}\n\ |
| 1633 | {scope_note}", |
| 1634 | plugin.content_hash |
| 1635 | ); |
| 1636 | let auto_review_summary = if in_agent_scope { |
| 1637 | Some(build_auto_review_summary( |
| 1638 | "remove", |
| 1639 | &safe_name, |
| 1640 | &parsed.target, |
| 1641 | "user_from_project", |
| 1642 | version.as_deref(), |
| 1643 | "installed bundle", |
| 1644 | &plugin.content_hash, |
| 1645 | &plugin.capability_hash, |
| 1646 | None, |
| 1647 | None, |
| 1648 | &plugin.inventory, |
| 1649 | &[], |
| 1650 | &[], |
| 1651 | )) |
| 1652 | } else { |
| 1653 | None |
| 1654 | }; |
| 1655 | return Ok(CreatorGatePlan { |
| 1656 | action: CreatorAction::Remove, |
| 1657 | in_agent_scope, |
| 1658 | unseen_network_fetch: false, |
| 1659 | outside_scope_reason, |
| 1660 | card_description, |
| 1661 | auto_review_summary, |
| 1662 | preview: PlannedChangePreview::ExistingRemove { |
| 1663 | plugin_id, |
| 1664 | plugin_name: raw_name, |
| 1665 | expected_gate_target, |
| 1666 | }, |
| 1667 | }); |
| 1668 | } |
| 1669 | |
| 1670 | let enabled = parsed.action == CreatorAction::Enable; |
| 1671 | let expected_gate_target = if enabled { |
| 1672 | format!("{raw_name} {} {plugin_id}", plugin.content_hash) |
| 1673 | } else { |
| 1674 | format!("{raw_name} {plugin_id}") |
| 1675 | }; |
| 1676 | |
| 1677 | let (person_review_lines, person_review_token, agent_review_lines, agent_review_token) = |
| 1678 | if enabled { |
| 1679 | let person_approver = PluginApprover::person(PersonVia::ApprovalCard); |
| 1680 | let person_review = fresh.host_service_review_for(&plugin_id, &person_approver); |
| 1681 | let p_lines = person_review.as_ref().map(|r| r.text()).unwrap_or_default(); |
| 1682 | let p_token = person_review.map(|r| r.token); |
| 1683 | |
| 1684 | let (a_lines, a_token) = if in_agent_scope { |
| 1685 | let ws = canon_ws.as_deref().unwrap_or_else(|| fresh.workspace()); |
| 1686 | let agent_approver = PluginApprover::Agent(AgentApproval { |
| 1687 | posture: AgentPosture::AutoReview, |
| 1688 | workspace: ws.to_string_lossy().into_owned(), |
| 1689 | thread_id: None, |
| 1690 | turn_id: None, |
| 1691 | tool_call_id: None, |
| 1692 | }); |
| 1693 | let agent_review = |
| 1694 | fresh.host_service_review_for(&plugin_id, &agent_approver); |
| 1695 | ( |
| 1696 | agent_review.as_ref().map(|r| r.text()).unwrap_or_default(), |
| 1697 | agent_review.map(|r| r.token), |
| 1698 | ) |
| 1699 | } else { |
| 1700 | (Vec::new(), None) |
| 1701 | }; |
| 1702 | (p_lines, p_token, a_lines, a_token) |
| 1703 | } else { |
| 1704 | (Vec::new(), None, Vec::new(), None) |
| 1705 | }; |
| 1706 | |
| 1707 | let card_description = format_toggle_card( |
| 1708 | enabled, |
| 1709 | &safe_name, |
| 1710 | &plugin_id, |
| 1711 | version.as_deref(), |
| 1712 | plugin.scope, |
| 1713 | &plugin.content_hash, |
| 1714 | &plugin.capability_hash, |
| 1715 | in_agent_scope, |
| 1716 | outside_scope_reason.as_deref(), |
| 1717 | &plugin.inventory, |
| 1718 | &person_review_lines, |
| 1719 | ); |
| 1720 | |
| 1721 | let auto_review_summary = if in_agent_scope { |
| 1722 | let lines = if enabled { |
| 1723 | &agent_review_lines |
| 1724 | } else { |
| 1725 | &[][..] |
| 1726 | }; |
| 1727 | Some(build_auto_review_summary( |
| 1728 | if enabled { "enable" } else { "disable" }, |
| 1729 | &safe_name, |
| 1730 | &parsed.target, |
| 1731 | scope_label(plugin.scope), |
| 1732 | version.as_deref(), |
| 1733 | "installed bundle", |
| 1734 | &plugin.content_hash, |
| 1735 | &plugin.capability_hash, |
| 1736 | Some(enabled), |
| 1737 | None, |
| 1738 | &plugin.inventory, |
| 1739 | lines, |
| 1740 | &[], |
| 1741 | )) |
| 1742 | } else { |
| 1743 | None |
| 1744 | }; |
| 1745 | |
| 1746 | Ok(CreatorGatePlan { |
| 1747 | action: parsed.action, |
| 1748 | in_agent_scope, |
| 1749 | unseen_network_fetch: false, |
| 1750 | outside_scope_reason, |
| 1751 | card_description, |
| 1752 | auto_review_summary, |
| 1753 | preview: PlannedChangePreview::ExistingToggle { |
| 1754 | enabled, |
| 1755 | plugin_id, |
| 1756 | plugin_name: raw_name, |
| 1757 | content_hash: plugin.content_hash.clone(), |
| 1758 | capability_hash: plugin.capability_hash.clone(), |
| 1759 | expected_gate_target, |
| 1760 | person_review_lines, |
| 1761 | person_review_token, |
| 1762 | agent_review_lines, |
| 1763 | agent_review_token, |
| 1764 | }, |
| 1765 | }) |
| 1766 | } |
| 1767 | |
| 1768 | fn check_local_install_scope( |
| 1769 | raw_path: &Path, |
| 1770 | canon_src: &Path, |
| 1771 | canon_ws: Option<&Path>, |
| 1772 | raw_user_plugins: Option<&Path>, |
| 1773 | canon_user_plugins: Option<&Path>, |
| 1774 | ) -> (bool, Option<String>) { |
| 1775 | let Some(canon_ws) = canon_ws else { |
| 1776 | return ( |
| 1777 | false, |
| 1778 | Some("project directory could not be resolved".to_string()), |
| 1779 | ); |
| 1780 | }; |
| 1781 | if workspace_is_root_or_home_sync(canon_ws) { |
| 1782 | return ( |
| 1783 | false, |
| 1784 | Some("project directory is your home folder or filesystem root".to_string()), |
| 1785 | ); |
| 1786 | } |
| 1787 | if path_has_dot_git_component(canon_ws) |
| 1788 | || path_has_dot_git_component(raw_path) |
| 1789 | || path_has_dot_git_component(canon_src) |
| 1790 | { |
| 1791 | return (false, Some("path sits inside .git".to_string())); |
| 1792 | } |
| 1793 | if canon_src == canon_ws { |
| 1794 | return ( |
| 1795 | false, |
| 1796 | Some("cannot install the project root itself".to_string()), |
| 1797 | ); |
| 1798 | } |
| 1799 | if raw_path |
| 1800 | .components() |
| 1801 | .any(|c| matches!(c, Component::ParentDir)) |
| 1802 | { |
| 1803 | return ( |
| 1804 | false, |
| 1805 | Some("path uses parent-directory traversal".to_string()), |
| 1806 | ); |
| 1807 | } |
| 1808 | if canon_user_plugins.is_some_and(|dir| path_is_within(dir, canon_src, true)) |
| 1809 | || raw_user_plugins.is_some_and(|dir| { |
| 1810 | std::fs::symlink_metadata(dir) |
| 1811 | .ok() |
| 1812 | .is_some_and(|m| metadata_is_link_or_reparse(&m)) |
| 1813 | || path_is_within(dir, raw_path, true) |
| 1814 | || path_is_within(dir, canon_src, true) |
| 1815 | }) |
| 1816 | { |
| 1817 | return ( |
| 1818 | false, |
| 1819 | Some("path sits inside the installed plugins folder".to_string()), |
| 1820 | ); |
| 1821 | } |
| 1822 | if !matches!(check_symlink_ancestors_sync(raw_path), Ok(false)) { |
| 1823 | return (false, Some("path traverses a symbolic link".to_string())); |
| 1824 | } |
| 1825 | if !clean_dir_is_strictly_inside(raw_path, canon_ws) { |
| 1826 | return (false, Some("folder is outside this project".to_string())); |
| 1827 | } |
| 1828 | (true, None) |
| 1829 | } |
| 1830 | |
| 1831 | fn check_existing_scope( |
| 1832 | registry: &PluginRegistry, |
| 1833 | plugin: &LoadedPlugin, |
| 1834 | canon_ws: Option<&Path>, |
| 1835 | canon_user_plugins: Option<&Path>, |
| 1836 | ) -> (bool, Option<String>) { |
| 1837 | if plugin.scope == PluginScope::Builtin { |
| 1838 | return ( |
| 1839 | false, |
| 1840 | Some("built-in plugins always require a person's approval".to_string()), |
| 1841 | ); |
| 1842 | } |
| 1843 | if registry.state_error().is_some() { |
| 1844 | return ( |
| 1845 | false, |
| 1846 | Some("plugin state is fail-closed or unreadable".to_string()), |
| 1847 | ); |
| 1848 | } |
| 1849 | let Some(canon_ws) = canon_ws else { |
| 1850 | return ( |
| 1851 | false, |
| 1852 | Some("project directory could not be resolved".to_string()), |
| 1853 | ); |
| 1854 | }; |
| 1855 | if workspace_is_root_or_home_sync(canon_ws) || path_has_dot_git_component(canon_ws) { |
| 1856 | return ( |
| 1857 | false, |
| 1858 | Some("this project root cannot establish agent ownership".to_string()), |
| 1859 | ); |
| 1860 | } |
| 1861 | match plugin.approved_by.as_ref() { |
| 1862 | Some(PluginApprover::Person { .. }) => { |
| 1863 | return ( |
| 1864 | false, |
| 1865 | Some("this plugin was approved by a person".to_string()), |
| 1866 | ); |
| 1867 | } |
| 1868 | Some(PluginApprover::CommandLine) => { |
| 1869 | return ( |
| 1870 | false, |
| 1871 | Some("this plugin was approved from the command line".to_string()), |
| 1872 | ); |
| 1873 | } |
| 1874 | Some(PluginApprover::Agent(agent)) => { |
| 1875 | if agent.posture == AgentPosture::CommandLine { |
| 1876 | return ( |
| 1877 | false, |
| 1878 | Some("this plugin was approved from the command line".to_string()), |
| 1879 | ); |
| 1880 | } |
| 1881 | if !agent_workspace_matches_sync(&agent.workspace, canon_ws) { |
| 1882 | return ( |
| 1883 | false, |
| 1884 | Some("this plugin was approved in another project".to_string()), |
| 1885 | ); |
| 1886 | } |
| 1887 | } |
| 1888 | None => { |
| 1889 | return ( |
| 1890 | false, |
| 1891 | Some("this plugin has not been reviewed by this agent".to_string()), |
| 1892 | ); |
| 1893 | } |
| 1894 | } |
| 1895 | if !plugin.trusted() { |
| 1896 | return ( |
| 1897 | false, |
| 1898 | Some( |
| 1899 | "this plugin's review record does not match the files on disk".to_string(), |
| 1900 | ), |
| 1901 | ); |
| 1902 | } |
| 1903 | if !installed_by_agent_strict_sync(&plugin.canonical_root, canon_ws, canon_user_plugins) |
| 1904 | { |
| 1905 | return ( |
| 1906 | false, |
| 1907 | Some( |
| 1908 | "this plugin was not installed from a clean subfolder of this project" |
| 1909 | .to_string(), |
| 1910 | ), |
| 1911 | ); |
| 1912 | } |
| 1913 | (true, None) |
| 1914 | } |
| 1915 | |
| 1916 | fn agent_workspace_matches_sync(recorded: &str, canon_ws: &Path) -> bool { |
| 1917 | let rec_path = Path::new(recorded); |
| 1918 | let rec_canon = |
| 1919 | std::fs::canonicalize(rec_path).unwrap_or_else(|_| rec_path.to_path_buf()); |
| 1920 | path_is_within(canon_ws, &rec_canon, true) && path_is_within(&rec_canon, canon_ws, true) |
| 1921 | } |
| 1922 | |
| 1923 | fn workspace_is_root_or_home_sync(canon_ws: &Path) -> bool { |
| 1924 | if canon_ws.parent().is_none() { |
| 1925 | return true; |
| 1926 | } |
| 1927 | let equal_canon = |candidate: PathBuf| { |
| 1928 | let canon_cand = std::fs::canonicalize(&candidate).unwrap_or(candidate); |
| 1929 | path_is_within(&canon_cand, canon_ws, true) |
| 1930 | && path_is_within(canon_ws, &canon_cand, true) |
| 1931 | }; |
| 1932 | if let Some(home) = user_home() |
| 1933 | && equal_canon(home) |
| 1934 | { |
| 1935 | return true; |
| 1936 | } |
| 1937 | if let Ok(Some(home)) = codewhale_home_override() |
| 1938 | && equal_canon(home) |
| 1939 | { |
| 1940 | return true; |
| 1941 | } |
| 1942 | false |
| 1943 | } |
| 1944 | |
| 1945 | fn installed_by_agent_strict_sync( |
| 1946 | bundle_root: &Path, |
| 1947 | canon_ws: &Path, |
| 1948 | canon_user_plugins: Option<&Path>, |
| 1949 | ) -> bool { |
| 1950 | if !installed_by_the_agent(bundle_root, canon_ws) { |
| 1951 | return false; |
| 1952 | } |
| 1953 | let marker_path = bundle_root.join(INSTALLED_FROM_MARKER); |
| 1954 | let Ok(file) = codewhale_util::bundle_file::open_bundle_file(&marker_path) else { |
| 1955 | return false; |
| 1956 | }; |
| 1957 | let mut body = String::new(); |
| 1958 | if file.take(64 * 1024 + 1).read_to_string(&mut body).is_err() || body.len() > 64 * 1024 |
| 1959 | { |
| 1960 | return false; |
| 1961 | } |
| 1962 | let Ok(marker) = serde_json::from_str::<InstalledFromMarker>(&body) else { |
| 1963 | return false; |
| 1964 | }; |
| 1965 | let Ok(source) = PluginInstallSource::parse_syntax(&marker.spec) else { |
| 1966 | return false; |
| 1967 | }; |
| 1968 | match source { |
| 1969 | PluginInstallSource::LocalPath(dir) | PluginInstallSource::Dsh(dir) => { |
| 1970 | if path_has_dot_git_component(&dir) { |
| 1971 | return false; |
| 1972 | } |
| 1973 | let Ok(canon_src) = std::fs::canonicalize(&dir) else { |
| 1974 | return false; |
| 1975 | }; |
| 1976 | if path_has_dot_git_component(&canon_src) { |
| 1977 | return false; |
| 1978 | } |
| 1979 | if canon_user_plugins.is_some_and(|u| path_is_within(u, &canon_src, true)) { |
| 1980 | return false; |
| 1981 | } |
| 1982 | if !matches!(check_symlink_ancestors_sync(&dir), Ok(false)) { |
| 1983 | return false; |
| 1984 | } |
| 1985 | if matches!(dsh::has_unresolved_npm_dependencies(&canon_src), Ok(true)) { |
| 1986 | return false; |
| 1987 | } |
| 1988 | true |
| 1989 | } |
| 1990 | PluginInstallSource::Remote(_) => false, |
| 1991 | } |
| 1992 | } |
| 1993 | |
| 1994 | fn clean_root_manifest_sync(dir: &Path) -> Option<PathBuf> { |
| 1995 | let manifest = resolve_manifest_path(dir)?; |
| 1996 | let mut cursor = manifest.parent(); |
| 1997 | while let Some(current) = cursor { |
| 1998 | if let Ok(meta) = std::fs::symlink_metadata(current) |
| 1999 | && metadata_is_link_or_reparse(&meta) |
| 2000 | { |
| 2001 | return None; |
| 2002 | } |
| 2003 | if current == dir { |
| 2004 | break; |
| 2005 | } |
| 2006 | cursor = current.parent(); |
| 2007 | } |
| 2008 | let meta = std::fs::symlink_metadata(&manifest).ok()?; |
| 2009 | (!metadata_is_link_or_reparse(&meta) && meta.is_file()).then_some(manifest) |
| 2010 | } |
| 2011 | |
| 2012 | fn scan_no_links_bounded( |
| 2013 | root: &Path, |
| 2014 | max_bytes: u64, |
| 2015 | max_entries: usize, |
| 2016 | ) -> Result<(), String> { |
| 2017 | let root_meta = std::fs::symlink_metadata(root) |
| 2018 | .map_err(|err| format!("failed to inspect install source: {err}"))?; |
| 2019 | if metadata_is_link_or_reparse(&root_meta) || root_meta.file_type().is_symlink() { |
| 2020 | return Err("plugin bundles cannot contain symbolic links".to_string()); |
| 2021 | } |
| 2022 | if !root_meta.is_dir() { |
| 2023 | return Err("not-bundle: install source must be a directory".to_string()); |
| 2024 | } |
| 2025 | let mut entries = 0usize; |
| 2026 | let mut total_bytes = 0u64; |
| 2027 | let mut stack = vec![root.to_path_buf()]; |
| 2028 | while let Some(dir) = stack.pop() { |
| 2029 | let dir_entries = std::fs::read_dir(&dir) |
| 2030 | .map_err(|err| format!("failed to inspect bundle: {err}"))?; |
| 2031 | for entry in dir_entries { |
| 2032 | let entry = |
| 2033 | entry.map_err(|err| format!("failed to read bundle entry: {err}"))?; |
| 2034 | entries = entries.saturating_add(1); |
| 2035 | if entries > max_entries { |
| 2036 | return Err(format!("plugin bundle has more than {max_entries} entries")); |
| 2037 | } |
| 2038 | let path = entry.path(); |
| 2039 | let meta = std::fs::symlink_metadata(&path) |
| 2040 | .map_err(|err| format!("failed to inspect entry: {err}"))?; |
| 2041 | if metadata_is_link_or_reparse(&meta) { |
| 2042 | return Err("plugin bundles cannot contain symbolic links".to_string()); |
| 2043 | } |
| 2044 | if meta.is_dir() { |
| 2045 | stack.push(path); |
| 2046 | } else if meta.is_file() { |
| 2047 | #[cfg(unix)] |
| 2048 | { |
| 2049 | use std::os::unix::fs::MetadataExt as _; |
| 2050 | if meta.nlink() != 1 { |
| 2051 | return Err("plugin bundles cannot contain hard links".to_string()); |
| 2052 | } |
| 2053 | } |
| 2054 | total_bytes = total_bytes.saturating_add(meta.len()); |
| 2055 | if total_bytes > max_bytes { |
| 2056 | return Err(format!( |
| 2057 | "plugin bundle exceeds the {} MiB size limit", |
| 2058 | max_bytes / (1024 * 1024) |
| 2059 | )); |
| 2060 | } |
| 2061 | } |
| 2062 | } |
| 2063 | } |
| 2064 | Ok(()) |
| 2065 | } |
| 2066 | |
| 2067 | fn check_symlink_ancestors_sync(path: &Path) -> Result<bool, std::io::Error> { |
| 2068 | let mut prefix = PathBuf::new(); |
| 2069 | for component in path.components() { |
| 2070 | prefix.push(component); |
| 2071 | if matches!( |
| 2072 | component, |
| 2073 | Component::Prefix(_) | Component::RootDir | Component::CurDir |
| 2074 | ) { |
| 2075 | continue; |
| 2076 | } |
| 2077 | if is_macos_system_root_link(&prefix) { |
| 2078 | continue; |
| 2079 | } |
| 2080 | let metadata = std::fs::symlink_metadata(&prefix)?; |
| 2081 | if metadata_is_link_or_reparse(&metadata) { |
| 2082 | return Ok(true); |
| 2083 | } |
| 2084 | } |
| 2085 | Ok(false) |
| 2086 | } |
| 2087 | |
| 2088 | fn read_dsh_source_package_sync(root: &Path) -> Option<String> { |
| 2089 | let pkg = root.join("package.json"); |
| 2090 | let meta = std::fs::symlink_metadata(&pkg).ok()?; |
| 2091 | if metadata_is_link_or_reparse(&meta) || !meta.is_file() { |
| 2092 | return None; |
| 2093 | } |
| 2094 | let file = codewhale_util::bundle_file::open_bundle_file(&pkg).ok()?; |
| 2095 | let mut raw = String::new(); |
| 2096 | file.take(1024 * 1024).read_to_string(&mut raw).ok()?; |
| 2097 | let json: Value = serde_json::from_str(&raw).ok()?; |
| 2098 | let name = json.get("name")?.as_str()?.trim(); |
| 2099 | if name.is_empty() { |
| 2100 | None |
| 2101 | } else { |
| 2102 | Some(name.to_string()) |
| 2103 | } |
| 2104 | } |
| 2105 | |
| 2106 | match job { |
| 2107 | BlockingPolicyJob::PlanChange { |
| 2108 | parsed, |
| 2109 | workspace, |
| 2110 | base_registry, |
| 2111 | can_prompt_outside_scope, |
| 2112 | allow_shell, |
| 2113 | policy, |
| 2114 | #[cfg(any(test, feature = "test-support"))] |
| 2115 | env_scope, |
| 2116 | #[cfg(any(test, feature = "test-support"))] |
| 2117 | test_offered, |
| 2118 | } => { |
| 2119 | #[cfg(any(test, feature = "test-support"))] |
| 2120 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 2121 | let _policy_scope = PolicyScope::propagate(policy); |
| 2122 | #[cfg(any(test, feature = "test-support"))] |
| 2123 | let _offer = TestOffer::only(&test_offered); |
| 2124 | let res = match parsed.action { |
| 2125 | CreatorAction::Install => plan_local_install_blocking( |
| 2126 | parsed, |
| 2127 | &workspace, |
| 2128 | &base_registry, |
| 2129 | can_prompt_outside_scope, |
| 2130 | allow_shell, |
| 2131 | ), |
| 2132 | CreatorAction::Remove | CreatorAction::Enable | CreatorAction::Disable => { |
| 2133 | plan_existing_blocking(parsed, &workspace, &base_registry, allow_shell) |
| 2134 | } |
| 2135 | }; |
| 2136 | BlockingPolicyResult::Plan(Box::new(res)) |
| 2137 | } |
| 2138 | BlockingPolicyJob::EnsureNoLinks { root } => BlockingPolicyResult::Unit( |
| 2139 | scan_no_links_bounded(&root, MAX_PREVIEW_TREE_BYTES, MAX_PREVIEW_TREE_ENTRIES), |
| 2140 | ), |
| 2141 | BlockingPolicyJob::CheckSymlinkAncestors { path } => { |
| 2142 | BlockingPolicyResult::BoolIo(check_symlink_ancestors_sync(&path)) |
| 2143 | } |
| 2144 | BlockingPolicyJob::DirInUserPlugins { |
| 2145 | dir, |
| 2146 | user_plugins_dir, |
| 2147 | } => { |
| 2148 | let inside = std::fs::canonicalize(&dir).ok().is_some_and(|canon_dir| { |
| 2149 | let canon_user = |
| 2150 | std::fs::canonicalize(&user_plugins_dir).unwrap_or(user_plugins_dir); |
| 2151 | path_is_within(&canon_user, &canon_dir, true) |
| 2152 | }); |
| 2153 | BlockingPolicyResult::Bool(inside) |
| 2154 | } |
| 2155 | } |
| 2156 | }) |
| 2157 | } |
| 2158 | |
| 2159 | fn scrub_path_error( |
| 2160 | raw: &str, |
| 2161 | workspace: &Path, |
| 2162 | canon_workspace: Option<&Path>, |
| 2163 | plugin_root: Option<&Path>, |
| 2164 | user_plugins_dir: Option<&Path>, |
| 2165 | state_path: Option<&Path>, |
| 2166 | ) -> String { |
| 2167 | let scrub = ScrubContext { |
| 2168 | workspace, |
| 2169 | canon_workspace, |
| 2170 | plugin_root, |
| 2171 | user_plugins_dir, |
| 2172 | state_path, |
| 2173 | }; |
| 2174 | scrub_message(raw, &scrub) |
| 2175 | } |
| 2176 | |
| 2177 | /// Build a [`HostServiceReview`] for an uninstalled bundle using the current discovered peer plugins. |
| 2178 | #[must_use] |
| 2179 | pub fn host_service_review_from_inventory( |
| 2180 | registry: &PluginRegistry, |
| 2181 | plugin_id: &str, |
| 2182 | plugin_name: &str, |
| 2183 | content_hash: &str, |
| 2184 | capability_hash: &str, |
| 2185 | inventory: &PluginInventory, |
| 2186 | cohort: &PluginCohort, |
| 2187 | ) -> HostServiceReview { |
| 2188 | let mut peers: Vec<&LoadedPlugin> = registry |
| 2189 | .list() |
| 2190 | .into_iter() |
| 2191 | .filter(|peer| peer.id.as_str() != plugin_id && peer.name() != plugin_name) |
| 2192 | .collect(); |
| 2193 | peers.sort_by(|left, right| left.id.cmp(&right.id)); |
| 2194 | |
| 2195 | let collect_peers = |holds: bool, service: HostService| -> Vec<ReviewPeer> { |
| 2196 | peers |
| 2197 | .iter() |
| 2198 | .filter(|peer| peer.trusted()) |
| 2199 | .filter(|peer| cohort_of(peer.approved_by.as_ref()) == *cohort) |
| 2200 | .filter(|peer| { |
| 2201 | if holds { |
| 2202 | peer.host_services.contains(&service) |
| 2203 | } else { |
| 2204 | peer.enabled |
| 2205 | && peer.inventory.native > 0 |
| 2206 | && !peer.host_services.contains(&service) |
| 2207 | } |
| 2208 | }) |
| 2209 | .map(|peer| ReviewPeer { |
| 2210 | id: peer.id.as_str().to_string(), |
| 2211 | name: peer.name().to_string(), |
| 2212 | }) |
| 2213 | .collect() |
| 2214 | }; |
| 2215 | |
| 2216 | let lines = inventory |
| 2217 | .host_services |
| 2218 | .iter() |
| 2219 | .map(|service| HostServiceLine { |
| 2220 | service: *service, |
| 2221 | offered: offered(*service), |
| 2222 | shared_with: collect_peers(true, *service), |
| 2223 | withheld_by: collect_peers(false, *service), |
| 2224 | }) |
| 2225 | .collect(); |
| 2226 | |
| 2227 | HostServiceReview::new(plugin_id, content_hash, capability_hash, cohort, lines) |
| 2228 | } |
| 2229 | |
| 2230 | /// Return true on macOS for system root symlinks `/var`, `/tmp`, `/etc`. |
| 2231 | #[must_use] |
| 2232 | pub(crate) fn is_macos_system_root_link(prefix: &Path) -> bool { |
| 2233 | cfg!(target_os = "macos") |
| 2234 | && (prefix == Path::new("/var") |
| 2235 | || prefix == Path::new("/tmp") |
| 2236 | || prefix == Path::new("/etc")) |
| 2237 | } |
| 2238 | |
| 2239 | /// Read the converted DSH source npm package name from `CONVERSION.json`, if present. |
| 2240 | pub(crate) fn read_dsh_source_package(root: &Path) -> Option<String> { |
| 2241 | let file = codewhale_util::bundle_file::open_bundle_file(&root.join("CONVERSION.json")).ok()?; |
| 2242 | let mut body = String::new(); |
| 2243 | file.take(64 * 1024 + 1).read_to_string(&mut body).ok()?; |
| 2244 | if body.len() > 64 * 1024 { |
| 2245 | return None; |
| 2246 | } |
| 2247 | let parsed: Value = serde_json::from_str(&body).ok()?; |
| 2248 | parsed |
| 2249 | .get("source") |
| 2250 | .and_then(|source| source.get("package")) |
| 2251 | .and_then(Value::as_str) |
| 2252 | .map(str::to_string) |
| 2253 | } |
| 2254 | |
| 2255 | /// Inspect tree links within bounds in a blocking worker. |
| 2256 | pub(crate) async fn ensure_no_links_in_tree(root: &Path) -> Result<(), String> { |
| 2257 | let root = root.to_path_buf(); |
| 2258 | match run_blocking_policy_job(BlockingPolicyJob::EnsureNoLinks { root }).await { |
| 2259 | Ok(BlockingPolicyResult::Unit(res)) => res, |
| 2260 | Ok(_) => Err("unexpected blocking job result".to_string()), |
| 2261 | Err(err) => Err(err), |
| 2262 | } |
| 2263 | } |
| 2264 | |
| 2265 | /// Check in a blocking worker whether any path component up to `path` is a symlink or reparse point. |
| 2266 | pub(crate) async fn has_symlink_or_reparse_ancestor_or_target( |
| 2267 | path: &Path, |
| 2268 | ) -> Result<bool, std::io::Error> { |
| 2269 | let path = path.to_path_buf(); |
| 2270 | match run_blocking_policy_job(BlockingPolicyJob::CheckSymlinkAncestors { path }).await { |
| 2271 | Ok(BlockingPolicyResult::BoolIo(res)) => res, |
| 2272 | Ok(_) => Err(std::io::Error::other("unexpected blocking job result")), |
| 2273 | Err(err) => Err(std::io::Error::other(err)), |
| 2274 | } |
| 2275 | } |
| 2276 | |
| 2277 | /// Check in a blocking worker whether `dir` lives inside `user_plugins_dir`. |
| 2278 | pub(crate) async fn dir_is_in_user_plugins(dir: &Path, user_plugins_dir: Option<&Path>) -> bool { |
| 2279 | let Some(user_plugins_dir) = user_plugins_dir.map(Path::to_path_buf) else { |
| 2280 | return false; |
| 2281 | }; |
| 2282 | let dir = dir.to_path_buf(); |
| 2283 | matches!( |
| 2284 | run_blocking_policy_job(BlockingPolicyJob::DirInUserPlugins { |
| 2285 | dir, |
| 2286 | user_plugins_dir, |
| 2287 | }) |
| 2288 | .await, |
| 2289 | Ok(BlockingPolicyResult::Bool(true)) |
| 2290 | ) |
| 2291 | } |
| 2292 | |
| 2293 | /// Return true for `http://127.0.0.1:<port>...` loopback specs during tests. |
| 2294 | #[must_use] |
| 2295 | pub(crate) fn is_test_loopback_http_url(spec: &str) -> bool { |
| 2296 | cfg!(any(test, feature = "test-support")) |
| 2297 | && spec.strip_prefix("http://127.0.0.1:").is_some_and(|rest| { |
| 2298 | rest.split('/') |
| 2299 | .next() |
| 2300 | .is_some_and(|port| !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit())) |
| 2301 | }) |
| 2302 | } |
| 2303 | |
| 2304 | /// Parse an install spec strictly from its string syntax without hitting the network or filesystem. |
| 2305 | pub(crate) fn parse_install_target_syntax( |
| 2306 | spec: &str, |
| 2307 | ) -> Result<PluginInstallSource, (&'static str, String)> { |
| 2308 | if spec.starts_with("http://") && !is_test_loopback_http_url(spec) { |
| 2309 | return Err(( |
| 2310 | "invalid-spec", |
| 2311 | "plugin archive URLs must use https://".to_string(), |
| 2312 | )); |
| 2313 | } |
| 2314 | let parsed = PluginInstallSource::parse_syntax(spec) |
| 2315 | .map_err(|error| ("invalid-spec", format!("invalid install spec: {error}")))?; |
| 2316 | match &parsed { |
| 2317 | PluginInstallSource::LocalPath(path) | PluginInstallSource::Dsh(path) => { |
| 2318 | if !path.is_absolute() { |
| 2319 | return Err(( |
| 2320 | "invalid-spec", |
| 2321 | "local or DSH install target must be an absolute directory path, or a valid npm/git/github/https spec".to_string(), |
| 2322 | )); |
| 2323 | } |
| 2324 | } |
| 2325 | PluginInstallSource::Remote(remote) => { |
| 2326 | if let codewhale_skill_install::install::InstallSource::DirectUrl(url) = remote |
| 2327 | && !url.starts_with("https://") |
| 2328 | && !is_test_loopback_http_url(url) |
| 2329 | { |
| 2330 | return Err(( |
| 2331 | "invalid-spec", |
| 2332 | "plugin archive URLs must use https://".to_string(), |
| 2333 | )); |
| 2334 | } |
| 2335 | } |
| 2336 | } |
| 2337 | Ok(parsed) |
| 2338 | } |
| 2339 | |
| 2340 | /// Extract display label and host name for a remote [`PluginInstallSource`]. |
| 2341 | #[must_use] |
| 2342 | pub(crate) fn remote_target_display(source: &PluginInstallSource, raw: &str) -> (String, String) { |
| 2343 | match source { |
| 2344 | PluginInstallSource::Remote(InstallSource::GitHubRepo(repo)) => { |
| 2345 | (repo.clone(), "github.com".to_string()) |
| 2346 | } |
| 2347 | PluginInstallSource::Remote(InstallSource::DirectUrl(url)) => { |
| 2348 | let host = reqwest::Url::parse(url) |
| 2349 | .ok() |
| 2350 | .and_then(|parsed| parsed.host_str().map(str::to_string)) |
| 2351 | .unwrap_or_else(|| "unknown-host".to_string()); |
| 2352 | (raw.to_string(), host) |
| 2353 | } |
| 2354 | _ => (raw.to_string(), "unknown-host".to_string()), |
| 2355 | } |
| 2356 | } |
| 2357 | |
| 2358 | /// Resolve an exact plugin id, plugin name, or converted DSH source package in `registry`. |
| 2359 | #[must_use] |
| 2360 | pub(crate) fn resolve_plugin_by_target<'a>( |
| 2361 | registry: &'a PluginRegistry, |
| 2362 | target: &str, |
| 2363 | ) -> TargetLookup<'a> { |
| 2364 | if let Some(plugin) = registry.get(target) { |
| 2365 | return TargetLookup::Found(plugin); |
| 2366 | } |
| 2367 | let matches: Vec<&LoadedPlugin> = registry |
| 2368 | .list() |
| 2369 | .into_iter() |
| 2370 | .filter(|plugin| { |
| 2371 | read_dsh_source_package(&plugin.canonical_root) |
| 2372 | .as_deref() |
| 2373 | .is_some_and(|pkg| pkg == target) |
| 2374 | }) |
| 2375 | .collect(); |
| 2376 | match matches.len() { |
| 2377 | 0 => TargetLookup::Missing, |
| 2378 | 1 => TargetLookup::Found(matches[0]), |
| 2379 | _ => { |
| 2380 | let names: Vec<_> = matches.iter().map(|plugin| plugin.name()).collect(); |
| 2381 | TargetLookup::Ambiguous { |
| 2382 | message: format!( |
| 2383 | "target `{target}` matches multiple installed plugins ({}); specify the plugin name or id", |
| 2384 | names.join(", ") |
| 2385 | ), |
| 2386 | first: matches[0], |
| 2387 | } |
| 2388 | } |
| 2389 | } |
| 2390 | } |
| 2391 | |
| 2392 | /// Return trimmed manifest version if non-empty. |
| 2393 | #[must_use] |
| 2394 | pub(crate) fn non_empty_version(raw: &str) -> Option<String> { |
| 2395 | let trimmed = raw.trim(); |
| 2396 | (!trimmed.is_empty()).then(|| trimmed.to_string()) |
| 2397 | } |
| 2398 | |
| 2399 | /// Wire string for [`PersonVia`]. |
| 2400 | #[must_use] |
| 2401 | pub(crate) const fn person_via_wire(via: PersonVia) -> &'static str { |
| 2402 | match via { |
| 2403 | PersonVia::Terminal => "terminal", |
| 2404 | PersonVia::App => "app", |
| 2405 | PersonVia::ApprovalCard => "approval_card", |
| 2406 | } |
| 2407 | } |
| 2408 | |
| 2409 | /// Wire string for [`AgentPosture`]. |
| 2410 | #[must_use] |
| 2411 | pub(crate) const fn agent_posture_wire(posture: AgentPosture) -> &'static str { |
| 2412 | match posture { |
| 2413 | AgentPosture::FullAccess => "full_access", |
| 2414 | AgentPosture::AutoReview => "auto_review", |
| 2415 | AgentPosture::CommandLine => "command_line", |
| 2416 | } |
| 2417 | } |
| 2418 | |
| 2419 | /// Remove or scrub `host`-private prefixes cleanly for model-visible diagnostics. |
| 2420 | pub(crate) fn scrub_message(raw: &str, scrub: &ScrubContext<'_>) -> String { |
| 2421 | let mut text = raw.to_string(); |
| 2422 | if let Some(root) = scrub.plugin_root { |
| 2423 | text = strip_path_prefix_clean(&text, root); |
| 2424 | } |
| 2425 | if let Some(user_dir) = scrub.user_plugins_dir { |
| 2426 | text = strip_path_with_replacement(&text, user_dir, "<plugins>"); |
| 2427 | } |
| 2428 | if let Some(state_path) = scrub.state_path { |
| 2429 | text = strip_path_with_replacement(&text, state_path, "plugin-state.json"); |
| 2430 | if let Some(parent) = state_path.parent() { |
| 2431 | text = strip_path_prefix_clean(&text, parent); |
| 2432 | } |
| 2433 | } |
| 2434 | text = strip_path_prefix_clean(&text, scrub.workspace); |
| 2435 | if let Some(canon_ws) = scrub.canon_workspace { |
| 2436 | text = strip_path_prefix_clean(&text, canon_ws); |
| 2437 | } |
| 2438 | text = scrub_outside_paths(&text); |
| 2439 | let cleaned = clean_diagnostic_fragment(&text); |
| 2440 | let mut truncated = false; |
| 2441 | cap_text(cleaned, MAX_DIAGNOSTIC_BYTES, &mut truncated) |
| 2442 | } |
| 2443 | |
| 2444 | /// Scrub and cap one plugin warning line. |
| 2445 | pub(crate) fn scrub_warning(raw: &str, scrub: &ScrubContext<'_>) -> String { |
| 2446 | let mut text = raw.to_string(); |
| 2447 | if let Some(root) = scrub.plugin_root { |
| 2448 | text = strip_path_prefix_clean(&text, root); |
| 2449 | } |
| 2450 | if let Some(user_dir) = scrub.user_plugins_dir { |
| 2451 | text = strip_path_with_replacement(&text, user_dir, "<plugins>"); |
| 2452 | } |
| 2453 | if let Some(state_path) = scrub.state_path { |
| 2454 | text = strip_path_with_replacement(&text, state_path, "plugin-state.json"); |
| 2455 | if let Some(parent) = state_path.parent() { |
| 2456 | text = strip_path_prefix_clean(&text, parent); |
| 2457 | } |
| 2458 | } |
| 2459 | text = strip_path_prefix_clean(&text, scrub.workspace); |
| 2460 | if let Some(canon_ws) = scrub.canon_workspace { |
| 2461 | text = strip_path_prefix_clean(&text, canon_ws); |
| 2462 | } |
| 2463 | let cleaned = clean_diagnostic_fragment(&text); |
| 2464 | let mut truncated = false; |
| 2465 | cap_text(cleaned, MAX_DIAGNOSTIC_BYTES, &mut truncated) |
| 2466 | } |
| 2467 | |
| 2468 | /// Strip ANSI, outside paths, control characters, bidi controls, and model-bound secret tokens from `raw`. |
| 2469 | #[must_use] |
| 2470 | pub(crate) fn clean_diagnostic_fragment(raw: &str) -> String { |
| 2471 | let mut no_ansi = String::with_capacity(raw.len()); |
| 2472 | strip_ansi_into(raw, &mut no_ansi); |
| 2473 | let paths_scrubbed = scrub_outside_paths(&no_ansi); |
| 2474 | let redacted = redact_model_bound_secrets(&sanitize_text(&paths_scrubbed)); |
| 2475 | collapse_controls(&redacted) |
| 2476 | } |
| 2477 | |
| 2478 | /// Clean and bound one inline display string. |
| 2479 | pub(crate) fn sanitize_inline(raw: &str, max_bytes: usize, truncated: &mut bool) -> String { |
| 2480 | let mut no_ansi = String::with_capacity(raw.len()); |
| 2481 | strip_ansi_into(raw, &mut no_ansi); |
| 2482 | let redacted = redact_model_bound_secrets(&sanitize_text(&no_ansi)); |
| 2483 | cap_text(collapse_controls(&redacted), max_bytes, truncated) |
| 2484 | } |
| 2485 | |
| 2486 | /// Collapse control, newline, and Unicode bidi-control runes into single spaces. |
| 2487 | #[must_use] |
| 2488 | pub(crate) fn collapse_controls(raw: &str) -> String { |
| 2489 | let mut out = String::with_capacity(raw.len()); |
| 2490 | let mut last_was_space = false; |
| 2491 | for ch in raw.chars() { |
| 2492 | if matches!(ch, '\r' | '\n' | '\t') { |
| 2493 | if !last_was_space { |
| 2494 | out.push(' '); |
| 2495 | last_was_space = true; |
| 2496 | } |
| 2497 | continue; |
| 2498 | } |
| 2499 | if ch.is_control() || is_bidi_control(ch) { |
| 2500 | continue; |
| 2501 | } |
| 2502 | last_was_space = ch == ' '; |
| 2503 | out.push(ch); |
| 2504 | } |
| 2505 | out.trim().to_string() |
| 2506 | } |
| 2507 | |
| 2508 | /// Truncate `cleaned` on a valid UTF-8 boundary to at most `max_bytes`. |
| 2509 | pub(crate) fn cap_text(mut cleaned: String, max_bytes: usize, truncated: &mut bool) -> String { |
| 2510 | if cleaned.len() <= max_bytes { |
| 2511 | return cleaned; |
| 2512 | } |
| 2513 | *truncated = true; |
| 2514 | const ELLIPSIS: char = '…'; |
| 2515 | let ellipsis_len = ELLIPSIS.len_utf8(); |
| 2516 | if max_bytes < ellipsis_len { |
| 2517 | return String::new(); |
| 2518 | } |
| 2519 | let mut cut = max_bytes - ellipsis_len; |
| 2520 | while cut > 0 && !cleaned.is_char_boundary(cut) { |
| 2521 | cut -= 1; |
| 2522 | } |
| 2523 | cleaned.truncate(cut); |
| 2524 | cleaned.push(ELLIPSIS); |
| 2525 | cleaned |
| 2526 | } |
| 2527 | |
| 2528 | pub(crate) fn strip_path_with_replacement(text: &str, target: &Path, replacement: &str) -> String { |
| 2529 | let raw = target.to_string_lossy(); |
| 2530 | if raw.is_empty() { |
| 2531 | return text.to_string(); |
| 2532 | } |
| 2533 | let mut out = text.replace(raw.as_ref(), replacement); |
| 2534 | if let Some(unprefixed) = raw.strip_prefix("/private/") { |
| 2535 | out = out.replace(&format!("/{unprefixed}"), replacement); |
| 2536 | } |
| 2537 | if let Some(unprefixed) = raw.strip_prefix(r"\\?\") { |
| 2538 | out = out.replace(unprefixed, replacement); |
| 2539 | } |
| 2540 | out |
| 2541 | } |
| 2542 | |
| 2543 | pub(crate) fn strip_path_prefix_clean(text: &str, root: &Path) -> String { |
| 2544 | let raw = root.to_string_lossy(); |
| 2545 | if raw.is_empty() { |
| 2546 | return text.to_string(); |
| 2547 | } |
| 2548 | let mut out = strip_single_root(text, raw.as_ref()); |
| 2549 | if let Some(unprefixed) = raw.strip_prefix("/private/") { |
| 2550 | out = strip_single_root(&out, &format!("/{unprefixed}")); |
| 2551 | } |
| 2552 | if let Some(unprefixed) = raw.strip_prefix(r"\\?\") { |
| 2553 | out = strip_single_root(&out, unprefixed); |
| 2554 | } |
| 2555 | out |
| 2556 | } |
| 2557 | |
| 2558 | fn strip_single_root(text: &str, root: &str) -> String { |
| 2559 | let trimmed = root.trim_end_matches(['/', '\\']); |
| 2560 | if trimmed.is_empty() { |
| 2561 | return text.to_string(); |
| 2562 | } |
| 2563 | let with_slash = format!("{trimmed}/"); |
| 2564 | let with_backslash = format!("{trimmed}\\"); |
| 2565 | text.replace(&with_slash, "") |
| 2566 | .replace(&with_backslash, "") |
| 2567 | .replace(trimmed, "<root>") |
| 2568 | } |
| 2569 | |
| 2570 | fn scrub_outside_paths(text: &str) -> String { |
| 2571 | static RE: OnceLock<Regex> = OnceLock::new(); |
| 2572 | let re = RE.get_or_init(|| { |
| 2573 | Regex::new( |
| 2574 | r#"(^|[\s(\['"=:<`{,|])((?:file://[^\s)\]'";,>`}|]+)|(?:/(?:etc|usr|var|tmp|home|Users|Volumes|private|opt|root|proc|sys|dev|mnt|media|srv|bin|sbin|lib|lib64|System|Library|Applications)(?:/[^\s)\]'";,>`}|]*)?)|(?:/[A-Za-z0-9._~@-]+/[^\s)\]'";,>`}|]*)|(?:[A-Za-z]:[/\\][^\s)\]'";,>`}|]*)|(?:\\\\[^\s)\]'";,>`}|]+))"#, |
| 2575 | ) |
| 2576 | .expect("outside-path regex") |
| 2577 | }); |
| 2578 | re.replace_all(text, "${1}<outside-path>").into_owned() |
| 2579 | } |
| 2580 | |
| 2581 | /// Also check if `plugin` has an explicit [`PluginApprover::Agent`] reason string for diagnostics. |
| 2582 | #[must_use] |
| 2583 | pub(crate) fn agent_denial_reason( |
| 2584 | plugin: &LoadedPlugin, |
| 2585 | state_error: Option<&str>, |
| 2586 | ) -> &'static str { |
| 2587 | if state_error.is_some() { |
| 2588 | return "this plugin has no valid review record"; |
| 2589 | } |
| 2590 | match plugin.approved_by.as_ref() { |
| 2591 | Some(PluginApprover::Person { .. }) => { |
| 2592 | "this plugin was approved by a person (ask the person: step to Ask, or use the Plugins page)" |
| 2593 | } |
| 2594 | Some(PluginApprover::CommandLine) => { |
| 2595 | "this plugin was approved from the command line (ask the person: step to Ask, or use the Plugins page)" |
| 2596 | } |
| 2597 | Some(PluginApprover::Agent(_)) => { |
| 2598 | "the agent can only change plugins it installed from this project (ask the person: step to Ask, or use the Plugins page)" |
| 2599 | } |
| 2600 | None => { |
| 2601 | "this plugin does not have an agent review record from this project (ask the person: step to Ask, or use the Plugins page)" |
| 2602 | } |
| 2603 | } |
| 2604 | } |
| 2605 |