Skip to main content

session_core/
session_resources.rs

1//! The resources a session loads, as resource-loader.ts `reload` assembles them for the session worker:
2//!
3//! - every local resource (crate::local_resources) in its precedence order: the settings' local `skills`/`prompts`
4//!   entries (paths, globs and `!`/`+`/`-` patterns, project scope first), and the auto-discovered ones
5//!   (`.pi/skills`, `.pi/prompts`, `.agents/skills` from the cwd up to the git root, `<agentDir>/skills`,
6//!   `<agentDir>/prompts`, `~/.agents/skills`). A project that is not trusted contributes no settings, no project
7//!   resources and no ancestor `.agents/skills`;
8//! - then the bundled skills (`bundledSkillPaths`), the first skill of a name kept;
9//! - the base system prompt and its addendum: `.pi/SYSTEM.md` / `.pi/APPEND_SYSTEM.md` in a trusted project, else
10//!   `<agentDir>/SYSTEM.md` / `<agentDir>/APPEND_SYSTEM.md` (`discoverSystemPromptFile`).
11//!
12//! Pi packages (the settings `packages`) and the `-e` sources are not supported by ultron-rs: they contribute
13//! nothing (the CLI notes the ignored packages once at startup).
14//!
15//! Every skill and prompt carries its `SourceInfo` as `findSourceInfoForPath` gives it (the resolved resource's
16//! metadata, exact path first, then the first resource directory holding it), else the loader's own.
17
18use crate::RunEnv as Env;
19use crate::local_resources::{LocalResources, PathMetadata};
20use resources::prompt_templates::PromptTemplate;
21use resources::skills::{LoadSkillsOptions, Skill, load_skills};
22use std::path::Path;
23
24pub const BUNDLED_SKILLS_ENV: &str = "ULTRON_BUNDLED_SKILLS";
25
26/// Where one resource came from (`PathMetadata` with its path): its source (`local` or `auto`), scope and origin
27/// (always `top-level`), and its base directory.
28#[derive(Clone, Debug, Default, PartialEq, Eq)]
29pub struct ResourceSource {
30    pub path: String,
31    pub source: String,
32    pub scope: String,
33    pub origin: String,
34    pub base_dir: Option<String>,
35}
36
37impl ResourceSource {
38    fn of(path: &str, metadata: &PathMetadata) -> ResourceSource {
39        ResourceSource {
40            path: path.to_string(),
41            source: metadata.source.clone(),
42            scope: metadata.scope.name().into(),
43            origin: "top-level".into(),
44            base_dir: metadata.base_dir.clone(),
45        }
46    }
47
48    /// `createSourceInfo(path, metadata)`.
49    pub fn source_info(&self, path: &str) -> serde_json::Value {
50        let mut info = serde_json::json!({
51            "path": path,
52            "source": self.source,
53            "scope": self.scope,
54            "origin": self.origin,
55        });
56        if let Some(base) = &self.base_dir {
57            info["baseDir"] = base.as_str().into();
58        }
59        info
60    }
61}
62
63#[derive(Clone, Debug, Default, PartialEq, Eq)]
64pub struct SessionResources {
65    /// `resolve()`'s enabled skills in precedence order. They are files already (`mapSkillPath` has nothing to map:
66    /// the resolver lists a skill directory's `SKILL.md`).
67    pub skill_paths: Vec<String>,
68    /// `resolve()`'s enabled prompt templates in precedence order.
69    pub prompt_paths: Vec<String>,
70    /// `metadataByPath` in insertion order: every resolved resource (enabled or not); the first entry of a path
71    /// kept.
72    pub metadata: Vec<ResourceSource>,
73    /// The discovered SYSTEM.md's text (`getSystemPrompt`), if any.
74    pub system_prompt: Option<String>,
75    /// The discovered APPEND_SYSTEM.md's text (`getAppendSystemPrompt`).
76    pub append_system_prompt: Vec<String>,
77    /// The session's home directory, which a leading `~` in a skill or prompt path names.
78    pub home: String,
79}
80
81/// `mergePaths`: each path (resolved against the cwd) once by its canonical path, first place kept.
82fn merge(cwd: &str, home: &str, paths: impl IntoIterator<Item = String>) -> Vec<String> {
83    let mut out: Vec<String> = Vec::new();
84    let mut seen: Vec<String> = Vec::new();
85    for path in paths {
86        let resolved = resources::paths::resolve_path(&path, cwd, home, true);
87        let canonical = resources::paths::canonicalize(&resolved);
88        if !seen.contains(&canonical) {
89            seen.push(canonical);
90            out.push(resolved);
91        }
92    }
93    out
94}
95
96/// The session's resources for the settings `settings` holds (with the session's project trust).
97/// `append_system_prompt` (`--append-system-prompt`) replaces a discovered APPEND_SYSTEM.md.
98pub fn resolve(
99    env: &Env,
100    settings: config::settings::SettingsManager,
101    append_system_prompt: Option<&[String]>,
102) -> SessionResources {
103    let home = env.home.display().to_string();
104    let cwd = resources::paths::resolve_path(&env.cwd.display().to_string(), "/", &home, false);
105    let agent_dir = env.agent_dir().display().to_string();
106    let trusted = settings.is_project_trusted();
107    let prompt_files =
108        resources::prompt_files::load_prompt_files(&cwd, &agent_dir, &home, trusted, None, append_system_prompt);
109    let resolved = LocalResources::new(env, settings).resolve();
110    let mut metadata: Vec<ResourceSource> = Vec::new();
111    for list in [&resolved.skills, &resolved.prompts, &resolved.themes] {
112        for r in list {
113            if !metadata.iter().any(|m| m.path == r.path) {
114                metadata.push(ResourceSource::of(&r.path, &r.metadata));
115            }
116        }
117    }
118    let enabled = |list: &[crate::local_resources::ResolvedResource]| -> Vec<String> {
119        list.iter().filter(|r| r.enabled).map(|r| r.path.clone()).collect()
120    };
121    SessionResources {
122        skill_paths: enabled(&resolved.skills),
123        prompt_paths: enabled(&resolved.prompts),
124        metadata,
125        system_prompt: prompt_files.system_prompt,
126        append_system_prompt: prompt_files.append_system_prompt,
127        home,
128    }
129}
130
131/// The resources a session in `env`'s directory loads with no flags, its project trust decided as the worker
132/// decides it (`workerProjectTrusted`).
133pub fn resolve_default(env: &Env) -> SessionResources {
134    let agent_dir = env.agent_dir();
135    let trusted = config::trust::worker_project_trusted(&env.cwd, &agent_dir, &env.home);
136    let settings = config::settings::SettingsManager::create(&env.cwd, &agent_dir, trusted);
137    resolve(env, settings, None)
138}
139
140/// The skills of a session (`updateSkillsFromPaths`): without `--no-skills`, the resolved ones and the bundled ones
141/// in `bundled` (a directory), the first skill of a name kept.
142pub fn skills(
143    cwd: &str,
144    agent_dir: &str,
145    resources: &SessionResources,
146    no_skills: bool,
147    bundled: Option<&str>,
148) -> Vec<Skill> {
149    if no_skills {
150        return Vec::new();
151    }
152    let paths = merge(
153        cwd,
154        &resources.home,
155        resources.skill_paths.iter().cloned().chain(bundled.map(str::to_string)),
156    );
157    if paths.is_empty() {
158        return Vec::new();
159    }
160    load_skills(&LoadSkillsOptions {
161        cwd,
162        agent_dir,
163        home: &resources.home,
164        skill_paths: &paths,
165        include_defaults: false,
166    })
167    .skills
168}
169
170/// The prompt templates of a session (`updatePromptsFromPaths`): the resolved ones, the first of a name kept.
171pub fn prompts(cwd: &str, agent_dir: &str, resources: &SessionResources) -> Vec<PromptTemplate> {
172    let paths = merge(cwd, &resources.home, resources.prompt_paths.iter().cloned());
173    let loaded = resources::prompt_templates::load_prompt_templates(cwd, agent_dir, &resources.home, &paths, false);
174    let mut out: Vec<PromptTemplate> = Vec::new();
175    for template in loaded.templates {
176        if !out.iter().any(|t| t.name == template.name) {
177            out.push(template);
178        }
179    }
180    out
181}
182
183/// `findSourceInfoForPath` over the resolved resources: the metadata of the first resource that is the file or a
184/// directory holding it; `None` for anything else. (TypeScript looks for the exact path first; here every resolved
185/// skill and prompt is a file of its own, listed before any directory that could hold it, so one pass is the same.)
186pub fn source_info(resources: &SessionResources, file_path: &str) -> Option<serde_json::Value> {
187    let file = jsrt::path::resolve("/", file_path);
188    resources
189        .metadata
190        .iter()
191        .find(|m| {
192            let root = jsrt::path::resolve("/", &m.path);
193            file == root || file.starts_with(&format!("{root}/"))
194        })
195        .map(|m| m.source_info(file_path))
196}
197
198/// A skill's `SourceInfo`: the resolved resource's, else the loader's own (`createSkillSourceInfo` for a path
199/// outside the profile's and project's skill directories, whose skills always have metadata: `local`, `temporary`,
200/// the skill's directory). In practice the bundled skills.
201pub fn skill_source_info(resources: &SessionResources, skill: &Skill) -> serde_json::Value {
202    source_info(resources, &skill.file_path).unwrap_or_else(|| {
203        serde_json::json!({
204            "path": skill.file_path, "source": "local", "scope": "temporary", "origin": "top-level",
205            "baseDir": skill.base_dir,
206        })
207    })
208}
209
210/// A prompt template's `SourceInfo`: the resolved resource's, else the loader's own (`local`; scope `user` or
211/// `project` with that prompts directory, else `temporary` with the file's directory).
212pub fn prompt_source_info(
213    resources: &SessionResources,
214    template: &PromptTemplate,
215    cwd: &str,
216    agent_dir: &str,
217) -> serde_json::Value {
218    source_info(resources, &template.file_path).unwrap_or_else(|| {
219        let (scope, base) = match template.scope {
220            "user" => ("user", jsrt::path::join(&[agent_dir, "prompts"])),
221            "project" => (
222                "project",
223                jsrt::path::join(&[cwd, config::paths::CONFIG_DIR_NAME, "prompts"]),
224            ),
225            _ => ("temporary", jsrt::path::dirname(&template.file_path)),
226        };
227        serde_json::json!({
228            "path": template.file_path, "source": "local", "scope": scope, "origin": "top-level", "baseDir": base,
229        })
230    })
231}
232
233/// `defaultBundledSkillPaths`: the bundled skills directory `dir`, unless `ULTRON_BUNDLED_SKILLS` is `off`, `0` or
234/// `false`.
235pub fn bundled_skills(dir: &Path, var: &dyn Fn(&str) -> Option<String>) -> Option<String> {
236    if crate::flag_off(var(BUNDLED_SKILLS_ENV).as_deref()) {
237        return None;
238    }
239    Some(config::paths::normalize(dir).display().to_string())
240}