返回 CodeWhale
runtime.rs
根目录 / crates / plugins / src / runtime.rs
1 //! Runtime adapters for reviewed, content-addressed plugin components.
2 //!
3 //! This module is the only place that translates mutable discovery paths into
4 //! immutable staged component paths. Consumers still revalidate the attached
5 //! [`PluginAuthority`] at their execution boundary so disable, revoke, and
6 //! uninstall transitions in another process fail closed immediately.
7
8 use std::path::{Path, PathBuf};
9
10 use super::PluginRegistry;
11 use super::activation::PluginActivationCapability;
12 use super::registry::verify_plugin_component_authority;
13 use super::types::{LoadedPlugin, PluginScope};
14 use codewhale_config::PluginAuthority;
15
16 #[derive(Debug, Clone, PartialEq, Eq)]
17 pub struct PluginComponentSource {
18 pub plugin_name: String,
19 pub path: PathBuf,
20 pub authority: PluginAuthority,
21 }
22
23 fn component_paths(plugin: &LoadedPlugin, capability: PluginActivationCapability) -> &[PathBuf] {
24 match capability {
25 PluginActivationCapability::Commands => &plugin.components.commands,
26 PluginActivationCapability::Agents => &plugin.components.agents,
27 PluginActivationCapability::Hooks => &plugin.components.hooks,
28 // Extension-host entry modules; only active under the extension-host policy.
29 PluginActivationCapability::Native => &plugin.components.native,
30 PluginActivationCapability::Skills
31 | PluginActivationCapability::McpStdio
32 | PluginActivationCapability::McpRemote
33 | PluginActivationCapability::Providers
34 | PluginActivationCapability::Lsp
35 | PluginActivationCapability::FilesystemRoots
36 | PluginActivationCapability::LifecycleMutation => &[],
37 }
38 }
39
40 /// Why `path` cannot be an extension-host entry, if it cannot.
41 ///
42 /// A `native` entry is one `.mjs`, `.js`, `.cjs`, `.mts` or `.cts` module file:
43 /// the host imports exactly that file and re-hashes it first. This is the one
44 /// statement of the rule. Discovery reports it as an error diagnostic (so
45 /// `/plugin validate` and the review screen show it) and activation refuses the
46 /// entry, both only while the activation policy supports `Native` (`[features]
47 /// extension_host`). With the flag off, `native` stays inventory-only and any
48 /// path is accepted as before.
49 ///
50 /// `is_regular_file` comes from the caller's own view of the bundle (the
51 /// validated manifest's hashed files, or the activation read), so this
52 /// function touches no filesystem.
53 #[must_use]
54 pub fn native_entry_problem(path: &Path, is_regular_file: bool) -> Option<&'static str> {
55 const RULE: &str = "a native entry must be one .mjs, .js, .cjs, .mts or .cts module file";
56 let is_module = path.extension().is_some_and(|extension| {
57 ["mjs", "js", "cjs", "mts", "cts"]
58 .iter()
59 .any(|candidate| extension == *candidate)
60 });
61 (!is_module || !is_regular_file).then_some(RULE)
62 }
63
64 #[must_use]
65 pub async fn component_file_names(
66 paths: &[PathBuf],
67 extension: Option<&str>,
68 lowercase: bool,
69 limit: usize,
70 ) -> (Vec<String>, bool) {
71 fn add(
72 names: &mut std::collections::BTreeSet<String>,
73 path: &Path,
74 extension: Option<&str>,
75 lowercase: bool,
76 ) {
77 if let Some(wanted) = extension
78 && path.extension().and_then(|value| value.to_str()) != Some(wanted)
79 {
80 return;
81 }
82 if let Some(stem) = path.file_stem().and_then(|value| value.to_str()) {
83 names.insert(if lowercase {
84 stem.to_lowercase()
85 } else {
86 stem.to_string()
87 });
88 }
89 }
90
91 let mut names = std::collections::BTreeSet::new();
92 let mut cut = false;
93 for path in paths {
94 let Ok(meta) = tokio::fs::symlink_metadata(path).await else {
95 continue;
96 };
97 if meta.is_file() {
98 add(&mut names, path, extension, lowercase);
99 } else if meta.is_dir()
100 && let Ok(mut entries) = tokio::fs::read_dir(path).await
101 {
102 let mut seen = 0;
103 while let Ok(Some(entry)) = entries.next_entry().await {
104 if seen >= limit {
105 cut = true;
106 break;
107 }
108 seen += 1;
109 if entry.file_type().await.is_ok_and(|kind| kind.is_file()) {
110 add(&mut names, &entry.path(), extension, lowercase);
111 }
112 }
113 }
114 if names.len() >= limit {
115 cut = true;
116 break;
117 }
118 }
119 if names.iter().any(|name| name.chars().any(char::is_control)) {
120 cut = true;
121 names.retain(|name| !name.chars().any(char::is_control));
122 }
123 (names.into_iter().take(limit).collect(), cut)
124 }
125
126 fn scope_precedence(scope: PluginScope) -> u8 {
127 match scope {
128 PluginScope::Workspace => 0,
129 PluginScope::User => 1,
130 PluginScope::Builtin => 2,
131 }
132 }
133
134 /// Resolve one active component kind into immutable staged paths.
135 ///
136 /// Workspace bundles win same-name collisions over user and built-in bundles;
137 /// consumers retain their existing non-plugin precedence above this list.
138 pub fn active_component_sources(
139 registry: &PluginRegistry,
140 capability: PluginActivationCapability,
141 ) -> (Vec<PluginComponentSource>, Vec<String>) {
142 let mut plugins = registry
143 .active_plugins()
144 .into_iter()
145 .filter(|plugin| plugin.component_active(capability))
146 .collect::<Vec<_>>();
147 plugins.sort_by(|left, right| {
148 scope_precedence(left.scope)
149 .cmp(&scope_precedence(right.scope))
150 .then_with(|| left.name().cmp(right.name()))
151 .then_with(|| left.id.cmp(&right.id))
152 });
153
154 let mut sources = Vec::new();
155 let mut errors = Vec::new();
156 for plugin in plugins {
157 let Some(authority) = registry.authority_for(plugin.id.as_str()) else {
158 errors.push(format!(
159 "Plugin `{}` has no persisted runtime authority",
160 plugin.name()
161 ));
162 continue;
163 };
164 if let Err(reason) = verify_plugin_component_authority(&authority, capability) {
165 errors.push(format!(
166 "Plugin `{}` {} adapter was denied: {reason}",
167 plugin.name(),
168 capability.as_str()
169 ));
170 continue;
171 }
172 let Some(staged_root) = plugin.staged_root.as_deref() else {
173 errors.push(format!(
174 "Plugin `{}` has no immutable runtime snapshot",
175 plugin.name()
176 ));
177 continue;
178 };
179 for source_path in component_paths(plugin, capability) {
180 match staged_component_path(&plugin.canonical_root, staged_root, source_path) {
181 Ok(path) => sources.push(PluginComponentSource {
182 plugin_name: plugin.name().to_string(),
183 path,
184 authority: authority.clone(),
185 }),
186 Err(reason) => errors.push(format!(
187 "Plugin `{}` {} component was denied: {reason}",
188 plugin.name(),
189 capability.as_str()
190 )),
191 }
192 }
193 }
194 (sources, errors)
195 }
196
197 pub(super) fn staged_component_path(
198 canonical_root: &Path,
199 staged_root: &Path,
200 source_path: &Path,
201 ) -> Result<PathBuf, String> {
202 let relative = source_path
203 .strip_prefix(canonical_root)
204 .map_err(|_| "reviewed component escaped the plugin root".to_string())?;
205 let staged_root = staged_root
206 .canonicalize()
207 .map_err(|_| "runtime snapshot is unavailable".to_string())?;
208 let candidate = staged_root.join(relative);
209 let candidate = candidate
210 .canonicalize()
211 .map_err(|_| "runtime component is unavailable".to_string())?;
212 if !candidate.starts_with(&staged_root) {
213 return Err("runtime component escaped the immutable snapshot".to_string());
214 }
215 Ok(candidate)
216 }
217
217 lines RUST