| 1 | use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | use std::sync::Arc; |
| 4 | use std::time::Duration; |
| 5 | |
| 6 | use codewhale_config::AppMode; |
| 7 | use codewhale_execpolicy::ApprovalMode; |
| 8 | use codewhale_mcp::config::McpServerConfig; |
| 9 | use codewhale_net::network_policy::NetworkPolicy; |
| 10 | use codewhale_plugins::activation::{PolicyScope, extension_host_policy_enabled}; |
| 11 | use codewhale_plugins::agent_plugin::resolve_manifest_path; |
| 12 | use codewhale_plugins::host_services::{ |
| 13 | AgentPosture, HostServiceReview, PluginApprover, ReviewApproval, approver_label, offered, |
| 14 | }; |
| 15 | #[cfg(any(test, feature = "test-support"))] |
| 16 | use codewhale_plugins::host_services::{HostService, TestOffer}; |
| 17 | use codewhale_plugins::install::dsh::{has_unresolved_npm_dependencies, try_is_dsh_package}; |
| 18 | use codewhale_plugins::install::{ |
| 19 | DEFAULT_MAX_SIZE_BYTES, NpmDepsNetworkError, PluginArchiveMismatch, PluginContentMismatch, |
| 20 | PluginInstallError, PluginInstallSource, PluginNameConflict, RemoteDownloadOutcome, |
| 21 | RemotePreviewOutcome, clean_dir_is_strictly_inside, download_remote_install_archive, |
| 22 | has_regular_install_marker, installed_by_the_agent, preview_dsh, preview_dsh_with_network, |
| 23 | stage_downloaded_remote_install, |
| 24 | }; |
| 25 | use codewhale_plugins::manifest::PluginManifest; |
| 26 | use codewhale_plugins::mutation::{ |
| 27 | PluginMutationContext, PluginMutationOutcome, PluginMutationRequest, execute, |
| 28 | }; |
| 29 | use codewhale_plugins::registry::PluginRegistry; |
| 30 | use codewhale_plugins::types::{LoadedPlugin, PluginDiagnosticLevel, PluginScope}; |
| 31 | use codewhale_runtime::runtime_policy::approval_wire; |
| 32 | use codewhale_util::path_identity::metadata_is_link_or_reparse; |
| 33 | use serde::{Deserialize, Serialize}; |
| 34 | use serde_json::{Value, json}; |
| 35 | |
| 36 | use super::creator_policy::{ |
| 37 | AdmittedChangeKind, CreatorDecider, CreatorDecisionCarrier, ScrubContext, TargetLookup, |
| 38 | agent_denial_reason, agent_posture_wire, cap_text, dir_is_in_user_plugins, |
| 39 | ensure_no_links_in_tree, has_symlink_or_reparse_ancestor_or_target, non_empty_version, |
| 40 | parse_install_target_syntax, person_via_wire, remote_target_display, resolve_plugin_by_target, |
| 41 | scrub_message, scrub_warning, strip_path_prefix_clean, strip_path_with_replacement, |
| 42 | }; |
| 43 | pub(super) use super::creator_policy::{clean_diagnostic_fragment, sanitize_inline}; |
| 44 | use super::dsh_broker::{ |
| 45 | BrokerCall, BrokerEffect, BrokerFuture, BrokerMethods, BrokerRefusal, builtin_services, decode, |
| 46 | }; |
| 47 | use super::protocol::DshService; |
| 48 | use super::registry::OwnerState; |
| 49 | use crate::core::engine::LiveRuntimeAuthority; |
| 50 | use crate::mcp::{ |
| 51 | McpPool, McpServerConfigExt, format_mcp_error_for_display, qualified_plugin_server_name, |
| 52 | }; |
| 53 | use crate::tools::spec::ToolContext; |
| 54 | |
| 55 | const LOG: &str = "codewhale::dsh_plugins"; |
| 56 | const MAX_INPUT_FIELDS: usize = 32; |
| 57 | const MAX_ENTRIES: usize = 100; |
| 58 | const MAX_ROWS_PER_BUNDLE: usize = 64; |
| 59 | const MAX_NAME_BYTES: usize = 128; |
| 60 | const MAX_ENTRY_ID_BYTES: usize = 256; |
| 61 | const MAX_VERSION_BYTES: usize = 64; |
| 62 | const MAX_TEXT_BYTES: usize = 512; |
| 63 | const MAX_DIAGNOSTIC_BYTES: usize = 1024; |
| 64 | const MAX_TARGET_BYTES: usize = 4096; |
| 65 | const MAX_REGISTRY_BYTES: usize = 1024; |
| 66 | const MAX_ROW_BYTES: usize = 512; |
| 67 | const MAX_APPROVED_BUILDS: usize = 64; |
| 68 | const HOST_LOAD_TIMEOUT_PER_ROW: Duration = Duration::from_secs(5); |
| 69 | const HOST_POLL_INTERVAL: Duration = Duration::from_millis(20); |
| 70 | const MAX_HOST_WAIT: Duration = Duration::from_secs(60); |
| 71 | const MAX_TOOL_WARNINGS_PER_CONNECTOR: usize = 20; |
| 72 | const HOST_OFF_DIAGNOSTIC: &str = |
| 73 | "the plugin host is switched off in this process, so native plugin code did not start"; |
| 74 | const ASK_PERSON_HINT: &str = "ask the person: step to Ask, or use the Plugins page"; |
| 75 | |
| 76 | #[derive(Deserialize)] |
| 77 | #[serde(deny_unknown_fields)] |
| 78 | struct NoInput {} |
| 79 | |
| 80 | #[derive(Deserialize)] |
| 81 | #[serde(deny_unknown_fields)] |
| 82 | struct InstallInput { |
| 83 | target: String, |
| 84 | #[serde(default = "default_enabled")] |
| 85 | enabled: bool, |
| 86 | #[serde(default)] |
| 87 | approved_builds: Option<Vec<String>>, |
| 88 | #[serde(default)] |
| 89 | registry: Option<String>, |
| 90 | } |
| 91 | |
| 92 | fn default_enabled() -> bool { |
| 93 | true |
| 94 | } |
| 95 | |
| 96 | #[derive(Deserialize)] |
| 97 | #[serde(deny_unknown_fields)] |
| 98 | struct RemoveInput { |
| 99 | target: String, |
| 100 | } |
| 101 | |
| 102 | #[derive(Deserialize)] |
| 103 | #[serde(deny_unknown_fields)] |
| 104 | struct ToggleInput { |
| 105 | target: String, |
| 106 | #[serde(default)] |
| 107 | row: Option<String>, |
| 108 | } |
| 109 | |
| 110 | #[derive(Deserialize)] |
| 111 | #[serde(tag = "method", content = "input", deny_unknown_fields)] |
| 112 | enum PluginsMethod { |
| 113 | #[serde(rename = "list")] |
| 114 | List(NoInput), |
| 115 | #[serde(rename = "status")] |
| 116 | Status(NoInput), |
| 117 | #[serde(rename = "posture")] |
| 118 | Posture(NoInput), |
| 119 | #[serde(rename = "tools")] |
| 120 | Tools(NoInput), |
| 121 | #[serde(rename = "install")] |
| 122 | Install(InstallInput), |
| 123 | #[serde(rename = "remove")] |
| 124 | Remove(RemoveInput), |
| 125 | #[serde(rename = "enable")] |
| 126 | Enable(ToggleInput), |
| 127 | #[serde(rename = "disable")] |
| 128 | Disable(ToggleInput), |
| 129 | } |
| 130 | |
| 131 | impl BrokerMethods for PluginsMethod { |
| 132 | const NAMES: &'static [&'static str] = &[ |
| 133 | "list", "status", "posture", "tools", "install", "remove", "enable", "disable", |
| 134 | ]; |
| 135 | } |
| 136 | |
| 137 | pub(super) fn serve(call: BrokerCall) -> BrokerFuture { |
| 138 | Box::pin(async move { |
| 139 | if let Some(fields) = call.input.as_object() |
| 140 | && fields.len() > MAX_INPUT_FIELDS |
| 141 | && PluginsMethod::NAMES.contains(&call.method.as_str()) |
| 142 | { |
| 143 | return Err(BrokerRefusal::InvalidInput { |
| 144 | service: DshService::Plugins, |
| 145 | message: format!( |
| 146 | "a plugins {} input has at most {MAX_INPUT_FIELDS} fields", |
| 147 | call.method |
| 148 | ), |
| 149 | }); |
| 150 | } |
| 151 | let method = decode::<PluginsMethod>(&call)?; |
| 152 | if !builtin_services(&call.owner.plugin_id).contains(&DshService::Plugins) { |
| 153 | tracing::info!(target: LOG, plugin = %call.owner.plugin_id, "plugins refused: not the creator module"); |
| 154 | return Err(refused()); |
| 155 | } |
| 156 | let (tool, authority) = live(&call); |
| 157 | if tool.execution.owner_agent_id.is_some() || tool.execution.child_host.is_some() { |
| 158 | tracing::info!(target: LOG, "plugins refused: a sub-agent caller"); |
| 159 | return Err(refused()); |
| 160 | } |
| 161 | match method { |
| 162 | PluginsMethod::List(_) => { |
| 163 | call.context.act("list", BrokerEffect::Read, None).await?; |
| 164 | list(&call, &tool).await |
| 165 | } |
| 166 | PluginsMethod::Status(_) => { |
| 167 | call.context.act("status", BrokerEffect::Read, None).await?; |
| 168 | status(&call, &tool) |
| 169 | } |
| 170 | PluginsMethod::Posture(_) => { |
| 171 | call.context |
| 172 | .act("posture", BrokerEffect::Read, None) |
| 173 | .await?; |
| 174 | posture(&tool, authority) |
| 175 | } |
| 176 | PluginsMethod::Tools(_) => { |
| 177 | call.context.act("tools", BrokerEffect::Read, None).await?; |
| 178 | tools(&call, &tool) |
| 179 | } |
| 180 | PluginsMethod::Install(input) => install(&call, tool, authority, input).await, |
| 181 | PluginsMethod::Remove(input) => remove(&call, tool, authority, input).await, |
| 182 | PluginsMethod::Enable(input) => toggle(&call, tool, authority, input, true).await, |
| 183 | PluginsMethod::Disable(input) => toggle(&call, tool, authority, input, false).await, |
| 184 | } |
| 185 | }) |
| 186 | } |
| 187 | |
| 188 | #[derive(Serialize)] |
| 189 | struct ListResponse { |
| 190 | entries: Vec<BundleInfo>, |
| 191 | truncated: bool, |
| 192 | #[serde(skip_serializing_if = "Option::is_none")] |
| 193 | diagnostic: Option<String>, |
| 194 | } |
| 195 | |
| 196 | #[derive(Serialize)] |
| 197 | #[serde(rename_all = "camelCase")] |
| 198 | struct BundleInfo { |
| 199 | name: String, |
| 200 | #[serde(skip_serializing_if = "Option::is_none")] |
| 201 | version: Option<String>, |
| 202 | #[serde(skip_serializing_if = "Option::is_none")] |
| 203 | description: Option<String>, |
| 204 | enabled: bool, |
| 205 | installed: bool, |
| 206 | removable: bool, |
| 207 | #[serde(skip_serializing_if = "Option::is_none")] |
| 208 | read_only_reason: Option<&'static str>, |
| 209 | rows: Vec<BundleRowInfo>, |
| 210 | overrides: Vec<Value>, |
| 211 | official: bool, |
| 212 | optional: bool, |
| 213 | updatable: bool, |
| 214 | #[serde(skip_serializing_if = "Option::is_none")] |
| 215 | update: Option<&'static str>, |
| 216 | availability: &'static str, |
| 217 | codewhale: BundleCodewhaleInfo, |
| 218 | } |
| 219 | |
| 220 | #[derive(Serialize)] |
| 221 | #[serde(rename_all = "camelCase")] |
| 222 | struct BundleRowInfo { |
| 223 | row_id: String, |
| 224 | module_name: String, |
| 225 | entry_id: String, |
| 226 | } |
| 227 | |
| 228 | #[derive(Serialize)] |
| 229 | struct BundleCodewhaleInfo { |
| 230 | plugin: String, |
| 231 | scope: &'static str, |
| 232 | trust: &'static str, |
| 233 | state: &'static str, |
| 234 | active: bool, |
| 235 | approved_by: Option<ApproverView>, |
| 236 | enabled_by: Option<ApproverView>, |
| 237 | services: Vec<ServiceStateView>, |
| 238 | } |
| 239 | |
| 240 | #[derive(Serialize)] |
| 241 | struct ApproverView { |
| 242 | kind: &'static str, |
| 243 | #[serde(skip_serializing_if = "Option::is_none")] |
| 244 | via: Option<&'static str>, |
| 245 | #[serde(skip_serializing_if = "Option::is_none")] |
| 246 | posture: Option<&'static str>, |
| 247 | this_project: bool, |
| 248 | label: &'static str, |
| 249 | } |
| 250 | |
| 251 | #[derive(Serialize)] |
| 252 | struct ServiceStateView { |
| 253 | service: &'static str, |
| 254 | state: &'static str, |
| 255 | } |
| 256 | |
| 257 | #[derive(Serialize)] |
| 258 | struct StatusResponse { |
| 259 | entries: Vec<StatusRow>, |
| 260 | truncated: bool, |
| 261 | #[serde(skip_serializing_if = "Option::is_none")] |
| 262 | diagnostic: Option<String>, |
| 263 | } |
| 264 | |
| 265 | #[derive(Serialize)] |
| 266 | #[serde(rename_all = "camelCase")] |
| 267 | struct StatusRow { |
| 268 | entry_id: String, |
| 269 | module_name: String, |
| 270 | enabled: bool, |
| 271 | fiber_phase: Option<&'static str>, |
| 272 | #[serde(skip_serializing_if = "Option::is_none")] |
| 273 | diagnostic: Option<String>, |
| 274 | #[serde(skip_serializing_if = "Option::is_none")] |
| 275 | patch_id: Option<String>, |
| 276 | #[serde(skip_serializing_if = "Option::is_none")] |
| 277 | read_only_reason: Option<&'static str>, |
| 278 | } |
| 279 | |
| 280 | #[derive(Serialize)] |
| 281 | struct PostureResponse { |
| 282 | mode: &'static str, |
| 283 | permission_mode: &'static str, |
| 284 | admitted_by_person: bool, |
| 285 | } |
| 286 | |
| 287 | struct ComponentRow { |
| 288 | label: String, |
| 289 | is_native: bool, |
| 290 | } |
| 291 | |
| 292 | async fn list(call: &BrokerCall, tool: &ToolContext) -> Result<Value, BrokerRefusal> { |
| 293 | let registry = live_registry(call, tool)?; |
| 294 | let all_plugins = registry.list(); |
| 295 | let counts = name_counts(&all_plugins); |
| 296 | let mut truncated = all_plugins.len() > MAX_ENTRIES; |
| 297 | let has_state_error = registry.state_error().is_some(); |
| 298 | let diagnostic = registry |
| 299 | .state_error() |
| 300 | .map(|error| scrub_state_error(error, registry.state_path(), &mut truncated)); |
| 301 | |
| 302 | let mut entries = Vec::with_capacity(all_plugins.len().min(MAX_ENTRIES)); |
| 303 | for plugin in all_plugins.into_iter().take(MAX_ENTRIES) { |
| 304 | let prefix = id_prefix(plugin, &counts); |
| 305 | let plugin_name = sanitize_inline(plugin.name(), MAX_NAME_BYTES, &mut truncated); |
| 306 | let version = Some(sanitize_inline( |
| 307 | &plugin.manifest.plugin.version, |
| 308 | MAX_VERSION_BYTES, |
| 309 | &mut truncated, |
| 310 | )) |
| 311 | .filter(|value| !value.is_empty()); |
| 312 | let description = plugin |
| 313 | .manifest |
| 314 | .plugin |
| 315 | .description |
| 316 | .as_deref() |
| 317 | .map(|raw| sanitize_inline(raw, MAX_TEXT_BYTES, &mut truncated)) |
| 318 | .filter(|value| !value.is_empty()); |
| 319 | let all_rows = collect_component_rows(plugin, &mut truncated); |
| 320 | if all_rows.len() > MAX_ROWS_PER_BUNDLE { |
| 321 | truncated = true; |
| 322 | } |
| 323 | let rows = all_rows |
| 324 | .into_iter() |
| 325 | .take(MAX_ROWS_PER_BUNDLE) |
| 326 | .map(|row| { |
| 327 | let (row_id, module_name, entry_id) = |
| 328 | row_identities(prefix, &row.label, &mut truncated); |
| 329 | BundleRowInfo { |
| 330 | row_id, |
| 331 | module_name, |
| 332 | entry_id, |
| 333 | } |
| 334 | }) |
| 335 | .collect(); |
| 336 | |
| 337 | let removable = |
| 338 | plugin.scope == PluginScope::User && has_install_record(&plugin.canonical_root).await; |
| 339 | let read_only_reason = match plugin.scope { |
| 340 | PluginScope::Builtin => Some("management-required"), |
| 341 | PluginScope::User | PluginScope::Workspace => None, |
| 342 | }; |
| 343 | let availability = match plugin.scope { |
| 344 | PluginScope::Builtin => "installation", |
| 345 | PluginScope::User | PluginScope::Workspace => "profile", |
| 346 | }; |
| 347 | let enabled = !has_state_error && plugin.enabled; |
| 348 | let active = !has_state_error && plugin.active(); |
| 349 | let state = if has_state_error { |
| 350 | "disabled" |
| 351 | } else { |
| 352 | plugin.state_label() |
| 353 | }; |
| 354 | let approved_by = if has_state_error { |
| 355 | None |
| 356 | } else { |
| 357 | plugin |
| 358 | .approved_by |
| 359 | .as_ref() |
| 360 | .map(|approver| approver_view(approver, plugin.outside_reach)) |
| 361 | }; |
| 362 | let enabled_by = if has_state_error { |
| 363 | None |
| 364 | } else { |
| 365 | plugin |
| 366 | .enabled_by |
| 367 | .as_ref() |
| 368 | .map(|approver| approver_view(approver, plugin.outside_reach)) |
| 369 | }; |
| 370 | let services = if has_state_error { |
| 371 | Vec::new() |
| 372 | } else { |
| 373 | service_views(®istry, plugin) |
| 374 | }; |
| 375 | |
| 376 | entries.push(BundleInfo { |
| 377 | name: plugin_name.clone(), |
| 378 | version, |
| 379 | description, |
| 380 | enabled, |
| 381 | installed: true, |
| 382 | removable, |
| 383 | read_only_reason, |
| 384 | rows, |
| 385 | overrides: Vec::new(), |
| 386 | official: false, |
| 387 | optional: false, |
| 388 | updatable: false, |
| 389 | update: None, |
| 390 | availability, |
| 391 | codewhale: BundleCodewhaleInfo { |
| 392 | plugin: plugin_name, |
| 393 | scope: plugin.scope.as_str(), |
| 394 | trust: plugin.trust_status.as_str(), |
| 395 | state, |
| 396 | active, |
| 397 | approved_by, |
| 398 | enabled_by, |
| 399 | services, |
| 400 | }, |
| 401 | }); |
| 402 | } |
| 403 | |
| 404 | serde_json::to_value(ListResponse { |
| 405 | entries, |
| 406 | truncated, |
| 407 | diagnostic, |
| 408 | }) |
| 409 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins)) |
| 410 | } |
| 411 | |
| 412 | fn status(call: &BrokerCall, tool: &ToolContext) -> Result<Value, BrokerRefusal> { |
| 413 | let registry = live_registry(call, tool)?; |
| 414 | let all_plugins = registry.list(); |
| 415 | let counts = name_counts(&all_plugins); |
| 416 | let mut truncated = false; |
| 417 | let mut hit_entry_limit = false; |
| 418 | let has_state_error = registry.state_error().is_some(); |
| 419 | let top_diagnostic = registry |
| 420 | .state_error() |
| 421 | .map(|error| scrub_state_error(error, registry.state_path(), &mut truncated)); |
| 422 | let host_policy = extension_host_policy_enabled(); |
| 423 | |
| 424 | let mut entries = Vec::new(); |
| 425 | for plugin in all_plugins { |
| 426 | let prefix = id_prefix(plugin, &counts); |
| 427 | let rows = collect_component_rows(plugin, &mut truncated); |
| 428 | let row_count = rows.len(); |
| 429 | let enabled = !has_state_error && plugin.enabled; |
| 430 | let report = if host_policy && enabled && rows.iter().any(|row| row.is_native) { |
| 431 | super::owner_report(plugin.id.as_str()) |
| 432 | } else { |
| 433 | None |
| 434 | }; |
| 435 | let single_name = sanitize_inline(plugin.name(), MAX_NAME_BYTES, &mut truncated); |
| 436 | let plugin_diagnostics = collect_plugin_diagnostics(plugin); |
| 437 | |
| 438 | for row in rows { |
| 439 | if entries.len() >= MAX_ENTRIES { |
| 440 | hit_entry_limit = true; |
| 441 | break; |
| 442 | } |
| 443 | let (_, module_name, entry_id) = row_identities(prefix, &row.label, &mut truncated); |
| 444 | let fiber_phase = row_fiber_phase(&row, enabled, host_policy, report.as_ref()); |
| 445 | let diagnostic = row_diagnostic( |
| 446 | plugin, |
| 447 | &row, |
| 448 | enabled, |
| 449 | host_policy, |
| 450 | report.as_ref(), |
| 451 | &plugin_diagnostics, |
| 452 | &mut truncated, |
| 453 | ); |
| 454 | let (patch_id, read_only_reason) = match plugin.scope { |
| 455 | PluginScope::Builtin => (None, Some("management-required")), |
| 456 | PluginScope::User | PluginScope::Workspace => { |
| 457 | if row_count == 1 { |
| 458 | (Some(single_name.clone()), None) |
| 459 | } else { |
| 460 | (None, Some("unaddressable")) |
| 461 | } |
| 462 | } |
| 463 | }; |
| 464 | |
| 465 | entries.push(StatusRow { |
| 466 | entry_id, |
| 467 | module_name, |
| 468 | enabled, |
| 469 | fiber_phase, |
| 470 | diagnostic, |
| 471 | patch_id, |
| 472 | read_only_reason, |
| 473 | }); |
| 474 | } |
| 475 | if hit_entry_limit { |
| 476 | break; |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | truncated |= hit_entry_limit; |
| 481 | |
| 482 | serde_json::to_value(StatusResponse { |
| 483 | entries, |
| 484 | truncated, |
| 485 | diagnostic: top_diagnostic, |
| 486 | }) |
| 487 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins)) |
| 488 | } |
| 489 | |
| 490 | fn posture( |
| 491 | tool: &ToolContext, |
| 492 | authority: Option<LiveRuntimeAuthority>, |
| 493 | ) -> Result<Value, BrokerRefusal> { |
| 494 | let Some(authority) = authority else { |
| 495 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 496 | }; |
| 497 | let app_mode = authority.mode(); |
| 498 | let approval_mode = authority.approval_mode(); |
| 499 | let mode = crate::core::authority::sandbox_policy_for_turn( |
| 500 | app_mode, |
| 501 | approval_mode, |
| 502 | authority.configured_sandbox_mode(), |
| 503 | &tool.workspace, |
| 504 | crate::core::authority::SandboxNetworkAccess::Restricted, |
| 505 | ) |
| 506 | .config_value(); |
| 507 | let permission_mode = if app_mode == AppMode::Plan { |
| 508 | "plan" |
| 509 | } else if approval_mode == ApprovalMode::Never { |
| 510 | "never" |
| 511 | } else { |
| 512 | approval_wire(approval_mode) |
| 513 | }; |
| 514 | serde_json::to_value(PostureResponse { |
| 515 | mode, |
| 516 | permission_mode, |
| 517 | admitted_by_person: tool.execution.creator_decision.as_ref().map_or_else( |
| 518 | || tool.execution.human_decision.is_some(), |
| 519 | |carrier| carrier.decider == CreatorDecider::Person, |
| 520 | ), |
| 521 | }) |
| 522 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins)) |
| 523 | } |
| 524 | |
| 525 | #[derive(Serialize)] |
| 526 | struct ToolsResponse { |
| 527 | names: Vec<String>, |
| 528 | tools: Vec<String>, |
| 529 | } |
| 530 | |
| 531 | fn tools(call: &BrokerCall, tool: &ToolContext) -> Result<Value, BrokerRefusal> { |
| 532 | let names: Vec<String> = call |
| 533 | .context |
| 534 | .caller_tools() |
| 535 | .iter() |
| 536 | .filter(|name| !super::dsh_broker::is_gate_tool(name)) |
| 537 | .filter(|name| { |
| 538 | !tool |
| 539 | .disallowed_tools |
| 540 | .iter() |
| 541 | .any(|denied| denied.eq_ignore_ascii_case(name)) |
| 542 | }) |
| 543 | .cloned() |
| 544 | .collect(); |
| 545 | serde_json::to_value(ToolsResponse { |
| 546 | names: names.clone(), |
| 547 | tools: names, |
| 548 | }) |
| 549 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins)) |
| 550 | } |
| 551 | |
| 552 | fn live_registry( |
| 553 | call: &BrokerCall, |
| 554 | tool: &ToolContext, |
| 555 | ) -> Result<Arc<PluginRegistry>, BrokerRefusal> { |
| 556 | let Some(fallback) = tool.plugin_registry.as_ref() else { |
| 557 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 558 | }; |
| 559 | Ok(super::caller_view( |
| 560 | &tool.workspace, |
| 561 | Some(&call.session_id), |
| 562 | tool.execution.owner_agent_id.as_deref(), |
| 563 | ) |
| 564 | .unwrap_or_else(|| Arc::clone(fallback))) |
| 565 | } |
| 566 | |
| 567 | async fn has_install_record(canonical_root: &Path) -> bool { |
| 568 | let root = canonical_root.to_path_buf(); |
| 569 | tokio::task::spawn_blocking(move || has_regular_install_marker(&root)) |
| 570 | .await |
| 571 | .unwrap_or(false) |
| 572 | } |
| 573 | |
| 574 | fn name_counts<'a>(plugins: &[&'a LoadedPlugin]) -> HashMap<&'a str, usize> { |
| 575 | let mut counts = HashMap::with_capacity(plugins.len()); |
| 576 | for plugin in plugins { |
| 577 | *counts.entry(plugin.name()).or_insert(0) += 1; |
| 578 | } |
| 579 | counts |
| 580 | } |
| 581 | |
| 582 | fn id_prefix<'a>(plugin: &'a LoadedPlugin, counts: &HashMap<&str, usize>) -> &'a str { |
| 583 | if counts.get(plugin.name()).copied().unwrap_or(0) > 1 { |
| 584 | plugin.id.as_str() |
| 585 | } else { |
| 586 | plugin.name() |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | fn row_identities(prefix: &str, label: &str, truncated: &mut bool) -> (String, String, String) { |
| 591 | let row_id = sanitize_inline(label, MAX_ENTRY_ID_BYTES, truncated); |
| 592 | let combined = sanitize_inline(&format!("{prefix}/{label}"), MAX_ENTRY_ID_BYTES, truncated); |
| 593 | (row_id, combined.clone(), combined) |
| 594 | } |
| 595 | |
| 596 | fn approver_view(approver: &PluginApprover, outside_reach: bool) -> ApproverView { |
| 597 | let (via, posture, this_project) = match approver { |
| 598 | PluginApprover::Person { via } => (Some(person_via_wire(*via)), None, true), |
| 599 | PluginApprover::Agent(agent) => ( |
| 600 | None, |
| 601 | Some(agent_posture_wire(agent.posture)), |
| 602 | !outside_reach, |
| 603 | ), |
| 604 | PluginApprover::CommandLine => (None, None, true), |
| 605 | }; |
| 606 | ApproverView { |
| 607 | kind: approver.kind(), |
| 608 | via, |
| 609 | posture, |
| 610 | this_project, |
| 611 | label: approver_label(Some(approver)), |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | fn service_views(registry: &PluginRegistry, plugin: &LoadedPlugin) -> Vec<ServiceStateView> { |
| 616 | let Some(review) = registry.host_service_review(plugin.id.as_str()) else { |
| 617 | return Vec::new(); |
| 618 | }; |
| 619 | review |
| 620 | .lines |
| 621 | .into_iter() |
| 622 | .map(|line| { |
| 623 | let can_use = plugin.host_services.contains(&line.service) && offered(line.service); |
| 624 | ServiceStateView { |
| 625 | service: line.service.name(), |
| 626 | state: if can_use { |
| 627 | "can use" |
| 628 | } else { |
| 629 | "this version does not offer it" |
| 630 | }, |
| 631 | } |
| 632 | }) |
| 633 | .collect() |
| 634 | } |
| 635 | |
| 636 | fn collect_component_rows(plugin: &LoadedPlugin, truncated: &mut bool) -> Vec<ComponentRow> { |
| 637 | let mut rows = Vec::new(); |
| 638 | let mut seen = BTreeSet::new(); |
| 639 | let root = &plugin.canonical_root; |
| 640 | |
| 641 | let mut push = |label: String, is_native: bool| { |
| 642 | let cleaned = sanitize_inline(&label, MAX_NAME_BYTES, truncated); |
| 643 | if !cleaned.is_empty() && seen.insert(cleaned.clone()) { |
| 644 | rows.push(ComponentRow { |
| 645 | label: cleaned, |
| 646 | is_native, |
| 647 | }); |
| 648 | } |
| 649 | }; |
| 650 | |
| 651 | for (category, paths, is_native) in [ |
| 652 | ("native", &plugin.components.native, true), |
| 653 | ("skills", &plugin.components.skills, false), |
| 654 | ("commands", &plugin.components.commands, false), |
| 655 | ("agents", &plugin.components.agents, false), |
| 656 | ("hooks", &plugin.components.hooks, false), |
| 657 | ("lsp", &plugin.components.lsp, false), |
| 658 | ] { |
| 659 | let mut labels: Vec<String> = paths |
| 660 | .iter() |
| 661 | .map(|path| relative_component_label(category, root, path)) |
| 662 | .collect(); |
| 663 | labels.sort(); |
| 664 | for label in labels { |
| 665 | push(label, is_native); |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | if let Some(mcp_servers) = plugin.manifest.mcp_servers.as_ref() { |
| 670 | for name in mcp_servers.keys() { |
| 671 | push(format!("mcp/{name}"), false); |
| 672 | } |
| 673 | } |
| 674 | for name in plugin.manifest.providers.keys() { |
| 675 | push(format!("providers/{name}"), false); |
| 676 | } |
| 677 | |
| 678 | rows |
| 679 | } |
| 680 | |
| 681 | fn relative_component_label(category: &str, root: &Path, path: &Path) -> String { |
| 682 | let rel = path.strip_prefix(root).ok().and_then(|stripped| { |
| 683 | let parts: Vec<String> = stripped |
| 684 | .components() |
| 685 | .filter_map(|component| match component { |
| 686 | std::path::Component::Normal(part) => Some(part.to_string_lossy().into_owned()), |
| 687 | _ => None, |
| 688 | }) |
| 689 | .collect(); |
| 690 | (!parts.is_empty()).then(|| parts.join("/")) |
| 691 | }); |
| 692 | match rel { |
| 693 | Some(rel) if rel == category || rel.starts_with(&format!("{category}/")) => rel, |
| 694 | Some(rel) => format!("{category}/{rel}"), |
| 695 | None => { |
| 696 | let leaf = path |
| 697 | .file_name() |
| 698 | .map(|name| name.to_string_lossy().into_owned()) |
| 699 | .filter(|name| !name.is_empty()) |
| 700 | .unwrap_or_else(|| "component".to_string()); |
| 701 | format!("{category}/{leaf}") |
| 702 | } |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | fn row_fiber_phase( |
| 707 | row: &ComponentRow, |
| 708 | enabled: bool, |
| 709 | host_policy: bool, |
| 710 | report: Option<&super::OwnerReport>, |
| 711 | ) -> Option<&'static str> { |
| 712 | if !row.is_native || !enabled || !host_policy { |
| 713 | return None; |
| 714 | } |
| 715 | match report.and_then(|entry| entry.state.as_ref()) { |
| 716 | Some(OwnerState::Activating) => Some("loading"), |
| 717 | Some(OwnerState::Active) => Some("active"), |
| 718 | Some(OwnerState::Failed(_)) | Some(OwnerState::Faulted(_)) => Some("failed"), |
| 719 | Some(OwnerState::Revoked) | None => None, |
| 720 | } |
| 721 | } |
| 722 | |
| 723 | fn collect_plugin_diagnostics(plugin: &LoadedPlugin) -> Vec<String> { |
| 724 | plugin |
| 725 | .diagnostics |
| 726 | .iter() |
| 727 | .map(|diagnostic| { |
| 728 | let level = match diagnostic.level { |
| 729 | PluginDiagnosticLevel::Warning => "warning", |
| 730 | PluginDiagnosticLevel::Error => "error", |
| 731 | }; |
| 732 | let suffix = diagnostic |
| 733 | .path |
| 734 | .as_deref() |
| 735 | .map(|path| format!(" ({})", diagnostic_path(&plugin.canonical_root, path))) |
| 736 | .unwrap_or_default(); |
| 737 | format!( |
| 738 | "{level} [{}]: {}{suffix}", |
| 739 | diagnostic.code, diagnostic.message |
| 740 | ) |
| 741 | }) |
| 742 | .collect() |
| 743 | } |
| 744 | |
| 745 | fn strip_root_variants<'a>(path: &'a Path, root: &Path) -> Option<&'a Path> { |
| 746 | if let Ok(rel) = path.strip_prefix(root) { |
| 747 | return Some(rel); |
| 748 | } |
| 749 | let root_str = root.to_str()?; |
| 750 | for (prefix, replacement) in [ |
| 751 | ("/private/var/", "/var/"), |
| 752 | ("/private/tmp/", "/tmp/"), |
| 753 | ("/private/etc/", "/etc/"), |
| 754 | ] { |
| 755 | if let Some(rest) = root_str.strip_prefix(prefix) { |
| 756 | let alt = format!("{replacement}{rest}"); |
| 757 | if let Ok(rel) = path.strip_prefix(&alt) { |
| 758 | return Some(rel); |
| 759 | } |
| 760 | } |
| 761 | } |
| 762 | if let Some(unprefixed) = root_str.strip_prefix(r"\\?\") |
| 763 | && let Ok(rel) = path.strip_prefix(unprefixed) |
| 764 | { |
| 765 | return Some(rel); |
| 766 | } |
| 767 | None |
| 768 | } |
| 769 | |
| 770 | fn diagnostic_path(root: &Path, path: &Path) -> String { |
| 771 | if let Some(rel) = strip_root_variants(path, root) { |
| 772 | let mut parts = Vec::new(); |
| 773 | for component in rel.components() { |
| 774 | match component { |
| 775 | std::path::Component::Normal(part) => { |
| 776 | parts.push(part.to_string_lossy().into_owned()); |
| 777 | } |
| 778 | std::path::Component::CurDir => {} |
| 779 | std::path::Component::ParentDir |
| 780 | | std::path::Component::RootDir |
| 781 | | std::path::Component::Prefix(_) => return "<outside-path>".to_string(), |
| 782 | } |
| 783 | } |
| 784 | if !parts.is_empty() { |
| 785 | return parts.join("/"); |
| 786 | } |
| 787 | } |
| 788 | "<outside-path>".to_string() |
| 789 | } |
| 790 | |
| 791 | fn row_diagnostic( |
| 792 | plugin: &LoadedPlugin, |
| 793 | row: &ComponentRow, |
| 794 | enabled: bool, |
| 795 | host_policy: bool, |
| 796 | report: Option<&super::OwnerReport>, |
| 797 | plugin_diagnostics: &[String], |
| 798 | truncated: &mut bool, |
| 799 | ) -> Option<String> { |
| 800 | let mut parts = Vec::new(); |
| 801 | let mut push_unique = |raw: &str| { |
| 802 | let stripped = strip_plugin_root(raw, &plugin.canonical_root); |
| 803 | let cleaned = clean_diagnostic_fragment(&stripped); |
| 804 | if !cleaned.is_empty() && !parts.contains(&cleaned) { |
| 805 | parts.push(cleaned); |
| 806 | } |
| 807 | }; |
| 808 | |
| 809 | if row.is_native && enabled && !host_policy { |
| 810 | push_unique(HOST_OFF_DIAGNOSTIC); |
| 811 | } |
| 812 | if let (true, Some(report)) = (row.is_native, report) { |
| 813 | match report.state.as_ref() { |
| 814 | Some(OwnerState::Failed(reason)) | Some(OwnerState::Faulted(reason)) => { |
| 815 | push_unique(reason); |
| 816 | for line in &report.diagnostics { |
| 817 | push_unique(line); |
| 818 | } |
| 819 | } |
| 820 | None => { |
| 821 | for line in &report.diagnostics { |
| 822 | push_unique(line); |
| 823 | } |
| 824 | } |
| 825 | Some(OwnerState::Activating | OwnerState::Active | OwnerState::Revoked) => {} |
| 826 | } |
| 827 | } |
| 828 | for line in plugin_diagnostics { |
| 829 | push_unique(line); |
| 830 | } |
| 831 | |
| 832 | if parts.is_empty() { |
| 833 | return None; |
| 834 | } |
| 835 | Some(cap_text(parts.join("; "), MAX_DIAGNOSTIC_BYTES, truncated)) |
| 836 | } |
| 837 | |
| 838 | fn scrub_state_error(error: &str, state_path: Option<&Path>, truncated: &mut bool) -> String { |
| 839 | let mut text = error.to_string(); |
| 840 | if let Some(path) = state_path { |
| 841 | let name = path |
| 842 | .file_name() |
| 843 | .map(|leaf| leaf.to_string_lossy().into_owned()) |
| 844 | .filter(|leaf| !leaf.is_empty()) |
| 845 | .unwrap_or_else(|| "plugin-state.json".to_string()); |
| 846 | text = strip_path_with_replacement(&text, path, &name); |
| 847 | if let Some(parent) = path.parent() { |
| 848 | text = strip_path_prefix_clean(&text, parent); |
| 849 | } |
| 850 | } |
| 851 | let cleaned = clean_diagnostic_fragment(&text); |
| 852 | cap_text(cleaned, MAX_DIAGNOSTIC_BYTES, truncated) |
| 853 | } |
| 854 | |
| 855 | fn strip_plugin_root(text: &str, root: &Path) -> String { |
| 856 | strip_path_prefix_clean(text, root) |
| 857 | } |
| 858 | |
| 859 | #[derive(Serialize)] |
| 860 | #[serde(rename_all = "camelCase")] |
| 861 | struct ChangeResult { |
| 862 | changed: bool, |
| 863 | application: &'static str, |
| 864 | stage: &'static str, |
| 865 | target: String, |
| 866 | #[serde(skip_serializing_if = "Option::is_none")] |
| 867 | enabled: Option<bool>, |
| 868 | #[serde(skip_serializing_if = "Option::is_none")] |
| 869 | error: Option<ManagementErrorWire>, |
| 870 | #[serde(skip_serializing_if = "Vec::is_empty")] |
| 871 | warnings: Vec<String>, |
| 872 | #[serde(skip_serializing_if = "Option::is_none")] |
| 873 | bundle: Option<String>, |
| 874 | #[serde(skip_serializing_if = "Option::is_none")] |
| 875 | version: Option<String>, |
| 876 | } |
| 877 | |
| 878 | #[derive(Serialize)] |
| 879 | struct ManagementErrorWire { |
| 880 | code: &'static str, |
| 881 | diagnostic: String, |
| 882 | message: String, |
| 883 | } |
| 884 | |
| 885 | enum PreparedExisting { |
| 886 | Found { |
| 887 | plugin: Box<LoadedPlugin>, |
| 888 | is_own: bool, |
| 889 | own_denial_reason: Option<&'static str>, |
| 890 | has_marker: bool, |
| 891 | canon_workspace: Option<PathBuf>, |
| 892 | }, |
| 893 | Missing, |
| 894 | Unremovable(String), |
| 895 | NotSoleRow(String), |
| 896 | Ambiguous(String), |
| 897 | } |
| 898 | |
| 899 | #[cfg(test)] |
| 900 | type PostInstallTestHook = Box<dyn FnOnce(&Path, &tokio_util::sync::CancellationToken) + Send>; |
| 901 | |
| 902 | #[cfg(test)] |
| 903 | type PostDisableTestHook = Box<dyn FnOnce(&LoadedPlugin) + Send>; |
| 904 | |
| 905 | #[cfg(test)] |
| 906 | type PreConnectTestHook = Box<dyn FnOnce() + Send>; |
| 907 | |
| 908 | #[cfg(test)] |
| 909 | thread_local! { |
| 910 | static POST_INSTALL_TEST_HOOK: std::cell::RefCell<Option<PostInstallTestHook>> = |
| 911 | const { std::cell::RefCell::new(None) }; |
| 912 | static POST_DISABLE_TEST_HOOK: std::cell::RefCell<Option<PostDisableTestHook>> = |
| 913 | const { std::cell::RefCell::new(None) }; |
| 914 | static PRE_CONNECT_TEST_HOOK: std::cell::RefCell<Option<PreConnectTestHook>> = |
| 915 | const { std::cell::RefCell::new(None) }; |
| 916 | static MCP_CONNECT_DEADLINE_FOR_TEST: std::cell::Cell<Option<Duration>> = |
| 917 | const { std::cell::Cell::new(None) }; |
| 918 | } |
| 919 | |
| 920 | #[cfg(test)] |
| 921 | pub(super) struct McpConnectDeadlineGuard { |
| 922 | previous: Option<Duration>, |
| 923 | } |
| 924 | |
| 925 | #[cfg(test)] |
| 926 | impl Drop for McpConnectDeadlineGuard { |
| 927 | fn drop(&mut self) { |
| 928 | MCP_CONNECT_DEADLINE_FOR_TEST.with(|cell| { |
| 929 | cell.set(self.previous); |
| 930 | }); |
| 931 | } |
| 932 | } |
| 933 | |
| 934 | #[cfg(test)] |
| 935 | pub(super) fn set_mcp_connect_deadline_for_test(deadline: Duration) -> McpConnectDeadlineGuard { |
| 936 | let previous = MCP_CONNECT_DEADLINE_FOR_TEST.with(|cell| cell.replace(Some(deadline))); |
| 937 | McpConnectDeadlineGuard { previous } |
| 938 | } |
| 939 | |
| 940 | fn mcp_connect_deadline() -> Duration { |
| 941 | #[cfg(test)] |
| 942 | if let Some(override_deadline) = MCP_CONNECT_DEADLINE_FOR_TEST.with(|cell| cell.get()) { |
| 943 | return override_deadline; |
| 944 | } |
| 945 | super::tool::TOOL_CALL_DEADLINE |
| 946 | } |
| 947 | |
| 948 | #[cfg(test)] |
| 949 | pub(super) fn set_post_install_hook_for_test(hook: PostInstallTestHook) { |
| 950 | POST_INSTALL_TEST_HOOK.with(|cell| { |
| 951 | *cell.borrow_mut() = Some(hook); |
| 952 | }); |
| 953 | } |
| 954 | |
| 955 | #[cfg(test)] |
| 956 | pub(super) fn set_post_disable_hook_for_test(hook: PostDisableTestHook) { |
| 957 | POST_DISABLE_TEST_HOOK.with(|cell| { |
| 958 | *cell.borrow_mut() = Some(hook); |
| 959 | }); |
| 960 | } |
| 961 | |
| 962 | #[cfg(test)] |
| 963 | fn fire_post_install_hook_for_test( |
| 964 | installed_dir: &Path, |
| 965 | cancel: &tokio_util::sync::CancellationToken, |
| 966 | ) { |
| 967 | if let Some(hook) = POST_INSTALL_TEST_HOOK.with(|cell| cell.borrow_mut().take()) { |
| 968 | hook(installed_dir, cancel); |
| 969 | } |
| 970 | } |
| 971 | |
| 972 | #[cfg(test)] |
| 973 | fn fire_post_disable_hook_for_test(plugin: &LoadedPlugin) { |
| 974 | if let Some(hook) = POST_DISABLE_TEST_HOOK.with(|cell| cell.borrow_mut().take()) { |
| 975 | hook(plugin); |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | #[cfg(test)] |
| 980 | pub(super) fn set_pre_connect_hook_for_test(hook: PreConnectTestHook) { |
| 981 | PRE_CONNECT_TEST_HOOK.with(|cell| { |
| 982 | *cell.borrow_mut() = Some(hook); |
| 983 | }); |
| 984 | } |
| 985 | |
| 986 | #[cfg(test)] |
| 987 | fn fire_pre_connect_hook_for_test() { |
| 988 | if let Some(hook) = PRE_CONNECT_TEST_HOOK.with(|cell| cell.borrow_mut().take()) { |
| 989 | hook(); |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | fn validate_required_str( |
| 994 | value: &str, |
| 995 | field: &str, |
| 996 | max_bytes: usize, |
| 997 | ) -> Result<String, BrokerRefusal> { |
| 998 | if value.contains('\0') { |
| 999 | return Err(BrokerRefusal::InvalidInput { |
| 1000 | service: DshService::Plugins, |
| 1001 | message: format!("plugin {field} must not contain NUL bytes"), |
| 1002 | }); |
| 1003 | } |
| 1004 | let trimmed = value.trim(); |
| 1005 | if trimmed.is_empty() { |
| 1006 | return Err(BrokerRefusal::InvalidInput { |
| 1007 | service: DshService::Plugins, |
| 1008 | message: format!("plugin {field} must not be empty"), |
| 1009 | }); |
| 1010 | } |
| 1011 | if trimmed.len() > max_bytes || value.len() > max_bytes { |
| 1012 | return Err(BrokerRefusal::InvalidInput { |
| 1013 | service: DshService::Plugins, |
| 1014 | message: format!("plugin {field} exceeds maximum length of {max_bytes} bytes"), |
| 1015 | }); |
| 1016 | } |
| 1017 | Ok(trimmed.to_string()) |
| 1018 | } |
| 1019 | |
| 1020 | fn validate_optional_str( |
| 1021 | value: Option<&str>, |
| 1022 | field: &str, |
| 1023 | max_bytes: usize, |
| 1024 | ) -> Result<Option<String>, BrokerRefusal> { |
| 1025 | value |
| 1026 | .map(|raw| validate_required_str(raw, field, max_bytes)) |
| 1027 | .transpose() |
| 1028 | } |
| 1029 | |
| 1030 | fn validate_approved_builds(builds: Option<&[String]>) -> Result<bool, BrokerRefusal> { |
| 1031 | let Some(list) = builds else { |
| 1032 | return Ok(false); |
| 1033 | }; |
| 1034 | if list.len() > MAX_APPROVED_BUILDS { |
| 1035 | return Err(BrokerRefusal::InvalidInput { |
| 1036 | service: DshService::Plugins, |
| 1037 | message: format!("approved_builds has at most {MAX_APPROVED_BUILDS} entries"), |
| 1038 | }); |
| 1039 | } |
| 1040 | for entry in list { |
| 1041 | validate_required_str(entry, "approved_builds entry", MAX_TEXT_BYTES)?; |
| 1042 | } |
| 1043 | Ok(true) |
| 1044 | } |
| 1045 | |
| 1046 | fn require_carried_decision( |
| 1047 | tool: &ToolContext, |
| 1048 | current_authority: &LiveRuntimeAuthority, |
| 1049 | method: &str, |
| 1050 | ) -> Result<CreatorDecisionCarrier, BrokerRefusal> { |
| 1051 | if current_authority.mode() == AppMode::Plan |
| 1052 | || current_authority.approval_mode() == ApprovalMode::Never |
| 1053 | { |
| 1054 | return Err(BrokerRefusal::Refused { |
| 1055 | service: DshService::Plugins, |
| 1056 | message: "cannot change plugins in this mode".to_string(), |
| 1057 | }); |
| 1058 | } |
| 1059 | let Some(carrier) = tool.execution.creator_decision.clone() else { |
| 1060 | return Err(BrokerRefusal::Refused { |
| 1061 | service: DshService::Plugins, |
| 1062 | message: "plugin changes require an admitted engine decision".to_string(), |
| 1063 | }); |
| 1064 | }; |
| 1065 | if current_authority.narrows(&carrier.admitted_authority) { |
| 1066 | return Err(BrokerRefusal::Refused { |
| 1067 | service: DshService::Plugins, |
| 1068 | message: "cannot continue after session permissions were narrowed".to_string(), |
| 1069 | }); |
| 1070 | } |
| 1071 | if matches!(carrier.decider, CreatorDecider::Agent(_)) |
| 1072 | && (!carrier.in_agent_scope || carrier.is_unseen_fetch()) |
| 1073 | { |
| 1074 | return Err(BrokerRefusal::Refused { |
| 1075 | service: DshService::Plugins, |
| 1076 | message: "agent decision cannot authorize an outside-scope plugin change".to_string(), |
| 1077 | }); |
| 1078 | } |
| 1079 | let expected_method = match &carrier.change { |
| 1080 | AdmittedChangeKind::LocalInstall { .. } | AdmittedChangeKind::UnseenFetchInstall { .. } => { |
| 1081 | "install" |
| 1082 | } |
| 1083 | AdmittedChangeKind::Remove { .. } => "remove", |
| 1084 | AdmittedChangeKind::Toggle { enabled: true, .. } => "enable", |
| 1085 | AdmittedChangeKind::Toggle { enabled: false, .. } => "disable", |
| 1086 | }; |
| 1087 | if method != expected_method { |
| 1088 | return Err(BrokerRefusal::Refused { |
| 1089 | service: DshService::Plugins, |
| 1090 | message: "plugin change decision does not match the requested method".to_string(), |
| 1091 | }); |
| 1092 | } |
| 1093 | Ok(carrier) |
| 1094 | } |
| 1095 | |
| 1096 | fn call_thread_id(call: &BrokerCall, tool: &ToolContext) -> String { |
| 1097 | tool.execution |
| 1098 | .runtime |
| 1099 | .active_thread_id |
| 1100 | .clone() |
| 1101 | .filter(|id| !id.is_empty()) |
| 1102 | .unwrap_or_else(|| call.session_id.clone()) |
| 1103 | } |
| 1104 | |
| 1105 | fn approver_from_carrier( |
| 1106 | call: &BrokerCall, |
| 1107 | tool: &ToolContext, |
| 1108 | carrier: &CreatorDecisionCarrier, |
| 1109 | canon_workspace: &Path, |
| 1110 | ) -> Result<PluginApprover, String> { |
| 1111 | carrier.trust_approver( |
| 1112 | canon_workspace, |
| 1113 | call_thread_id(call, tool), |
| 1114 | tool.origin_turn_id.clone(), |
| 1115 | tool.origin_tool_call_id.clone(), |
| 1116 | ) |
| 1117 | } |
| 1118 | |
| 1119 | enum CarrierLiveCheck { |
| 1120 | Valid(ToolContext), |
| 1121 | Narrowed, |
| 1122 | Unavailable, |
| 1123 | } |
| 1124 | |
| 1125 | fn check_live_after_act(call: &BrokerCall, carrier: &CreatorDecisionCarrier) -> CarrierLiveCheck { |
| 1126 | let (tool, refreshed) = live(call); |
| 1127 | let Some(refreshed) = refreshed else { |
| 1128 | return CarrierLiveCheck::Unavailable; |
| 1129 | }; |
| 1130 | if refreshed.mode() == AppMode::Plan |
| 1131 | || refreshed.approval_mode() == ApprovalMode::Never |
| 1132 | || refreshed.narrows(&carrier.admitted_authority) |
| 1133 | { |
| 1134 | return CarrierLiveCheck::Narrowed; |
| 1135 | } |
| 1136 | CarrierLiveCheck::Valid(tool) |
| 1137 | } |
| 1138 | |
| 1139 | fn has_agent_call_identity(call: &BrokerCall, tool: &ToolContext) -> bool { |
| 1140 | (!tool |
| 1141 | .execution |
| 1142 | .runtime |
| 1143 | .active_thread_id |
| 1144 | .as_deref() |
| 1145 | .is_none_or(str::is_empty) |
| 1146 | || !call.session_id.is_empty()) |
| 1147 | && tool |
| 1148 | .origin_turn_id |
| 1149 | .as_deref() |
| 1150 | .is_some_and(|id| !id.is_empty()) |
| 1151 | && tool |
| 1152 | .origin_tool_call_id |
| 1153 | .as_deref() |
| 1154 | .is_some_and(|id| !id.is_empty()) |
| 1155 | } |
| 1156 | |
| 1157 | fn network_policy_for(tool: &ToolContext) -> NetworkPolicy { |
| 1158 | tool.network_policy |
| 1159 | .as_ref() |
| 1160 | .map(|decider| decider.policy().clone()) |
| 1161 | .unwrap_or_default() |
| 1162 | } |
| 1163 | |
| 1164 | fn classify_install_error(error: &anyhow::Error) -> &'static str { |
| 1165 | if error.downcast_ref::<PluginNameConflict>().is_some() |
| 1166 | || error |
| 1167 | .downcast_ref::<PluginInstallError>() |
| 1168 | .is_some_and(|kind| matches!(kind, PluginInstallError::AlreadyInstalled(_))) |
| 1169 | { |
| 1170 | return "already-installed"; |
| 1171 | } |
| 1172 | if error |
| 1173 | .downcast_ref::<PluginInstallError>() |
| 1174 | .is_some_and(|kind| matches!(kind, PluginInstallError::NotInstalledHere(_))) |
| 1175 | { |
| 1176 | return "not-removable"; |
| 1177 | } |
| 1178 | if error |
| 1179 | .downcast_ref::<PluginInstallError>() |
| 1180 | .is_some_and(|kind| matches!(kind, PluginInstallError::PluginTomlRoots(_))) |
| 1181 | { |
| 1182 | return "not-bundle"; |
| 1183 | } |
| 1184 | let message = format!("{error:#}"); |
| 1185 | classify_error_message(&message) |
| 1186 | } |
| 1187 | |
| 1188 | fn classify_error_message(message: &str) -> &'static str { |
| 1189 | if message.contains("incompatible-version") { |
| 1190 | "incompatible-version" |
| 1191 | } else if message.contains("unsupported-platform") { |
| 1192 | "unsupported-platform" |
| 1193 | } else if message.contains("not-bundle:") |
| 1194 | || message.contains("no plugin.json") |
| 1195 | || message.contains("not a valid plugin bundle") |
| 1196 | || message.contains("not a DSH bundle") |
| 1197 | || message.contains("does not declare `dsh.bundle`") |
| 1198 | || message.contains("does not declare dsh.bundle") |
| 1199 | || message.contains("package.json") && message.contains("no such file") |
| 1200 | { |
| 1201 | "not-bundle" |
| 1202 | } else { |
| 1203 | "operation-error" |
| 1204 | } |
| 1205 | } |
| 1206 | |
| 1207 | fn change_ok( |
| 1208 | stage: &'static str, |
| 1209 | target: String, |
| 1210 | changed: bool, |
| 1211 | enabled: Option<bool>, |
| 1212 | bundle: Option<String>, |
| 1213 | version: Option<String>, |
| 1214 | warnings: Vec<String>, |
| 1215 | ) -> Result<Value, BrokerRefusal> { |
| 1216 | serde_json::to_value(ChangeResult { |
| 1217 | changed, |
| 1218 | application: "applied", |
| 1219 | stage, |
| 1220 | target, |
| 1221 | enabled, |
| 1222 | error: None, |
| 1223 | warnings, |
| 1224 | bundle, |
| 1225 | version, |
| 1226 | }) |
| 1227 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins)) |
| 1228 | } |
| 1229 | |
| 1230 | struct ChangeOutcome { |
| 1231 | application: &'static str, |
| 1232 | stage: &'static str, |
| 1233 | target: String, |
| 1234 | changed: bool, |
| 1235 | enabled: Option<bool>, |
| 1236 | code: &'static str, |
| 1237 | diagnostic: String, |
| 1238 | bundle: Option<String>, |
| 1239 | version: Option<String>, |
| 1240 | warnings: Vec<String>, |
| 1241 | } |
| 1242 | |
| 1243 | fn change_with_outcome(outcome: ChangeOutcome) -> Result<Value, BrokerRefusal> { |
| 1244 | let error = Some(ManagementErrorWire { |
| 1245 | code: outcome.code, |
| 1246 | diagnostic: outcome.diagnostic.clone(), |
| 1247 | message: outcome.diagnostic, |
| 1248 | }); |
| 1249 | serde_json::to_value(ChangeResult { |
| 1250 | changed: outcome.changed, |
| 1251 | application: outcome.application, |
| 1252 | stage: outcome.stage, |
| 1253 | target: outcome.target, |
| 1254 | enabled: outcome.enabled, |
| 1255 | error, |
| 1256 | warnings: outcome.warnings, |
| 1257 | bundle: outcome.bundle, |
| 1258 | version: outcome.version, |
| 1259 | }) |
| 1260 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins)) |
| 1261 | } |
| 1262 | |
| 1263 | fn cancelled_result( |
| 1264 | stage: &'static str, |
| 1265 | target: String, |
| 1266 | bundle: Option<String>, |
| 1267 | version: Option<String>, |
| 1268 | warnings: Vec<String>, |
| 1269 | ) -> Result<Value, BrokerRefusal> { |
| 1270 | serde_json::to_value(ChangeResult { |
| 1271 | changed: false, |
| 1272 | application: "cancelled", |
| 1273 | stage, |
| 1274 | target, |
| 1275 | enabled: None, |
| 1276 | error: None, |
| 1277 | warnings, |
| 1278 | bundle, |
| 1279 | version, |
| 1280 | }) |
| 1281 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins)) |
| 1282 | } |
| 1283 | |
| 1284 | fn record_outcome( |
| 1285 | call: &BrokerCall, |
| 1286 | method: &str, |
| 1287 | plugin: Option<&str>, |
| 1288 | hash: Option<&str>, |
| 1289 | approver: Option<&PluginApprover>, |
| 1290 | application: &str, |
| 1291 | ) { |
| 1292 | let (approver_kind, posture) = match approver { |
| 1293 | Some(PluginApprover::Person { via }) => ("person", Some(person_via_wire(*via))), |
| 1294 | Some(PluginApprover::Agent(agent)) => ("agent", Some(agent_posture_wire(agent.posture))), |
| 1295 | Some(PluginApprover::CommandLine) => ("command_line", None), |
| 1296 | None => ("none", None), |
| 1297 | }; |
| 1298 | let mut entry = json!({ |
| 1299 | "method": method, |
| 1300 | "plugin": plugin.unwrap_or(""), |
| 1301 | "hash": hash.unwrap_or(""), |
| 1302 | "approver": approver_kind, |
| 1303 | "application": application, |
| 1304 | }); |
| 1305 | if let Some(posture) = posture { |
| 1306 | entry["posture"] = json!(posture); |
| 1307 | } |
| 1308 | let _ = call.context.record(entry); |
| 1309 | } |
| 1310 | |
| 1311 | fn is_managed_policy_error(msg: &str) -> bool { |
| 1312 | msg.contains("Managed plugin policy") || msg.contains("forbidden by the managed plugin policy") |
| 1313 | } |
| 1314 | |
| 1315 | fn map_enable_failure_diagnostic( |
| 1316 | err: &str, |
| 1317 | has_native: bool, |
| 1318 | host_policy_enabled: bool, |
| 1319 | scrub: &ScrubContext<'_>, |
| 1320 | ) -> String { |
| 1321 | if !host_policy_enabled |
| 1322 | && has_native |
| 1323 | && err.contains("has no supported declarative components to activate") |
| 1324 | && let Some((_, labels)) = err.rsplit_once("; inactive: ") |
| 1325 | { |
| 1326 | if labels.trim() == "native" { |
| 1327 | return HOST_OFF_DIAGNOSTIC.to_string(); |
| 1328 | } |
| 1329 | if labels.split(',').any(|label| label.trim() == "native") { |
| 1330 | return format!("{HOST_OFF_DIAGNOSTIC}; {}", scrub_message(err, scrub)); |
| 1331 | } |
| 1332 | } |
| 1333 | scrub_message(err, scrub) |
| 1334 | } |
| 1335 | |
| 1336 | fn is_existing_own( |
| 1337 | registry: &PluginRegistry, |
| 1338 | plugin: &LoadedPlugin, |
| 1339 | ) -> (bool, Option<&'static str>) { |
| 1340 | if registry.state_error().is_some() { |
| 1341 | return (false, Some("this plugin has no valid review record")); |
| 1342 | } |
| 1343 | let valid_agent = plugin.trusted() |
| 1344 | && !plugin.outside_reach |
| 1345 | && matches!( |
| 1346 | plugin.approved_by.as_ref(), |
| 1347 | Some(PluginApprover::Agent(agent)) if agent.posture != AgentPosture::CommandLine |
| 1348 | ); |
| 1349 | let installed_own = installed_by_the_agent(&plugin.canonical_root, registry.workspace()); |
| 1350 | if valid_agent && installed_own { |
| 1351 | (true, None) |
| 1352 | } else { |
| 1353 | (false, Some(agent_denial_reason(plugin, None))) |
| 1354 | } |
| 1355 | } |
| 1356 | |
| 1357 | fn collect_enable_warnings( |
| 1358 | registry: &PluginRegistry, |
| 1359 | plugin: &LoadedPlugin, |
| 1360 | approver: &PluginApprover, |
| 1361 | enabled_now: bool, |
| 1362 | registry_ignored: bool, |
| 1363 | scrub: &ScrubContext<'_>, |
| 1364 | ) -> Vec<String> { |
| 1365 | let mut warnings = Vec::new(); |
| 1366 | if enabled_now { |
| 1367 | let reach = match approver { |
| 1368 | PluginApprover::Agent(_) => "enabled for this project only", |
| 1369 | PluginApprover::Person { .. } | PluginApprover::CommandLine => { |
| 1370 | "enabled for every project" |
| 1371 | } |
| 1372 | }; |
| 1373 | warnings.push(reach.to_string()); |
| 1374 | } |
| 1375 | warnings.push(approver_label(Some(approver)).to_string()); |
| 1376 | if let Some(review) = registry.host_service_review(plugin.id.as_str()) { |
| 1377 | for line in review.lines { |
| 1378 | if !line.offered || !plugin.host_services.contains(&line.service) { |
| 1379 | warnings.push(scrub_warning( |
| 1380 | &format!( |
| 1381 | "service `{}`: this version does not offer it", |
| 1382 | line.service.name() |
| 1383 | ), |
| 1384 | scrub, |
| 1385 | )); |
| 1386 | } |
| 1387 | } |
| 1388 | } |
| 1389 | if registry_ignored { |
| 1390 | warnings.push( |
| 1391 | "registry was ignored; Codewhale installs from the configured source".to_string(), |
| 1392 | ); |
| 1393 | } |
| 1394 | warnings |
| 1395 | } |
| 1396 | |
| 1397 | fn plugin_services(loaded: Option<&LoadedPlugin>) -> Vec<String> { |
| 1398 | let mut services: Vec<String> = loaded |
| 1399 | .map(|plugin| { |
| 1400 | plugin |
| 1401 | .host_services |
| 1402 | .iter() |
| 1403 | .map(|service| service.name().to_string()) |
| 1404 | .collect() |
| 1405 | }) |
| 1406 | .unwrap_or_default(); |
| 1407 | services.sort(); |
| 1408 | services.dedup(); |
| 1409 | services |
| 1410 | } |
| 1411 | |
| 1412 | fn make_change_mark( |
| 1413 | plugin: &str, |
| 1414 | action: &str, |
| 1415 | content_hash: Option<&str>, |
| 1416 | approver: Option<&PluginApprover>, |
| 1417 | services: Vec<String>, |
| 1418 | tools_added: Vec<String>, |
| 1419 | tools_removed: Vec<String>, |
| 1420 | ) -> super::core_call::PluginChangeMark { |
| 1421 | super::core_call::PluginChangeMark { |
| 1422 | plugin: plugin.to_string(), |
| 1423 | action: action.to_string(), |
| 1424 | content_hash: content_hash.filter(|h| !h.is_empty()).map(str::to_string), |
| 1425 | decided_by: approver.map(|who| approver_label(Some(who)).to_string()), |
| 1426 | services, |
| 1427 | tools_added, |
| 1428 | tools_removed, |
| 1429 | } |
| 1430 | } |
| 1431 | |
| 1432 | fn wait_timeout_for(loaded: &LoadedPlugin) -> Duration { |
| 1433 | let rows = (loaded.inventory.native as u32).max(1); |
| 1434 | HOST_LOAD_TIMEOUT_PER_ROW |
| 1435 | .saturating_mul(rows) |
| 1436 | .min(MAX_HOST_WAIT) |
| 1437 | } |
| 1438 | |
| 1439 | fn sanitize_host_failure(reason: &str, diagnostics: &[String], scrub: &ScrubContext<'_>) -> String { |
| 1440 | let mut combined = Vec::new(); |
| 1441 | let head = scrub_message(reason, scrub); |
| 1442 | if !head.is_empty() { |
| 1443 | combined.push(head); |
| 1444 | } |
| 1445 | for line in diagnostics { |
| 1446 | let cleaned = scrub_message(line, scrub); |
| 1447 | if !cleaned.is_empty() && !combined.contains(&cleaned) { |
| 1448 | combined.push(cleaned); |
| 1449 | } |
| 1450 | } |
| 1451 | let mut truncated = false; |
| 1452 | cap_text(combined.join("; "), MAX_DIAGNOSTIC_BYTES, &mut truncated) |
| 1453 | } |
| 1454 | |
| 1455 | fn format_activated_tools_warning(tool_names: &[String], scrub: &ScrubContext<'_>) -> String { |
| 1456 | let mut listed = Vec::new(); |
| 1457 | let mut listed_bytes = 0usize; |
| 1458 | for raw_name in tool_names { |
| 1459 | if listed.len() >= MAX_TOOL_WARNINGS_PER_CONNECTOR { |
| 1460 | break; |
| 1461 | } |
| 1462 | let mut name_truncated = false; |
| 1463 | let clean_name = sanitize_inline(raw_name, MAX_ENTRY_ID_BYTES, &mut name_truncated); |
| 1464 | if clean_name.is_empty() { |
| 1465 | continue; |
| 1466 | } |
| 1467 | let next_bytes = listed_bytes + clean_name.len() + usize::from(!listed.is_empty()) * 2; |
| 1468 | if next_bytes > MAX_TEXT_BYTES.saturating_sub(64) && !listed.is_empty() { |
| 1469 | break; |
| 1470 | } |
| 1471 | listed_bytes = next_bytes; |
| 1472 | listed.push(clean_name); |
| 1473 | } |
| 1474 | let remaining = tool_names.len().saturating_sub(listed.len()); |
| 1475 | let summary = if listed.is_empty() { |
| 1476 | format!("plugin tools active ({})", tool_names.len()) |
| 1477 | } else if remaining > 0 { |
| 1478 | format!( |
| 1479 | "plugin tools active: {} (+{remaining} more)", |
| 1480 | listed.join(", ") |
| 1481 | ) |
| 1482 | } else { |
| 1483 | format!("plugin tools active: {}", listed.join(", ")) |
| 1484 | }; |
| 1485 | scrub_warning(&summary, scrub) |
| 1486 | } |
| 1487 | |
| 1488 | fn append_unique_warning(warnings: &mut Vec<String>, line: String) { |
| 1489 | if !line.is_empty() && !warnings.contains(&line) { |
| 1490 | warnings.push(line); |
| 1491 | } |
| 1492 | } |
| 1493 | |
| 1494 | fn is_active_summary_diagnostic(plugin_name: &str, line: &str) -> bool { |
| 1495 | let prefix = format!("plugin `{plugin_name}` active ("); |
| 1496 | line.starts_with(&prefix) |
| 1497 | } |
| 1498 | |
| 1499 | fn append_native_activation_warnings( |
| 1500 | report: &super::OwnerReport, |
| 1501 | plugin_name: &str, |
| 1502 | prior_tools: &[String], |
| 1503 | caller_tools: &[String], |
| 1504 | scrub: &ScrubContext<'_>, |
| 1505 | warnings: &mut Vec<String>, |
| 1506 | ) -> Vec<String> { |
| 1507 | let mut clean_plugin_trunc = false; |
| 1508 | let clean_plugin = sanitize_inline(plugin_name, MAX_NAME_BYTES, &mut clean_plugin_trunc); |
| 1509 | let mut added = Vec::new(); |
| 1510 | for name in &report.tools { |
| 1511 | let already_had = prior_tools |
| 1512 | .iter() |
| 1513 | .any(|existing| existing.eq_ignore_ascii_case(name)); |
| 1514 | let collides = !already_had |
| 1515 | && caller_tools |
| 1516 | .iter() |
| 1517 | .any(|existing| existing.eq_ignore_ascii_case(name)); |
| 1518 | if collides { |
| 1519 | let mut trunc = false; |
| 1520 | let clean_tool = sanitize_inline(name, MAX_ENTRY_ID_BYTES, &mut trunc); |
| 1521 | if !clean_tool.is_empty() { |
| 1522 | append_unique_warning( |
| 1523 | warnings, |
| 1524 | scrub_warning( |
| 1525 | &format!( |
| 1526 | "plugin tool `{clean_tool}` from `{clean_plugin}` skipped: the name is already registered" |
| 1527 | ), |
| 1528 | scrub, |
| 1529 | ), |
| 1530 | ); |
| 1531 | } |
| 1532 | continue; |
| 1533 | } |
| 1534 | if !added.contains(name) { |
| 1535 | added.push(name.clone()); |
| 1536 | } |
| 1537 | } |
| 1538 | added.sort(); |
| 1539 | added.dedup(); |
| 1540 | if !added.is_empty() { |
| 1541 | append_unique_warning(warnings, format_activated_tools_warning(&added, scrub)); |
| 1542 | } |
| 1543 | for line in &report.diagnostics { |
| 1544 | if is_active_summary_diagnostic(plugin_name, line) { |
| 1545 | continue; |
| 1546 | } |
| 1547 | append_unique_warning(warnings, scrub_warning(line, scrub)); |
| 1548 | } |
| 1549 | added |
| 1550 | } |
| 1551 | |
| 1552 | async fn settle_non_active_change( |
| 1553 | call: &BrokerCall, |
| 1554 | registry: &Arc<PluginRegistry>, |
| 1555 | mark: Option<super::core_call::PluginChangeMark>, |
| 1556 | ) { |
| 1557 | if let Some(mark) = mark { |
| 1558 | call.context.record_plugin_change(mark); |
| 1559 | } |
| 1560 | let _ = super::plugins_changed_and_wait( |
| 1561 | registry, |
| 1562 | None, |
| 1563 | None, |
| 1564 | Some(call.context.invocation_id()), |
| 1565 | false, |
| 1566 | call.context.cancel(), |
| 1567 | HOST_LOAD_TIMEOUT_PER_ROW, |
| 1568 | ) |
| 1569 | .await; |
| 1570 | } |
| 1571 | |
| 1572 | enum McpActivationError { |
| 1573 | Cancelled, |
| 1574 | Failed(String), |
| 1575 | HostRestarting(String), |
| 1576 | } |
| 1577 | |
| 1578 | struct EnableActivation<'a> { |
| 1579 | method: &'static str, |
| 1580 | stage: &'static str, |
| 1581 | target: String, |
| 1582 | changed: bool, |
| 1583 | registry: &'a Arc<PluginRegistry>, |
| 1584 | loaded: &'a LoadedPlugin, |
| 1585 | approver: &'a PluginApprover, |
| 1586 | version: Option<String>, |
| 1587 | warnings: Vec<String>, |
| 1588 | prior_tools: Vec<String>, |
| 1589 | } |
| 1590 | |
| 1591 | fn record_mcp_attempt( |
| 1592 | call: &BrokerCall, |
| 1593 | plugin_name: &str, |
| 1594 | server_name: &str, |
| 1595 | qualified: &str, |
| 1596 | outcome: &str, |
| 1597 | ) { |
| 1598 | let _ = call.context.record(json!({ |
| 1599 | "method": "mcp_connect", |
| 1600 | "plugin": plugin_name, |
| 1601 | "server": server_name, |
| 1602 | "qualified": qualified, |
| 1603 | "outcome": outcome, |
| 1604 | })); |
| 1605 | } |
| 1606 | |
| 1607 | fn record_remaining_timeouts( |
| 1608 | call: &BrokerCall, |
| 1609 | plugin_name: &str, |
| 1610 | servers: &[(&str, &McpServerConfig)], |
| 1611 | first_detail: &str, |
| 1612 | failures: &mut Vec<String>, |
| 1613 | ) { |
| 1614 | for (index, (server_name, _)) in servers.iter().enumerate() { |
| 1615 | let qualified = qualified_plugin_server_name(plugin_name, server_name); |
| 1616 | record_mcp_attempt(call, plugin_name, server_name, &qualified, "timed_out"); |
| 1617 | let detail = if index == 0 { |
| 1618 | first_detail |
| 1619 | } else { |
| 1620 | "not attempted before call deadline elapsed" |
| 1621 | }; |
| 1622 | failures.push(format!("`{server_name}`: {detail}")); |
| 1623 | } |
| 1624 | } |
| 1625 | |
| 1626 | fn format_connected_tools_warning( |
| 1627 | server_name: &str, |
| 1628 | tool_names: &[String], |
| 1629 | scrub: &ScrubContext<'_>, |
| 1630 | ) -> String { |
| 1631 | let mut clean_server_trunc = false; |
| 1632 | let clean_server = sanitize_inline(server_name, MAX_NAME_BYTES, &mut clean_server_trunc); |
| 1633 | if tool_names.is_empty() { |
| 1634 | return scrub_warning( |
| 1635 | &format!("connector `{clean_server}` connected with no tools"), |
| 1636 | scrub, |
| 1637 | ); |
| 1638 | } |
| 1639 | let mut listed = Vec::new(); |
| 1640 | let mut listed_bytes = 0usize; |
| 1641 | for raw_name in tool_names { |
| 1642 | if listed.len() >= MAX_TOOL_WARNINGS_PER_CONNECTOR { |
| 1643 | break; |
| 1644 | } |
| 1645 | let mut name_truncated = false; |
| 1646 | let clean_name = sanitize_inline(raw_name, MAX_ENTRY_ID_BYTES, &mut name_truncated); |
| 1647 | if clean_name.is_empty() { |
| 1648 | continue; |
| 1649 | } |
| 1650 | let next_bytes = listed_bytes + clean_name.len() + usize::from(!listed.is_empty()) * 2; |
| 1651 | if next_bytes > MAX_TEXT_BYTES.saturating_sub(96) && !listed.is_empty() { |
| 1652 | break; |
| 1653 | } |
| 1654 | listed_bytes = next_bytes; |
| 1655 | listed.push(clean_name); |
| 1656 | } |
| 1657 | let remaining = tool_names.len().saturating_sub(listed.len()); |
| 1658 | let summary = if listed.is_empty() { |
| 1659 | format!( |
| 1660 | "connector `{clean_server}` connected ({} tools)", |
| 1661 | tool_names.len() |
| 1662 | ) |
| 1663 | } else if remaining > 0 { |
| 1664 | format!( |
| 1665 | "connector `{clean_server}` tools: {} (+{remaining} more)", |
| 1666 | listed.join(", ") |
| 1667 | ) |
| 1668 | } else { |
| 1669 | format!("connector `{clean_server}` tools: {}", listed.join(", ")) |
| 1670 | }; |
| 1671 | scrub_warning(&summary, scrub) |
| 1672 | } |
| 1673 | |
| 1674 | fn plugin_host_cohort(registry: &PluginRegistry, plugin: &LoadedPlugin) -> super::tier::HostCohort { |
| 1675 | if matches!(plugin.approved_by, Some(PluginApprover::Agent(_))) { |
| 1676 | super::tier::HostCohort::agent(registry.workspace()) |
| 1677 | } else { |
| 1678 | super::tier::HostCohort::reviewed() |
| 1679 | } |
| 1680 | } |
| 1681 | |
| 1682 | fn host_generation(shared: &super::ManagerShared, cohort: &super::tier::HostCohort) -> Option<u64> { |
| 1683 | shared.cohort_runtime(cohort).map(|runtime| { |
| 1684 | runtime |
| 1685 | .host_generation |
| 1686 | .load(std::sync::atomic::Ordering::SeqCst) |
| 1687 | }) |
| 1688 | } |
| 1689 | |
| 1690 | fn host_recycling( |
| 1691 | shared: &super::ManagerShared, |
| 1692 | cohort: &super::tier::HostCohort, |
| 1693 | since_generation: Option<u64>, |
| 1694 | ) -> bool { |
| 1695 | match shared.ready_host(cohort) { |
| 1696 | Ok(_) => since_generation.is_some() && host_generation(shared, cohort) != since_generation, |
| 1697 | Err( |
| 1698 | super::HostStatus::Starting |
| 1699 | | super::HostStatus::Restarting { .. } |
| 1700 | | super::HostStatus::Unresponsive { .. }, |
| 1701 | ) => true, |
| 1702 | Err(_) => false, |
| 1703 | } |
| 1704 | } |
| 1705 | |
| 1706 | async fn connect_required_plugin_mcp_servers( |
| 1707 | call: &BrokerCall, |
| 1708 | forked: &mut McpPool, |
| 1709 | plugin_name: &str, |
| 1710 | required_servers: &[(&str, &McpServerConfig)], |
| 1711 | cohort: &super::tier::HostCohort, |
| 1712 | since_generation: Option<u64>, |
| 1713 | deadline: tokio::time::Instant, |
| 1714 | scrub: &ScrubContext<'_>, |
| 1715 | ) -> Result<Vec<String>, McpActivationError> { |
| 1716 | let mut connected_warnings = Vec::new(); |
| 1717 | let mut failures = Vec::new(); |
| 1718 | let mut deadline_hit = false; |
| 1719 | for (index, (server_name, server_config)) in required_servers.iter().enumerate() { |
| 1720 | let qualified = qualified_plugin_server_name(plugin_name, server_name); |
| 1721 | if call.context.cancel().is_cancelled() { |
| 1722 | record_mcp_attempt(call, plugin_name, server_name, &qualified, "cancelled"); |
| 1723 | return Err(McpActivationError::Cancelled); |
| 1724 | } |
| 1725 | let is_reviewed_plugin_server = |
| 1726 | forked.static_server_config(&qualified).is_some_and(|cfg| { |
| 1727 | cfg.reviewed_plugin_source() |
| 1728 | .is_some_and(|src| src.plugin_name() == plugin_name) |
| 1729 | }); |
| 1730 | if !is_reviewed_plugin_server { |
| 1731 | record_mcp_attempt(call, plugin_name, server_name, &qualified, "failed"); |
| 1732 | failures.push(format!( |
| 1733 | "`{server_name}`: missing reviewed plugin MCP entry `{qualified}`" |
| 1734 | )); |
| 1735 | continue; |
| 1736 | } |
| 1737 | if tokio::time::Instant::now() >= deadline { |
| 1738 | record_remaining_timeouts( |
| 1739 | call, |
| 1740 | plugin_name, |
| 1741 | &required_servers[index..], |
| 1742 | "call deadline elapsed before connecting", |
| 1743 | &mut failures, |
| 1744 | ); |
| 1745 | deadline_hit = true; |
| 1746 | break; |
| 1747 | } |
| 1748 | let attempt_cancel = tokio_util::sync::CancellationToken::new(); |
| 1749 | let timed_out = Arc::new(std::sync::atomic::AtomicBool::new(false)); |
| 1750 | let watcher_cancel = attempt_cancel.clone(); |
| 1751 | let turn_cancel = call.context.cancel().clone(); |
| 1752 | let watcher_timed_out = Arc::clone(&timed_out); |
| 1753 | let watcher = tokio::spawn(async move { |
| 1754 | tokio::select! { |
| 1755 | biased; |
| 1756 | () = turn_cancel.cancelled() => { |
| 1757 | watcher_cancel.cancel(); |
| 1758 | } |
| 1759 | () = tokio::time::sleep_until(deadline) => { |
| 1760 | watcher_timed_out.store(true, std::sync::atomic::Ordering::SeqCst); |
| 1761 | watcher_cancel.cancel(); |
| 1762 | } |
| 1763 | } |
| 1764 | }); |
| 1765 | let connect_res = forked |
| 1766 | .get_or_connect_with_cancel(&qualified, &attempt_cancel) |
| 1767 | .await; |
| 1768 | watcher.abort(); |
| 1769 | let _ = watcher.await; |
| 1770 | if call.context.cancel().is_cancelled() { |
| 1771 | record_mcp_attempt(call, plugin_name, server_name, &qualified, "cancelled"); |
| 1772 | return Err(McpActivationError::Cancelled); |
| 1773 | } |
| 1774 | if timed_out.load(std::sync::atomic::Ordering::SeqCst) && connect_res.is_err() { |
| 1775 | record_remaining_timeouts( |
| 1776 | call, |
| 1777 | plugin_name, |
| 1778 | &required_servers[index..], |
| 1779 | "timed out waiting for required MCP connector response", |
| 1780 | &mut failures, |
| 1781 | ); |
| 1782 | deadline_hit = true; |
| 1783 | break; |
| 1784 | } |
| 1785 | match connect_res { |
| 1786 | Ok(conn) => { |
| 1787 | let raw_tools: Vec<String> = conn |
| 1788 | .tools() |
| 1789 | .iter() |
| 1790 | .filter(|tool| server_config.is_tool_enabled(&tool.name)) |
| 1791 | .map(|tool| McpPool::mcp_model_tool_name(&qualified, &tool.name)) |
| 1792 | .collect(); |
| 1793 | let allowed_tools: Vec<String> = raw_tools |
| 1794 | .into_iter() |
| 1795 | .filter(|tool_name| forked.tool_allowed(tool_name)) |
| 1796 | .collect(); |
| 1797 | record_mcp_attempt(call, plugin_name, server_name, &qualified, "connected"); |
| 1798 | connected_warnings.push(format_connected_tools_warning( |
| 1799 | server_name, |
| 1800 | &allowed_tools, |
| 1801 | scrub, |
| 1802 | )); |
| 1803 | } |
| 1804 | Err(error) => { |
| 1805 | record_mcp_attempt(call, plugin_name, server_name, &qualified, "failed"); |
| 1806 | let reason = scrub_message(&format_mcp_error_for_display(&error), scrub); |
| 1807 | failures.push(format!("`{server_name}`: {reason}")); |
| 1808 | } |
| 1809 | } |
| 1810 | } |
| 1811 | if !failures.is_empty() { |
| 1812 | let joined = if failures.len() == 1 { |
| 1813 | format!("required MCP connector {}", failures[0]) |
| 1814 | } else { |
| 1815 | format!("required MCP connectors failed: {}", failures.join("; ")) |
| 1816 | }; |
| 1817 | let mut truncated = false; |
| 1818 | let capped = cap_text(joined, MAX_DIAGNOSTIC_BYTES, &mut truncated); |
| 1819 | let recycling = |
| 1820 | !deadline_hit && host_recycling(&super::manager().shared, cohort, since_generation); |
| 1821 | return Err(if recycling { |
| 1822 | McpActivationError::HostRestarting(capped) |
| 1823 | } else { |
| 1824 | McpActivationError::Failed(capped) |
| 1825 | }); |
| 1826 | } |
| 1827 | Ok(connected_warnings) |
| 1828 | } |
| 1829 | |
| 1830 | fn find_settled_attachment_registry( |
| 1831 | attachments: &std::sync::Mutex<BTreeMap<u64, super::AttachmentState>>, |
| 1832 | workspace: &Path, |
| 1833 | plugin_id: &str, |
| 1834 | content_hash: &str, |
| 1835 | ) -> (Option<Arc<PluginRegistry>>, bool) { |
| 1836 | let guard = attachments.lock().expect("attachments lock"); |
| 1837 | let mut matching_workspace_pending = false; |
| 1838 | for state in guard.values() { |
| 1839 | if state.plugins.workspace() != workspace { |
| 1840 | continue; |
| 1841 | } |
| 1842 | let Some(loaded) = state.plugins.get(plugin_id) else { |
| 1843 | continue; |
| 1844 | }; |
| 1845 | if !loaded.active() || loaded.content_hash != content_hash { |
| 1846 | continue; |
| 1847 | } |
| 1848 | if let Some(sel) = state.plugins.caller_selection() |
| 1849 | && state.selection.revision == Some(sel) |
| 1850 | && state.selection.desired.get(plugin_id) == Some(&loaded.content_hash) |
| 1851 | { |
| 1852 | return (Some(Arc::clone(&state.plugins)), false); |
| 1853 | } |
| 1854 | matching_workspace_pending = true; |
| 1855 | } |
| 1856 | (None, matching_workspace_pending) |
| 1857 | } |
| 1858 | |
| 1859 | async fn resolve_plugin_enabled_servers( |
| 1860 | call: &BrokerCall, |
| 1861 | registry: &Arc<PluginRegistry>, |
| 1862 | plugin: &LoadedPlugin, |
| 1863 | cohort: &super::tier::HostCohort, |
| 1864 | since_generation: Option<u64>, |
| 1865 | remaining: Duration, |
| 1866 | deadline: tokio::time::Instant, |
| 1867 | scrub: &ScrubContext<'_>, |
| 1868 | ) -> Result<(Arc<PluginRegistry>, Vec<(String, McpServerConfig)>), McpActivationError> { |
| 1869 | let mut servers: BTreeMap<String, McpServerConfig> = plugin |
| 1870 | .manifest |
| 1871 | .mcp_servers |
| 1872 | .iter() |
| 1873 | .flatten() |
| 1874 | .filter(|(_, config)| config.is_enabled()) |
| 1875 | .map(|(name, config)| (name.clone(), config.clone())) |
| 1876 | .collect(); |
| 1877 | if plugin.inventory.native == 0 { |
| 1878 | return Ok((Arc::clone(registry), servers.into_iter().collect())); |
| 1879 | } |
| 1880 | |
| 1881 | let shared = &super::manager().shared; |
| 1882 | let live_native: Vec<(String, McpServerConfig)> = { |
| 1883 | let owners = shared.registry.lock().expect("registry lock"); |
| 1884 | owners |
| 1885 | .live_mcp() |
| 1886 | .into_iter() |
| 1887 | .filter(|reg| { |
| 1888 | reg.owner.plugin_id == plugin.id.as_str() |
| 1889 | && reg.content_hash == plugin.content_hash |
| 1890 | && reg.config.is_enabled() |
| 1891 | }) |
| 1892 | .map(|reg| (reg.name, reg.config)) |
| 1893 | .collect() |
| 1894 | }; |
| 1895 | if live_native.is_empty() { |
| 1896 | if host_recycling(shared, cohort, since_generation) { |
| 1897 | return Err(McpActivationError::HostRestarting(scrub_message( |
| 1898 | "native MCP definitions were not admitted by the plugin host while it was restarting", |
| 1899 | scrub, |
| 1900 | ))); |
| 1901 | } |
| 1902 | return Ok((Arc::clone(registry), servers.into_iter().collect())); |
| 1903 | } |
| 1904 | |
| 1905 | let mut live_seen = HashSet::new(); |
| 1906 | let live_required: Vec<(&str, &McpServerConfig)> = live_native |
| 1907 | .iter() |
| 1908 | .filter(|(_, cfg)| cfg.required) |
| 1909 | .map(|(name, cfg)| (name.as_str(), cfg)) |
| 1910 | .collect(); |
| 1911 | for (name, _) in &live_native { |
| 1912 | if !live_seen.insert(name.as_str()) || servers.contains_key(name) { |
| 1913 | for (req_name, _) in &live_required { |
| 1914 | let qualified = qualified_plugin_server_name(plugin.name(), req_name); |
| 1915 | record_mcp_attempt(call, plugin.name(), req_name, &qualified, "failed"); |
| 1916 | } |
| 1917 | return Err(McpActivationError::Failed(scrub_message( |
| 1918 | &format!("duplicate plugin MCP server definition `{name}`"), |
| 1919 | scrub, |
| 1920 | ))); |
| 1921 | } |
| 1922 | } |
| 1923 | |
| 1924 | let mut timed_out_waiting_settlement = false; |
| 1925 | let registry_for_fork = loop { |
| 1926 | if call.context.cancel().is_cancelled() { |
| 1927 | return Err(McpActivationError::Cancelled); |
| 1928 | } |
| 1929 | let (settled, pending) = find_settled_attachment_registry( |
| 1930 | &shared.attachments, |
| 1931 | registry.workspace(), |
| 1932 | plugin.id.as_str(), |
| 1933 | &plugin.content_hash, |
| 1934 | ); |
| 1935 | if let Some(settled_registry) = settled { |
| 1936 | break settled_registry; |
| 1937 | } |
| 1938 | if !pending { |
| 1939 | break Arc::clone(registry); |
| 1940 | } |
| 1941 | if remaining.is_zero() || tokio::time::Instant::now() >= deadline { |
| 1942 | timed_out_waiting_settlement = true; |
| 1943 | break Arc::clone(registry); |
| 1944 | } |
| 1945 | tokio::select! { |
| 1946 | biased; |
| 1947 | () = call.context.cancel().cancelled() => return Err(McpActivationError::Cancelled), |
| 1948 | () = tokio::time::sleep_until(deadline) => { |
| 1949 | timed_out_waiting_settlement = true; |
| 1950 | break Arc::clone(registry); |
| 1951 | } |
| 1952 | () = tokio::time::sleep(HOST_POLL_INTERVAL) => {} |
| 1953 | } |
| 1954 | }; |
| 1955 | |
| 1956 | if timed_out_waiting_settlement && !live_required.is_empty() { |
| 1957 | let mut failures = Vec::new(); |
| 1958 | record_remaining_timeouts( |
| 1959 | call, |
| 1960 | plugin.name(), |
| 1961 | &live_required, |
| 1962 | "timed out waiting for plugin attachment selection", |
| 1963 | &mut failures, |
| 1964 | ); |
| 1965 | return Err(McpActivationError::Failed(scrub_message( |
| 1966 | &failures.join("; "), |
| 1967 | scrub, |
| 1968 | ))); |
| 1969 | } |
| 1970 | |
| 1971 | let admitted = match super::native_mcp::for_plugins(®istry_for_fork) { |
| 1972 | Ok(entries) => entries, |
| 1973 | Err(error) => { |
| 1974 | for (req_name, _) in &live_required { |
| 1975 | let qualified = qualified_plugin_server_name(plugin.name(), req_name); |
| 1976 | record_mcp_attempt(call, plugin.name(), req_name, &qualified, "failed"); |
| 1977 | } |
| 1978 | let diag = scrub_message(&error, scrub); |
| 1979 | return Err(if host_recycling(shared, cohort, since_generation) { |
| 1980 | McpActivationError::HostRestarting(diag) |
| 1981 | } else { |
| 1982 | McpActivationError::Failed(diag) |
| 1983 | }); |
| 1984 | } |
| 1985 | }; |
| 1986 | |
| 1987 | let mut admitted_names = HashSet::new(); |
| 1988 | for (name, cfg, authority, _) in admitted { |
| 1989 | if authority.plugin_id == plugin.id && cfg.is_enabled() { |
| 1990 | if servers.contains_key(&name) { |
| 1991 | for (req_name, _) in &live_required { |
| 1992 | let qualified = qualified_plugin_server_name(plugin.name(), req_name); |
| 1993 | record_mcp_attempt(call, plugin.name(), req_name, &qualified, "failed"); |
| 1994 | } |
| 1995 | return Err(McpActivationError::Failed(scrub_message( |
| 1996 | &format!("native MCP connector `{name}` collides with manifest entry"), |
| 1997 | scrub, |
| 1998 | ))); |
| 1999 | } |
| 2000 | admitted_names.insert(name.clone()); |
| 2001 | servers.insert(name, cfg); |
| 2002 | } |
| 2003 | } |
| 2004 | |
| 2005 | let mut missing_required = Vec::new(); |
| 2006 | for (name, _) in &live_required { |
| 2007 | if !admitted_names.contains(*name) { |
| 2008 | let qualified = qualified_plugin_server_name(plugin.name(), name); |
| 2009 | record_mcp_attempt(call, plugin.name(), name, &qualified, "failed"); |
| 2010 | missing_required.push(format!("`{name}`")); |
| 2011 | } |
| 2012 | } |
| 2013 | if !missing_required.is_empty() { |
| 2014 | let diag = scrub_message( |
| 2015 | &format!( |
| 2016 | "required native MCP connector(s) were not admitted by the plugin host: {}", |
| 2017 | missing_required.join(", ") |
| 2018 | ), |
| 2019 | scrub, |
| 2020 | ); |
| 2021 | return Err(if host_recycling(shared, cohort, since_generation) { |
| 2022 | McpActivationError::HostRestarting(diag) |
| 2023 | } else { |
| 2024 | McpActivationError::Failed(diag) |
| 2025 | }); |
| 2026 | } |
| 2027 | |
| 2028 | Ok((registry_for_fork, servers.into_iter().collect())) |
| 2029 | } |
| 2030 | |
| 2031 | async fn activate_plugin_mcp_connectors( |
| 2032 | call: &BrokerCall, |
| 2033 | registry: &Arc<PluginRegistry>, |
| 2034 | plugin: &LoadedPlugin, |
| 2035 | scrub: &ScrubContext<'_>, |
| 2036 | warnings: &mut Vec<String>, |
| 2037 | ) -> Result<(), McpActivationError> { |
| 2038 | let remaining = mcp_connect_deadline(); |
| 2039 | let deadline = tokio::time::Instant::now() + remaining; |
| 2040 | loop { |
| 2041 | match activate_plugin_mcp_connectors_once( |
| 2042 | call, registry, plugin, remaining, deadline, scrub, warnings, |
| 2043 | ) |
| 2044 | .await |
| 2045 | { |
| 2046 | Ok(()) => return Ok(()), |
| 2047 | Err(McpActivationError::HostRestarting(diag)) => { |
| 2048 | if call.context.cancel().is_cancelled() { |
| 2049 | return Err(McpActivationError::Cancelled); |
| 2050 | } |
| 2051 | if remaining.is_zero() || tokio::time::Instant::now() >= deadline { |
| 2052 | return Err(McpActivationError::Failed(diag)); |
| 2053 | } |
| 2054 | let cohort = plugin_host_cohort(registry, plugin); |
| 2055 | wait_for_host_recycle(call, registry, plugin, &cohort, deadline, scrub, diag) |
| 2056 | .await?; |
| 2057 | } |
| 2058 | Err(error) => return Err(error), |
| 2059 | } |
| 2060 | } |
| 2061 | } |
| 2062 | |
| 2063 | async fn wait_for_host_recycle( |
| 2064 | call: &BrokerCall, |
| 2065 | registry: &Arc<PluginRegistry>, |
| 2066 | plugin: &LoadedPlugin, |
| 2067 | cohort: &super::tier::HostCohort, |
| 2068 | deadline: tokio::time::Instant, |
| 2069 | scrub: &ScrubContext<'_>, |
| 2070 | diag: String, |
| 2071 | ) -> Result<(), McpActivationError> { |
| 2072 | let manager = super::manager(); |
| 2073 | let shared = &manager.shared; |
| 2074 | let expected_authority = registry.authority_for(plugin.id.as_str()); |
| 2075 | loop { |
| 2076 | if call.context.cancel().is_cancelled() { |
| 2077 | return Err(McpActivationError::Cancelled); |
| 2078 | } |
| 2079 | let settled = shared.reconcile_settled.notified(); |
| 2080 | tokio::pin!(settled); |
| 2081 | settled.as_mut().enable(); |
| 2082 | let report = manager.owner_report_for(plugin.id.as_str(), expected_authority.as_ref()); |
| 2083 | if let Some(report) = &report { |
| 2084 | match report.state.as_ref() { |
| 2085 | Some(OwnerState::Failed(reason)) | Some(OwnerState::Faulted(reason)) => { |
| 2086 | return Err(McpActivationError::Failed(scrub_message(reason, scrub))); |
| 2087 | } |
| 2088 | Some(OwnerState::Revoked) => { |
| 2089 | return Err(McpActivationError::Failed( |
| 2090 | "the plugin host revoked the plugin owner".to_string(), |
| 2091 | )); |
| 2092 | } |
| 2093 | _ => {} |
| 2094 | } |
| 2095 | } |
| 2096 | match shared.ready_host(cohort) { |
| 2097 | Ok(_) => { |
| 2098 | let owner_active = plugin.inventory.native == 0 |
| 2099 | || matches!( |
| 2100 | report.as_ref().and_then(|report| report.state.as_ref()), |
| 2101 | Some(OwnerState::Active) |
| 2102 | ); |
| 2103 | if owner_active { |
| 2104 | return Ok(()); |
| 2105 | } |
| 2106 | } |
| 2107 | Err(super::HostStatus::Failed { reason, .. }) => { |
| 2108 | return Err(McpActivationError::Failed(scrub_message(&reason, scrub))); |
| 2109 | } |
| 2110 | Err(super::HostStatus::Disabled) => { |
| 2111 | return Err(McpActivationError::Failed(HOST_OFF_DIAGNOSTIC.to_string())); |
| 2112 | } |
| 2113 | Err(_) => {} |
| 2114 | } |
| 2115 | tokio::select! { |
| 2116 | biased; |
| 2117 | () = call.context.cancel().cancelled() => { |
| 2118 | return Err(McpActivationError::Cancelled); |
| 2119 | } |
| 2120 | () = tokio::time::sleep_until(deadline) => { |
| 2121 | return Err(McpActivationError::Failed(diag)); |
| 2122 | } |
| 2123 | () = settled => {} |
| 2124 | () = tokio::time::sleep(HOST_POLL_INTERVAL) => {} |
| 2125 | } |
| 2126 | } |
| 2127 | } |
| 2128 | |
| 2129 | async fn activate_plugin_mcp_connectors_once( |
| 2130 | call: &BrokerCall, |
| 2131 | registry: &Arc<PluginRegistry>, |
| 2132 | plugin: &LoadedPlugin, |
| 2133 | remaining: Duration, |
| 2134 | deadline: tokio::time::Instant, |
| 2135 | scrub: &ScrubContext<'_>, |
| 2136 | warnings: &mut Vec<String>, |
| 2137 | ) -> Result<(), McpActivationError> { |
| 2138 | #[cfg(test)] |
| 2139 | fire_pre_connect_hook_for_test(); |
| 2140 | let cohort = plugin_host_cohort(registry, plugin); |
| 2141 | let since_generation = host_generation(&super::manager().shared, &cohort); |
| 2142 | let (registry_for_fork, enabled_servers) = resolve_plugin_enabled_servers( |
| 2143 | call, |
| 2144 | registry, |
| 2145 | plugin, |
| 2146 | &cohort, |
| 2147 | since_generation, |
| 2148 | remaining, |
| 2149 | deadline, |
| 2150 | scrub, |
| 2151 | ) |
| 2152 | .await?; |
| 2153 | if enabled_servers.is_empty() { |
| 2154 | return Ok(()); |
| 2155 | } |
| 2156 | |
| 2157 | let required_servers: Vec<(&str, &McpServerConfig)> = enabled_servers |
| 2158 | .iter() |
| 2159 | .filter(|(_, config)| config.required) |
| 2160 | .map(|(name, config)| (name.as_str(), config)) |
| 2161 | .collect(); |
| 2162 | let optional_servers: Vec<(&str, &McpServerConfig)> = enabled_servers |
| 2163 | .iter() |
| 2164 | .filter(|(_, config)| !config.required) |
| 2165 | .map(|(name, config)| (name.as_str(), config)) |
| 2166 | .collect(); |
| 2167 | |
| 2168 | let mut connected_warnings = Vec::new(); |
| 2169 | if !required_servers.is_empty() { |
| 2170 | if call.context.cancel().is_cancelled() { |
| 2171 | return Err(McpActivationError::Cancelled); |
| 2172 | } |
| 2173 | let Some(session_pool) = call.context.mcp_pool() else { |
| 2174 | let mut failures = Vec::new(); |
| 2175 | for (server_name, _) in &required_servers { |
| 2176 | let qualified = qualified_plugin_server_name(plugin.name(), server_name); |
| 2177 | record_mcp_attempt(call, plugin.name(), server_name, &qualified, "failed"); |
| 2178 | failures.push(format!("`{server_name}`")); |
| 2179 | } |
| 2180 | return Err(McpActivationError::Failed(scrub_message( |
| 2181 | &format!( |
| 2182 | "the session MCP pool is unavailable to verify required MCP connector(s): {}", |
| 2183 | failures.join(", ") |
| 2184 | ), |
| 2185 | scrub, |
| 2186 | ))); |
| 2187 | }; |
| 2188 | |
| 2189 | if remaining.is_zero() || tokio::time::Instant::now() >= deadline { |
| 2190 | let mut failures = Vec::new(); |
| 2191 | record_remaining_timeouts( |
| 2192 | call, |
| 2193 | plugin.name(), |
| 2194 | &required_servers, |
| 2195 | "call deadline elapsed before connecting", |
| 2196 | &mut failures, |
| 2197 | ); |
| 2198 | return Err(McpActivationError::Failed(scrub_message( |
| 2199 | &failures.join("; "), |
| 2200 | scrub, |
| 2201 | ))); |
| 2202 | } |
| 2203 | |
| 2204 | let live_network_policy = call.context.tool().network_policy.clone(); |
| 2205 | let mut forked = tokio::select! { |
| 2206 | biased; |
| 2207 | () = call.context.cancel().cancelled() => return Err(McpActivationError::Cancelled), |
| 2208 | () = tokio::time::sleep_until(deadline) => { |
| 2209 | let mut failures = Vec::new(); |
| 2210 | record_remaining_timeouts( |
| 2211 | call, |
| 2212 | plugin.name(), |
| 2213 | &required_servers, |
| 2214 | "timed out waiting for MCP pool lock before deadline", |
| 2215 | &mut failures, |
| 2216 | ); |
| 2217 | return Err(McpActivationError::Failed(scrub_message( |
| 2218 | &failures.join("; "), |
| 2219 | scrub, |
| 2220 | ))); |
| 2221 | } |
| 2222 | fork_res = async { |
| 2223 | let guard = session_pool.lock().await; |
| 2224 | guard.fork_isolated_for_plugins( |
| 2225 | Arc::clone(®istry_for_fork), |
| 2226 | live_network_policy, |
| 2227 | ) |
| 2228 | } => match fork_res { |
| 2229 | Ok(pool) => pool, |
| 2230 | Err(error) => { |
| 2231 | let diag = scrub_message(&format_mcp_error_for_display(&error), scrub); |
| 2232 | for (server_name, _) in &required_servers { |
| 2233 | let qualified = qualified_plugin_server_name(plugin.name(), server_name); |
| 2234 | record_mcp_attempt(call, plugin.name(), server_name, &qualified, "failed"); |
| 2235 | } |
| 2236 | return Err( |
| 2237 | if host_recycling(&super::manager().shared, &cohort, since_generation) { |
| 2238 | McpActivationError::HostRestarting(diag) |
| 2239 | } else { |
| 2240 | McpActivationError::Failed(diag) |
| 2241 | }, |
| 2242 | ); |
| 2243 | } |
| 2244 | } |
| 2245 | }; |
| 2246 | |
| 2247 | let connect_outcome = connect_required_plugin_mcp_servers( |
| 2248 | call, |
| 2249 | &mut forked, |
| 2250 | plugin.name(), |
| 2251 | &required_servers, |
| 2252 | &cohort, |
| 2253 | since_generation, |
| 2254 | deadline, |
| 2255 | scrub, |
| 2256 | ) |
| 2257 | .await; |
| 2258 | forked.shutdown_all().await; |
| 2259 | connected_warnings = connect_outcome?; |
| 2260 | } |
| 2261 | |
| 2262 | warnings.extend(connected_warnings); |
| 2263 | for (server_name, _) in optional_servers { |
| 2264 | let mut clean_server_trunc = false; |
| 2265 | let clean_server = sanitize_inline(server_name, MAX_NAME_BYTES, &mut clean_server_trunc); |
| 2266 | let qualified = qualified_plugin_server_name(plugin.name(), server_name); |
| 2267 | let prefix = McpPool::mcp_model_tool_name(&qualified, ""); |
| 2268 | warnings.push(scrub_warning( |
| 2269 | &format!( |
| 2270 | "connector `{clean_server}` was not started upfront; expected tools start with `{prefix}`" |
| 2271 | ), |
| 2272 | scrub, |
| 2273 | )); |
| 2274 | } |
| 2275 | warnings.push("connector tools become callable from the next message on".to_string()); |
| 2276 | Ok(()) |
| 2277 | } |
| 2278 | |
| 2279 | async fn finish_enabled_activation( |
| 2280 | call: &BrokerCall, |
| 2281 | mut activation: EnableActivation<'_>, |
| 2282 | scrub: &ScrubContext<'_>, |
| 2283 | ) -> std::ops::ControlFlow<Result<Value, BrokerRefusal>, Vec<String>> { |
| 2284 | let services = plugin_services(Some(activation.loaded)); |
| 2285 | let mark_action = if activation.method == "install" { |
| 2286 | "installed" |
| 2287 | } else { |
| 2288 | activation.method |
| 2289 | }; |
| 2290 | if activation.changed { |
| 2291 | call.context.record_plugin_change(make_change_mark( |
| 2292 | activation.loaded.name(), |
| 2293 | mark_action, |
| 2294 | Some(&activation.loaded.content_hash), |
| 2295 | Some(activation.approver), |
| 2296 | services.clone(), |
| 2297 | Vec::new(), |
| 2298 | Vec::new(), |
| 2299 | )); |
| 2300 | } |
| 2301 | let wait_for_owner = activation.loaded.inventory.native > 0 && activation.loaded.enabled; |
| 2302 | let expected_authority = activation |
| 2303 | .registry |
| 2304 | .authority_for(activation.loaded.id.as_str()); |
| 2305 | let host_err = match super::plugins_changed_and_wait( |
| 2306 | activation.registry, |
| 2307 | Some(activation.loaded.id.as_str()), |
| 2308 | expected_authority.as_ref(), |
| 2309 | Some(call.context.invocation_id()), |
| 2310 | wait_for_owner, |
| 2311 | call.context.cancel(), |
| 2312 | wait_timeout_for(activation.loaded), |
| 2313 | ) |
| 2314 | .await |
| 2315 | { |
| 2316 | Ok(Some(report)) => match report.state.as_ref() { |
| 2317 | Some(OwnerState::Active) => { |
| 2318 | let added_tools = append_native_activation_warnings( |
| 2319 | &report, |
| 2320 | activation.loaded.name(), |
| 2321 | &activation.prior_tools, |
| 2322 | call.context.caller_tools(), |
| 2323 | scrub, |
| 2324 | &mut activation.warnings, |
| 2325 | ); |
| 2326 | if activation.changed && !added_tools.is_empty() { |
| 2327 | call.context.record_plugin_change(make_change_mark( |
| 2328 | activation.loaded.name(), |
| 2329 | mark_action, |
| 2330 | Some(&activation.loaded.content_hash), |
| 2331 | Some(activation.approver), |
| 2332 | services, |
| 2333 | added_tools, |
| 2334 | Vec::new(), |
| 2335 | )); |
| 2336 | } |
| 2337 | None |
| 2338 | } |
| 2339 | Some(OwnerState::Failed(reason)) | Some(OwnerState::Faulted(reason)) => { |
| 2340 | for line in &report.diagnostics { |
| 2341 | if !is_active_summary_diagnostic(activation.loaded.name(), line) { |
| 2342 | append_unique_warning(&mut activation.warnings, scrub_warning(line, scrub)); |
| 2343 | } |
| 2344 | } |
| 2345 | Some(sanitize_host_failure(reason, &report.diagnostics, scrub)) |
| 2346 | } |
| 2347 | Some(OwnerState::Revoked) => { |
| 2348 | Some("the plugin host revoked the plugin owner".to_string()) |
| 2349 | } |
| 2350 | Some(OwnerState::Activating) | None => Some( |
| 2351 | "the plugin host did not finish starting native plugin code in time".to_string(), |
| 2352 | ), |
| 2353 | }, |
| 2354 | Ok(None) => { |
| 2355 | if wait_for_owner { |
| 2356 | Some("plugin activation did not register an owner in the plugin host".to_string()) |
| 2357 | } else { |
| 2358 | None |
| 2359 | } |
| 2360 | } |
| 2361 | Err(reason) => Some(sanitize_host_failure(&reason, &[], scrub)), |
| 2362 | }; |
| 2363 | if let Some(host_err) = host_err { |
| 2364 | record_outcome( |
| 2365 | call, |
| 2366 | activation.method, |
| 2367 | Some(activation.loaded.name()), |
| 2368 | Some(&activation.loaded.content_hash), |
| 2369 | Some(activation.approver), |
| 2370 | "failed", |
| 2371 | ); |
| 2372 | return std::ops::ControlFlow::Break(change_with_outcome(ChangeOutcome { |
| 2373 | application: "failed", |
| 2374 | stage: activation.stage, |
| 2375 | target: activation.target, |
| 2376 | changed: activation.changed, |
| 2377 | enabled: Some(activation.loaded.enabled), |
| 2378 | code: "operation-error", |
| 2379 | diagnostic: host_err, |
| 2380 | bundle: Some(activation.loaded.name().to_string()), |
| 2381 | version: non_empty_version(&activation.loaded.manifest.plugin.version) |
| 2382 | .or(activation.version), |
| 2383 | warnings: activation.warnings, |
| 2384 | })); |
| 2385 | } |
| 2386 | let (outcome_tag, diagnostic) = match activate_plugin_mcp_connectors( |
| 2387 | call, |
| 2388 | activation.registry, |
| 2389 | activation.loaded, |
| 2390 | scrub, |
| 2391 | &mut activation.warnings, |
| 2392 | ) |
| 2393 | .await |
| 2394 | { |
| 2395 | Ok(()) => return std::ops::ControlFlow::Continue(activation.warnings), |
| 2396 | Err(McpActivationError::Cancelled) => ( |
| 2397 | "cancelled", |
| 2398 | "operation cancelled before required MCP connector verification finished".to_string(), |
| 2399 | ), |
| 2400 | Err(McpActivationError::Failed(diag)) => ("failed", diag), |
| 2401 | Err(McpActivationError::HostRestarting(diag)) => ("failed", diag), |
| 2402 | }; |
| 2403 | record_outcome( |
| 2404 | call, |
| 2405 | activation.method, |
| 2406 | Some(activation.loaded.name()), |
| 2407 | Some(&activation.loaded.content_hash), |
| 2408 | Some(activation.approver), |
| 2409 | outcome_tag, |
| 2410 | ); |
| 2411 | std::ops::ControlFlow::Break(change_with_outcome(ChangeOutcome { |
| 2412 | application: "failed", |
| 2413 | stage: activation.stage, |
| 2414 | target: activation.target, |
| 2415 | changed: activation.changed, |
| 2416 | enabled: Some(activation.loaded.enabled), |
| 2417 | code: "operation-error", |
| 2418 | diagnostic, |
| 2419 | bundle: Some(activation.loaded.name().to_string()), |
| 2420 | version: non_empty_version(&activation.loaded.manifest.plugin.version) |
| 2421 | .or(activation.version), |
| 2422 | warnings: activation.warnings, |
| 2423 | })) |
| 2424 | } |
| 2425 | |
| 2426 | async fn prepare_local_source_and_hash_with_network( |
| 2427 | source: &PluginInstallSource, |
| 2428 | dir: &Path, |
| 2429 | network: Option<&NetworkPolicy>, |
| 2430 | ) -> Result<(String, Option<String>, Option<String>, String), (&'static str, String)> { |
| 2431 | match has_symlink_or_reparse_ancestor_or_target(dir).await { |
| 2432 | Ok(true) => { |
| 2433 | return Err(( |
| 2434 | "operation-error", |
| 2435 | "symbolic links and reparse points are not allowed in plugin bundles".to_string(), |
| 2436 | )); |
| 2437 | } |
| 2438 | Ok(false) => {} |
| 2439 | Err(error) => { |
| 2440 | return Err(( |
| 2441 | classify_error_message(&error.to_string()), |
| 2442 | format!("failed to inspect install source: {error}"), |
| 2443 | )); |
| 2444 | } |
| 2445 | } |
| 2446 | ensure_no_links_in_tree(dir) |
| 2447 | .await |
| 2448 | .map_err(|msg| (classify_error_message(&msg), msg))?; |
| 2449 | let source = source.clone(); |
| 2450 | let dir = dir.to_path_buf(); |
| 2451 | let network = network.cloned(); |
| 2452 | let policy = extension_host_policy_enabled(); |
| 2453 | #[cfg(any(test, feature = "test-support"))] |
| 2454 | let env_scope = crate::test_support::env_scope_ticket(); |
| 2455 | tokio::task::spawn_blocking(move || { |
| 2456 | #[cfg(any(test, feature = "test-support"))] |
| 2457 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 2458 | let _scope = PolicyScope::propagate(policy); |
| 2459 | match source { |
| 2460 | PluginInstallSource::LocalPath(_) => { |
| 2461 | let Some(manifest_path) = resolve_manifest_path(&dir) else { |
| 2462 | return Err(( |
| 2463 | "not-bundle", |
| 2464 | "not-bundle: source directory has no plugin.json, kimi.plugin.json, plugin.toml, or dsh.bundle" |
| 2465 | .to_string(), |
| 2466 | )); |
| 2467 | }; |
| 2468 | let validated = PluginManifest::validate_from_path(&manifest_path) |
| 2469 | .map_err(|error| ("not-bundle", format!("not-bundle: {error}")))?; |
| 2470 | Ok(( |
| 2471 | validated.manifest.plugin.name.clone(), |
| 2472 | None, |
| 2473 | non_empty_version(&validated.manifest.plugin.version), |
| 2474 | validated.content_hash, |
| 2475 | )) |
| 2476 | } |
| 2477 | PluginInstallSource::Dsh(_) => { |
| 2478 | match try_is_dsh_package(&dir) { |
| 2479 | Ok(true) => {} |
| 2480 | Ok(false) => { |
| 2481 | return Err(( |
| 2482 | "not-bundle", |
| 2483 | "not-bundle: source directory does not declare dsh.bundle".to_string(), |
| 2484 | )); |
| 2485 | } |
| 2486 | Err(error) => { |
| 2487 | return Err(("not-bundle", format!("not-bundle: {error:#}"))); |
| 2488 | } |
| 2489 | } |
| 2490 | let result = match network.as_ref() { |
| 2491 | Some(policy) => preview_dsh_with_network(&dir, policy), |
| 2492 | None => preview_dsh(&dir), |
| 2493 | }; |
| 2494 | let (conversion, hash) = result.map_err(|error| { |
| 2495 | let code = if error.downcast_ref::<NpmDepsNetworkError>().is_some() { |
| 2496 | "operation-error" |
| 2497 | } else { |
| 2498 | let msg = format!("{error:#}"); |
| 2499 | classify_error_message(&msg) |
| 2500 | }; |
| 2501 | (code, format!("{error:#}")) |
| 2502 | })?; |
| 2503 | Ok(( |
| 2504 | conversion.plugin_name, |
| 2505 | conversion.source_package, |
| 2506 | conversion.source_version.and_then(|v| non_empty_version(&v)), |
| 2507 | hash, |
| 2508 | )) |
| 2509 | } |
| 2510 | PluginInstallSource::Remote(_) => Err(("invalid-spec", "unexpected remote source".to_string())), |
| 2511 | } |
| 2512 | }) |
| 2513 | .await |
| 2514 | .map_err(|_| ("operation-error", "source preview task failed".to_string()))? |
| 2515 | } |
| 2516 | |
| 2517 | struct LocalAdmittedInstall { |
| 2518 | raw_target: String, |
| 2519 | parsed: PluginInstallSource, |
| 2520 | canon_source: PathBuf, |
| 2521 | is_dsh: bool, |
| 2522 | plugin_name: String, |
| 2523 | pre_hash: String, |
| 2524 | want_enabled: bool, |
| 2525 | expected_gate_target: String, |
| 2526 | shown_service_lines: Vec<String>, |
| 2527 | base_warnings: Vec<String>, |
| 2528 | registry_ignored: bool, |
| 2529 | } |
| 2530 | |
| 2531 | async fn install( |
| 2532 | call: &BrokerCall, |
| 2533 | tool: ToolContext, |
| 2534 | authority: Option<LiveRuntimeAuthority>, |
| 2535 | input: InstallInput, |
| 2536 | ) -> Result<Value, BrokerRefusal> { |
| 2537 | let raw_target = validate_required_str(&input.target, "target", MAX_TARGET_BYTES)?; |
| 2538 | let registry_opt = |
| 2539 | validate_optional_str(input.registry.as_deref(), "registry", MAX_REGISTRY_BYTES)?; |
| 2540 | let has_approved_builds = validate_approved_builds(input.approved_builds.as_deref())?; |
| 2541 | let initial_registry = live_registry(call, &tool)?; |
| 2542 | let Some(current_authority) = authority else { |
| 2543 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 2544 | }; |
| 2545 | let carrier = require_carried_decision(&tool, ¤t_authority, "install")?; |
| 2546 | |
| 2547 | let mut base_warnings = Vec::new(); |
| 2548 | let registry_ignored = registry_opt.is_some(); |
| 2549 | if registry_ignored { |
| 2550 | base_warnings.push( |
| 2551 | "registry was ignored; Codewhale installs from the configured source".to_string(), |
| 2552 | ); |
| 2553 | } |
| 2554 | if has_approved_builds { |
| 2555 | record_outcome(call, "install", None, None, None, "failed"); |
| 2556 | return change_with_outcome(ChangeOutcome { |
| 2557 | application: "failed", |
| 2558 | stage: "install", |
| 2559 | target: raw_target, |
| 2560 | changed: false, |
| 2561 | enabled: None, |
| 2562 | code: "stale-approval", |
| 2563 | diagnostic: |
| 2564 | "pending build approvals are not used here; call install again without approved_builds" |
| 2565 | .to_string(), |
| 2566 | bundle: None, |
| 2567 | version: None, |
| 2568 | warnings: base_warnings, |
| 2569 | }); |
| 2570 | } |
| 2571 | |
| 2572 | let parsed = match parse_install_target_syntax(&raw_target) { |
| 2573 | Ok(parsed) => parsed, |
| 2574 | Err((code, msg)) => { |
| 2575 | let scrub = ScrubContext { |
| 2576 | workspace: initial_registry.workspace(), |
| 2577 | canon_workspace: None, |
| 2578 | plugin_root: None, |
| 2579 | user_plugins_dir: initial_registry.user_plugins_dir(), |
| 2580 | state_path: initial_registry.state_path(), |
| 2581 | }; |
| 2582 | record_outcome(call, "install", None, None, None, "failed"); |
| 2583 | return change_with_outcome(ChangeOutcome { |
| 2584 | application: "failed", |
| 2585 | stage: "install", |
| 2586 | target: raw_target, |
| 2587 | changed: false, |
| 2588 | enabled: None, |
| 2589 | code, |
| 2590 | diagnostic: scrub_message(&msg, &scrub), |
| 2591 | bundle: None, |
| 2592 | version: None, |
| 2593 | warnings: base_warnings, |
| 2594 | }); |
| 2595 | } |
| 2596 | }; |
| 2597 | |
| 2598 | match carrier.change.clone() { |
| 2599 | AdmittedChangeKind::LocalInstall { |
| 2600 | raw_target: approved_target, |
| 2601 | canon_source, |
| 2602 | is_dsh, |
| 2603 | plugin_name, |
| 2604 | pre_hash, |
| 2605 | want_enabled, |
| 2606 | expected_gate_target, |
| 2607 | shown_service_lines, |
| 2608 | .. |
| 2609 | } => { |
| 2610 | if raw_target != approved_target || input.enabled != want_enabled { |
| 2611 | return Err(BrokerRefusal::Refused { |
| 2612 | service: DshService::Plugins, |
| 2613 | message: "plugin install input changed after approval".to_string(), |
| 2614 | }); |
| 2615 | } |
| 2616 | install_local_admitted( |
| 2617 | call, |
| 2618 | tool, |
| 2619 | initial_registry, |
| 2620 | carrier, |
| 2621 | LocalAdmittedInstall { |
| 2622 | raw_target, |
| 2623 | parsed, |
| 2624 | canon_source, |
| 2625 | is_dsh, |
| 2626 | plugin_name, |
| 2627 | pre_hash, |
| 2628 | want_enabled, |
| 2629 | expected_gate_target, |
| 2630 | shown_service_lines, |
| 2631 | base_warnings, |
| 2632 | registry_ignored, |
| 2633 | }, |
| 2634 | ) |
| 2635 | .await |
| 2636 | } |
| 2637 | AdmittedChangeKind::UnseenFetchInstall { |
| 2638 | raw_target: approved_spec, |
| 2639 | is_remote, |
| 2640 | canon_source, |
| 2641 | remote_label, |
| 2642 | remote_host, |
| 2643 | .. |
| 2644 | } => { |
| 2645 | if raw_target != approved_spec { |
| 2646 | return Err(BrokerRefusal::Refused { |
| 2647 | service: DshService::Plugins, |
| 2648 | message: "plugin install target changed after approval".to_string(), |
| 2649 | }); |
| 2650 | } |
| 2651 | if is_remote { |
| 2652 | install_remote_unseen( |
| 2653 | call, |
| 2654 | RemoteUnseenInstall { |
| 2655 | initial_registry, |
| 2656 | carrier, |
| 2657 | raw_target, |
| 2658 | parsed, |
| 2659 | remote_label, |
| 2660 | remote_host, |
| 2661 | base_warnings, |
| 2662 | registry_ignored, |
| 2663 | }, |
| 2664 | ) |
| 2665 | .await |
| 2666 | } else { |
| 2667 | install_local_dsh_unseen( |
| 2668 | call, |
| 2669 | LocalDshUnseenInstall { |
| 2670 | initial_registry, |
| 2671 | carrier, |
| 2672 | raw_target, |
| 2673 | parsed, |
| 2674 | canon_source, |
| 2675 | base_warnings, |
| 2676 | registry_ignored, |
| 2677 | }, |
| 2678 | ) |
| 2679 | .await |
| 2680 | } |
| 2681 | } |
| 2682 | _ => Err(BrokerRefusal::Refused { |
| 2683 | service: DshService::Plugins, |
| 2684 | message: "plugin change decision is not an install decision".to_string(), |
| 2685 | }), |
| 2686 | } |
| 2687 | } |
| 2688 | |
| 2689 | struct RemoteUnseenInstall { |
| 2690 | initial_registry: Arc<PluginRegistry>, |
| 2691 | carrier: CreatorDecisionCarrier, |
| 2692 | raw_target: String, |
| 2693 | parsed: PluginInstallSource, |
| 2694 | remote_label: String, |
| 2695 | remote_host: String, |
| 2696 | base_warnings: Vec<String>, |
| 2697 | registry_ignored: bool, |
| 2698 | } |
| 2699 | |
| 2700 | async fn install_remote_unseen( |
| 2701 | call: &BrokerCall, |
| 2702 | input: RemoteUnseenInstall, |
| 2703 | ) -> Result<Value, BrokerRefusal> { |
| 2704 | let RemoteUnseenInstall { |
| 2705 | initial_registry, |
| 2706 | carrier, |
| 2707 | raw_target, |
| 2708 | parsed, |
| 2709 | remote_label, |
| 2710 | remote_host, |
| 2711 | base_warnings, |
| 2712 | registry_ignored, |
| 2713 | } = input; |
| 2714 | if carrier.decider != CreatorDecider::Person { |
| 2715 | return Err(BrokerRefusal::Refused { |
| 2716 | service: DshService::Plugins, |
| 2717 | message: "remote plugin install requires a person's approval".to_string(), |
| 2718 | }); |
| 2719 | } |
| 2720 | let PluginInstallSource::Remote(remote_source) = parsed else { |
| 2721 | return Err(BrokerRefusal::Refused { |
| 2722 | service: DshService::Plugins, |
| 2723 | message: "plugin install target does not match the approved remote fetch".to_string(), |
| 2724 | }); |
| 2725 | }; |
| 2726 | let (label, host) = remote_target_display( |
| 2727 | &PluginInstallSource::Remote(remote_source.clone()), |
| 2728 | &raw_target, |
| 2729 | ); |
| 2730 | if label != remote_label || host != remote_host { |
| 2731 | return Err(BrokerRefusal::Refused { |
| 2732 | service: DshService::Plugins, |
| 2733 | message: "remote install host or spec changed after approval".to_string(), |
| 2734 | }); |
| 2735 | } |
| 2736 | |
| 2737 | let policy = extension_host_policy_enabled(); |
| 2738 | #[cfg(any(test, feature = "test-support"))] |
| 2739 | let env_scope = crate::test_support::env_scope_ticket(); |
| 2740 | let ws = initial_registry.workspace().to_path_buf(); |
| 2741 | let canon_workspace = tokio::fs::canonicalize(&ws).await.ok(); |
| 2742 | let scrub = ScrubContext { |
| 2743 | workspace: initial_registry.workspace(), |
| 2744 | canon_workspace: canon_workspace.as_deref(), |
| 2745 | plugin_root: None, |
| 2746 | user_plugins_dir: initial_registry.user_plugins_dir(), |
| 2747 | state_path: initial_registry.state_path(), |
| 2748 | }; |
| 2749 | |
| 2750 | let reach_target = format!("{label} from {host}"); |
| 2751 | call.context |
| 2752 | .act("install", BrokerEffect::Reach, Some(&reach_target)) |
| 2753 | .await?; |
| 2754 | |
| 2755 | if call.context.cancel().is_cancelled() { |
| 2756 | record_outcome(call, "install", Some(&label), None, None, "cancelled"); |
| 2757 | return cancelled_result("install", raw_target, None, None, base_warnings); |
| 2758 | } |
| 2759 | let mut tool = match check_live_after_act(call, &carrier) { |
| 2760 | CarrierLiveCheck::Valid(refreshed) => refreshed, |
| 2761 | CarrierLiveCheck::Unavailable => { |
| 2762 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 2763 | } |
| 2764 | CarrierLiveCheck::Narrowed => { |
| 2765 | record_outcome(call, "install", Some(&label), None, None, "failed"); |
| 2766 | return change_with_outcome(ChangeOutcome { |
| 2767 | application: "failed", |
| 2768 | stage: "install", |
| 2769 | target: raw_target, |
| 2770 | changed: false, |
| 2771 | enabled: None, |
| 2772 | code: "operation-error", |
| 2773 | diagnostic: |
| 2774 | "permission mode changed during review and no longer allows plugin installation" |
| 2775 | .to_string(), |
| 2776 | bundle: None, |
| 2777 | version: None, |
| 2778 | warnings: base_warnings, |
| 2779 | }); |
| 2780 | } |
| 2781 | }; |
| 2782 | |
| 2783 | let network = network_policy_for(&tool); |
| 2784 | let prepared_res = match download_remote_install_archive( |
| 2785 | remote_source, |
| 2786 | DEFAULT_MAX_SIZE_BYTES, |
| 2787 | &network, |
| 2788 | ) |
| 2789 | .await |
| 2790 | { |
| 2791 | Ok(RemoteDownloadOutcome::Downloaded { |
| 2792 | archive, |
| 2793 | has_npm_deps, |
| 2794 | }) => { |
| 2795 | let stage_network = if has_npm_deps { |
| 2796 | let npm_reach = format!("{label} npm dependencies from registry.npmjs.org"); |
| 2797 | call.context |
| 2798 | .act("install", BrokerEffect::Reach, Some(&npm_reach)) |
| 2799 | .await?; |
| 2800 | if call.context.cancel().is_cancelled() { |
| 2801 | record_outcome(call, "install", Some(&label), None, None, "cancelled"); |
| 2802 | return cancelled_result("install", raw_target, None, None, base_warnings); |
| 2803 | } |
| 2804 | match check_live_after_act(call, &carrier) { |
| 2805 | CarrierLiveCheck::Valid(refreshed) => tool = refreshed, |
| 2806 | CarrierLiveCheck::Unavailable => { |
| 2807 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 2808 | } |
| 2809 | CarrierLiveCheck::Narrowed => { |
| 2810 | record_outcome(call, "install", Some(&label), None, None, "failed"); |
| 2811 | return change_with_outcome(ChangeOutcome { |
| 2812 | application: "failed", |
| 2813 | stage: "install", |
| 2814 | target: raw_target, |
| 2815 | changed: false, |
| 2816 | enabled: None, |
| 2817 | code: "operation-error", |
| 2818 | diagnostic: |
| 2819 | "permission mode changed during review and no longer allows plugin installation" |
| 2820 | .to_string(), |
| 2821 | bundle: None, |
| 2822 | version: None, |
| 2823 | warnings: base_warnings, |
| 2824 | }); |
| 2825 | } |
| 2826 | } |
| 2827 | Some(network_policy_for(&tool)) |
| 2828 | } else { |
| 2829 | None |
| 2830 | }; |
| 2831 | match stage_downloaded_remote_install( |
| 2832 | archive, |
| 2833 | DEFAULT_MAX_SIZE_BYTES, |
| 2834 | stage_network.as_ref(), |
| 2835 | ) |
| 2836 | .await |
| 2837 | { |
| 2838 | Ok(RemotePreviewOutcome::Ready(prepared)) => Ok(prepared), |
| 2839 | Ok(RemotePreviewOutcome::NeedsApproval(blocked_host)) => Err(( |
| 2840 | "operation-error", |
| 2841 | format!("network approval required for {blocked_host}"), |
| 2842 | )), |
| 2843 | Ok(RemotePreviewOutcome::NetworkDenied(denied_host)) => Err(( |
| 2844 | "operation-error", |
| 2845 | format!("network access denied for {denied_host}"), |
| 2846 | )), |
| 2847 | Err(error) => Err(( |
| 2848 | classify_install_error(&error), |
| 2849 | scrub_message(&format!("{error:#}"), &scrub), |
| 2850 | )), |
| 2851 | } |
| 2852 | } |
| 2853 | Ok(RemoteDownloadOutcome::NeedsApproval(blocked_host)) => Err(( |
| 2854 | "operation-error", |
| 2855 | format!("network approval required for {blocked_host}"), |
| 2856 | )), |
| 2857 | Ok(RemoteDownloadOutcome::NetworkDenied(denied_host)) => Err(( |
| 2858 | "operation-error", |
| 2859 | format!("network access denied for {denied_host}"), |
| 2860 | )), |
| 2861 | Err(error) => Err(( |
| 2862 | classify_install_error(&error), |
| 2863 | scrub_message(&format!("{error:#}"), &scrub), |
| 2864 | )), |
| 2865 | }; |
| 2866 | |
| 2867 | let prepared = match prepared_res { |
| 2868 | Ok(prepared) => prepared, |
| 2869 | Err((code, msg)) => { |
| 2870 | record_outcome(call, "install", Some(&label), None, None, "failed"); |
| 2871 | return change_with_outcome(ChangeOutcome { |
| 2872 | application: "failed", |
| 2873 | stage: "install", |
| 2874 | target: raw_target, |
| 2875 | changed: false, |
| 2876 | enabled: None, |
| 2877 | code, |
| 2878 | diagnostic: msg, |
| 2879 | bundle: None, |
| 2880 | version: None, |
| 2881 | warnings: base_warnings, |
| 2882 | }); |
| 2883 | } |
| 2884 | }; |
| 2885 | |
| 2886 | let fresh_snapshot = Arc::clone(&initial_registry); |
| 2887 | let prepared_name = prepared.name.clone(); |
| 2888 | let pre_collision = tokio::task::spawn_blocking(move || { |
| 2889 | #[cfg(any(test, feature = "test-support"))] |
| 2890 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 2891 | let _scope = PolicyScope::propagate(policy); |
| 2892 | let fresh = fresh_snapshot.rediscover_for_workspace(fresh_snapshot.workspace()); |
| 2893 | fresh |
| 2894 | .get(&prepared_name) |
| 2895 | .map(|p| (p.name().to_string(), p.scope.as_str())) |
| 2896 | }) |
| 2897 | .await |
| 2898 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 2899 | if let Some((existing_name, scope)) = pre_collision { |
| 2900 | record_outcome( |
| 2901 | call, |
| 2902 | "install", |
| 2903 | Some(&existing_name), |
| 2904 | Some(&prepared.content_hash), |
| 2905 | None, |
| 2906 | "failed", |
| 2907 | ); |
| 2908 | return change_with_outcome(ChangeOutcome { |
| 2909 | application: "failed", |
| 2910 | stage: "install", |
| 2911 | target: raw_target, |
| 2912 | changed: false, |
| 2913 | enabled: None, |
| 2914 | code: "already-installed", |
| 2915 | diagnostic: format!( |
| 2916 | "plugin `{existing_name}` is already installed ({scope} scope); remove it first, then install" |
| 2917 | ), |
| 2918 | bundle: Some(existing_name), |
| 2919 | version: None, |
| 2920 | warnings: base_warnings, |
| 2921 | }); |
| 2922 | } |
| 2923 | |
| 2924 | let write_target = format!("{} {} {}", prepared.name, prepared.content_hash, raw_target); |
| 2925 | call.context |
| 2926 | .act("install", BrokerEffect::Write, Some(&write_target)) |
| 2927 | .await?; |
| 2928 | |
| 2929 | if call.context.cancel().is_cancelled() { |
| 2930 | record_outcome( |
| 2931 | call, |
| 2932 | "install", |
| 2933 | Some(&prepared.name), |
| 2934 | Some(&prepared.content_hash), |
| 2935 | None, |
| 2936 | "cancelled", |
| 2937 | ); |
| 2938 | return cancelled_result( |
| 2939 | "install", |
| 2940 | raw_target, |
| 2941 | Some(prepared.name), |
| 2942 | None, |
| 2943 | base_warnings, |
| 2944 | ); |
| 2945 | } |
| 2946 | match check_live_after_act(call, &carrier) { |
| 2947 | CarrierLiveCheck::Valid(refreshed) => tool = refreshed, |
| 2948 | CarrierLiveCheck::Unavailable => { |
| 2949 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 2950 | } |
| 2951 | CarrierLiveCheck::Narrowed => { |
| 2952 | record_outcome( |
| 2953 | call, |
| 2954 | "install", |
| 2955 | Some(&prepared.name), |
| 2956 | Some(&prepared.content_hash), |
| 2957 | None, |
| 2958 | "failed", |
| 2959 | ); |
| 2960 | return change_with_outcome(ChangeOutcome { |
| 2961 | application: "failed", |
| 2962 | stage: "install", |
| 2963 | target: raw_target, |
| 2964 | changed: false, |
| 2965 | enabled: None, |
| 2966 | code: "operation-error", |
| 2967 | diagnostic: |
| 2968 | "permission mode changed during review and no longer allows plugin installation" |
| 2969 | .to_string(), |
| 2970 | bundle: Some(prepared.name), |
| 2971 | version: None, |
| 2972 | warnings: base_warnings, |
| 2973 | }); |
| 2974 | } |
| 2975 | } |
| 2976 | |
| 2977 | let post_network = network_policy_for(&tool); |
| 2978 | let fresh_snapshot = Arc::clone(&initial_registry); |
| 2979 | let mut registry_for_exec = tokio::task::spawn_blocking(move || { |
| 2980 | #[cfg(any(test, feature = "test-support"))] |
| 2981 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 2982 | let _scope = PolicyScope::propagate(policy); |
| 2983 | (*fresh_snapshot.rediscover_for_workspace(fresh_snapshot.workspace())).clone() |
| 2984 | }) |
| 2985 | .await |
| 2986 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 2987 | |
| 2988 | let prepared_name_for_exec = prepared.name.clone(); |
| 2989 | let expected_hash = prepared.content_hash.clone(); |
| 2990 | let exec_result = execute( |
| 2991 | PluginMutationRequest::InstallRemoteExact { |
| 2992 | prepared, |
| 2993 | expected_content_hash: expected_hash.clone(), |
| 2994 | }, |
| 2995 | &PluginMutationContext { |
| 2996 | network: &post_network, |
| 2997 | max_size: DEFAULT_MAX_SIZE_BYTES, |
| 2998 | }, |
| 2999 | &mut registry_for_exec, |
| 3000 | ) |
| 3001 | .await; |
| 3002 | |
| 3003 | let receipt = match exec_result { |
| 3004 | Ok(receipt) => receipt, |
| 3005 | Err(error) => { |
| 3006 | let is_mismatch = error.downcast_ref::<PluginContentMismatch>().is_some() |
| 3007 | || error.downcast_ref::<PluginArchiveMismatch>().is_some(); |
| 3008 | let code = classify_install_error(&error); |
| 3009 | let msg = if is_mismatch { |
| 3010 | "changed after review".to_string() |
| 3011 | } else if code == "already-installed" { |
| 3012 | format!( |
| 3013 | "plugin `{prepared_name_for_exec}` is already installed; remove it first, then install" |
| 3014 | ) |
| 3015 | } else { |
| 3016 | scrub_message(&format!("{error:#}"), &scrub) |
| 3017 | }; |
| 3018 | record_outcome( |
| 3019 | call, |
| 3020 | "install", |
| 3021 | Some(&prepared_name_for_exec), |
| 3022 | Some(&expected_hash), |
| 3023 | None, |
| 3024 | "failed", |
| 3025 | ); |
| 3026 | return change_with_outcome(ChangeOutcome { |
| 3027 | application: "failed", |
| 3028 | stage: "install", |
| 3029 | target: raw_target, |
| 3030 | changed: false, |
| 3031 | enabled: None, |
| 3032 | code, |
| 3033 | diagnostic: msg, |
| 3034 | bundle: Some(prepared_name_for_exec), |
| 3035 | version: None, |
| 3036 | warnings: base_warnings, |
| 3037 | }); |
| 3038 | } |
| 3039 | }; |
| 3040 | |
| 3041 | match receipt.outcome { |
| 3042 | PluginMutationOutcome::NeedsApproval(blocked_host) => { |
| 3043 | record_outcome( |
| 3044 | call, |
| 3045 | "install", |
| 3046 | Some(&prepared_name_for_exec), |
| 3047 | Some(&expected_hash), |
| 3048 | None, |
| 3049 | "failed", |
| 3050 | ); |
| 3051 | return change_with_outcome(ChangeOutcome { |
| 3052 | application: "failed", |
| 3053 | stage: "install", |
| 3054 | target: raw_target, |
| 3055 | changed: false, |
| 3056 | enabled: None, |
| 3057 | code: "operation-error", |
| 3058 | diagnostic: format!("network approval required for {blocked_host}"), |
| 3059 | bundle: Some(prepared_name_for_exec), |
| 3060 | version: None, |
| 3061 | warnings: base_warnings, |
| 3062 | }); |
| 3063 | } |
| 3064 | PluginMutationOutcome::NetworkDenied(denied_host) => { |
| 3065 | record_outcome( |
| 3066 | call, |
| 3067 | "install", |
| 3068 | Some(&prepared_name_for_exec), |
| 3069 | Some(&expected_hash), |
| 3070 | None, |
| 3071 | "failed", |
| 3072 | ); |
| 3073 | return change_with_outcome(ChangeOutcome { |
| 3074 | application: "failed", |
| 3075 | stage: "install", |
| 3076 | target: raw_target, |
| 3077 | changed: false, |
| 3078 | enabled: None, |
| 3079 | code: "operation-error", |
| 3080 | diagnostic: format!("network access denied for {denied_host}"), |
| 3081 | bundle: Some(prepared_name_for_exec), |
| 3082 | version: None, |
| 3083 | warnings: base_warnings, |
| 3084 | }); |
| 3085 | } |
| 3086 | PluginMutationOutcome::Installed => {} |
| 3087 | _ => { |
| 3088 | record_outcome( |
| 3089 | call, |
| 3090 | "install", |
| 3091 | Some(&prepared_name_for_exec), |
| 3092 | Some(&expected_hash), |
| 3093 | None, |
| 3094 | "failed", |
| 3095 | ); |
| 3096 | return change_with_outcome(ChangeOutcome { |
| 3097 | application: "failed", |
| 3098 | stage: "install", |
| 3099 | target: raw_target, |
| 3100 | changed: false, |
| 3101 | enabled: None, |
| 3102 | code: "operation-error", |
| 3103 | diagnostic: "unexpected remote install outcome".to_string(), |
| 3104 | bundle: Some(prepared_name_for_exec), |
| 3105 | version: None, |
| 3106 | warnings: base_warnings, |
| 3107 | }); |
| 3108 | } |
| 3109 | } |
| 3110 | |
| 3111 | if let Some(installed_dir) = receipt.path.as_deref() { |
| 3112 | #[cfg(test)] |
| 3113 | fire_post_install_hook_for_test(installed_dir, call.context.cancel()); |
| 3114 | let _ = installed_dir; |
| 3115 | } |
| 3116 | let installed_hash = receipt.installed_content_hash.unwrap_or_default(); |
| 3117 | finish_post_install( |
| 3118 | call, |
| 3119 | PostInstallInput { |
| 3120 | reg_after_place: Arc::new(registry_for_exec), |
| 3121 | installed_name: receipt.name, |
| 3122 | expected_installed_hash: installed_hash, |
| 3123 | version: None, |
| 3124 | raw_target, |
| 3125 | want_enabled: false, |
| 3126 | warnings: base_warnings, |
| 3127 | carrier, |
| 3128 | shown_service_lines: Vec::new(), |
| 3129 | source_dir: None, |
| 3130 | canon_workspace, |
| 3131 | registry_ignored, |
| 3132 | }, |
| 3133 | ) |
| 3134 | .await |
| 3135 | } |
| 3136 | |
| 3137 | struct LocalDshUnseenInstall { |
| 3138 | initial_registry: Arc<PluginRegistry>, |
| 3139 | carrier: CreatorDecisionCarrier, |
| 3140 | raw_target: String, |
| 3141 | parsed: PluginInstallSource, |
| 3142 | canon_source: Option<PathBuf>, |
| 3143 | base_warnings: Vec<String>, |
| 3144 | registry_ignored: bool, |
| 3145 | } |
| 3146 | |
| 3147 | async fn install_local_dsh_unseen( |
| 3148 | call: &BrokerCall, |
| 3149 | input: LocalDshUnseenInstall, |
| 3150 | ) -> Result<Value, BrokerRefusal> { |
| 3151 | let LocalDshUnseenInstall { |
| 3152 | initial_registry, |
| 3153 | carrier, |
| 3154 | raw_target, |
| 3155 | parsed, |
| 3156 | canon_source, |
| 3157 | base_warnings, |
| 3158 | registry_ignored, |
| 3159 | } = input; |
| 3160 | if carrier.decider != CreatorDecider::Person { |
| 3161 | return Err(BrokerRefusal::Refused { |
| 3162 | service: DshService::Plugins, |
| 3163 | message: "DSH install with external npm dependencies requires a person's approval" |
| 3164 | .to_string(), |
| 3165 | }); |
| 3166 | } |
| 3167 | let (PluginInstallSource::LocalPath(dir_path) | PluginInstallSource::Dsh(dir_path)) = parsed |
| 3168 | else { |
| 3169 | return Err(BrokerRefusal::Refused { |
| 3170 | service: DshService::Plugins, |
| 3171 | message: "plugin install target does not match the approved folder".to_string(), |
| 3172 | }); |
| 3173 | }; |
| 3174 | |
| 3175 | let policy = extension_host_policy_enabled(); |
| 3176 | #[cfg(any(test, feature = "test-support"))] |
| 3177 | let env_scope = crate::test_support::env_scope_ticket(); |
| 3178 | let ancestor_bad = has_symlink_or_reparse_ancestor_or_target(&dir_path) |
| 3179 | .await |
| 3180 | .unwrap_or(true); |
| 3181 | if ancestor_bad || ensure_no_links_in_tree(&dir_path).await.is_err() { |
| 3182 | record_outcome(call, "install", None, None, None, "failed"); |
| 3183 | return change_with_outcome(ChangeOutcome { |
| 3184 | application: "failed", |
| 3185 | stage: "install", |
| 3186 | target: raw_target, |
| 3187 | changed: false, |
| 3188 | enabled: None, |
| 3189 | code: "operation-error", |
| 3190 | diagnostic: "symbolic links and reparse points are not allowed in plugin bundles" |
| 3191 | .to_string(), |
| 3192 | bundle: None, |
| 3193 | version: None, |
| 3194 | warnings: base_warnings, |
| 3195 | }); |
| 3196 | } |
| 3197 | |
| 3198 | let snap = Arc::clone(&initial_registry); |
| 3199 | let probe = dir_path.clone(); |
| 3200 | let (fresh, canon_ws, canon_actual, actual_is_dsh) = tokio::task::spawn_blocking(move || { |
| 3201 | #[cfg(any(test, feature = "test-support"))] |
| 3202 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 3203 | let _scope = PolicyScope::propagate(policy); |
| 3204 | let fresh = snap.rediscover_for_workspace(snap.workspace()); |
| 3205 | let canon_ws = std::fs::canonicalize(fresh.workspace()).ok(); |
| 3206 | let canon_actual = std::fs::canonicalize(&probe).ok(); |
| 3207 | let is_dsh = try_is_dsh_package(&probe).unwrap_or(false); |
| 3208 | (fresh, canon_ws, canon_actual, is_dsh) |
| 3209 | }) |
| 3210 | .await |
| 3211 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 3212 | |
| 3213 | if !actual_is_dsh |
| 3214 | || canon_source |
| 3215 | .as_ref() |
| 3216 | .is_some_and(|exp| canon_actual.as_ref() != Some(exp)) |
| 3217 | { |
| 3218 | record_outcome(call, "install", None, None, None, "failed"); |
| 3219 | return change_with_outcome(ChangeOutcome { |
| 3220 | application: "failed", |
| 3221 | stage: "install", |
| 3222 | target: raw_target, |
| 3223 | changed: false, |
| 3224 | enabled: None, |
| 3225 | code: "operation-error", |
| 3226 | diagnostic: "changed after review".to_string(), |
| 3227 | bundle: None, |
| 3228 | version: None, |
| 3229 | warnings: base_warnings, |
| 3230 | }); |
| 3231 | } |
| 3232 | |
| 3233 | let scrub = ScrubContext { |
| 3234 | workspace: fresh.workspace(), |
| 3235 | canon_workspace: canon_ws.as_deref(), |
| 3236 | plugin_root: Some(&dir_path), |
| 3237 | user_plugins_dir: fresh.user_plugins_dir(), |
| 3238 | state_path: fresh.state_path(), |
| 3239 | }; |
| 3240 | |
| 3241 | let reach_target = format!("{raw_target} npm dependencies from registry.npmjs.org"); |
| 3242 | call.context |
| 3243 | .act("install", BrokerEffect::Reach, Some(&reach_target)) |
| 3244 | .await?; |
| 3245 | |
| 3246 | if call.context.cancel().is_cancelled() { |
| 3247 | record_outcome(call, "install", None, None, None, "cancelled"); |
| 3248 | return cancelled_result("install", raw_target, None, None, base_warnings); |
| 3249 | } |
| 3250 | let tool = match check_live_after_act(call, &carrier) { |
| 3251 | CarrierLiveCheck::Valid(refreshed) => refreshed, |
| 3252 | CarrierLiveCheck::Unavailable => { |
| 3253 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 3254 | } |
| 3255 | CarrierLiveCheck::Narrowed => { |
| 3256 | record_outcome(call, "install", None, None, None, "failed"); |
| 3257 | return change_with_outcome(ChangeOutcome { |
| 3258 | application: "failed", |
| 3259 | stage: "install", |
| 3260 | target: raw_target, |
| 3261 | changed: false, |
| 3262 | enabled: None, |
| 3263 | code: "operation-error", |
| 3264 | diagnostic: |
| 3265 | "permission mode changed during review and no longer allows plugin installation" |
| 3266 | .to_string(), |
| 3267 | bundle: None, |
| 3268 | version: None, |
| 3269 | warnings: base_warnings, |
| 3270 | }); |
| 3271 | } |
| 3272 | }; |
| 3273 | |
| 3274 | let net = network_policy_for(&tool); |
| 3275 | let dsh_source = PluginInstallSource::Dsh(dir_path.clone()); |
| 3276 | let (plugin_name, source_package, version, pre_hash) = |
| 3277 | match prepare_local_source_and_hash_with_network(&dsh_source, &dir_path, Some(&net)).await { |
| 3278 | Ok(values) => values, |
| 3279 | Err((code, msg)) => { |
| 3280 | record_outcome(call, "install", None, None, None, "failed"); |
| 3281 | return change_with_outcome(ChangeOutcome { |
| 3282 | application: "failed", |
| 3283 | stage: "install", |
| 3284 | target: raw_target, |
| 3285 | changed: false, |
| 3286 | enabled: None, |
| 3287 | code, |
| 3288 | diagnostic: scrub_message(&msg, &scrub), |
| 3289 | bundle: None, |
| 3290 | version: None, |
| 3291 | warnings: base_warnings, |
| 3292 | }); |
| 3293 | } |
| 3294 | }; |
| 3295 | |
| 3296 | if let Some((existing_name, scope)) = check_local_collision( |
| 3297 | Arc::clone(&fresh), |
| 3298 | plugin_name.clone(), |
| 3299 | source_package.clone(), |
| 3300 | policy, |
| 3301 | #[cfg(any(test, feature = "test-support"))] |
| 3302 | env_scope, |
| 3303 | ) |
| 3304 | .await? |
| 3305 | { |
| 3306 | record_outcome( |
| 3307 | call, |
| 3308 | "install", |
| 3309 | Some(&existing_name), |
| 3310 | Some(&pre_hash), |
| 3311 | None, |
| 3312 | "failed", |
| 3313 | ); |
| 3314 | return change_with_outcome(ChangeOutcome { |
| 3315 | application: "failed", |
| 3316 | stage: "install", |
| 3317 | target: raw_target, |
| 3318 | changed: false, |
| 3319 | enabled: None, |
| 3320 | code: "already-installed", |
| 3321 | diagnostic: format!( |
| 3322 | "plugin `{existing_name}` is already installed ({scope} scope); remove it first, then install" |
| 3323 | ), |
| 3324 | bundle: Some(existing_name), |
| 3325 | version, |
| 3326 | warnings: base_warnings, |
| 3327 | }); |
| 3328 | } |
| 3329 | |
| 3330 | let gate_target = format!("{plugin_name} {pre_hash} {raw_target}"); |
| 3331 | call.context |
| 3332 | .act("install", BrokerEffect::Write, Some(&gate_target)) |
| 3333 | .await?; |
| 3334 | |
| 3335 | if call.context.cancel().is_cancelled() { |
| 3336 | record_outcome( |
| 3337 | call, |
| 3338 | "install", |
| 3339 | Some(&plugin_name), |
| 3340 | Some(&pre_hash), |
| 3341 | None, |
| 3342 | "cancelled", |
| 3343 | ); |
| 3344 | return cancelled_result( |
| 3345 | "install", |
| 3346 | raw_target, |
| 3347 | Some(plugin_name), |
| 3348 | version, |
| 3349 | base_warnings, |
| 3350 | ); |
| 3351 | } |
| 3352 | let tool = match check_live_after_act(call, &carrier) { |
| 3353 | CarrierLiveCheck::Valid(refreshed) => refreshed, |
| 3354 | CarrierLiveCheck::Unavailable => { |
| 3355 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 3356 | } |
| 3357 | CarrierLiveCheck::Narrowed => { |
| 3358 | record_outcome( |
| 3359 | call, |
| 3360 | "install", |
| 3361 | Some(&plugin_name), |
| 3362 | Some(&pre_hash), |
| 3363 | None, |
| 3364 | "failed", |
| 3365 | ); |
| 3366 | return change_with_outcome(ChangeOutcome { |
| 3367 | application: "failed", |
| 3368 | stage: "install", |
| 3369 | target: raw_target, |
| 3370 | changed: false, |
| 3371 | enabled: None, |
| 3372 | code: "operation-error", |
| 3373 | diagnostic: |
| 3374 | "permission mode changed during review and no longer allows plugin installation" |
| 3375 | .to_string(), |
| 3376 | bundle: Some(plugin_name), |
| 3377 | version, |
| 3378 | warnings: base_warnings, |
| 3379 | }); |
| 3380 | } |
| 3381 | }; |
| 3382 | |
| 3383 | let post_network = network_policy_for(&tool); |
| 3384 | if has_symlink_or_reparse_ancestor_or_target(&dir_path) |
| 3385 | .await |
| 3386 | .unwrap_or(true) |
| 3387 | || ensure_no_links_in_tree(&dir_path).await.is_err() |
| 3388 | { |
| 3389 | record_outcome( |
| 3390 | call, |
| 3391 | "install", |
| 3392 | Some(&plugin_name), |
| 3393 | Some(&pre_hash), |
| 3394 | None, |
| 3395 | "failed", |
| 3396 | ); |
| 3397 | return change_with_outcome(ChangeOutcome { |
| 3398 | application: "failed", |
| 3399 | stage: "install", |
| 3400 | target: raw_target, |
| 3401 | changed: false, |
| 3402 | enabled: None, |
| 3403 | code: "operation-error", |
| 3404 | diagnostic: "changed after review".to_string(), |
| 3405 | bundle: Some(plugin_name), |
| 3406 | version, |
| 3407 | warnings: base_warnings, |
| 3408 | }); |
| 3409 | } |
| 3410 | match prepare_local_source_and_hash_with_network(&dsh_source, &dir_path, Some(&post_network)) |
| 3411 | .await |
| 3412 | { |
| 3413 | Ok((cur_name, _, _, cur_hash)) if cur_name == plugin_name && cur_hash == pre_hash => {} |
| 3414 | Ok((_, _, _, cur_hash)) => { |
| 3415 | record_outcome( |
| 3416 | call, |
| 3417 | "install", |
| 3418 | Some(&plugin_name), |
| 3419 | Some(&cur_hash), |
| 3420 | None, |
| 3421 | "failed", |
| 3422 | ); |
| 3423 | return change_with_outcome(ChangeOutcome { |
| 3424 | application: "failed", |
| 3425 | stage: "install", |
| 3426 | target: raw_target, |
| 3427 | changed: false, |
| 3428 | enabled: None, |
| 3429 | code: "operation-error", |
| 3430 | diagnostic: "changed after review".to_string(), |
| 3431 | bundle: Some(plugin_name), |
| 3432 | version, |
| 3433 | warnings: base_warnings, |
| 3434 | }); |
| 3435 | } |
| 3436 | Err((code, msg)) => { |
| 3437 | record_outcome( |
| 3438 | call, |
| 3439 | "install", |
| 3440 | Some(&plugin_name), |
| 3441 | Some(&pre_hash), |
| 3442 | None, |
| 3443 | "failed", |
| 3444 | ); |
| 3445 | return change_with_outcome(ChangeOutcome { |
| 3446 | application: "failed", |
| 3447 | stage: "install", |
| 3448 | target: raw_target, |
| 3449 | changed: false, |
| 3450 | enabled: None, |
| 3451 | code, |
| 3452 | diagnostic: scrub_message(&msg, &scrub), |
| 3453 | bundle: Some(plugin_name), |
| 3454 | version, |
| 3455 | warnings: base_warnings, |
| 3456 | }); |
| 3457 | } |
| 3458 | } |
| 3459 | |
| 3460 | let snap2 = Arc::clone(&initial_registry); |
| 3461 | let fresh2 = tokio::task::spawn_blocking(move || { |
| 3462 | #[cfg(any(test, feature = "test-support"))] |
| 3463 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 3464 | let _scope = PolicyScope::propagate(policy); |
| 3465 | snap2.rediscover_for_workspace(snap2.workspace()) |
| 3466 | }) |
| 3467 | .await |
| 3468 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 3469 | |
| 3470 | if let Some((existing_name, scope)) = check_local_collision( |
| 3471 | Arc::clone(&fresh2), |
| 3472 | plugin_name.clone(), |
| 3473 | source_package, |
| 3474 | policy, |
| 3475 | #[cfg(any(test, feature = "test-support"))] |
| 3476 | env_scope, |
| 3477 | ) |
| 3478 | .await? |
| 3479 | { |
| 3480 | record_outcome( |
| 3481 | call, |
| 3482 | "install", |
| 3483 | Some(&existing_name), |
| 3484 | Some(&pre_hash), |
| 3485 | None, |
| 3486 | "failed", |
| 3487 | ); |
| 3488 | return change_with_outcome(ChangeOutcome { |
| 3489 | application: "failed", |
| 3490 | stage: "install", |
| 3491 | target: raw_target, |
| 3492 | changed: false, |
| 3493 | enabled: None, |
| 3494 | code: "already-installed", |
| 3495 | diagnostic: format!( |
| 3496 | "plugin `{existing_name}` is already installed ({scope} scope); remove it first, then install" |
| 3497 | ), |
| 3498 | bundle: Some(existing_name), |
| 3499 | version, |
| 3500 | warnings: base_warnings, |
| 3501 | }); |
| 3502 | } |
| 3503 | |
| 3504 | let mut reg_for_exec = (*fresh2).clone(); |
| 3505 | let exec_result = execute( |
| 3506 | PluginMutationRequest::InstallExact { |
| 3507 | source: dsh_source, |
| 3508 | expected_content_hash: pre_hash.clone(), |
| 3509 | }, |
| 3510 | &PluginMutationContext { |
| 3511 | network: &post_network, |
| 3512 | max_size: DEFAULT_MAX_SIZE_BYTES, |
| 3513 | }, |
| 3514 | &mut reg_for_exec, |
| 3515 | ) |
| 3516 | .await; |
| 3517 | |
| 3518 | let receipt = match unwrap_local_install_exec( |
| 3519 | call, |
| 3520 | LocalInstallExecCheck { |
| 3521 | exec_result, |
| 3522 | plugin_name: &plugin_name, |
| 3523 | pre_hash: &pre_hash, |
| 3524 | raw_target: &raw_target, |
| 3525 | version: &version, |
| 3526 | base_warnings: &base_warnings, |
| 3527 | scrub: &scrub, |
| 3528 | }, |
| 3529 | )? { |
| 3530 | Ok(receipt) => receipt, |
| 3531 | Err(failure) => return Ok(failure), |
| 3532 | }; |
| 3533 | |
| 3534 | if let Some(installed_dir) = receipt.path.as_deref() { |
| 3535 | #[cfg(test)] |
| 3536 | fire_post_install_hook_for_test(installed_dir, call.context.cancel()); |
| 3537 | let _ = installed_dir; |
| 3538 | } |
| 3539 | let installed_hash = receipt.installed_content_hash.unwrap_or_default(); |
| 3540 | finish_post_install( |
| 3541 | call, |
| 3542 | PostInstallInput { |
| 3543 | reg_after_place: Arc::new(reg_for_exec), |
| 3544 | installed_name: receipt.name, |
| 3545 | expected_installed_hash: installed_hash, |
| 3546 | version, |
| 3547 | raw_target, |
| 3548 | want_enabled: false, |
| 3549 | warnings: base_warnings, |
| 3550 | carrier, |
| 3551 | shown_service_lines: Vec::new(), |
| 3552 | source_dir: Some(dir_path), |
| 3553 | canon_workspace: canon_ws, |
| 3554 | registry_ignored, |
| 3555 | }, |
| 3556 | ) |
| 3557 | .await |
| 3558 | } |
| 3559 | |
| 3560 | async fn install_local_admitted( |
| 3561 | call: &BrokerCall, |
| 3562 | tool: ToolContext, |
| 3563 | initial_registry: Arc<PluginRegistry>, |
| 3564 | carrier: CreatorDecisionCarrier, |
| 3565 | admitted: LocalAdmittedInstall, |
| 3566 | ) -> Result<Value, BrokerRefusal> { |
| 3567 | let LocalAdmittedInstall { |
| 3568 | raw_target, |
| 3569 | parsed, |
| 3570 | canon_source, |
| 3571 | is_dsh, |
| 3572 | plugin_name, |
| 3573 | pre_hash, |
| 3574 | want_enabled, |
| 3575 | expected_gate_target, |
| 3576 | shown_service_lines, |
| 3577 | base_warnings, |
| 3578 | registry_ignored, |
| 3579 | } = admitted; |
| 3580 | let is_agent = matches!(carrier.decider, CreatorDecider::Agent(_)); |
| 3581 | if is_agent && !has_agent_call_identity(call, &tool) { |
| 3582 | record_outcome( |
| 3583 | call, |
| 3584 | "install", |
| 3585 | Some(&plugin_name), |
| 3586 | Some(&pre_hash), |
| 3587 | None, |
| 3588 | "failed", |
| 3589 | ); |
| 3590 | return change_with_outcome(ChangeOutcome { |
| 3591 | application: "failed", |
| 3592 | stage: "install", |
| 3593 | target: raw_target, |
| 3594 | changed: false, |
| 3595 | enabled: None, |
| 3596 | code: "operation-error", |
| 3597 | diagnostic: |
| 3598 | "An approval by the agent must name the thread, turn and tool call that made it" |
| 3599 | .to_string(), |
| 3600 | bundle: Some(plugin_name), |
| 3601 | version: None, |
| 3602 | warnings: base_warnings, |
| 3603 | }); |
| 3604 | } |
| 3605 | let explicit_dsh = matches!(&parsed, PluginInstallSource::Dsh(_)); |
| 3606 | let (PluginInstallSource::LocalPath(dir_path) | PluginInstallSource::Dsh(dir_path)) = parsed |
| 3607 | else { |
| 3608 | return Err(BrokerRefusal::Refused { |
| 3609 | service: DshService::Plugins, |
| 3610 | message: "plugin install target does not match the approved folder".to_string(), |
| 3611 | }); |
| 3612 | }; |
| 3613 | |
| 3614 | let policy = extension_host_policy_enabled(); |
| 3615 | #[cfg(any(test, feature = "test-support"))] |
| 3616 | let env_scope = crate::test_support::env_scope_ticket(); |
| 3617 | let ancestor_clean = !has_symlink_or_reparse_ancestor_or_target(&dir_path) |
| 3618 | .await |
| 3619 | .unwrap_or(true); |
| 3620 | let tree_clean = ensure_no_links_in_tree(&dir_path).await.is_ok(); |
| 3621 | let snap = Arc::clone(&initial_registry); |
| 3622 | let probe = dir_path.clone(); |
| 3623 | let ( |
| 3624 | fresh, |
| 3625 | canon_ws, |
| 3626 | in_project, |
| 3627 | user_plugins_dir, |
| 3628 | canon_actual, |
| 3629 | parsed_refined, |
| 3630 | actual_is_dsh, |
| 3631 | has_npm, |
| 3632 | ) = tokio::task::spawn_blocking(move || { |
| 3633 | #[cfg(any(test, feature = "test-support"))] |
| 3634 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 3635 | let _scope = PolicyScope::propagate(policy); |
| 3636 | let fresh = snap.rediscover_for_workspace(snap.workspace()); |
| 3637 | let canon_ws = std::fs::canonicalize(fresh.workspace()).ok(); |
| 3638 | let in_project = clean_dir_is_strictly_inside(&probe, fresh.workspace()); |
| 3639 | let user_plugins_dir = fresh.user_plugins_dir().map(Path::to_path_buf); |
| 3640 | let canon_actual = std::fs::canonicalize(&probe).ok(); |
| 3641 | let actual_dsh = if explicit_dsh { |
| 3642 | true |
| 3643 | } else { |
| 3644 | try_is_dsh_package(&probe).unwrap_or(false) |
| 3645 | }; |
| 3646 | let refined = if actual_dsh { |
| 3647 | PluginInstallSource::Dsh(probe.clone()) |
| 3648 | } else { |
| 3649 | PluginInstallSource::LocalPath(probe.clone()) |
| 3650 | }; |
| 3651 | let has_npm = actual_dsh && has_unresolved_npm_dependencies(&probe).unwrap_or(true); |
| 3652 | ( |
| 3653 | fresh, |
| 3654 | canon_ws, |
| 3655 | in_project, |
| 3656 | user_plugins_dir, |
| 3657 | canon_actual, |
| 3658 | refined, |
| 3659 | actual_dsh, |
| 3660 | has_npm, |
| 3661 | ) |
| 3662 | }) |
| 3663 | .await |
| 3664 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 3665 | |
| 3666 | let in_user_plugins = dir_is_in_user_plugins(&dir_path, user_plugins_dir.as_deref()).await; |
| 3667 | let is_own = in_project && ancestor_clean && !in_user_plugins; |
| 3668 | if is_agent && !is_own { |
| 3669 | record_outcome( |
| 3670 | call, |
| 3671 | "install", |
| 3672 | Some(&plugin_name), |
| 3673 | Some(&pre_hash), |
| 3674 | None, |
| 3675 | "failed", |
| 3676 | ); |
| 3677 | return change_with_outcome(ChangeOutcome { |
| 3678 | application: "failed", |
| 3679 | stage: "install", |
| 3680 | target: raw_target, |
| 3681 | changed: false, |
| 3682 | enabled: None, |
| 3683 | code: "operation-error", |
| 3684 | diagnostic: format!( |
| 3685 | "source folder is outside this project, inside user plugins, under .git, or reached through a link; {ASK_PERSON_HINT}" |
| 3686 | ), |
| 3687 | bundle: Some(plugin_name), |
| 3688 | version: None, |
| 3689 | warnings: base_warnings, |
| 3690 | }); |
| 3691 | } |
| 3692 | if !ancestor_clean |
| 3693 | || !tree_clean |
| 3694 | || canon_actual.as_ref() != Some(&canon_source) |
| 3695 | || actual_is_dsh != is_dsh |
| 3696 | || has_npm |
| 3697 | { |
| 3698 | record_outcome( |
| 3699 | call, |
| 3700 | "install", |
| 3701 | Some(&plugin_name), |
| 3702 | Some(&pre_hash), |
| 3703 | None, |
| 3704 | "failed", |
| 3705 | ); |
| 3706 | return change_with_outcome(ChangeOutcome { |
| 3707 | application: "failed", |
| 3708 | stage: "install", |
| 3709 | target: raw_target, |
| 3710 | changed: false, |
| 3711 | enabled: None, |
| 3712 | code: "operation-error", |
| 3713 | diagnostic: "changed after review".to_string(), |
| 3714 | bundle: Some(plugin_name), |
| 3715 | version: None, |
| 3716 | warnings: base_warnings, |
| 3717 | }); |
| 3718 | } |
| 3719 | |
| 3720 | let scrub = ScrubContext { |
| 3721 | workspace: fresh.workspace(), |
| 3722 | canon_workspace: canon_ws.as_deref(), |
| 3723 | plugin_root: Some(&dir_path), |
| 3724 | user_plugins_dir: fresh.user_plugins_dir(), |
| 3725 | state_path: fresh.state_path(), |
| 3726 | }; |
| 3727 | let (source_package, version) = |
| 3728 | match prepare_local_source_and_hash_with_network(&parsed_refined, &dir_path, None).await { |
| 3729 | Ok((cur_name, spkg, ver, cur_hash)) |
| 3730 | if cur_name == plugin_name && cur_hash == pre_hash => |
| 3731 | { |
| 3732 | (spkg, ver) |
| 3733 | } |
| 3734 | Ok((_, _, ver, cur_hash)) => { |
| 3735 | record_outcome( |
| 3736 | call, |
| 3737 | "install", |
| 3738 | Some(&plugin_name), |
| 3739 | Some(&cur_hash), |
| 3740 | None, |
| 3741 | "failed", |
| 3742 | ); |
| 3743 | return change_with_outcome(ChangeOutcome { |
| 3744 | application: "failed", |
| 3745 | stage: "install", |
| 3746 | target: raw_target, |
| 3747 | changed: false, |
| 3748 | enabled: None, |
| 3749 | code: "operation-error", |
| 3750 | diagnostic: "changed after review".to_string(), |
| 3751 | bundle: Some(plugin_name), |
| 3752 | version: ver, |
| 3753 | warnings: base_warnings, |
| 3754 | }); |
| 3755 | } |
| 3756 | Err(_) => { |
| 3757 | record_outcome( |
| 3758 | call, |
| 3759 | "install", |
| 3760 | Some(&plugin_name), |
| 3761 | Some(&pre_hash), |
| 3762 | None, |
| 3763 | "failed", |
| 3764 | ); |
| 3765 | return change_with_outcome(ChangeOutcome { |
| 3766 | application: "failed", |
| 3767 | stage: "install", |
| 3768 | target: raw_target, |
| 3769 | changed: false, |
| 3770 | enabled: None, |
| 3771 | code: "operation-error", |
| 3772 | diagnostic: "changed after review".to_string(), |
| 3773 | bundle: Some(plugin_name), |
| 3774 | version: None, |
| 3775 | warnings: base_warnings, |
| 3776 | }); |
| 3777 | } |
| 3778 | }; |
| 3779 | |
| 3780 | if let Some((existing_name, scope)) = check_local_collision( |
| 3781 | Arc::clone(&fresh), |
| 3782 | plugin_name.clone(), |
| 3783 | source_package.clone(), |
| 3784 | policy, |
| 3785 | #[cfg(any(test, feature = "test-support"))] |
| 3786 | env_scope, |
| 3787 | ) |
| 3788 | .await? |
| 3789 | { |
| 3790 | record_outcome( |
| 3791 | call, |
| 3792 | "install", |
| 3793 | Some(&existing_name), |
| 3794 | Some(&pre_hash), |
| 3795 | None, |
| 3796 | "failed", |
| 3797 | ); |
| 3798 | return change_with_outcome(ChangeOutcome { |
| 3799 | application: "failed", |
| 3800 | stage: "install", |
| 3801 | target: raw_target, |
| 3802 | changed: false, |
| 3803 | enabled: None, |
| 3804 | code: "already-installed", |
| 3805 | diagnostic: format!( |
| 3806 | "plugin `{existing_name}` is already installed ({scope} scope); remove it first, then install" |
| 3807 | ), |
| 3808 | bundle: Some(existing_name), |
| 3809 | version, |
| 3810 | warnings: base_warnings, |
| 3811 | }); |
| 3812 | } |
| 3813 | |
| 3814 | call.context |
| 3815 | .act("install", BrokerEffect::Write, Some(&expected_gate_target)) |
| 3816 | .await?; |
| 3817 | |
| 3818 | if call.context.cancel().is_cancelled() { |
| 3819 | record_outcome( |
| 3820 | call, |
| 3821 | "install", |
| 3822 | Some(&plugin_name), |
| 3823 | Some(&pre_hash), |
| 3824 | None, |
| 3825 | "cancelled", |
| 3826 | ); |
| 3827 | return cancelled_result( |
| 3828 | "install", |
| 3829 | raw_target, |
| 3830 | Some(plugin_name), |
| 3831 | version, |
| 3832 | base_warnings, |
| 3833 | ); |
| 3834 | } |
| 3835 | let tool = match check_live_after_act(call, &carrier) { |
| 3836 | CarrierLiveCheck::Valid(refreshed) => refreshed, |
| 3837 | CarrierLiveCheck::Unavailable => { |
| 3838 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 3839 | } |
| 3840 | CarrierLiveCheck::Narrowed => { |
| 3841 | record_outcome( |
| 3842 | call, |
| 3843 | "install", |
| 3844 | Some(&plugin_name), |
| 3845 | Some(&pre_hash), |
| 3846 | None, |
| 3847 | "failed", |
| 3848 | ); |
| 3849 | return change_with_outcome(ChangeOutcome { |
| 3850 | application: "failed", |
| 3851 | stage: "install", |
| 3852 | target: raw_target, |
| 3853 | changed: false, |
| 3854 | enabled: None, |
| 3855 | code: "operation-error", |
| 3856 | diagnostic: |
| 3857 | "permission mode changed during review and no longer allows plugin installation" |
| 3858 | .to_string(), |
| 3859 | bundle: Some(plugin_name), |
| 3860 | version, |
| 3861 | warnings: base_warnings, |
| 3862 | }); |
| 3863 | } |
| 3864 | }; |
| 3865 | if is_agent && !has_agent_call_identity(call, &tool) { |
| 3866 | record_outcome( |
| 3867 | call, |
| 3868 | "install", |
| 3869 | Some(&plugin_name), |
| 3870 | Some(&pre_hash), |
| 3871 | None, |
| 3872 | "failed", |
| 3873 | ); |
| 3874 | return change_with_outcome(ChangeOutcome { |
| 3875 | application: "failed", |
| 3876 | stage: "install", |
| 3877 | target: raw_target, |
| 3878 | changed: false, |
| 3879 | enabled: None, |
| 3880 | code: "operation-error", |
| 3881 | diagnostic: |
| 3882 | "An approval by the agent must name the thread, turn and tool call that made it" |
| 3883 | .to_string(), |
| 3884 | bundle: Some(plugin_name), |
| 3885 | version, |
| 3886 | warnings: base_warnings, |
| 3887 | }); |
| 3888 | } |
| 3889 | |
| 3890 | let ancestor_clean2 = !has_symlink_or_reparse_ancestor_or_target(&dir_path) |
| 3891 | .await |
| 3892 | .unwrap_or(true); |
| 3893 | let tree_clean2 = ensure_no_links_in_tree(&dir_path).await.is_ok(); |
| 3894 | let snap2 = Arc::clone(&initial_registry); |
| 3895 | let probe2 = dir_path.clone(); |
| 3896 | let (fresh2, canon_ws2, in_project2, user_plugins_dir2, canon_actual2, has_npm2) = |
| 3897 | tokio::task::spawn_blocking(move || { |
| 3898 | #[cfg(any(test, feature = "test-support"))] |
| 3899 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 3900 | let _scope = PolicyScope::propagate(policy); |
| 3901 | let fresh = snap2.rediscover_for_workspace(snap2.workspace()); |
| 3902 | let canon_ws = std::fs::canonicalize(fresh.workspace()).ok(); |
| 3903 | let in_project = clean_dir_is_strictly_inside(&probe2, fresh.workspace()); |
| 3904 | let user_plugins_dir = fresh.user_plugins_dir().map(Path::to_path_buf); |
| 3905 | let canon_actual = std::fs::canonicalize(&probe2).ok(); |
| 3906 | let has_npm = is_dsh && has_unresolved_npm_dependencies(&probe2).unwrap_or(true); |
| 3907 | ( |
| 3908 | fresh, |
| 3909 | canon_ws, |
| 3910 | in_project, |
| 3911 | user_plugins_dir, |
| 3912 | canon_actual, |
| 3913 | has_npm, |
| 3914 | ) |
| 3915 | }) |
| 3916 | .await |
| 3917 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 3918 | let in_user_plugins2 = dir_is_in_user_plugins(&dir_path, user_plugins_dir2.as_deref()).await; |
| 3919 | let still_own = in_project2 && ancestor_clean2 && !in_user_plugins2; |
| 3920 | let effective_canon_ws = canon_ws.as_ref().or(canon_ws2.as_ref()).cloned(); |
| 3921 | |
| 3922 | if is_agent && !still_own { |
| 3923 | record_outcome( |
| 3924 | call, |
| 3925 | "install", |
| 3926 | Some(&plugin_name), |
| 3927 | Some(&pre_hash), |
| 3928 | None, |
| 3929 | "failed", |
| 3930 | ); |
| 3931 | return change_with_outcome(ChangeOutcome { |
| 3932 | application: "failed", |
| 3933 | stage: "install", |
| 3934 | target: raw_target, |
| 3935 | changed: false, |
| 3936 | enabled: None, |
| 3937 | code: "operation-error", |
| 3938 | diagnostic: format!( |
| 3939 | "source folder is no longer cleanly inside this project; {ASK_PERSON_HINT}" |
| 3940 | ), |
| 3941 | bundle: Some(plugin_name), |
| 3942 | version, |
| 3943 | warnings: base_warnings, |
| 3944 | }); |
| 3945 | } |
| 3946 | if !ancestor_clean2 || !tree_clean2 || canon_actual2.as_ref() != Some(&canon_source) || has_npm2 |
| 3947 | { |
| 3948 | record_outcome( |
| 3949 | call, |
| 3950 | "install", |
| 3951 | Some(&plugin_name), |
| 3952 | Some(&pre_hash), |
| 3953 | None, |
| 3954 | "failed", |
| 3955 | ); |
| 3956 | return change_with_outcome(ChangeOutcome { |
| 3957 | application: "failed", |
| 3958 | stage: "install", |
| 3959 | target: raw_target, |
| 3960 | changed: false, |
| 3961 | enabled: None, |
| 3962 | code: "operation-error", |
| 3963 | diagnostic: "changed after review".to_string(), |
| 3964 | bundle: Some(plugin_name), |
| 3965 | version, |
| 3966 | warnings: base_warnings, |
| 3967 | }); |
| 3968 | } |
| 3969 | |
| 3970 | match prepare_local_source_and_hash_with_network(&parsed_refined, &dir_path, None).await { |
| 3971 | Ok((cur_name, _, _, cur_hash)) if cur_name == plugin_name && cur_hash == pre_hash => {} |
| 3972 | _ => { |
| 3973 | record_outcome( |
| 3974 | call, |
| 3975 | "install", |
| 3976 | Some(&plugin_name), |
| 3977 | Some(&pre_hash), |
| 3978 | None, |
| 3979 | "failed", |
| 3980 | ); |
| 3981 | return change_with_outcome(ChangeOutcome { |
| 3982 | application: "failed", |
| 3983 | stage: "install", |
| 3984 | target: raw_target, |
| 3985 | changed: false, |
| 3986 | enabled: None, |
| 3987 | code: "operation-error", |
| 3988 | diagnostic: "changed after review".to_string(), |
| 3989 | bundle: Some(plugin_name), |
| 3990 | version, |
| 3991 | warnings: base_warnings, |
| 3992 | }); |
| 3993 | } |
| 3994 | } |
| 3995 | |
| 3996 | if let Some((existing_name, scope)) = check_local_collision( |
| 3997 | Arc::clone(&fresh2), |
| 3998 | plugin_name.clone(), |
| 3999 | source_package, |
| 4000 | policy, |
| 4001 | #[cfg(any(test, feature = "test-support"))] |
| 4002 | env_scope, |
| 4003 | ) |
| 4004 | .await? |
| 4005 | { |
| 4006 | record_outcome( |
| 4007 | call, |
| 4008 | "install", |
| 4009 | Some(&existing_name), |
| 4010 | Some(&pre_hash), |
| 4011 | None, |
| 4012 | "failed", |
| 4013 | ); |
| 4014 | return change_with_outcome(ChangeOutcome { |
| 4015 | application: "failed", |
| 4016 | stage: "install", |
| 4017 | target: raw_target, |
| 4018 | changed: false, |
| 4019 | enabled: None, |
| 4020 | code: "already-installed", |
| 4021 | diagnostic: format!( |
| 4022 | "plugin `{existing_name}` is already installed ({scope} scope); remove it first, then install" |
| 4023 | ), |
| 4024 | bundle: Some(existing_name), |
| 4025 | version, |
| 4026 | warnings: base_warnings, |
| 4027 | }); |
| 4028 | } |
| 4029 | |
| 4030 | if call.context.cancel().is_cancelled() { |
| 4031 | record_outcome( |
| 4032 | call, |
| 4033 | "install", |
| 4034 | Some(&plugin_name), |
| 4035 | Some(&pre_hash), |
| 4036 | None, |
| 4037 | "cancelled", |
| 4038 | ); |
| 4039 | return cancelled_result( |
| 4040 | "install", |
| 4041 | raw_target, |
| 4042 | Some(plugin_name), |
| 4043 | version, |
| 4044 | base_warnings, |
| 4045 | ); |
| 4046 | } |
| 4047 | |
| 4048 | let exec_network = NetworkPolicy::default(); |
| 4049 | let mut reg_for_exec = (*fresh2).clone(); |
| 4050 | let exec_result = execute( |
| 4051 | PluginMutationRequest::InstallExact { |
| 4052 | source: parsed_refined, |
| 4053 | expected_content_hash: pre_hash.clone(), |
| 4054 | }, |
| 4055 | &PluginMutationContext { |
| 4056 | network: &exec_network, |
| 4057 | max_size: DEFAULT_MAX_SIZE_BYTES, |
| 4058 | }, |
| 4059 | &mut reg_for_exec, |
| 4060 | ) |
| 4061 | .await; |
| 4062 | |
| 4063 | let receipt = match unwrap_local_install_exec( |
| 4064 | call, |
| 4065 | LocalInstallExecCheck { |
| 4066 | exec_result, |
| 4067 | plugin_name: &plugin_name, |
| 4068 | pre_hash: &pre_hash, |
| 4069 | raw_target: &raw_target, |
| 4070 | version: &version, |
| 4071 | base_warnings: &base_warnings, |
| 4072 | scrub: &scrub, |
| 4073 | }, |
| 4074 | )? { |
| 4075 | Ok(receipt) => receipt, |
| 4076 | Err(failure) => return Ok(failure), |
| 4077 | }; |
| 4078 | |
| 4079 | if let Some(installed_dir) = receipt.path.as_deref() { |
| 4080 | #[cfg(test)] |
| 4081 | fire_post_install_hook_for_test(installed_dir, call.context.cancel()); |
| 4082 | let _ = installed_dir; |
| 4083 | } |
| 4084 | let installed_hash = receipt.installed_content_hash.unwrap_or_default(); |
| 4085 | finish_post_install( |
| 4086 | call, |
| 4087 | PostInstallInput { |
| 4088 | reg_after_place: Arc::new(reg_for_exec), |
| 4089 | installed_name: receipt.name, |
| 4090 | expected_installed_hash: installed_hash, |
| 4091 | version, |
| 4092 | raw_target, |
| 4093 | want_enabled, |
| 4094 | warnings: base_warnings, |
| 4095 | carrier, |
| 4096 | shown_service_lines, |
| 4097 | source_dir: Some(dir_path), |
| 4098 | canon_workspace: effective_canon_ws, |
| 4099 | registry_ignored, |
| 4100 | }, |
| 4101 | ) |
| 4102 | .await |
| 4103 | } |
| 4104 | |
| 4105 | async fn check_local_collision( |
| 4106 | fresh_ref: Arc<PluginRegistry>, |
| 4107 | pname: String, |
| 4108 | spkg: Option<String>, |
| 4109 | policy: bool, |
| 4110 | #[cfg(any(test, feature = "test-support"))] env_scope: Option< |
| 4111 | crate::test_support::EnvScopeTicket, |
| 4112 | >, |
| 4113 | ) -> Result<Option<(String, &'static str)>, BrokerRefusal> { |
| 4114 | tokio::task::spawn_blocking(move || { |
| 4115 | #[cfg(any(test, feature = "test-support"))] |
| 4116 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 4117 | let _scope = PolicyScope::propagate(policy); |
| 4118 | if let Some(p) = fresh_ref.get(&pname) { |
| 4119 | return Some((p.name().to_string(), p.scope.as_str())); |
| 4120 | } |
| 4121 | if let Some(pkg) = spkg.as_deref() { |
| 4122 | match resolve_plugin_by_target(&fresh_ref, pkg) { |
| 4123 | TargetLookup::Found(p) => { |
| 4124 | return Some((p.name().to_string(), p.scope.as_str())); |
| 4125 | } |
| 4126 | TargetLookup::Ambiguous { first, .. } => { |
| 4127 | return Some((first.name().to_string(), first.scope.as_str())); |
| 4128 | } |
| 4129 | TargetLookup::Missing => {} |
| 4130 | } |
| 4131 | } |
| 4132 | None |
| 4133 | }) |
| 4134 | .await |
| 4135 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins)) |
| 4136 | } |
| 4137 | |
| 4138 | struct LocalInstallExecCheck<'a> { |
| 4139 | exec_result: anyhow::Result<codewhale_plugins::mutation::PluginMutationReceipt>, |
| 4140 | plugin_name: &'a str, |
| 4141 | pre_hash: &'a str, |
| 4142 | raw_target: &'a str, |
| 4143 | version: &'a Option<String>, |
| 4144 | base_warnings: &'a [String], |
| 4145 | scrub: &'a ScrubContext<'a>, |
| 4146 | } |
| 4147 | |
| 4148 | fn unwrap_local_install_exec( |
| 4149 | call: &BrokerCall, |
| 4150 | input: LocalInstallExecCheck<'_>, |
| 4151 | ) -> Result<Result<codewhale_plugins::mutation::PluginMutationReceipt, Value>, BrokerRefusal> { |
| 4152 | let LocalInstallExecCheck { |
| 4153 | exec_result, |
| 4154 | plugin_name, |
| 4155 | pre_hash, |
| 4156 | raw_target, |
| 4157 | version, |
| 4158 | base_warnings, |
| 4159 | scrub, |
| 4160 | } = input; |
| 4161 | let receipt = match exec_result { |
| 4162 | Ok(receipt) => receipt, |
| 4163 | Err(error) => { |
| 4164 | let is_mismatch = error.downcast_ref::<PluginContentMismatch>().is_some() |
| 4165 | || error.downcast_ref::<PluginArchiveMismatch>().is_some(); |
| 4166 | let code = classify_install_error(&error); |
| 4167 | let msg = if is_mismatch { |
| 4168 | "changed after review".to_string() |
| 4169 | } else if code == "already-installed" { |
| 4170 | format!( |
| 4171 | "plugin `{plugin_name}` is already installed; remove it first, then install" |
| 4172 | ) |
| 4173 | } else { |
| 4174 | scrub_message(&format!("{error:#}"), scrub) |
| 4175 | }; |
| 4176 | record_outcome( |
| 4177 | call, |
| 4178 | "install", |
| 4179 | Some(plugin_name), |
| 4180 | Some(pre_hash), |
| 4181 | None, |
| 4182 | "failed", |
| 4183 | ); |
| 4184 | return Ok(Err(change_with_outcome(ChangeOutcome { |
| 4185 | application: "failed", |
| 4186 | stage: "install", |
| 4187 | target: raw_target.to_string(), |
| 4188 | changed: false, |
| 4189 | enabled: None, |
| 4190 | code, |
| 4191 | diagnostic: msg, |
| 4192 | bundle: Some(plugin_name.to_string()), |
| 4193 | version: version.clone(), |
| 4194 | warnings: base_warnings.to_vec(), |
| 4195 | })?)); |
| 4196 | } |
| 4197 | }; |
| 4198 | |
| 4199 | match receipt.outcome { |
| 4200 | PluginMutationOutcome::NeedsApproval(blocked_host) => { |
| 4201 | record_outcome( |
| 4202 | call, |
| 4203 | "install", |
| 4204 | Some(plugin_name), |
| 4205 | Some(pre_hash), |
| 4206 | None, |
| 4207 | "failed", |
| 4208 | ); |
| 4209 | Ok(Err(change_with_outcome(ChangeOutcome { |
| 4210 | application: "failed", |
| 4211 | stage: "install", |
| 4212 | target: raw_target.to_string(), |
| 4213 | changed: false, |
| 4214 | enabled: None, |
| 4215 | code: "operation-error", |
| 4216 | diagnostic: format!("network approval required for {blocked_host}"), |
| 4217 | bundle: Some(plugin_name.to_string()), |
| 4218 | version: version.clone(), |
| 4219 | warnings: base_warnings.to_vec(), |
| 4220 | })?)) |
| 4221 | } |
| 4222 | PluginMutationOutcome::NetworkDenied(denied_host) => { |
| 4223 | record_outcome( |
| 4224 | call, |
| 4225 | "install", |
| 4226 | Some(plugin_name), |
| 4227 | Some(pre_hash), |
| 4228 | None, |
| 4229 | "failed", |
| 4230 | ); |
| 4231 | Ok(Err(change_with_outcome(ChangeOutcome { |
| 4232 | application: "failed", |
| 4233 | stage: "install", |
| 4234 | target: raw_target.to_string(), |
| 4235 | changed: false, |
| 4236 | enabled: None, |
| 4237 | code: "operation-error", |
| 4238 | diagnostic: format!("network access denied for {denied_host}"), |
| 4239 | bundle: Some(plugin_name.to_string()), |
| 4240 | version: version.clone(), |
| 4241 | warnings: base_warnings.to_vec(), |
| 4242 | })?)) |
| 4243 | } |
| 4244 | PluginMutationOutcome::Installed => Ok(Ok(receipt)), |
| 4245 | _ => { |
| 4246 | record_outcome( |
| 4247 | call, |
| 4248 | "install", |
| 4249 | Some(plugin_name), |
| 4250 | Some(pre_hash), |
| 4251 | None, |
| 4252 | "failed", |
| 4253 | ); |
| 4254 | Ok(Err(change_with_outcome(ChangeOutcome { |
| 4255 | application: "failed", |
| 4256 | stage: "install", |
| 4257 | target: raw_target.to_string(), |
| 4258 | changed: false, |
| 4259 | enabled: None, |
| 4260 | code: "operation-error", |
| 4261 | diagnostic: "unexpected local install outcome".to_string(), |
| 4262 | bundle: Some(plugin_name.to_string()), |
| 4263 | version: version.clone(), |
| 4264 | warnings: base_warnings.to_vec(), |
| 4265 | })?)) |
| 4266 | } |
| 4267 | } |
| 4268 | } |
| 4269 | |
| 4270 | struct PostInstallInput { |
| 4271 | reg_after_place: Arc<PluginRegistry>, |
| 4272 | installed_name: String, |
| 4273 | expected_installed_hash: String, |
| 4274 | version: Option<String>, |
| 4275 | raw_target: String, |
| 4276 | want_enabled: bool, |
| 4277 | warnings: Vec<String>, |
| 4278 | carrier: CreatorDecisionCarrier, |
| 4279 | shown_service_lines: Vec<String>, |
| 4280 | source_dir: Option<PathBuf>, |
| 4281 | canon_workspace: Option<PathBuf>, |
| 4282 | registry_ignored: bool, |
| 4283 | } |
| 4284 | |
| 4285 | async fn finish_post_install( |
| 4286 | call: &BrokerCall, |
| 4287 | input: PostInstallInput, |
| 4288 | ) -> Result<Value, BrokerRefusal> { |
| 4289 | let PostInstallInput { |
| 4290 | reg_after_place, |
| 4291 | installed_name, |
| 4292 | expected_installed_hash, |
| 4293 | version, |
| 4294 | raw_target, |
| 4295 | want_enabled, |
| 4296 | mut warnings, |
| 4297 | carrier, |
| 4298 | shown_service_lines, |
| 4299 | source_dir, |
| 4300 | canon_workspace, |
| 4301 | registry_ignored, |
| 4302 | } = input; |
| 4303 | let policy = extension_host_policy_enabled(); |
| 4304 | #[cfg(any(test, feature = "test-support"))] |
| 4305 | let env_scope = crate::test_support::env_scope_ticket(); |
| 4306 | #[cfg(any(test, feature = "test-support"))] |
| 4307 | let test_offered: Vec<HostService> = HostService::ALL |
| 4308 | .into_iter() |
| 4309 | .filter(|service| offered(*service)) |
| 4310 | .collect(); |
| 4311 | |
| 4312 | if call.context.cancel().is_cancelled() { |
| 4313 | let fresh = tokio::task::spawn_blocking(move || { |
| 4314 | #[cfg(any(test, feature = "test-support"))] |
| 4315 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 4316 | let _scope = PolicyScope::propagate(policy); |
| 4317 | reg_after_place.rediscover_for_workspace(reg_after_place.workspace()) |
| 4318 | }) |
| 4319 | .await |
| 4320 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 4321 | let services = plugin_services(fresh.get(&installed_name)); |
| 4322 | settle_non_active_change( |
| 4323 | call, |
| 4324 | &fresh, |
| 4325 | Some(make_change_mark( |
| 4326 | &installed_name, |
| 4327 | "installed", |
| 4328 | Some(&expected_installed_hash), |
| 4329 | None, |
| 4330 | services, |
| 4331 | Vec::new(), |
| 4332 | Vec::new(), |
| 4333 | )), |
| 4334 | ) |
| 4335 | .await; |
| 4336 | record_outcome( |
| 4337 | call, |
| 4338 | "install", |
| 4339 | Some(&installed_name), |
| 4340 | Some(&expected_installed_hash), |
| 4341 | None, |
| 4342 | "failed", |
| 4343 | ); |
| 4344 | return change_with_outcome(ChangeOutcome { |
| 4345 | application: "failed", |
| 4346 | stage: "install", |
| 4347 | target: raw_target, |
| 4348 | changed: true, |
| 4349 | enabled: Some(false), |
| 4350 | code: "operation-error", |
| 4351 | diagnostic: |
| 4352 | "cancelled after installation; the plugin remains installed on disk, disabled and untrusted" |
| 4353 | .to_string(), |
| 4354 | bundle: Some(installed_name), |
| 4355 | version, |
| 4356 | warnings, |
| 4357 | }); |
| 4358 | } |
| 4359 | |
| 4360 | let tool = match check_live_after_act(call, &carrier) { |
| 4361 | CarrierLiveCheck::Valid(refreshed) => refreshed, |
| 4362 | CarrierLiveCheck::Unavailable => { |
| 4363 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 4364 | } |
| 4365 | CarrierLiveCheck::Narrowed => { |
| 4366 | let fresh = tokio::task::spawn_blocking(move || { |
| 4367 | #[cfg(any(test, feature = "test-support"))] |
| 4368 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 4369 | let _scope = PolicyScope::propagate(policy); |
| 4370 | reg_after_place.rediscover_for_workspace(reg_after_place.workspace()) |
| 4371 | }) |
| 4372 | .await |
| 4373 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 4374 | let services = plugin_services(fresh.get(&installed_name)); |
| 4375 | settle_non_active_change( |
| 4376 | call, |
| 4377 | &fresh, |
| 4378 | Some(make_change_mark( |
| 4379 | &installed_name, |
| 4380 | "installed", |
| 4381 | Some(&expected_installed_hash), |
| 4382 | None, |
| 4383 | services, |
| 4384 | Vec::new(), |
| 4385 | Vec::new(), |
| 4386 | )), |
| 4387 | ) |
| 4388 | .await; |
| 4389 | record_outcome( |
| 4390 | call, |
| 4391 | "install", |
| 4392 | Some(&installed_name), |
| 4393 | Some(&expected_installed_hash), |
| 4394 | None, |
| 4395 | "failed", |
| 4396 | ); |
| 4397 | return change_with_outcome(ChangeOutcome { |
| 4398 | application: "failed", |
| 4399 | stage: "install", |
| 4400 | target: raw_target, |
| 4401 | changed: true, |
| 4402 | enabled: Some(false), |
| 4403 | code: "operation-error", |
| 4404 | diagnostic: |
| 4405 | "permission mode changed after installation, so the plugin remains disabled and untrusted" |
| 4406 | .to_string(), |
| 4407 | bundle: Some(installed_name), |
| 4408 | version, |
| 4409 | warnings, |
| 4410 | }); |
| 4411 | } |
| 4412 | }; |
| 4413 | |
| 4414 | if carrier.is_unseen_fetch() { |
| 4415 | let name_for_commit = installed_name.clone(); |
| 4416 | let expected_hash_clone = expected_installed_hash.clone(); |
| 4417 | let outcome = tokio::task::spawn_blocking(move || { |
| 4418 | #[cfg(any(test, feature = "test-support"))] |
| 4419 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 4420 | let _scope = PolicyScope::propagate(policy); |
| 4421 | let fresh_arc = reg_after_place.rediscover_for_workspace(reg_after_place.workspace()); |
| 4422 | let Some(loaded) = fresh_arc.get(&name_for_commit).cloned() else { |
| 4423 | return Err(fresh_arc); |
| 4424 | }; |
| 4425 | if loaded.content_hash != expected_hash_clone { |
| 4426 | return Err(fresh_arc); |
| 4427 | } |
| 4428 | Ok((fresh_arc, loaded)) |
| 4429 | }) |
| 4430 | .await |
| 4431 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 4432 | |
| 4433 | let (final_reg, final_loaded) = match outcome { |
| 4434 | Ok(pair) => pair, |
| 4435 | Err(fresh) => { |
| 4436 | let services = plugin_services(fresh.get(&installed_name)); |
| 4437 | settle_non_active_change( |
| 4438 | call, |
| 4439 | &fresh, |
| 4440 | Some(make_change_mark( |
| 4441 | &installed_name, |
| 4442 | "installed", |
| 4443 | Some(&expected_installed_hash), |
| 4444 | None, |
| 4445 | services, |
| 4446 | Vec::new(), |
| 4447 | Vec::new(), |
| 4448 | )), |
| 4449 | ) |
| 4450 | .await; |
| 4451 | record_outcome( |
| 4452 | call, |
| 4453 | "install", |
| 4454 | Some(&installed_name), |
| 4455 | Some(&expected_installed_hash), |
| 4456 | None, |
| 4457 | "failed", |
| 4458 | ); |
| 4459 | return change_with_outcome(ChangeOutcome { |
| 4460 | application: "failed", |
| 4461 | stage: "install", |
| 4462 | target: raw_target, |
| 4463 | changed: true, |
| 4464 | enabled: Some(false), |
| 4465 | code: "operation-error", |
| 4466 | diagnostic: "changed after review".to_string(), |
| 4467 | bundle: Some(installed_name), |
| 4468 | version, |
| 4469 | warnings, |
| 4470 | }); |
| 4471 | } |
| 4472 | }; |
| 4473 | settle_non_active_change( |
| 4474 | call, |
| 4475 | &final_reg, |
| 4476 | Some(make_change_mark( |
| 4477 | final_loaded.name(), |
| 4478 | "installed", |
| 4479 | Some(&final_loaded.content_hash), |
| 4480 | None, |
| 4481 | plugin_services(Some(&final_loaded)), |
| 4482 | Vec::new(), |
| 4483 | Vec::new(), |
| 4484 | )), |
| 4485 | ) |
| 4486 | .await; |
| 4487 | warnings.push(format!( |
| 4488 | "installed disabled and untrusted because it fetched unseen bytes from the network; review it and turn it on from the Plugins page or `/plugin trust {}`", |
| 4489 | final_loaded.name() |
| 4490 | )); |
| 4491 | record_outcome( |
| 4492 | call, |
| 4493 | "install", |
| 4494 | Some(final_loaded.name()), |
| 4495 | Some(&final_loaded.content_hash), |
| 4496 | None, |
| 4497 | "applied", |
| 4498 | ); |
| 4499 | return change_ok( |
| 4500 | "install", |
| 4501 | raw_target, |
| 4502 | true, |
| 4503 | Some(final_loaded.enabled), |
| 4504 | Some(final_loaded.name().to_string()), |
| 4505 | non_empty_version(&final_loaded.manifest.plugin.version).or(version), |
| 4506 | warnings, |
| 4507 | ); |
| 4508 | } |
| 4509 | |
| 4510 | let ws_for_approver = canon_workspace |
| 4511 | .as_deref() |
| 4512 | .unwrap_or_else(|| reg_after_place.workspace()); |
| 4513 | let approver = match approver_from_carrier(call, &tool, &carrier, ws_for_approver) { |
| 4514 | Ok(approver) => approver, |
| 4515 | Err(msg) => { |
| 4516 | let fresh = tokio::task::spawn_blocking(move || { |
| 4517 | #[cfg(any(test, feature = "test-support"))] |
| 4518 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 4519 | let _scope = PolicyScope::propagate(policy); |
| 4520 | reg_after_place.rediscover_for_workspace(reg_after_place.workspace()) |
| 4521 | }) |
| 4522 | .await |
| 4523 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 4524 | let services = plugin_services(fresh.get(&installed_name)); |
| 4525 | settle_non_active_change( |
| 4526 | call, |
| 4527 | &fresh, |
| 4528 | Some(make_change_mark( |
| 4529 | &installed_name, |
| 4530 | "installed", |
| 4531 | Some(&expected_installed_hash), |
| 4532 | None, |
| 4533 | services, |
| 4534 | Vec::new(), |
| 4535 | Vec::new(), |
| 4536 | )), |
| 4537 | ) |
| 4538 | .await; |
| 4539 | record_outcome( |
| 4540 | call, |
| 4541 | "install", |
| 4542 | Some(&installed_name), |
| 4543 | Some(&expected_installed_hash), |
| 4544 | None, |
| 4545 | "failed", |
| 4546 | ); |
| 4547 | return change_with_outcome(ChangeOutcome { |
| 4548 | application: "failed", |
| 4549 | stage: "install", |
| 4550 | target: raw_target, |
| 4551 | changed: true, |
| 4552 | enabled: Some(false), |
| 4553 | code: "operation-error", |
| 4554 | diagnostic: msg, |
| 4555 | bundle: Some(installed_name), |
| 4556 | version, |
| 4557 | warnings, |
| 4558 | }); |
| 4559 | } |
| 4560 | }; |
| 4561 | |
| 4562 | let approver_for_commit = approver.clone(); |
| 4563 | let name_for_commit = installed_name.clone(); |
| 4564 | let expected_hash_clone = expected_installed_hash.clone(); |
| 4565 | enum PostCommit { |
| 4566 | Mismatch(Arc<PluginRegistry>), |
| 4567 | ServiceReviewChanged { |
| 4568 | registry: Arc<PluginRegistry>, |
| 4569 | enabled: bool, |
| 4570 | }, |
| 4571 | Failed { |
| 4572 | registry: Arc<PluginRegistry>, |
| 4573 | enabled: bool, |
| 4574 | has_native: bool, |
| 4575 | err: String, |
| 4576 | }, |
| 4577 | Overridden { |
| 4578 | registry: Arc<PluginRegistry>, |
| 4579 | enabled: bool, |
| 4580 | err: String, |
| 4581 | }, |
| 4582 | Done { |
| 4583 | registry: Arc<PluginRegistry>, |
| 4584 | loaded: Box<LoadedPlugin>, |
| 4585 | warnings: Vec<String>, |
| 4586 | }, |
| 4587 | } |
| 4588 | let outcome = tokio::task::spawn_blocking(move || { |
| 4589 | #[cfg(any(test, feature = "test-support"))] |
| 4590 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 4591 | #[cfg(any(test, feature = "test-support"))] |
| 4592 | let _test_offer = TestOffer::only(&test_offered); |
| 4593 | let _scope = PolicyScope::propagate(policy); |
| 4594 | let fresh_arc = reg_after_place.rediscover_for_workspace(reg_after_place.workspace()); |
| 4595 | let Some(loaded) = fresh_arc.get(&name_for_commit).cloned() else { |
| 4596 | return PostCommit::Mismatch(fresh_arc); |
| 4597 | }; |
| 4598 | if loaded.content_hash != expected_hash_clone { |
| 4599 | return PostCommit::Mismatch(fresh_arc); |
| 4600 | } |
| 4601 | let mut reg = (*fresh_arc).clone(); |
| 4602 | let selector = loaded.id.as_str().to_string(); |
| 4603 | let post_review = reg.host_service_review_for(&selector, &approver_for_commit); |
| 4604 | let post_lines = post_review |
| 4605 | .as_ref() |
| 4606 | .map(HostServiceReview::text) |
| 4607 | .unwrap_or_default(); |
| 4608 | if post_lines != shown_service_lines { |
| 4609 | return PostCommit::ServiceReviewChanged { |
| 4610 | registry: fresh_arc, |
| 4611 | enabled: loaded.enabled, |
| 4612 | }; |
| 4613 | } |
| 4614 | let host_services = post_review.map(|review| review.token); |
| 4615 | let approval = ReviewApproval { |
| 4616 | approved_by: approver_for_commit.clone(), |
| 4617 | host_services, |
| 4618 | }; |
| 4619 | let commit_res = if want_enabled { |
| 4620 | reg.trust_and_enable_by(&selector, approval, approver_for_commit.clone()) |
| 4621 | } else { |
| 4622 | reg.trust_reviewed(&selector, approval) |
| 4623 | }; |
| 4624 | if let Err(err) = commit_res { |
| 4625 | let latest = reg.rediscover_for_workspace(reg.workspace()); |
| 4626 | let persisted_enabled = latest.get(&selector).is_some_and(|p| p.enabled); |
| 4627 | let has_native = latest |
| 4628 | .get(&selector) |
| 4629 | .map_or(loaded.inventory.native > 0, |p| p.inventory.native > 0); |
| 4630 | if want_enabled && is_managed_policy_error(&err) { |
| 4631 | return PostCommit::Overridden { |
| 4632 | registry: latest, |
| 4633 | enabled: persisted_enabled, |
| 4634 | err, |
| 4635 | }; |
| 4636 | } |
| 4637 | return PostCommit::Failed { |
| 4638 | registry: latest, |
| 4639 | enabled: persisted_enabled, |
| 4640 | has_native, |
| 4641 | err, |
| 4642 | }; |
| 4643 | } |
| 4644 | let final_reg = reg.rediscover_for_workspace(reg.workspace()); |
| 4645 | let final_loaded = final_reg.get(&selector).cloned().unwrap_or(loaded); |
| 4646 | let scrub = ScrubContext { |
| 4647 | workspace: final_reg.workspace(), |
| 4648 | canon_workspace: canon_workspace.as_deref(), |
| 4649 | plugin_root: Some(&final_loaded.canonical_root), |
| 4650 | user_plugins_dir: final_reg.user_plugins_dir(), |
| 4651 | state_path: final_reg.state_path(), |
| 4652 | }; |
| 4653 | let extra_warnings = collect_enable_warnings( |
| 4654 | &final_reg, |
| 4655 | &final_loaded, |
| 4656 | &approver_for_commit, |
| 4657 | final_loaded.enabled, |
| 4658 | registry_ignored, |
| 4659 | &scrub, |
| 4660 | ); |
| 4661 | PostCommit::Done { |
| 4662 | registry: final_reg, |
| 4663 | loaded: Box::new(final_loaded), |
| 4664 | warnings: extra_warnings, |
| 4665 | } |
| 4666 | }) |
| 4667 | .await |
| 4668 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 4669 | |
| 4670 | match outcome { |
| 4671 | PostCommit::Mismatch(fresh) => { |
| 4672 | let services = plugin_services(fresh.get(&installed_name)); |
| 4673 | settle_non_active_change( |
| 4674 | call, |
| 4675 | &fresh, |
| 4676 | Some(make_change_mark( |
| 4677 | &installed_name, |
| 4678 | "installed", |
| 4679 | Some(&expected_installed_hash), |
| 4680 | Some(&approver), |
| 4681 | services, |
| 4682 | Vec::new(), |
| 4683 | Vec::new(), |
| 4684 | )), |
| 4685 | ) |
| 4686 | .await; |
| 4687 | record_outcome( |
| 4688 | call, |
| 4689 | "install", |
| 4690 | Some(&installed_name), |
| 4691 | Some(&expected_installed_hash), |
| 4692 | Some(&approver), |
| 4693 | "failed", |
| 4694 | ); |
| 4695 | change_with_outcome(ChangeOutcome { |
| 4696 | application: "failed", |
| 4697 | stage: "install", |
| 4698 | target: raw_target, |
| 4699 | changed: true, |
| 4700 | enabled: Some(false), |
| 4701 | code: "operation-error", |
| 4702 | diagnostic: "changed after review".to_string(), |
| 4703 | bundle: Some(installed_name), |
| 4704 | version, |
| 4705 | warnings, |
| 4706 | }) |
| 4707 | } |
| 4708 | PostCommit::ServiceReviewChanged { registry, enabled } => { |
| 4709 | let services = plugin_services(registry.get(&installed_name)); |
| 4710 | settle_non_active_change( |
| 4711 | call, |
| 4712 | ®istry, |
| 4713 | Some(make_change_mark( |
| 4714 | &installed_name, |
| 4715 | "installed", |
| 4716 | Some(&expected_installed_hash), |
| 4717 | Some(&approver), |
| 4718 | services, |
| 4719 | Vec::new(), |
| 4720 | Vec::new(), |
| 4721 | )), |
| 4722 | ) |
| 4723 | .await; |
| 4724 | record_outcome( |
| 4725 | call, |
| 4726 | "install", |
| 4727 | Some(&installed_name), |
| 4728 | Some(&expected_installed_hash), |
| 4729 | Some(&approver), |
| 4730 | "failed", |
| 4731 | ); |
| 4732 | change_with_outcome(ChangeOutcome { |
| 4733 | application: "failed", |
| 4734 | stage: "enable", |
| 4735 | target: raw_target, |
| 4736 | changed: true, |
| 4737 | enabled: Some(enabled), |
| 4738 | code: "operation-error", |
| 4739 | diagnostic: "the services it asks for changed after review".to_string(), |
| 4740 | bundle: Some(installed_name), |
| 4741 | version, |
| 4742 | warnings, |
| 4743 | }) |
| 4744 | } |
| 4745 | PostCommit::Overridden { |
| 4746 | registry: fresh, |
| 4747 | enabled, |
| 4748 | err, |
| 4749 | } => { |
| 4750 | let scrub = ScrubContext { |
| 4751 | workspace: fresh.workspace(), |
| 4752 | canon_workspace: None, |
| 4753 | plugin_root: source_dir.as_deref(), |
| 4754 | user_plugins_dir: fresh.user_plugins_dir(), |
| 4755 | state_path: fresh.state_path(), |
| 4756 | }; |
| 4757 | let diag = scrub_message(&err, &scrub); |
| 4758 | let services = plugin_services(fresh.get(&installed_name)); |
| 4759 | settle_non_active_change( |
| 4760 | call, |
| 4761 | &fresh, |
| 4762 | Some(make_change_mark( |
| 4763 | &installed_name, |
| 4764 | "installed", |
| 4765 | Some(&expected_installed_hash), |
| 4766 | Some(&approver), |
| 4767 | services, |
| 4768 | Vec::new(), |
| 4769 | Vec::new(), |
| 4770 | )), |
| 4771 | ) |
| 4772 | .await; |
| 4773 | record_outcome( |
| 4774 | call, |
| 4775 | "install", |
| 4776 | Some(&installed_name), |
| 4777 | Some(&expected_installed_hash), |
| 4778 | Some(&approver), |
| 4779 | "overridden", |
| 4780 | ); |
| 4781 | change_with_outcome(ChangeOutcome { |
| 4782 | application: "overridden", |
| 4783 | stage: "enable", |
| 4784 | target: raw_target, |
| 4785 | changed: true, |
| 4786 | enabled: Some(enabled), |
| 4787 | code: "operation-error", |
| 4788 | diagnostic: diag, |
| 4789 | bundle: Some(installed_name), |
| 4790 | version, |
| 4791 | warnings, |
| 4792 | }) |
| 4793 | } |
| 4794 | PostCommit::Failed { |
| 4795 | registry: fresh, |
| 4796 | enabled, |
| 4797 | has_native, |
| 4798 | err, |
| 4799 | } => { |
| 4800 | let scrub = ScrubContext { |
| 4801 | workspace: fresh.workspace(), |
| 4802 | canon_workspace: None, |
| 4803 | plugin_root: source_dir.as_deref(), |
| 4804 | user_plugins_dir: fresh.user_plugins_dir(), |
| 4805 | state_path: fresh.state_path(), |
| 4806 | }; |
| 4807 | let diag = if want_enabled { |
| 4808 | map_enable_failure_diagnostic(&err, has_native, policy, &scrub) |
| 4809 | } else { |
| 4810 | scrub_message(&err, &scrub) |
| 4811 | }; |
| 4812 | let services = plugin_services(fresh.get(&installed_name)); |
| 4813 | settle_non_active_change( |
| 4814 | call, |
| 4815 | &fresh, |
| 4816 | Some(make_change_mark( |
| 4817 | &installed_name, |
| 4818 | "installed", |
| 4819 | Some(&expected_installed_hash), |
| 4820 | Some(&approver), |
| 4821 | services, |
| 4822 | Vec::new(), |
| 4823 | Vec::new(), |
| 4824 | )), |
| 4825 | ) |
| 4826 | .await; |
| 4827 | record_outcome( |
| 4828 | call, |
| 4829 | "install", |
| 4830 | Some(&installed_name), |
| 4831 | Some(&expected_installed_hash), |
| 4832 | Some(&approver), |
| 4833 | "failed", |
| 4834 | ); |
| 4835 | change_with_outcome(ChangeOutcome { |
| 4836 | application: "failed", |
| 4837 | stage: "enable", |
| 4838 | target: raw_target, |
| 4839 | changed: true, |
| 4840 | enabled: Some(enabled), |
| 4841 | code: "operation-error", |
| 4842 | diagnostic: diag, |
| 4843 | bundle: Some(installed_name), |
| 4844 | version, |
| 4845 | warnings, |
| 4846 | }) |
| 4847 | } |
| 4848 | PostCommit::Done { |
| 4849 | registry: final_reg, |
| 4850 | loaded: final_loaded, |
| 4851 | warnings: built_warnings, |
| 4852 | } => { |
| 4853 | warnings = built_warnings; |
| 4854 | let scrub = ScrubContext { |
| 4855 | workspace: final_reg.workspace(), |
| 4856 | canon_workspace: None, |
| 4857 | plugin_root: Some(&final_loaded.canonical_root), |
| 4858 | user_plugins_dir: final_reg.user_plugins_dir(), |
| 4859 | state_path: final_reg.state_path(), |
| 4860 | }; |
| 4861 | if want_enabled && final_loaded.enabled { |
| 4862 | match finish_enabled_activation( |
| 4863 | call, |
| 4864 | EnableActivation { |
| 4865 | method: "install", |
| 4866 | stage: "enable", |
| 4867 | target: raw_target.clone(), |
| 4868 | changed: true, |
| 4869 | registry: &final_reg, |
| 4870 | loaded: &final_loaded, |
| 4871 | approver: &approver, |
| 4872 | version: version.clone(), |
| 4873 | warnings, |
| 4874 | prior_tools: Vec::new(), |
| 4875 | }, |
| 4876 | &scrub, |
| 4877 | ) |
| 4878 | .await |
| 4879 | { |
| 4880 | std::ops::ControlFlow::Continue(updated) => warnings = updated, |
| 4881 | std::ops::ControlFlow::Break(early) => return early, |
| 4882 | } |
| 4883 | } else { |
| 4884 | settle_non_active_change( |
| 4885 | call, |
| 4886 | &final_reg, |
| 4887 | Some(make_change_mark( |
| 4888 | final_loaded.name(), |
| 4889 | "installed", |
| 4890 | Some(&final_loaded.content_hash), |
| 4891 | Some(&approver), |
| 4892 | plugin_services(Some(&final_loaded)), |
| 4893 | Vec::new(), |
| 4894 | Vec::new(), |
| 4895 | )), |
| 4896 | ) |
| 4897 | .await; |
| 4898 | } |
| 4899 | record_outcome( |
| 4900 | call, |
| 4901 | "install", |
| 4902 | Some(final_loaded.name()), |
| 4903 | Some(&final_loaded.content_hash), |
| 4904 | Some(&approver), |
| 4905 | "applied", |
| 4906 | ); |
| 4907 | change_ok( |
| 4908 | if want_enabled { "enable" } else { "install" }, |
| 4909 | raw_target, |
| 4910 | true, |
| 4911 | Some(final_loaded.enabled), |
| 4912 | Some(final_loaded.name().to_string()), |
| 4913 | non_empty_version(&final_loaded.manifest.plugin.version).or(version), |
| 4914 | warnings, |
| 4915 | ) |
| 4916 | } |
| 4917 | } |
| 4918 | } |
| 4919 | |
| 4920 | async fn load_existing_plugin( |
| 4921 | registry: Arc<PluginRegistry>, |
| 4922 | target: String, |
| 4923 | row: Option<String>, |
| 4924 | ) -> Result<PreparedExisting, BrokerRefusal> { |
| 4925 | let policy = extension_host_policy_enabled(); |
| 4926 | #[cfg(any(test, feature = "test-support"))] |
| 4927 | let env_scope = crate::test_support::env_scope_ticket(); |
| 4928 | tokio::task::spawn_blocking(move || { |
| 4929 | #[cfg(any(test, feature = "test-support"))] |
| 4930 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 4931 | let _scope = PolicyScope::propagate(policy); |
| 4932 | let fresh = registry.rediscover_for_workspace(registry.workspace()); |
| 4933 | let canon_ws = std::fs::canonicalize(fresh.workspace()).ok(); |
| 4934 | let all_plugins = fresh.list(); |
| 4935 | let counts = name_counts(&all_plugins); |
| 4936 | |
| 4937 | let matching_row = |plugin: &LoadedPlugin, wanted: &str| -> (usize, bool) { |
| 4938 | let prefix = id_prefix(plugin, &counts); |
| 4939 | let mut truncated = false; |
| 4940 | let rows = collect_component_rows(plugin, &mut truncated); |
| 4941 | let total = rows.len(); |
| 4942 | let hit = rows.into_iter().any(|item| { |
| 4943 | let (row_id, module_name, entry_id) = |
| 4944 | row_identities(prefix, &item.label, &mut truncated); |
| 4945 | row_id == wanted || module_name == wanted || entry_id == wanted |
| 4946 | }); |
| 4947 | (total, hit) |
| 4948 | }; |
| 4949 | |
| 4950 | let found = match resolve_plugin_by_target(&fresh, &target) { |
| 4951 | TargetLookup::Ambiguous { message, .. } => { |
| 4952 | return PreparedExisting::Ambiguous(message); |
| 4953 | } |
| 4954 | TargetLookup::Found(plugin) => { |
| 4955 | if let Some(ref requested_row) = row { |
| 4956 | let (total, hit) = matching_row(plugin, requested_row); |
| 4957 | if !hit { |
| 4958 | return PreparedExisting::Missing; |
| 4959 | } |
| 4960 | if total != 1 { |
| 4961 | return PreparedExisting::NotSoleRow(plugin.name().to_string()); |
| 4962 | } |
| 4963 | } |
| 4964 | Some(plugin.clone()) |
| 4965 | } |
| 4966 | TargetLookup::Missing => { |
| 4967 | if row.is_none() { |
| 4968 | let mut resolved: Option<LoadedPlugin> = None; |
| 4969 | let mut resolved_total = 0usize; |
| 4970 | for plugin in &all_plugins { |
| 4971 | let prefix = id_prefix(plugin, &counts); |
| 4972 | let mut truncated = false; |
| 4973 | let rows = collect_component_rows(plugin, &mut truncated); |
| 4974 | let total = rows.len(); |
| 4975 | let hit = rows.into_iter().any(|item| { |
| 4976 | let (_, _, entry_id) = |
| 4977 | row_identities(prefix, &item.label, &mut truncated); |
| 4978 | entry_id == target |
| 4979 | }); |
| 4980 | if hit { |
| 4981 | if resolved.is_some() { |
| 4982 | return PreparedExisting::Ambiguous(format!( |
| 4983 | "target `{target}` matches multiple installed plugins" |
| 4984 | )); |
| 4985 | } |
| 4986 | resolved = Some((*plugin).clone()); |
| 4987 | resolved_total = total; |
| 4988 | } |
| 4989 | } |
| 4990 | if let Some(plugin) = &resolved |
| 4991 | && resolved_total != 1 |
| 4992 | { |
| 4993 | return PreparedExisting::NotSoleRow(plugin.name().to_string()); |
| 4994 | } |
| 4995 | resolved |
| 4996 | } else { |
| 4997 | None |
| 4998 | } |
| 4999 | } |
| 5000 | }; |
| 5001 | |
| 5002 | let Some(plugin) = found else { |
| 5003 | if row.is_none() |
| 5004 | && codewhale_skill_install::install::validate_skill_name_segment(&target).is_ok() |
| 5005 | && let Some(user_plugins_dir) = fresh.user_plugins_dir() |
| 5006 | { |
| 5007 | let candidate = user_plugins_dir.join(&target); |
| 5008 | if let Ok(meta) = std::fs::symlink_metadata(&candidate) { |
| 5009 | let link_or_non_dir = metadata_is_link_or_reparse(&meta) || !meta.is_dir(); |
| 5010 | let marker_present = std::fs::symlink_metadata( |
| 5011 | candidate.join(codewhale_skill_install::install::INSTALLED_FROM_MARKER), |
| 5012 | ) |
| 5013 | .is_ok(); |
| 5014 | let canon_dir = std::fs::canonicalize(user_plugins_dir) |
| 5015 | .ok() |
| 5016 | .map(|root| root.join(&target)); |
| 5017 | let has_bundle_diag = fresh.diagnostics().iter().any(|diag| { |
| 5018 | diag.path.as_ref().is_some_and(|path| { |
| 5019 | path.starts_with(&candidate) |
| 5020 | || canon_dir.as_ref().is_some_and(|dir| path.starts_with(dir)) |
| 5021 | }) |
| 5022 | }); |
| 5023 | if link_or_non_dir |
| 5024 | || (!has_regular_install_marker(&candidate) |
| 5025 | && (marker_present || has_bundle_diag)) |
| 5026 | { |
| 5027 | return PreparedExisting::Unremovable(target); |
| 5028 | } |
| 5029 | } |
| 5030 | } |
| 5031 | return PreparedExisting::Missing; |
| 5032 | }; |
| 5033 | let (is_own, own_denial_reason) = is_existing_own(&fresh, &plugin); |
| 5034 | let marker_ok = has_regular_install_marker(&plugin.canonical_root); |
| 5035 | PreparedExisting::Found { |
| 5036 | plugin: Box::new(plugin), |
| 5037 | is_own, |
| 5038 | own_denial_reason, |
| 5039 | has_marker: marker_ok, |
| 5040 | canon_workspace: canon_ws, |
| 5041 | } |
| 5042 | }) |
| 5043 | .await |
| 5044 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins)) |
| 5045 | } |
| 5046 | |
| 5047 | async fn remove( |
| 5048 | call: &BrokerCall, |
| 5049 | mut tool: ToolContext, |
| 5050 | authority: Option<LiveRuntimeAuthority>, |
| 5051 | input: RemoveInput, |
| 5052 | ) -> Result<Value, BrokerRefusal> { |
| 5053 | let raw_target = validate_required_str(&input.target, "target", MAX_TARGET_BYTES)?; |
| 5054 | let initial_registry = live_registry(call, &tool)?; |
| 5055 | let Some(current_authority) = authority else { |
| 5056 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 5057 | }; |
| 5058 | let carrier = require_carried_decision(&tool, ¤t_authority, "remove")?; |
| 5059 | let (approved_plugin_id, approved_plugin_name, expected_gate_target) = match &carrier.change { |
| 5060 | AdmittedChangeKind::Remove { |
| 5061 | plugin_id, |
| 5062 | plugin_name, |
| 5063 | expected_gate_target, |
| 5064 | .. |
| 5065 | } => ( |
| 5066 | plugin_id.clone(), |
| 5067 | plugin_name.clone(), |
| 5068 | expected_gate_target.clone(), |
| 5069 | ), |
| 5070 | _ => { |
| 5071 | return Err(BrokerRefusal::Refused { |
| 5072 | service: DshService::Plugins, |
| 5073 | message: "plugin change decision is not a remove decision".to_string(), |
| 5074 | }); |
| 5075 | } |
| 5076 | }; |
| 5077 | let is_agent = matches!(carrier.decider, CreatorDecider::Agent(_)); |
| 5078 | |
| 5079 | let (initial_plugin, is_own, own_denial_reason, has_marker) = match load_existing_plugin( |
| 5080 | Arc::clone(&initial_registry), |
| 5081 | raw_target.clone(), |
| 5082 | None, |
| 5083 | ) |
| 5084 | .await? |
| 5085 | { |
| 5086 | PreparedExisting::Missing => { |
| 5087 | record_outcome(call, "remove", None, None, None, "failed"); |
| 5088 | return change_with_outcome(ChangeOutcome { |
| 5089 | application: "failed", |
| 5090 | stage: "remove", |
| 5091 | target: raw_target.clone(), |
| 5092 | changed: false, |
| 5093 | enabled: None, |
| 5094 | code: "unknown-plugin", |
| 5095 | diagnostic: format!("no plugin `{raw_target}` is installed"), |
| 5096 | bundle: None, |
| 5097 | version: None, |
| 5098 | warnings: Vec::new(), |
| 5099 | }); |
| 5100 | } |
| 5101 | PreparedExisting::Unremovable(plugin_name) => { |
| 5102 | record_outcome(call, "remove", Some(&plugin_name), None, None, "failed"); |
| 5103 | return change_with_outcome(ChangeOutcome { |
| 5104 | application: "failed", |
| 5105 | stage: "remove", |
| 5106 | target: raw_target, |
| 5107 | changed: false, |
| 5108 | enabled: None, |
| 5109 | code: "not-removable", |
| 5110 | diagnostic: format!( |
| 5111 | "plugin `{plugin_name}` has no valid regular .installed-from record, so Codewhale refuses to remove it" |
| 5112 | ), |
| 5113 | bundle: Some(plugin_name), |
| 5114 | version: None, |
| 5115 | warnings: Vec::new(), |
| 5116 | }); |
| 5117 | } |
| 5118 | PreparedExisting::NotSoleRow(plugin_name) => { |
| 5119 | record_outcome(call, "remove", Some(&plugin_name), None, None, "failed"); |
| 5120 | return change_with_outcome(ChangeOutcome { |
| 5121 | application: "failed", |
| 5122 | stage: "remove", |
| 5123 | target: raw_target, |
| 5124 | changed: false, |
| 5125 | enabled: None, |
| 5126 | code: "operation-error", |
| 5127 | diagnostic: "Codewhale removes a plugin as a whole; use the bundle name" |
| 5128 | .to_string(), |
| 5129 | bundle: Some(plugin_name), |
| 5130 | version: None, |
| 5131 | warnings: Vec::new(), |
| 5132 | }); |
| 5133 | } |
| 5134 | PreparedExisting::Ambiguous(msg) => { |
| 5135 | record_outcome(call, "remove", None, None, None, "failed"); |
| 5136 | return change_with_outcome(ChangeOutcome { |
| 5137 | application: "failed", |
| 5138 | stage: "remove", |
| 5139 | target: raw_target, |
| 5140 | changed: false, |
| 5141 | enabled: None, |
| 5142 | code: "operation-error", |
| 5143 | diagnostic: msg, |
| 5144 | bundle: None, |
| 5145 | version: None, |
| 5146 | warnings: Vec::new(), |
| 5147 | }); |
| 5148 | } |
| 5149 | PreparedExisting::Found { |
| 5150 | plugin, |
| 5151 | is_own, |
| 5152 | own_denial_reason, |
| 5153 | has_marker, |
| 5154 | canon_workspace: _, |
| 5155 | } => (plugin, is_own, own_denial_reason, has_marker), |
| 5156 | }; |
| 5157 | |
| 5158 | let bundle_name = initial_plugin.name().to_string(); |
| 5159 | let version = non_empty_version(&initial_plugin.manifest.plugin.version); |
| 5160 | match initial_plugin.scope { |
| 5161 | PluginScope::Builtin => { |
| 5162 | record_outcome( |
| 5163 | call, |
| 5164 | "remove", |
| 5165 | Some(&bundle_name), |
| 5166 | Some(&initial_plugin.content_hash), |
| 5167 | None, |
| 5168 | "failed", |
| 5169 | ); |
| 5170 | return change_with_outcome(ChangeOutcome { |
| 5171 | application: "failed", |
| 5172 | stage: "remove", |
| 5173 | target: raw_target, |
| 5174 | changed: false, |
| 5175 | enabled: Some(initial_plugin.enabled), |
| 5176 | code: "management-required", |
| 5177 | diagnostic: format!( |
| 5178 | "built-in plugin `{bundle_name}` ships with Codewhale and cannot be removed" |
| 5179 | ), |
| 5180 | bundle: Some(bundle_name), |
| 5181 | version, |
| 5182 | warnings: Vec::new(), |
| 5183 | }); |
| 5184 | } |
| 5185 | PluginScope::Workspace => { |
| 5186 | record_outcome( |
| 5187 | call, |
| 5188 | "remove", |
| 5189 | Some(&bundle_name), |
| 5190 | Some(&initial_plugin.content_hash), |
| 5191 | None, |
| 5192 | "failed", |
| 5193 | ); |
| 5194 | return change_with_outcome(ChangeOutcome { |
| 5195 | application: "failed", |
| 5196 | stage: "remove", |
| 5197 | target: raw_target, |
| 5198 | changed: false, |
| 5199 | enabled: Some(initial_plugin.enabled), |
| 5200 | code: "not-removable", |
| 5201 | diagnostic: format!( |
| 5202 | "workspace plugin `{bundle_name}` lives in the project repository and is not removable here" |
| 5203 | ), |
| 5204 | bundle: Some(bundle_name), |
| 5205 | version, |
| 5206 | warnings: Vec::new(), |
| 5207 | }); |
| 5208 | } |
| 5209 | PluginScope::User if !has_marker => { |
| 5210 | record_outcome( |
| 5211 | call, |
| 5212 | "remove", |
| 5213 | Some(&bundle_name), |
| 5214 | Some(&initial_plugin.content_hash), |
| 5215 | None, |
| 5216 | "failed", |
| 5217 | ); |
| 5218 | return change_with_outcome(ChangeOutcome { |
| 5219 | application: "failed", |
| 5220 | stage: "remove", |
| 5221 | target: raw_target, |
| 5222 | changed: false, |
| 5223 | enabled: Some(initial_plugin.enabled), |
| 5224 | code: "not-removable", |
| 5225 | diagnostic: format!( |
| 5226 | "plugin `{bundle_name}` has no .installed-from record, so Codewhale refuses to remove it" |
| 5227 | ), |
| 5228 | bundle: Some(bundle_name), |
| 5229 | version, |
| 5230 | warnings: Vec::new(), |
| 5231 | }); |
| 5232 | } |
| 5233 | PluginScope::User => {} |
| 5234 | } |
| 5235 | |
| 5236 | if is_agent && !has_agent_call_identity(call, &tool) { |
| 5237 | record_outcome( |
| 5238 | call, |
| 5239 | "remove", |
| 5240 | Some(&bundle_name), |
| 5241 | Some(&initial_plugin.content_hash), |
| 5242 | None, |
| 5243 | "failed", |
| 5244 | ); |
| 5245 | return change_with_outcome(ChangeOutcome { |
| 5246 | application: "failed", |
| 5247 | stage: "remove", |
| 5248 | target: raw_target, |
| 5249 | changed: false, |
| 5250 | enabled: Some(initial_plugin.enabled), |
| 5251 | code: "operation-error", |
| 5252 | diagnostic: |
| 5253 | "An approval by the agent must name the thread, turn and tool call that made it" |
| 5254 | .to_string(), |
| 5255 | bundle: Some(bundle_name), |
| 5256 | version, |
| 5257 | warnings: Vec::new(), |
| 5258 | }); |
| 5259 | } |
| 5260 | if !is_own && is_agent { |
| 5261 | let reason = |
| 5262 | own_denial_reason.unwrap_or("this plugin was not installed and approved by this agent"); |
| 5263 | record_outcome( |
| 5264 | call, |
| 5265 | "remove", |
| 5266 | Some(&bundle_name), |
| 5267 | Some(&initial_plugin.content_hash), |
| 5268 | None, |
| 5269 | "failed", |
| 5270 | ); |
| 5271 | return change_with_outcome(ChangeOutcome { |
| 5272 | application: "failed", |
| 5273 | stage: "remove", |
| 5274 | target: raw_target, |
| 5275 | changed: false, |
| 5276 | enabled: Some(initial_plugin.enabled), |
| 5277 | code: "operation-error", |
| 5278 | diagnostic: format!("{reason}; {ASK_PERSON_HINT}"), |
| 5279 | bundle: Some(bundle_name), |
| 5280 | version, |
| 5281 | warnings: Vec::new(), |
| 5282 | }); |
| 5283 | } |
| 5284 | |
| 5285 | let gate_target = format!("{bundle_name} {}", initial_plugin.id.as_str()); |
| 5286 | if initial_plugin.id.as_str() != approved_plugin_id |
| 5287 | || bundle_name != approved_plugin_name |
| 5288 | || gate_target != expected_gate_target |
| 5289 | { |
| 5290 | return Err(BrokerRefusal::Refused { |
| 5291 | service: DshService::Plugins, |
| 5292 | message: "plugin remove target changed after review".to_string(), |
| 5293 | }); |
| 5294 | } |
| 5295 | call.context |
| 5296 | .act("remove", BrokerEffect::Write, Some(&gate_target)) |
| 5297 | .await?; |
| 5298 | |
| 5299 | if call.context.cancel().is_cancelled() { |
| 5300 | record_outcome( |
| 5301 | call, |
| 5302 | "remove", |
| 5303 | Some(&bundle_name), |
| 5304 | Some(&initial_plugin.content_hash), |
| 5305 | None, |
| 5306 | "cancelled", |
| 5307 | ); |
| 5308 | return cancelled_result("remove", raw_target, Some(bundle_name), version, Vec::new()); |
| 5309 | } |
| 5310 | |
| 5311 | tool = match check_live_after_act(call, &carrier) { |
| 5312 | CarrierLiveCheck::Valid(refreshed) => refreshed, |
| 5313 | CarrierLiveCheck::Unavailable => { |
| 5314 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 5315 | } |
| 5316 | CarrierLiveCheck::Narrowed => { |
| 5317 | record_outcome( |
| 5318 | call, |
| 5319 | "remove", |
| 5320 | Some(&bundle_name), |
| 5321 | Some(&initial_plugin.content_hash), |
| 5322 | None, |
| 5323 | "failed", |
| 5324 | ); |
| 5325 | return change_with_outcome(ChangeOutcome { |
| 5326 | application: "failed", |
| 5327 | stage: "remove", |
| 5328 | target: raw_target, |
| 5329 | changed: false, |
| 5330 | enabled: Some(initial_plugin.enabled), |
| 5331 | code: "operation-error", |
| 5332 | diagnostic: |
| 5333 | "permission mode changed during review and no longer allows removing plugins" |
| 5334 | .to_string(), |
| 5335 | bundle: Some(bundle_name), |
| 5336 | version, |
| 5337 | warnings: Vec::new(), |
| 5338 | }); |
| 5339 | } |
| 5340 | }; |
| 5341 | |
| 5342 | let (plugin_now, still_own, reason_now, still_has_marker, canon_ws_now) = |
| 5343 | match load_existing_plugin(Arc::clone(&initial_registry), raw_target.clone(), None).await? { |
| 5344 | PreparedExisting::Missing => { |
| 5345 | record_outcome(call, "remove", Some(&bundle_name), None, None, "failed"); |
| 5346 | return change_with_outcome(ChangeOutcome { |
| 5347 | application: "failed", |
| 5348 | stage: "remove", |
| 5349 | target: raw_target, |
| 5350 | changed: false, |
| 5351 | enabled: None, |
| 5352 | code: "unknown-plugin", |
| 5353 | diagnostic: format!("plugin `{bundle_name}` is no longer installed"), |
| 5354 | bundle: Some(bundle_name), |
| 5355 | version, |
| 5356 | warnings: Vec::new(), |
| 5357 | }); |
| 5358 | } |
| 5359 | PreparedExisting::Unremovable(plugin_name) => { |
| 5360 | record_outcome(call, "remove", Some(&plugin_name), None, None, "failed"); |
| 5361 | return change_with_outcome(ChangeOutcome { |
| 5362 | application: "failed", |
| 5363 | stage: "remove", |
| 5364 | target: raw_target, |
| 5365 | changed: false, |
| 5366 | enabled: None, |
| 5367 | code: "not-removable", |
| 5368 | diagnostic: format!( |
| 5369 | "plugin `{plugin_name}` has no valid regular .installed-from record, so Codewhale refuses to remove it" |
| 5370 | ), |
| 5371 | bundle: Some(plugin_name), |
| 5372 | version, |
| 5373 | warnings: Vec::new(), |
| 5374 | }); |
| 5375 | } |
| 5376 | PreparedExisting::NotSoleRow(name) => { |
| 5377 | record_outcome(call, "remove", Some(&name), None, None, "failed"); |
| 5378 | return change_with_outcome(ChangeOutcome { |
| 5379 | application: "failed", |
| 5380 | stage: "remove", |
| 5381 | target: raw_target, |
| 5382 | changed: false, |
| 5383 | enabled: None, |
| 5384 | code: "operation-error", |
| 5385 | diagnostic: "Codewhale removes a plugin as a whole; use the bundle name" |
| 5386 | .to_string(), |
| 5387 | bundle: Some(name), |
| 5388 | version, |
| 5389 | warnings: Vec::new(), |
| 5390 | }); |
| 5391 | } |
| 5392 | PreparedExisting::Ambiguous(msg) => { |
| 5393 | record_outcome(call, "remove", Some(&bundle_name), None, None, "failed"); |
| 5394 | return change_with_outcome(ChangeOutcome { |
| 5395 | application: "failed", |
| 5396 | stage: "remove", |
| 5397 | target: raw_target, |
| 5398 | changed: false, |
| 5399 | enabled: None, |
| 5400 | code: "operation-error", |
| 5401 | diagnostic: msg, |
| 5402 | bundle: Some(bundle_name), |
| 5403 | version, |
| 5404 | warnings: Vec::new(), |
| 5405 | }); |
| 5406 | } |
| 5407 | PreparedExisting::Found { |
| 5408 | plugin, |
| 5409 | is_own, |
| 5410 | own_denial_reason, |
| 5411 | has_marker, |
| 5412 | canon_workspace, |
| 5413 | } => ( |
| 5414 | plugin, |
| 5415 | is_own, |
| 5416 | own_denial_reason, |
| 5417 | has_marker, |
| 5418 | canon_workspace, |
| 5419 | ), |
| 5420 | }; |
| 5421 | |
| 5422 | if is_agent && !has_agent_call_identity(call, &tool) { |
| 5423 | record_outcome( |
| 5424 | call, |
| 5425 | "remove", |
| 5426 | Some(&bundle_name), |
| 5427 | Some(&plugin_now.content_hash), |
| 5428 | None, |
| 5429 | "failed", |
| 5430 | ); |
| 5431 | return change_with_outcome(ChangeOutcome { |
| 5432 | application: "failed", |
| 5433 | stage: "remove", |
| 5434 | target: raw_target, |
| 5435 | changed: false, |
| 5436 | enabled: Some(plugin_now.enabled), |
| 5437 | code: "operation-error", |
| 5438 | diagnostic: |
| 5439 | "An approval by the agent must name the thread, turn and tool call that made it" |
| 5440 | .to_string(), |
| 5441 | bundle: Some(bundle_name), |
| 5442 | version, |
| 5443 | warnings: Vec::new(), |
| 5444 | }); |
| 5445 | } |
| 5446 | if is_agent && !still_own { |
| 5447 | let reason = reason_now.unwrap_or("this plugin is not owned by this agent"); |
| 5448 | record_outcome( |
| 5449 | call, |
| 5450 | "remove", |
| 5451 | Some(&bundle_name), |
| 5452 | Some(&plugin_now.content_hash), |
| 5453 | None, |
| 5454 | "failed", |
| 5455 | ); |
| 5456 | return change_with_outcome(ChangeOutcome { |
| 5457 | application: "failed", |
| 5458 | stage: "remove", |
| 5459 | target: raw_target, |
| 5460 | changed: false, |
| 5461 | enabled: Some(plugin_now.enabled), |
| 5462 | code: "operation-error", |
| 5463 | diagnostic: format!("{reason}; {ASK_PERSON_HINT}"), |
| 5464 | bundle: Some(bundle_name), |
| 5465 | version, |
| 5466 | warnings: Vec::new(), |
| 5467 | }); |
| 5468 | } |
| 5469 | if plugin_now.scope != PluginScope::User || !still_has_marker { |
| 5470 | record_outcome( |
| 5471 | call, |
| 5472 | "remove", |
| 5473 | Some(&bundle_name), |
| 5474 | Some(&plugin_now.content_hash), |
| 5475 | None, |
| 5476 | "failed", |
| 5477 | ); |
| 5478 | return change_with_outcome(ChangeOutcome { |
| 5479 | application: "failed", |
| 5480 | stage: "remove", |
| 5481 | target: raw_target, |
| 5482 | changed: false, |
| 5483 | enabled: Some(plugin_now.enabled), |
| 5484 | code: "not-removable", |
| 5485 | diagnostic: format!("plugin `{bundle_name}` is no longer removable"), |
| 5486 | bundle: Some(bundle_name), |
| 5487 | version, |
| 5488 | warnings: Vec::new(), |
| 5489 | }); |
| 5490 | } |
| 5491 | if plugin_now.id != initial_plugin.id |
| 5492 | || plugin_now.install_nonce != initial_plugin.install_nonce |
| 5493 | || plugin_now.content_hash != initial_plugin.content_hash |
| 5494 | { |
| 5495 | record_outcome( |
| 5496 | call, |
| 5497 | "remove", |
| 5498 | Some(&bundle_name), |
| 5499 | Some(&plugin_now.content_hash), |
| 5500 | None, |
| 5501 | "failed", |
| 5502 | ); |
| 5503 | return change_with_outcome(ChangeOutcome { |
| 5504 | application: "failed", |
| 5505 | stage: "remove", |
| 5506 | target: raw_target, |
| 5507 | changed: false, |
| 5508 | enabled: Some(plugin_now.enabled), |
| 5509 | code: "operation-error", |
| 5510 | diagnostic: "changed after review".to_string(), |
| 5511 | bundle: Some(bundle_name), |
| 5512 | version, |
| 5513 | warnings: Vec::new(), |
| 5514 | }); |
| 5515 | } |
| 5516 | |
| 5517 | let prior_tools = super::owner_report(plugin_now.id.as_str()) |
| 5518 | .map(|report| report.tools) |
| 5519 | .unwrap_or_default(); |
| 5520 | let ws_for_approver_now = canon_ws_now |
| 5521 | .as_deref() |
| 5522 | .unwrap_or_else(|| initial_registry.workspace()); |
| 5523 | let approver_used_now = approver_from_carrier(call, &tool, &carrier, ws_for_approver_now).ok(); |
| 5524 | let policy = extension_host_policy_enabled(); |
| 5525 | #[cfg(any(test, feature = "test-support"))] |
| 5526 | let env_scope = crate::test_support::env_scope_ticket(); |
| 5527 | let selector = plugin_now.id.as_str().to_string(); |
| 5528 | let plugin_ref_copy = (*plugin_now).clone(); |
| 5529 | let base_reg = Arc::clone(&initial_registry); |
| 5530 | let step_disable = tokio::task::spawn_blocking(move || { |
| 5531 | #[cfg(any(test, feature = "test-support"))] |
| 5532 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 5533 | let _scope = PolicyScope::propagate(policy); |
| 5534 | let fresh = base_reg.rediscover_for_workspace(base_reg.workspace()); |
| 5535 | let mut reg = (*fresh).clone(); |
| 5536 | let was_enabled = reg.get(&selector).is_some_and(|p| p.enabled); |
| 5537 | let disable_res = if was_enabled { |
| 5538 | reg.disable(&selector).map(|()| true) |
| 5539 | } else { |
| 5540 | Ok(false) |
| 5541 | }; |
| 5542 | let fresh_after_disable = if matches!(disable_res, Ok(true)) { |
| 5543 | Some(reg.rediscover_for_workspace(reg.workspace())) |
| 5544 | } else { |
| 5545 | None |
| 5546 | }; |
| 5547 | (reg, fresh_after_disable, disable_res) |
| 5548 | }) |
| 5549 | .await |
| 5550 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 5551 | |
| 5552 | let (mut reg_for_uninstall, fresh_after_disable, disable_res) = step_disable; |
| 5553 | let turned_off = match disable_res { |
| 5554 | Ok(changed_flag) => changed_flag, |
| 5555 | Err(err) => { |
| 5556 | let scrub = ScrubContext { |
| 5557 | workspace: reg_for_uninstall.workspace(), |
| 5558 | canon_workspace: canon_ws_now.as_deref(), |
| 5559 | plugin_root: Some(&plugin_now.canonical_root), |
| 5560 | user_plugins_dir: reg_for_uninstall.user_plugins_dir(), |
| 5561 | state_path: reg_for_uninstall.state_path(), |
| 5562 | }; |
| 5563 | record_outcome( |
| 5564 | call, |
| 5565 | "remove", |
| 5566 | Some(&bundle_name), |
| 5567 | Some(&plugin_now.content_hash), |
| 5568 | None, |
| 5569 | "failed", |
| 5570 | ); |
| 5571 | return change_with_outcome(ChangeOutcome { |
| 5572 | application: "failed", |
| 5573 | stage: "remove", |
| 5574 | target: raw_target, |
| 5575 | changed: false, |
| 5576 | enabled: Some(plugin_now.enabled), |
| 5577 | code: "operation-error", |
| 5578 | diagnostic: scrub_message(&err, &scrub), |
| 5579 | bundle: Some(bundle_name), |
| 5580 | version, |
| 5581 | warnings: Vec::new(), |
| 5582 | }); |
| 5583 | } |
| 5584 | }; |
| 5585 | |
| 5586 | if turned_off && let Some(fresh_after_disable) = fresh_after_disable { |
| 5587 | settle_non_active_change( |
| 5588 | call, |
| 5589 | &fresh_after_disable, |
| 5590 | Some(make_change_mark( |
| 5591 | &bundle_name, |
| 5592 | "disabled", |
| 5593 | Some(&plugin_now.content_hash), |
| 5594 | approver_used_now.as_ref(), |
| 5595 | plugin_services(Some(&plugin_now)), |
| 5596 | Vec::new(), |
| 5597 | prior_tools.clone(), |
| 5598 | )), |
| 5599 | ) |
| 5600 | .await; |
| 5601 | } |
| 5602 | |
| 5603 | #[cfg(test)] |
| 5604 | fire_post_disable_hook_for_test(&plugin_ref_copy); |
| 5605 | let _ = &plugin_ref_copy; |
| 5606 | |
| 5607 | let network = network_policy_for(&tool); |
| 5608 | let uninstall_res = execute( |
| 5609 | PluginMutationRequest::Uninstall { |
| 5610 | selector: plugin_now.id.as_str().to_string(), |
| 5611 | }, |
| 5612 | &PluginMutationContext { |
| 5613 | network: &network, |
| 5614 | max_size: DEFAULT_MAX_SIZE_BYTES, |
| 5615 | }, |
| 5616 | &mut reg_for_uninstall, |
| 5617 | ) |
| 5618 | .await; |
| 5619 | |
| 5620 | let final_reg = tokio::task::spawn_blocking(move || { |
| 5621 | #[cfg(any(test, feature = "test-support"))] |
| 5622 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 5623 | let _scope = PolicyScope::propagate(policy); |
| 5624 | reg_for_uninstall.rediscover_for_workspace(reg_for_uninstall.workspace()) |
| 5625 | }) |
| 5626 | .await |
| 5627 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 5628 | |
| 5629 | match uninstall_res { |
| 5630 | Ok(_) => { |
| 5631 | let leaf = super::supervisor::plugin_data_dir( |
| 5632 | Path::new("~"), |
| 5633 | plugin_now.id.as_str(), |
| 5634 | &bundle_name, |
| 5635 | ) |
| 5636 | .file_name() |
| 5637 | .map(|name| name.to_string_lossy().into_owned()) |
| 5638 | .filter(|name| !name.is_empty()) |
| 5639 | .unwrap_or_else(|| bundle_name.clone()); |
| 5640 | let mut truncated = false; |
| 5641 | let safe_leaf = sanitize_inline(&leaf, MAX_NAME_BYTES, &mut truncated); |
| 5642 | let data_warning = format!( |
| 5643 | "kept plugin data folder at ~/.codewhale/extension-host/data/plugins/{safe_leaf}" |
| 5644 | ); |
| 5645 | let ws_for_approver = canon_ws_now |
| 5646 | .as_deref() |
| 5647 | .unwrap_or_else(|| final_reg.workspace()); |
| 5648 | let approver_used = approver_from_carrier(call, &tool, &carrier, ws_for_approver) |
| 5649 | .ok() |
| 5650 | .or(approver_used_now); |
| 5651 | settle_non_active_change( |
| 5652 | call, |
| 5653 | &final_reg, |
| 5654 | Some(make_change_mark( |
| 5655 | &bundle_name, |
| 5656 | "removed", |
| 5657 | Some(&plugin_now.content_hash), |
| 5658 | approver_used.as_ref(), |
| 5659 | Vec::new(), |
| 5660 | Vec::new(), |
| 5661 | prior_tools, |
| 5662 | )), |
| 5663 | ) |
| 5664 | .await; |
| 5665 | record_outcome( |
| 5666 | call, |
| 5667 | "remove", |
| 5668 | Some(&bundle_name), |
| 5669 | Some(&plugin_now.content_hash), |
| 5670 | approver_used.as_ref(), |
| 5671 | "applied", |
| 5672 | ); |
| 5673 | change_ok( |
| 5674 | "remove", |
| 5675 | raw_target, |
| 5676 | true, |
| 5677 | Some(false), |
| 5678 | Some(bundle_name), |
| 5679 | version, |
| 5680 | vec![data_warning], |
| 5681 | ) |
| 5682 | } |
| 5683 | Err(err) => { |
| 5684 | settle_non_active_change(call, &final_reg, None).await; |
| 5685 | let scrub = ScrubContext { |
| 5686 | workspace: final_reg.workspace(), |
| 5687 | canon_workspace: canon_ws_now.as_deref(), |
| 5688 | plugin_root: Some(&plugin_now.canonical_root), |
| 5689 | user_plugins_dir: final_reg.user_plugins_dir(), |
| 5690 | state_path: final_reg.state_path(), |
| 5691 | }; |
| 5692 | let code = classify_install_error(&err); |
| 5693 | let detail = scrub_message(&format!("{err:#}"), &scrub); |
| 5694 | let msg = if turned_off { |
| 5695 | format!("plugin was turned off, then removal failed: {detail}") |
| 5696 | } else { |
| 5697 | detail |
| 5698 | }; |
| 5699 | let persisted_enabled = final_reg |
| 5700 | .get(plugin_now.id.as_str()) |
| 5701 | .is_some_and(|p| p.enabled); |
| 5702 | record_outcome( |
| 5703 | call, |
| 5704 | "remove", |
| 5705 | Some(&bundle_name), |
| 5706 | Some(&plugin_now.content_hash), |
| 5707 | None, |
| 5708 | "failed", |
| 5709 | ); |
| 5710 | change_with_outcome(ChangeOutcome { |
| 5711 | application: "failed", |
| 5712 | stage: "remove", |
| 5713 | target: raw_target, |
| 5714 | changed: turned_off, |
| 5715 | enabled: Some(persisted_enabled), |
| 5716 | code, |
| 5717 | diagnostic: msg, |
| 5718 | bundle: Some(bundle_name), |
| 5719 | version, |
| 5720 | warnings: Vec::new(), |
| 5721 | }) |
| 5722 | } |
| 5723 | } |
| 5724 | } |
| 5725 | |
| 5726 | async fn toggle( |
| 5727 | call: &BrokerCall, |
| 5728 | mut tool: ToolContext, |
| 5729 | authority: Option<LiveRuntimeAuthority>, |
| 5730 | input: ToggleInput, |
| 5731 | want_enabled: bool, |
| 5732 | ) -> Result<Value, BrokerRefusal> { |
| 5733 | let method_name = if want_enabled { "enable" } else { "disable" }; |
| 5734 | let raw_target = validate_required_str(&input.target, "target", MAX_TARGET_BYTES)?; |
| 5735 | let row = validate_optional_str(input.row.as_deref(), "row", MAX_ROW_BYTES)?; |
| 5736 | let initial_registry = live_registry(call, &tool)?; |
| 5737 | let Some(current_authority) = authority else { |
| 5738 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 5739 | }; |
| 5740 | let carrier = require_carried_decision(&tool, ¤t_authority, method_name)?; |
| 5741 | let ( |
| 5742 | approved_enabled, |
| 5743 | approved_plugin_id, |
| 5744 | approved_plugin_name, |
| 5745 | approved_content_hash, |
| 5746 | approved_capability_hash, |
| 5747 | expected_gate_target, |
| 5748 | shown_service_lines, |
| 5749 | shown_service_token, |
| 5750 | ) = match &carrier.change { |
| 5751 | AdmittedChangeKind::Toggle { |
| 5752 | enabled, |
| 5753 | plugin_id, |
| 5754 | plugin_name, |
| 5755 | content_hash, |
| 5756 | capability_hash, |
| 5757 | expected_gate_target, |
| 5758 | shown_service_lines, |
| 5759 | shown_service_token, |
| 5760 | .. |
| 5761 | } => ( |
| 5762 | *enabled, |
| 5763 | plugin_id.clone(), |
| 5764 | plugin_name.clone(), |
| 5765 | content_hash.clone(), |
| 5766 | capability_hash.clone(), |
| 5767 | expected_gate_target.clone(), |
| 5768 | shown_service_lines.clone(), |
| 5769 | shown_service_token.clone(), |
| 5770 | ), |
| 5771 | _ => { |
| 5772 | return Err(BrokerRefusal::Refused { |
| 5773 | service: DshService::Plugins, |
| 5774 | message: "plugin change decision is not a switch decision".to_string(), |
| 5775 | }); |
| 5776 | } |
| 5777 | }; |
| 5778 | if approved_enabled != want_enabled { |
| 5779 | return Err(BrokerRefusal::Refused { |
| 5780 | service: DshService::Plugins, |
| 5781 | message: "plugin change decision does not match enable/disable state".to_string(), |
| 5782 | }); |
| 5783 | } |
| 5784 | let is_agent = matches!(carrier.decider, CreatorDecider::Agent(_)); |
| 5785 | |
| 5786 | let (initial_plugin, is_own, own_denial_reason, _) = match load_existing_plugin( |
| 5787 | Arc::clone(&initial_registry), |
| 5788 | raw_target.clone(), |
| 5789 | row.clone(), |
| 5790 | ) |
| 5791 | .await? |
| 5792 | { |
| 5793 | PreparedExisting::Missing | PreparedExisting::Unremovable(_) => { |
| 5794 | record_outcome(call, method_name, None, None, None, "failed"); |
| 5795 | return change_with_outcome(ChangeOutcome { |
| 5796 | application: "failed", |
| 5797 | stage: method_name, |
| 5798 | target: raw_target.clone(), |
| 5799 | changed: false, |
| 5800 | enabled: None, |
| 5801 | code: "unknown-plugin", |
| 5802 | diagnostic: format!("no plugin `{raw_target}` is installed"), |
| 5803 | bundle: None, |
| 5804 | version: None, |
| 5805 | warnings: Vec::new(), |
| 5806 | }); |
| 5807 | } |
| 5808 | PreparedExisting::NotSoleRow(plugin_name) => { |
| 5809 | record_outcome(call, method_name, Some(&plugin_name), None, None, "failed"); |
| 5810 | return change_with_outcome(ChangeOutcome { |
| 5811 | application: "failed", |
| 5812 | stage: method_name, |
| 5813 | target: raw_target, |
| 5814 | changed: false, |
| 5815 | enabled: None, |
| 5816 | code: "operation-error", |
| 5817 | diagnostic: "Codewhale switches a plugin as a whole; use set_bundle".to_string(), |
| 5818 | bundle: Some(plugin_name), |
| 5819 | version: None, |
| 5820 | warnings: Vec::new(), |
| 5821 | }); |
| 5822 | } |
| 5823 | PreparedExisting::Ambiguous(msg) => { |
| 5824 | record_outcome(call, method_name, None, None, None, "failed"); |
| 5825 | return change_with_outcome(ChangeOutcome { |
| 5826 | application: "failed", |
| 5827 | stage: method_name, |
| 5828 | target: raw_target, |
| 5829 | changed: false, |
| 5830 | enabled: None, |
| 5831 | code: "operation-error", |
| 5832 | diagnostic: msg, |
| 5833 | bundle: None, |
| 5834 | version: None, |
| 5835 | warnings: Vec::new(), |
| 5836 | }); |
| 5837 | } |
| 5838 | PreparedExisting::Found { |
| 5839 | plugin, |
| 5840 | is_own, |
| 5841 | own_denial_reason, |
| 5842 | has_marker: _, |
| 5843 | canon_workspace, |
| 5844 | } => (plugin, is_own, own_denial_reason, canon_workspace), |
| 5845 | }; |
| 5846 | |
| 5847 | let bundle_name = initial_plugin.name().to_string(); |
| 5848 | let version = non_empty_version(&initial_plugin.manifest.plugin.version); |
| 5849 | if initial_plugin.scope == PluginScope::Builtin && is_agent { |
| 5850 | record_outcome( |
| 5851 | call, |
| 5852 | method_name, |
| 5853 | Some(&bundle_name), |
| 5854 | Some(&initial_plugin.content_hash), |
| 5855 | None, |
| 5856 | "failed", |
| 5857 | ); |
| 5858 | return change_with_outcome(ChangeOutcome { |
| 5859 | application: "failed", |
| 5860 | stage: method_name, |
| 5861 | target: raw_target, |
| 5862 | changed: false, |
| 5863 | enabled: Some(initial_plugin.enabled), |
| 5864 | code: "management-required", |
| 5865 | diagnostic: format!( |
| 5866 | "built-in plugin `{bundle_name}` ships with Codewhale and cannot be switched here" |
| 5867 | ), |
| 5868 | bundle: Some(bundle_name), |
| 5869 | version, |
| 5870 | warnings: Vec::new(), |
| 5871 | }); |
| 5872 | } |
| 5873 | |
| 5874 | if is_agent && !has_agent_call_identity(call, &tool) { |
| 5875 | record_outcome( |
| 5876 | call, |
| 5877 | method_name, |
| 5878 | Some(&bundle_name), |
| 5879 | Some(&initial_plugin.content_hash), |
| 5880 | None, |
| 5881 | "failed", |
| 5882 | ); |
| 5883 | return change_with_outcome(ChangeOutcome { |
| 5884 | application: "failed", |
| 5885 | stage: method_name, |
| 5886 | target: raw_target, |
| 5887 | changed: false, |
| 5888 | enabled: Some(initial_plugin.enabled), |
| 5889 | code: "operation-error", |
| 5890 | diagnostic: |
| 5891 | "An approval by the agent must name the thread, turn and tool call that made it" |
| 5892 | .to_string(), |
| 5893 | bundle: Some(bundle_name), |
| 5894 | version, |
| 5895 | warnings: Vec::new(), |
| 5896 | }); |
| 5897 | } |
| 5898 | if !is_own && is_agent { |
| 5899 | let reason = |
| 5900 | own_denial_reason.unwrap_or("this plugin was not installed and approved by this agent"); |
| 5901 | record_outcome( |
| 5902 | call, |
| 5903 | method_name, |
| 5904 | Some(&bundle_name), |
| 5905 | Some(&initial_plugin.content_hash), |
| 5906 | None, |
| 5907 | "failed", |
| 5908 | ); |
| 5909 | return change_with_outcome(ChangeOutcome { |
| 5910 | application: "failed", |
| 5911 | stage: method_name, |
| 5912 | target: raw_target, |
| 5913 | changed: false, |
| 5914 | enabled: Some(initial_plugin.enabled), |
| 5915 | code: "operation-error", |
| 5916 | diagnostic: format!("{reason}; {ASK_PERSON_HINT}"), |
| 5917 | bundle: Some(bundle_name), |
| 5918 | version, |
| 5919 | warnings: Vec::new(), |
| 5920 | }); |
| 5921 | } |
| 5922 | |
| 5923 | let gate_target = if want_enabled { |
| 5924 | format!( |
| 5925 | "{bundle_name} {} {}", |
| 5926 | initial_plugin.content_hash, |
| 5927 | initial_plugin.id.as_str() |
| 5928 | ) |
| 5929 | } else { |
| 5930 | format!("{bundle_name} {}", initial_plugin.id.as_str()) |
| 5931 | }; |
| 5932 | if initial_plugin.id.as_str() != approved_plugin_id || bundle_name != approved_plugin_name { |
| 5933 | return Err(BrokerRefusal::Refused { |
| 5934 | service: DshService::Plugins, |
| 5935 | message: "plugin switch target changed after review".to_string(), |
| 5936 | }); |
| 5937 | } |
| 5938 | if initial_plugin.content_hash != approved_content_hash |
| 5939 | || initial_plugin.capability_hash != approved_capability_hash |
| 5940 | || gate_target != expected_gate_target |
| 5941 | { |
| 5942 | record_outcome( |
| 5943 | call, |
| 5944 | method_name, |
| 5945 | Some(&bundle_name), |
| 5946 | Some(&initial_plugin.content_hash), |
| 5947 | None, |
| 5948 | "failed", |
| 5949 | ); |
| 5950 | return change_with_outcome(ChangeOutcome { |
| 5951 | application: "failed", |
| 5952 | stage: method_name, |
| 5953 | target: raw_target, |
| 5954 | changed: false, |
| 5955 | enabled: Some(initial_plugin.enabled), |
| 5956 | code: "operation-error", |
| 5957 | diagnostic: "changed after review".to_string(), |
| 5958 | bundle: Some(bundle_name), |
| 5959 | version, |
| 5960 | warnings: Vec::new(), |
| 5961 | }); |
| 5962 | } |
| 5963 | call.context |
| 5964 | .act(method_name, BrokerEffect::Write, Some(&gate_target)) |
| 5965 | .await?; |
| 5966 | |
| 5967 | if call.context.cancel().is_cancelled() { |
| 5968 | record_outcome( |
| 5969 | call, |
| 5970 | method_name, |
| 5971 | Some(&bundle_name), |
| 5972 | Some(&initial_plugin.content_hash), |
| 5973 | None, |
| 5974 | "cancelled", |
| 5975 | ); |
| 5976 | return cancelled_result( |
| 5977 | method_name, |
| 5978 | raw_target, |
| 5979 | Some(bundle_name), |
| 5980 | version, |
| 5981 | Vec::new(), |
| 5982 | ); |
| 5983 | } |
| 5984 | |
| 5985 | tool = match check_live_after_act(call, &carrier) { |
| 5986 | CarrierLiveCheck::Valid(refreshed) => refreshed, |
| 5987 | CarrierLiveCheck::Unavailable => { |
| 5988 | return Err(BrokerRefusal::NotAvailable(DshService::Plugins)); |
| 5989 | } |
| 5990 | CarrierLiveCheck::Narrowed => { |
| 5991 | record_outcome( |
| 5992 | call, |
| 5993 | method_name, |
| 5994 | Some(&bundle_name), |
| 5995 | Some(&initial_plugin.content_hash), |
| 5996 | None, |
| 5997 | "failed", |
| 5998 | ); |
| 5999 | return change_with_outcome(ChangeOutcome { |
| 6000 | application: "failed", |
| 6001 | stage: method_name, |
| 6002 | target: raw_target, |
| 6003 | changed: false, |
| 6004 | enabled: Some(initial_plugin.enabled), |
| 6005 | code: "operation-error", |
| 6006 | diagnostic: |
| 6007 | "permission mode changed during review and no longer allows changing plugin state" |
| 6008 | .to_string(), |
| 6009 | bundle: Some(bundle_name), |
| 6010 | version, |
| 6011 | warnings: Vec::new(), |
| 6012 | }); |
| 6013 | } |
| 6014 | }; |
| 6015 | |
| 6016 | let (plugin_now, still_own, reason_now, canon_ws_now) = |
| 6017 | match load_existing_plugin(Arc::clone(&initial_registry), raw_target.clone(), row).await? { |
| 6018 | PreparedExisting::Missing | PreparedExisting::Unremovable(_) => { |
| 6019 | record_outcome(call, method_name, Some(&bundle_name), None, None, "failed"); |
| 6020 | return change_with_outcome(ChangeOutcome { |
| 6021 | application: "failed", |
| 6022 | stage: method_name, |
| 6023 | target: raw_target, |
| 6024 | changed: false, |
| 6025 | enabled: None, |
| 6026 | code: "unknown-plugin", |
| 6027 | diagnostic: format!("plugin `{bundle_name}` is no longer installed"), |
| 6028 | bundle: Some(bundle_name), |
| 6029 | version, |
| 6030 | warnings: Vec::new(), |
| 6031 | }); |
| 6032 | } |
| 6033 | PreparedExisting::NotSoleRow(name) => { |
| 6034 | record_outcome(call, method_name, Some(&name), None, None, "failed"); |
| 6035 | return change_with_outcome(ChangeOutcome { |
| 6036 | application: "failed", |
| 6037 | stage: method_name, |
| 6038 | target: raw_target, |
| 6039 | changed: false, |
| 6040 | enabled: None, |
| 6041 | code: "operation-error", |
| 6042 | diagnostic: "Codewhale switches a plugin as a whole; use set_bundle" |
| 6043 | .to_string(), |
| 6044 | bundle: Some(name), |
| 6045 | version, |
| 6046 | warnings: Vec::new(), |
| 6047 | }); |
| 6048 | } |
| 6049 | PreparedExisting::Ambiguous(msg) => { |
| 6050 | record_outcome(call, method_name, Some(&bundle_name), None, None, "failed"); |
| 6051 | return change_with_outcome(ChangeOutcome { |
| 6052 | application: "failed", |
| 6053 | stage: method_name, |
| 6054 | target: raw_target, |
| 6055 | changed: false, |
| 6056 | enabled: None, |
| 6057 | code: "operation-error", |
| 6058 | diagnostic: msg, |
| 6059 | bundle: Some(bundle_name), |
| 6060 | version, |
| 6061 | warnings: Vec::new(), |
| 6062 | }); |
| 6063 | } |
| 6064 | PreparedExisting::Found { |
| 6065 | plugin, |
| 6066 | is_own, |
| 6067 | own_denial_reason, |
| 6068 | has_marker: _, |
| 6069 | canon_workspace, |
| 6070 | } => (plugin, is_own, own_denial_reason, canon_workspace), |
| 6071 | }; |
| 6072 | |
| 6073 | if plugin_now.scope == PluginScope::Builtin && is_agent { |
| 6074 | record_outcome( |
| 6075 | call, |
| 6076 | method_name, |
| 6077 | Some(&bundle_name), |
| 6078 | Some(&plugin_now.content_hash), |
| 6079 | None, |
| 6080 | "failed", |
| 6081 | ); |
| 6082 | return change_with_outcome(ChangeOutcome { |
| 6083 | application: "failed", |
| 6084 | stage: method_name, |
| 6085 | target: raw_target, |
| 6086 | changed: false, |
| 6087 | enabled: Some(plugin_now.enabled), |
| 6088 | code: "management-required", |
| 6089 | diagnostic: format!( |
| 6090 | "built-in plugin `{bundle_name}` ships with Codewhale and cannot be switched here" |
| 6091 | ), |
| 6092 | bundle: Some(bundle_name), |
| 6093 | version, |
| 6094 | warnings: Vec::new(), |
| 6095 | }); |
| 6096 | } |
| 6097 | if is_agent && !has_agent_call_identity(call, &tool) { |
| 6098 | record_outcome( |
| 6099 | call, |
| 6100 | method_name, |
| 6101 | Some(&bundle_name), |
| 6102 | Some(&plugin_now.content_hash), |
| 6103 | None, |
| 6104 | "failed", |
| 6105 | ); |
| 6106 | return change_with_outcome(ChangeOutcome { |
| 6107 | application: "failed", |
| 6108 | stage: method_name, |
| 6109 | target: raw_target, |
| 6110 | changed: false, |
| 6111 | enabled: Some(plugin_now.enabled), |
| 6112 | code: "operation-error", |
| 6113 | diagnostic: |
| 6114 | "An approval by the agent must name the thread, turn and tool call that made it" |
| 6115 | .to_string(), |
| 6116 | bundle: Some(bundle_name), |
| 6117 | version, |
| 6118 | warnings: Vec::new(), |
| 6119 | }); |
| 6120 | } |
| 6121 | if is_agent && !still_own { |
| 6122 | let reason = reason_now.unwrap_or("this plugin is not owned by this agent"); |
| 6123 | record_outcome( |
| 6124 | call, |
| 6125 | method_name, |
| 6126 | Some(&bundle_name), |
| 6127 | Some(&plugin_now.content_hash), |
| 6128 | None, |
| 6129 | "failed", |
| 6130 | ); |
| 6131 | return change_with_outcome(ChangeOutcome { |
| 6132 | application: "failed", |
| 6133 | stage: method_name, |
| 6134 | target: raw_target, |
| 6135 | changed: false, |
| 6136 | enabled: Some(plugin_now.enabled), |
| 6137 | code: "operation-error", |
| 6138 | diagnostic: format!("{reason}; {ASK_PERSON_HINT}"), |
| 6139 | bundle: Some(bundle_name), |
| 6140 | version, |
| 6141 | warnings: Vec::new(), |
| 6142 | }); |
| 6143 | } |
| 6144 | if plugin_now.id != initial_plugin.id |
| 6145 | || plugin_now.install_nonce != initial_plugin.install_nonce |
| 6146 | || plugin_now.content_hash != initial_plugin.content_hash |
| 6147 | || plugin_now.capability_hash != initial_plugin.capability_hash |
| 6148 | { |
| 6149 | record_outcome( |
| 6150 | call, |
| 6151 | method_name, |
| 6152 | Some(&bundle_name), |
| 6153 | Some(&plugin_now.content_hash), |
| 6154 | None, |
| 6155 | "failed", |
| 6156 | ); |
| 6157 | return change_with_outcome(ChangeOutcome { |
| 6158 | application: "failed", |
| 6159 | stage: method_name, |
| 6160 | target: raw_target, |
| 6161 | changed: false, |
| 6162 | enabled: Some(plugin_now.enabled), |
| 6163 | code: "operation-error", |
| 6164 | diagnostic: "changed after review".to_string(), |
| 6165 | bundle: Some(bundle_name), |
| 6166 | version, |
| 6167 | warnings: Vec::new(), |
| 6168 | }); |
| 6169 | } |
| 6170 | |
| 6171 | let policy = extension_host_policy_enabled(); |
| 6172 | #[cfg(any(test, feature = "test-support"))] |
| 6173 | let env_scope = crate::test_support::env_scope_ticket(); |
| 6174 | #[cfg(any(test, feature = "test-support"))] |
| 6175 | let test_offered: Vec<HostService> = HostService::ALL |
| 6176 | .into_iter() |
| 6177 | .filter(|service| offered(*service)) |
| 6178 | .collect(); |
| 6179 | let ws_for_approver = canon_ws_now |
| 6180 | .as_deref() |
| 6181 | .unwrap_or_else(|| initial_registry.workspace()); |
| 6182 | let approver = match approver_from_carrier(call, &tool, &carrier, ws_for_approver) { |
| 6183 | Ok(approver) => approver, |
| 6184 | Err(msg) => { |
| 6185 | record_outcome( |
| 6186 | call, |
| 6187 | method_name, |
| 6188 | Some(&bundle_name), |
| 6189 | Some(&plugin_now.content_hash), |
| 6190 | None, |
| 6191 | "failed", |
| 6192 | ); |
| 6193 | return change_with_outcome(ChangeOutcome { |
| 6194 | application: "failed", |
| 6195 | stage: method_name, |
| 6196 | target: raw_target, |
| 6197 | changed: false, |
| 6198 | enabled: Some(plugin_now.enabled), |
| 6199 | code: "operation-error", |
| 6200 | diagnostic: msg, |
| 6201 | bundle: Some(bundle_name), |
| 6202 | version, |
| 6203 | warnings: Vec::new(), |
| 6204 | }); |
| 6205 | } |
| 6206 | }; |
| 6207 | let approver_for_commit = approver.clone(); |
| 6208 | let selector = plugin_now.id.as_str().to_string(); |
| 6209 | let was_enabled = plugin_now.enabled; |
| 6210 | let was_trusted = plugin_now.trusted(); |
| 6211 | let base_reg = Arc::clone(&initial_registry); |
| 6212 | let canon_ws_clone = canon_ws_now.clone(); |
| 6213 | |
| 6214 | enum ToggleOutcome { |
| 6215 | ServiceReviewChanged { |
| 6216 | registry: Arc<PluginRegistry>, |
| 6217 | changed: bool, |
| 6218 | enabled: bool, |
| 6219 | }, |
| 6220 | Failed { |
| 6221 | registry: Arc<PluginRegistry>, |
| 6222 | changed: bool, |
| 6223 | enabled: bool, |
| 6224 | err: String, |
| 6225 | }, |
| 6226 | Overridden { |
| 6227 | registry: Arc<PluginRegistry>, |
| 6228 | changed: bool, |
| 6229 | enabled: bool, |
| 6230 | err: String, |
| 6231 | }, |
| 6232 | Done { |
| 6233 | registry: Arc<PluginRegistry>, |
| 6234 | loaded: Box<LoadedPlugin>, |
| 6235 | changed: bool, |
| 6236 | warnings: Vec<String>, |
| 6237 | }, |
| 6238 | } |
| 6239 | |
| 6240 | let prior_tools = super::owner_report(plugin_now.id.as_str()) |
| 6241 | .map(|report| report.tools) |
| 6242 | .unwrap_or_default(); |
| 6243 | |
| 6244 | let outcome = tokio::task::spawn_blocking(move || { |
| 6245 | #[cfg(any(test, feature = "test-support"))] |
| 6246 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 6247 | #[cfg(any(test, feature = "test-support"))] |
| 6248 | let _test_offer = TestOffer::only(&test_offered); |
| 6249 | let _scope = PolicyScope::propagate(policy); |
| 6250 | let fresh = base_reg.rediscover_for_workspace(base_reg.workspace()); |
| 6251 | let mut reg = (*fresh).clone(); |
| 6252 | let needs_person_upgrade = matches!(approver_for_commit, PluginApprover::Person { .. }) |
| 6253 | && matches!( |
| 6254 | fresh.get(&selector).and_then(|p| p.approved_by.as_ref()), |
| 6255 | Some(PluginApprover::Agent(_)) |
| 6256 | ); |
| 6257 | let changed = if want_enabled { |
| 6258 | let post_review = reg.host_service_review_for(&selector, &approver_for_commit); |
| 6259 | let post_lines = post_review |
| 6260 | .as_ref() |
| 6261 | .map(HostServiceReview::text) |
| 6262 | .unwrap_or_default(); |
| 6263 | let post_token = post_review.as_ref().map(|review| review.token.clone()); |
| 6264 | if post_lines != shown_service_lines || post_token != shown_service_token { |
| 6265 | return ToggleOutcome::ServiceReviewChanged { |
| 6266 | registry: fresh, |
| 6267 | changed: false, |
| 6268 | enabled: was_enabled, |
| 6269 | }; |
| 6270 | } |
| 6271 | let commit_res = if !was_trusted || needs_person_upgrade { |
| 6272 | let host_services = post_review.map(|review| review.token); |
| 6273 | reg.trust_and_enable_by( |
| 6274 | &selector, |
| 6275 | ReviewApproval { |
| 6276 | approved_by: approver_for_commit.clone(), |
| 6277 | host_services, |
| 6278 | }, |
| 6279 | approver_for_commit.clone(), |
| 6280 | ) |
| 6281 | } else { |
| 6282 | reg.enable_by(&selector, approver_for_commit.clone()) |
| 6283 | }; |
| 6284 | if let Err(err) = commit_res { |
| 6285 | let latest = reg.rediscover_for_workspace(reg.workspace()); |
| 6286 | let actual_enabled = latest.get(&selector).is_some_and(|p| p.enabled); |
| 6287 | if is_managed_policy_error(&err) { |
| 6288 | return ToggleOutcome::Overridden { |
| 6289 | registry: latest, |
| 6290 | changed: false, |
| 6291 | enabled: actual_enabled, |
| 6292 | err, |
| 6293 | }; |
| 6294 | } |
| 6295 | return ToggleOutcome::Failed { |
| 6296 | registry: latest, |
| 6297 | changed: false, |
| 6298 | enabled: actual_enabled, |
| 6299 | err, |
| 6300 | }; |
| 6301 | } |
| 6302 | !was_enabled || !was_trusted || needs_person_upgrade |
| 6303 | } else { |
| 6304 | if let Err(err) = reg.disable(&selector) { |
| 6305 | let latest = reg.rediscover_for_workspace(reg.workspace()); |
| 6306 | let actual_enabled = latest.get(&selector).is_some_and(|p| p.enabled); |
| 6307 | return ToggleOutcome::Failed { |
| 6308 | registry: latest, |
| 6309 | changed: false, |
| 6310 | enabled: actual_enabled, |
| 6311 | err, |
| 6312 | }; |
| 6313 | } |
| 6314 | was_enabled |
| 6315 | }; |
| 6316 | let final_reg = reg.rediscover_for_workspace(reg.workspace()); |
| 6317 | let Some(final_loaded) = final_reg.get(&selector).cloned() else { |
| 6318 | return ToggleOutcome::Failed { |
| 6319 | registry: final_reg, |
| 6320 | changed, |
| 6321 | enabled: false, |
| 6322 | err: "plugin vanished while updating state".to_string(), |
| 6323 | }; |
| 6324 | }; |
| 6325 | let scrub = ScrubContext { |
| 6326 | workspace: final_reg.workspace(), |
| 6327 | canon_workspace: canon_ws_clone.as_deref(), |
| 6328 | plugin_root: Some(&final_loaded.canonical_root), |
| 6329 | user_plugins_dir: final_reg.user_plugins_dir(), |
| 6330 | state_path: final_reg.state_path(), |
| 6331 | }; |
| 6332 | let warnings = if want_enabled { |
| 6333 | let effective_approver = final_loaded |
| 6334 | .approved_by |
| 6335 | .as_ref() |
| 6336 | .unwrap_or(&approver_for_commit); |
| 6337 | collect_enable_warnings( |
| 6338 | &final_reg, |
| 6339 | &final_loaded, |
| 6340 | effective_approver, |
| 6341 | final_loaded.enabled, |
| 6342 | false, |
| 6343 | &scrub, |
| 6344 | ) |
| 6345 | } else { |
| 6346 | vec![approver_label(final_loaded.approved_by.as_ref()).to_string()] |
| 6347 | }; |
| 6348 | ToggleOutcome::Done { |
| 6349 | registry: final_reg, |
| 6350 | loaded: Box::new(final_loaded), |
| 6351 | changed, |
| 6352 | warnings, |
| 6353 | } |
| 6354 | }) |
| 6355 | .await |
| 6356 | .map_err(|_| BrokerRefusal::NotAvailable(DshService::Plugins))?; |
| 6357 | |
| 6358 | match outcome { |
| 6359 | ToggleOutcome::ServiceReviewChanged { |
| 6360 | registry: fresh, |
| 6361 | changed, |
| 6362 | enabled, |
| 6363 | } => { |
| 6364 | let mark = changed.then(|| { |
| 6365 | make_change_mark( |
| 6366 | &bundle_name, |
| 6367 | if want_enabled { "enabled" } else { "disabled" }, |
| 6368 | Some(&plugin_now.content_hash), |
| 6369 | Some(&approver), |
| 6370 | plugin_services(fresh.get(plugin_now.id.as_str())), |
| 6371 | Vec::new(), |
| 6372 | if want_enabled { |
| 6373 | Vec::new() |
| 6374 | } else { |
| 6375 | prior_tools.clone() |
| 6376 | }, |
| 6377 | ) |
| 6378 | }); |
| 6379 | settle_non_active_change(call, &fresh, mark).await; |
| 6380 | record_outcome( |
| 6381 | call, |
| 6382 | method_name, |
| 6383 | Some(&bundle_name), |
| 6384 | Some(&plugin_now.content_hash), |
| 6385 | Some(&approver), |
| 6386 | "failed", |
| 6387 | ); |
| 6388 | change_with_outcome(ChangeOutcome { |
| 6389 | application: "failed", |
| 6390 | stage: method_name, |
| 6391 | target: raw_target, |
| 6392 | changed, |
| 6393 | enabled: Some(enabled), |
| 6394 | code: "operation-error", |
| 6395 | diagnostic: "the services it asks for changed after review".to_string(), |
| 6396 | bundle: Some(bundle_name), |
| 6397 | version, |
| 6398 | warnings: Vec::new(), |
| 6399 | }) |
| 6400 | } |
| 6401 | ToggleOutcome::Overridden { |
| 6402 | registry: fresh, |
| 6403 | changed, |
| 6404 | enabled, |
| 6405 | err, |
| 6406 | } => { |
| 6407 | let scrub = ScrubContext { |
| 6408 | workspace: fresh.workspace(), |
| 6409 | canon_workspace: canon_ws_now.as_deref(), |
| 6410 | plugin_root: Some(&plugin_now.canonical_root), |
| 6411 | user_plugins_dir: fresh.user_plugins_dir(), |
| 6412 | state_path: fresh.state_path(), |
| 6413 | }; |
| 6414 | let diag = scrub_message(&err, &scrub); |
| 6415 | let mark = changed.then(|| { |
| 6416 | make_change_mark( |
| 6417 | &bundle_name, |
| 6418 | if want_enabled { "enabled" } else { "disabled" }, |
| 6419 | Some(&plugin_now.content_hash), |
| 6420 | Some(&approver), |
| 6421 | plugin_services(fresh.get(plugin_now.id.as_str())), |
| 6422 | Vec::new(), |
| 6423 | if want_enabled { |
| 6424 | Vec::new() |
| 6425 | } else { |
| 6426 | prior_tools.clone() |
| 6427 | }, |
| 6428 | ) |
| 6429 | }); |
| 6430 | settle_non_active_change(call, &fresh, mark).await; |
| 6431 | record_outcome( |
| 6432 | call, |
| 6433 | method_name, |
| 6434 | Some(&bundle_name), |
| 6435 | Some(&plugin_now.content_hash), |
| 6436 | Some(&approver), |
| 6437 | "overridden", |
| 6438 | ); |
| 6439 | change_with_outcome(ChangeOutcome { |
| 6440 | application: "overridden", |
| 6441 | stage: method_name, |
| 6442 | target: raw_target, |
| 6443 | changed, |
| 6444 | enabled: Some(enabled), |
| 6445 | code: "operation-error", |
| 6446 | diagnostic: diag, |
| 6447 | bundle: Some(bundle_name), |
| 6448 | version, |
| 6449 | warnings: Vec::new(), |
| 6450 | }) |
| 6451 | } |
| 6452 | ToggleOutcome::Failed { |
| 6453 | registry: fresh, |
| 6454 | changed, |
| 6455 | enabled, |
| 6456 | err, |
| 6457 | } => { |
| 6458 | let scrub = ScrubContext { |
| 6459 | workspace: fresh.workspace(), |
| 6460 | canon_workspace: canon_ws_now.as_deref(), |
| 6461 | plugin_root: Some(&plugin_now.canonical_root), |
| 6462 | user_plugins_dir: fresh.user_plugins_dir(), |
| 6463 | state_path: fresh.state_path(), |
| 6464 | }; |
| 6465 | let has_native = fresh |
| 6466 | .get(plugin_now.id.as_str()) |
| 6467 | .map_or(plugin_now.inventory.native > 0, |p| p.inventory.native > 0); |
| 6468 | let diag = if want_enabled { |
| 6469 | map_enable_failure_diagnostic(&err, has_native, policy, &scrub) |
| 6470 | } else { |
| 6471 | scrub_message(&err, &scrub) |
| 6472 | }; |
| 6473 | let mark = changed.then(|| { |
| 6474 | make_change_mark( |
| 6475 | &bundle_name, |
| 6476 | if want_enabled { "enabled" } else { "disabled" }, |
| 6477 | Some(&plugin_now.content_hash), |
| 6478 | Some(&approver), |
| 6479 | plugin_services(fresh.get(plugin_now.id.as_str())), |
| 6480 | Vec::new(), |
| 6481 | if want_enabled { |
| 6482 | Vec::new() |
| 6483 | } else { |
| 6484 | prior_tools.clone() |
| 6485 | }, |
| 6486 | ) |
| 6487 | }); |
| 6488 | settle_non_active_change(call, &fresh, mark).await; |
| 6489 | record_outcome( |
| 6490 | call, |
| 6491 | method_name, |
| 6492 | Some(&bundle_name), |
| 6493 | Some(&plugin_now.content_hash), |
| 6494 | Some(&approver), |
| 6495 | "failed", |
| 6496 | ); |
| 6497 | change_with_outcome(ChangeOutcome { |
| 6498 | application: "failed", |
| 6499 | stage: method_name, |
| 6500 | target: raw_target, |
| 6501 | changed, |
| 6502 | enabled: Some(enabled), |
| 6503 | code: "operation-error", |
| 6504 | diagnostic: diag, |
| 6505 | bundle: Some(bundle_name), |
| 6506 | version, |
| 6507 | warnings: Vec::new(), |
| 6508 | }) |
| 6509 | } |
| 6510 | ToggleOutcome::Done { |
| 6511 | registry: final_reg, |
| 6512 | loaded: final_loaded, |
| 6513 | changed, |
| 6514 | warnings, |
| 6515 | } => { |
| 6516 | let scrub = ScrubContext { |
| 6517 | workspace: final_reg.workspace(), |
| 6518 | canon_workspace: canon_ws_now.as_deref(), |
| 6519 | plugin_root: Some(&final_loaded.canonical_root), |
| 6520 | user_plugins_dir: final_reg.user_plugins_dir(), |
| 6521 | state_path: final_reg.state_path(), |
| 6522 | }; |
| 6523 | let warnings = if want_enabled && final_loaded.enabled { |
| 6524 | match finish_enabled_activation( |
| 6525 | call, |
| 6526 | EnableActivation { |
| 6527 | method: method_name, |
| 6528 | stage: method_name, |
| 6529 | target: raw_target.clone(), |
| 6530 | changed, |
| 6531 | registry: &final_reg, |
| 6532 | loaded: &final_loaded, |
| 6533 | approver: &approver, |
| 6534 | version: version.clone(), |
| 6535 | warnings, |
| 6536 | prior_tools, |
| 6537 | }, |
| 6538 | &scrub, |
| 6539 | ) |
| 6540 | .await |
| 6541 | { |
| 6542 | std::ops::ControlFlow::Continue(updated) => updated, |
| 6543 | std::ops::ControlFlow::Break(early) => return early, |
| 6544 | } |
| 6545 | } else { |
| 6546 | let mark = changed.then(|| { |
| 6547 | make_change_mark( |
| 6548 | final_loaded.name(), |
| 6549 | if final_loaded.enabled { |
| 6550 | "enabled" |
| 6551 | } else { |
| 6552 | "disabled" |
| 6553 | }, |
| 6554 | Some(&final_loaded.content_hash), |
| 6555 | Some(&approver), |
| 6556 | plugin_services(Some(&final_loaded)), |
| 6557 | Vec::new(), |
| 6558 | if final_loaded.enabled { |
| 6559 | Vec::new() |
| 6560 | } else { |
| 6561 | prior_tools |
| 6562 | }, |
| 6563 | ) |
| 6564 | }); |
| 6565 | settle_non_active_change(call, &final_reg, mark).await; |
| 6566 | warnings |
| 6567 | }; |
| 6568 | record_outcome( |
| 6569 | call, |
| 6570 | method_name, |
| 6571 | Some(final_loaded.name()), |
| 6572 | Some(&final_loaded.content_hash), |
| 6573 | Some(&approver), |
| 6574 | "applied", |
| 6575 | ); |
| 6576 | change_ok( |
| 6577 | method_name, |
| 6578 | raw_target, |
| 6579 | changed, |
| 6580 | Some(final_loaded.enabled), |
| 6581 | Some(final_loaded.name().to_string()), |
| 6582 | non_empty_version(&final_loaded.manifest.plugin.version).or(version), |
| 6583 | warnings, |
| 6584 | ) |
| 6585 | } |
| 6586 | } |
| 6587 | } |
| 6588 | |
| 6589 | fn live(call: &BrokerCall) -> (ToolContext, Option<LiveRuntimeAuthority>) { |
| 6590 | let mut tool = call.context.tool().clone(); |
| 6591 | let authority = tool.refresh_live_posture(); |
| 6592 | (tool, authority) |
| 6593 | } |
| 6594 | |
| 6595 | fn refused() -> BrokerRefusal { |
| 6596 | BrokerRefusal::Refused { |
| 6597 | service: DshService::Plugins, |
| 6598 | message: "the plugins service is not available to this caller".to_string(), |
| 6599 | } |
| 6600 | } |
| 6601 | |
| 6602 | #[cfg(test)] |
| 6603 | #[path = "dsh_plugins_tests.rs"] |
| 6604 | mod tests; |
| 6605 |