Skip to main content

session_core/local_resources/
mod.rs

1//! The local resources a session and `ultron config` resolve (the local half of `core/package-manager.ts`
2//! `resolve()`): the settings' `skills`/`prompts`/`themes` entries (paths, globs and `!`/`+`/`-` patterns, project
3//! scope first) and the auto-discovered ones (`.pi/skills`, `.pi/prompts`, `.pi/themes`, `.agents/skills` from the
4//! cwd up to the git root, `<agentDir>/skills`, `<agentDir>/prompts`, `<agentDir>/themes`, `~/.agents/skills`). A
5//! project that is not trusted contributes no settings entries, no project resources and no ancestor
6//! `.agents/skills`.
7//!
8//! Pi packages (the settings `packages`) and Pi extensions are not supported by ultron-rs: nothing is installed and
9//! no package resources are resolved; the extensions TypeScript would load are only named (see [`extensions`]).
10
11pub mod extensions;
12pub mod files;
13
14pub use files::{RESOURCE_TYPES, ResourceType};
15
16use ::resources::paths as resources_paths;
17use config::settings::SettingsManager;
18use indexmap::IndexMap;
19use jsrt::path::dirname;
20use resources_paths::canonicalize;
21use serde_json::Value;
22use std::path::Path;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25pub enum Scope {
26    User,
27    Project,
28}
29
30impl Scope {
31    pub fn name(self) -> &'static str {
32        match self {
33            Scope::User => "user",
34            Scope::Project => "project",
35        }
36    }
37}
38
39/// `PathMetadata` of a top-level resource: `source` is `local` (a settings entry) or `auto` (auto-discovered).
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct PathMetadata {
42    pub source: String,
43    pub scope: Scope,
44    pub base_dir: Option<String>,
45}
46
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct ResolvedResource {
49    pub path: String,
50    pub enabled: bool,
51    pub metadata: PathMetadata,
52}
53
54/// `ResolvedPaths`, indexed by [`ResourceType`].
55#[derive(Clone, Debug, Default, PartialEq, Eq)]
56pub struct ResolvedPaths {
57    pub skills: Vec<ResolvedResource>,
58    pub prompts: Vec<ResolvedResource>,
59    pub themes: Vec<ResolvedResource>,
60}
61
62impl ResolvedPaths {
63    pub fn of(&self, kind: ResourceType) -> &[ResolvedResource] {
64        match kind {
65            ResourceType::Skills => &self.skills,
66            ResourceType::Prompts => &self.prompts,
67            ResourceType::Themes => &self.themes,
68        }
69    }
70}
71
72type Accumulator = [IndexMap<String, (PathMetadata, bool)>; 3];
73
74fn slot(kind: ResourceType) -> usize {
75    match kind {
76        ResourceType::Skills => 0,
77        ResourceType::Prompts => 1,
78        ResourceType::Themes => 2,
79    }
80}
81
82/// `addResource`: the first entry for a path wins.
83fn add(acc: &mut Accumulator, kind: ResourceType, path: &str, metadata: &PathMetadata, enabled: bool) {
84    if path.is_empty() {
85        return;
86    }
87    acc[slot(kind)]
88        .entry(path.to_string())
89        .or_insert_with(|| (metadata.clone(), enabled));
90}
91
92/// `resourcePrecedenceRank` of a top-level resource: project before user, a settings entry before an
93/// auto-discovered one.
94fn rank(m: &PathMetadata) -> u8 {
95    let base = if m.scope == Scope::Project { 0 } else { 2 };
96    base + u8::from(m.source != "local")
97}
98
99fn string_list(value: Option<&Value>) -> Option<Vec<String>> {
100    value
101        .and_then(Value::as_array)
102        .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect())
103}
104
105/// The settings `packages` entries of both scopes (a manager of an untrusted project has no project settings): Pi
106/// packages are not supported, so a session reports how many it ignores.
107pub fn ignored_packages(settings: &SettingsManager) -> usize {
108    let count = |s: &serde_json::Map<String, Value>| s.get("packages").and_then(Value::as_array).map_or(0, Vec::len);
109    count(settings.global_settings()) + count(settings.project_settings())
110}
111
112/// The startup note for settings `packages` entries ultron-rs ignores; none when there are none.
113pub fn ignored_packages_note(settings: &SettingsManager) -> Option<String> {
114    match ignored_packages(settings) {
115        0 => None,
116        n => Some(format!(
117            "Pi packages are not supported by ultron-rs; ignoring {n} package{} in settings",
118            if n == 1 { "" } else { "s" }
119        )),
120    }
121}
122
123/// Resolves the local resources of one working directory and profile.
124pub struct LocalResources {
125    pub cwd: String,
126    pub agent_dir: String,
127    home: String,
128    pub settings: SettingsManager,
129}
130
131impl LocalResources {
132    pub fn new(env: &crate::RunEnv, settings: SettingsManager) -> Self {
133        let resolve = |p: &str| config::paths::resolve(p, &env.cwd, &env.home).display().to_string();
134        Self {
135            cwd: resolve(&env.cwd.display().to_string()),
136            agent_dir: resolve(&env.agent_dir().display().to_string()),
137            home: env.home.display().to_string(),
138            settings,
139        }
140    }
141
142    fn resolve_from(&self, input: &str, base: &str) -> String {
143        config::paths::resolve(input.trim(), Path::new(base), Path::new(&self.home))
144            .display()
145            .to_string()
146    }
147
148    /// Every local resource, by precedence: the settings' entries (`resolveLocalEntries`, project scope first),
149    /// then `addAutoDiscoveredResources`.
150    pub fn resolve(&self) -> ResolvedPaths {
151        let mut acc: Accumulator = Default::default();
152        let global_base = self.agent_dir.clone();
153        let project_base = jsrt::path::join(&[&self.cwd, config::paths::CONFIG_DIR_NAME]);
154        for kind in RESOURCE_TYPES {
155            for (scope, base) in [(Scope::Project, &project_base), (Scope::User, &global_base)] {
156                let list = self.entries(scope, kind);
157                if list.is_empty() {
158                    continue;
159                }
160                let (plain, patterns): (Vec<String>, Vec<String>) =
161                    list.into_iter().partition(|e| !files::is_pattern(e));
162                let resolved: Vec<String> = plain.iter().map(|p| self.resolve_from(p, base)).collect();
163                let found = files::files_from_paths(&resolved, kind);
164                let enabled = files::apply_patterns(&found, &patterns, base);
165                let m = PathMetadata {
166                    source: "local".into(),
167                    scope,
168                    base_dir: None,
169                };
170                for f in &found {
171                    add(&mut acc, kind, f, &m, enabled.contains(f));
172                }
173            }
174        }
175        self.add_auto_discovered(&mut acc, &global_base, &project_base);
176        to_resolved(acc)
177    }
178
179    fn entries(&self, scope: Scope, kind: ResourceType) -> Vec<String> {
180        let s = match scope {
181            Scope::User => self.settings.global_settings(),
182            Scope::Project => self.settings.project_settings(),
183        };
184        string_list(s.get(kind.key())).unwrap_or_default()
185    }
186
187    fn add_auto_discovered(&self, acc: &mut Accumulator, global_base: &str, project_base: &str) {
188        let meta = |scope: Scope, base: &str| PathMetadata {
189            source: "auto".into(),
190            scope,
191            base_dir: Some(base.to_string()),
192        };
193        let mut put = |kind: ResourceType, paths: Vec<String>, m: &PathMetadata, scope: Scope, base: &str| {
194            let overrides = self.entries(scope, kind);
195            for p in paths {
196                let enabled = files::enabled_by_overrides(&p, &overrides, base);
197                add(acc, kind, &p, m, enabled);
198            }
199        };
200        let user_agents = jsrt::path::join(&[&self.home, ".agents", "skills"]);
201        let trusted = self.settings.is_project_trusted();
202        let project_agents: Vec<String> = if trusted {
203            let user_resolved = jsrt::path::resolve("/", &user_agents);
204            files::ancestor_agents_skill_dirs(&self.cwd)
205                .into_iter()
206                .filter(|d| jsrt::path::resolve("/", d) != user_resolved)
207                .collect()
208        } else {
209            Vec::new()
210        };
211        let pm = meta(Scope::Project, project_base);
212        let dir = |base: &str, kind: ResourceType| jsrt::path::join(&[base, kind.key()]);
213        if trusted {
214            put(
215                ResourceType::Skills,
216                files::auto_skills(&dir(project_base, ResourceType::Skills), false),
217                &pm,
218                Scope::Project,
219                project_base,
220            );
221        }
222        for agents_dir in &project_agents {
223            let base = dirname(agents_dir);
224            put(
225                ResourceType::Skills,
226                files::auto_skills(agents_dir, true),
227                &meta(Scope::Project, &base),
228                Scope::Project,
229                &base,
230            );
231        }
232        if trusted {
233            put(
234                ResourceType::Prompts,
235                files::auto_prompts(&dir(project_base, ResourceType::Prompts)),
236                &pm,
237                Scope::Project,
238                project_base,
239            );
240            put(
241                ResourceType::Themes,
242                files::auto_themes(&dir(project_base, ResourceType::Themes)),
243                &pm,
244                Scope::Project,
245                project_base,
246            );
247        }
248        let um = meta(Scope::User, global_base);
249        put(
250            ResourceType::Skills,
251            files::auto_skills(&dir(global_base, ResourceType::Skills), false),
252            &um,
253            Scope::User,
254            global_base,
255        );
256        let user_agents_base = dirname(&user_agents);
257        put(
258            ResourceType::Skills,
259            files::auto_skills(&user_agents, true),
260            &meta(Scope::User, &user_agents_base),
261            Scope::User,
262            &user_agents_base,
263        );
264        put(
265            ResourceType::Prompts,
266            files::auto_prompts(&dir(global_base, ResourceType::Prompts)),
267            &um,
268            Scope::User,
269            global_base,
270        );
271        put(
272            ResourceType::Themes,
273            files::auto_themes(&dir(global_base, ResourceType::Themes)),
274            &um,
275            Scope::User,
276            global_base,
277        );
278    }
279}
280
281/// `toResolvedPaths`: by precedence (stable), the first of each canonical path kept.
282fn to_resolved(acc: Accumulator) -> ResolvedPaths {
283    let convert = |map: &IndexMap<String, (PathMetadata, bool)>| -> Vec<ResolvedResource> {
284        let mut list: Vec<ResolvedResource> = map
285            .iter()
286            .map(|(path, (metadata, enabled))| ResolvedResource {
287                path: path.clone(),
288                enabled: *enabled,
289                metadata: metadata.clone(),
290            })
291            .collect();
292        list.sort_by_key(|r| rank(&r.metadata));
293        let mut seen = std::collections::HashSet::new();
294        list.retain(|r| seen.insert(canonicalize(&r.path)));
295        list
296    };
297    ResolvedPaths {
298        skills: convert(&acc[0]),
299        prompts: convert(&acc[1]),
300        themes: convert(&acc[2]),
301    }
302}