返回 CodeWhale
types.rs
根目录 / crates / plugins / src / types.rs
1 use std::collections::HashMap;
2 use std::fmt;
3 use std::path::PathBuf;
4
5 use serde::{Deserialize, Serialize};
6
7 use codewhale_config::{PluginAuthority, PluginId};
8
9 use super::activation::{PluginActivationCapability, PluginActivationPolicy};
10 use super::manifest::{
11 PluginCompatibility, PluginInventory, PluginManifest, ResolvedPluginComponents,
12 };
13
14 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
15 #[serde(rename_all = "snake_case")]
16 pub enum PluginScope {
17 Builtin,
18 User,
19 Workspace,
20 }
21
22 impl PluginScope {
23 #[must_use]
24 pub fn as_str(self) -> &'static str {
25 match self {
26 Self::Builtin => "builtin",
27 Self::User => "user",
28 Self::Workspace => "workspace",
29 }
30 }
31 }
32
33 impl fmt::Display for PluginScope {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 f.write_str(self.as_str())
36 }
37 }
38
39 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
40 #[serde(rename_all = "snake_case")]
41 pub enum PluginOrigin {
42 Builtin,
43 CodeWhaleHome,
44 Workspace,
45 }
46
47 impl PluginOrigin {
48 #[must_use]
49 pub fn as_str(self) -> &'static str {
50 match self {
51 Self::Builtin => "codewhale-builtin",
52 Self::CodeWhaleHome => "codewhale-home",
53 Self::Workspace => "workspace-codewhale",
54 }
55 }
56 }
57
58 impl fmt::Display for PluginOrigin {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 f.write_str(self.as_str())
61 }
62 }
63
64 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
65 #[serde(rename_all = "snake_case")]
66 pub enum PluginDiagnosticLevel {
67 Warning,
68 Error,
69 }
70
71 #[derive(Debug, Clone, PartialEq, Eq)]
72 pub struct PluginDiagnostic {
73 pub level: PluginDiagnosticLevel,
74 pub code: &'static str,
75 pub message: String,
76 pub path: Option<PathBuf>,
77 }
78
79 impl PluginDiagnostic {
80 #[must_use]
81 pub fn warning(code: &'static str, message: impl Into<String>, path: Option<PathBuf>) -> Self {
82 Self {
83 level: PluginDiagnosticLevel::Warning,
84 code,
85 message: message.into(),
86 path,
87 }
88 }
89
90 #[must_use]
91 pub fn error(code: &'static str, message: impl Into<String>, path: Option<PathBuf>) -> Self {
92 Self {
93 level: PluginDiagnosticLevel::Error,
94 code,
95 message: message.into(),
96 path,
97 }
98 }
99 }
100
101 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
102 pub enum PluginTrustStatus {
103 Trusted,
104 NeverReviewed,
105 ContentChanged,
106 CapabilitiesChanged,
107 }
108
109 impl PluginTrustStatus {
110 #[must_use]
111 pub fn as_str(self) -> &'static str {
112 match self {
113 Self::Trusted => "trusted",
114 Self::NeverReviewed => "not-reviewed",
115 Self::ContentChanged => "content-changed",
116 Self::CapabilitiesChanged => "capabilities-changed",
117 }
118 }
119 }
120
121 #[derive(Debug, Clone)]
122 pub struct PluginSkillSnapshot {
123 pub name: String,
124 pub legacy_activation_name: Option<String>,
125 pub description: String,
126 pub localized_descriptions: HashMap<String, String>,
127 pub invocation: codewhale_skill_install::skill_parse::SkillInvocation,
128 pub dependencies: codewhale_skill_install::frontmatter::SkillDependencies,
129 pub aliases: Vec<String>,
130 pub argument_hint: Option<String>,
131 pub body: String,
132 pub path: PathBuf,
133 /// Digest of the exact UTF-8 bytes parsed into this snapshot. This is the
134 /// corresponding entry in the reviewed bundle's file-hash inventory.
135 pub source_hash: String,
136 }
137
138 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139 pub struct PluginReviewEntry {
140 pub reviewed_at: String,
141 #[serde(default, skip_serializing_if = "Option::is_none")]
142 pub approved_by: Option<super::host_services::PluginApprover>,
143 }
144
145 #[derive(Debug, Clone)]
146 pub struct LoadedPlugin {
147 pub id: PluginId,
148 pub manifest: PluginManifest,
149 pub base_path: PathBuf,
150 pub canonical_root: PathBuf,
151 /// Codewhale-owned, content-addressed copy used for active execution.
152 /// `None` means the reviewed bundle has not been staged safely and cannot
153 /// become active even if an older state file says it was enabled.
154 pub staged_root: Option<PathBuf>,
155 pub scope: PluginScope,
156 pub origin: PluginOrigin,
157 pub enabled: bool,
158 pub trust_status: PluginTrustStatus,
159 pub applicable: bool,
160 pub inventory: PluginInventory,
161 pub components: ResolvedPluginComponents,
162 pub content_hash: String,
163 pub capability_hash: String,
164 pub state_generation: u64,
165 pub approved_by: Option<super::host_services::PluginApprover>,
166 pub enabled_by: Option<super::host_services::PluginApprover>,
167 pub host_services: Vec<super::host_services::HostService>,
168 pub outside_reach: bool,
169 pub reviewed_at: Option<String>,
170 pub review_history: Vec<PluginReviewEntry>,
171 pub install_nonce: Option<String>,
172 pub skill_snapshots: Vec<PluginSkillSnapshot>,
173 pub diagnostics: Vec<PluginDiagnostic>,
174 }
175
176 impl LoadedPlugin {
177 #[must_use]
178 pub fn name(&self) -> &str {
179 &self.manifest.plugin.name
180 }
181
182 #[must_use]
183 pub fn trusted(&self) -> bool {
184 self.trust_status == PluginTrustStatus::Trusted
185 }
186
187 /// Explicit-review confirmation token binding a trust confirmation to
188 /// both complete SHA-256 receipts, so a same-inventory bundle cannot
189 /// collide through a short content prefix. The TUI `/plugin trust` flow
190 /// and the Runtime API trust endpoint both compare against this value.
191 #[must_use]
192 pub fn review_token(&self) -> String {
193 format!("{}.{}", self.content_hash, self.capability_hash)
194 }
195
196 #[must_use]
197 pub fn compatibility(&self) -> PluginCompatibility {
198 self.inventory.compatibility()
199 }
200
201 #[must_use]
202 pub fn active(&self) -> bool {
203 self.enabled
204 && self.trusted()
205 && !self.outside_reach
206 && self.staged_root.is_some()
207 && self.applicable
208 && self.inventory.can_activate_supported_components()
209 && !self
210 .diagnostics
211 .iter()
212 .any(|diagnostic| diagnostic.level == PluginDiagnosticLevel::Error)
213 }
214
215 /// Bundle-wide `active()` is not enough at a consumption boundary. Skills
216 /// must request Skills; each MCP server must request its stdio or remote
217 /// transport. A later policy that drops an adapter refuses that adapter
218 /// even if the bundle stays active for another supported surface.
219 #[must_use]
220 pub fn component_active(&self, capability: PluginActivationCapability) -> bool {
221 self.active() && PluginActivationPolicy::current().is_supported(capability)
222 }
223
224 #[must_use]
225 pub(super) fn authority(
226 &self,
227 state_path: PathBuf,
228 workspace: PathBuf,
229 managed_policy_path: PathBuf,
230 ) -> Option<PluginAuthority> {
231 let staged_root = self.staged_root.as_ref()?;
232 let manifest_path = match super::agent_plugin::resolve_manifest_path(&self.canonical_root) {
233 Some(path) => path.strip_prefix(&self.canonical_root).ok()?.to_path_buf(),
234 None => PathBuf::from("plugin.toml"),
235 };
236 Some(PluginAuthority {
237 plugin_id: self.id.clone(),
238 plugin_name: self.name().to_string(),
239 workspace,
240 state_path,
241 managed_policy_path: Some(managed_policy_path.clone()),
242 managed_policy_source: Some(managed_policy_path),
243 source_manifest: self.canonical_root.join(&manifest_path),
244 staged_manifest: staged_root.join(&manifest_path),
245 content_hash: self.content_hash.clone(),
246 capability_hash: self.capability_hash.clone(),
247 state_generation: self.state_generation,
248 })
249 }
250
251 #[must_use]
252 pub fn state_label(&self) -> &'static str {
253 if self.active() {
254 "active"
255 } else if !self.enabled {
256 "disabled"
257 } else if !self.trusted() {
258 "enabled-untrusted"
259 } else if self.staged_root.is_none() {
260 "unstaged"
261 } else if !self.applicable {
262 "inapplicable"
263 } else if !self.inventory.can_activate_supported_components() {
264 "unsupported"
265 } else {
266 "inactive"
267 }
268 }
269
270 #[must_use]
271 pub fn earlier_review_history(&self) -> &[PluginReviewEntry] {
272 if !self.trusted() {
273 return &self.review_history;
274 }
275 match (self.review_history.first(), self.reviewed_at.as_deref()) {
276 (Some(first), Some(current))
277 if first.reviewed_at == current && first.approved_by == self.approved_by =>
278 {
279 &self.review_history[1..]
280 }
281 _ => &self.review_history,
282 }
283 }
284 }
285
285 lines RUST