vtcode_core/prompts/
context.rs1use crate::config::types::CapabilityLevel;
2use crate::skills::command_skills::is_model_catalog_eligible;
3use crate::skills::manager::SkillsManager;
4use crate::skills::model::SkillMetadata;
5use crate::tools::search_runtime::snapshot_for_workspace;
6use std::path::Path;
7use std::path::PathBuf;
8
9#[derive(Debug, Clone, Default)]
11pub struct PromptContext {
12 pub workspace: Option<PathBuf>,
14 pub languages: Vec<String>,
16 pub project_type: Option<String>,
18 pub available_tools: Vec<String>,
20 pub available_skills: Vec<(String, String)>,
22 pub available_skill_metadata: Vec<SkillMetadata>,
24 pub user_preferences: Option<UserPreferences>,
26 pub capability_level: Option<CapabilityLevel>,
28 pub current_directory: Option<PathBuf>,
30}
31
32#[derive(Debug, Clone)]
34pub struct UserPreferences {
35 pub preferred_languages: Vec<String>,
37 pub coding_style: Option<String>,
39 pub preferred_frameworks: Vec<String>,
41}
42
43impl PromptContext {
44 pub fn add_language(&mut self, language: String) {
46 if !self.languages.contains(&language) {
47 self.languages.push(language);
48 }
49 }
50
51 pub fn add_tool(&mut self, tool: String) {
53 if !self.available_tools.contains(&tool) {
54 self.available_tools.push(tool);
55 }
56 }
57
58 pub fn add_skill(&mut self, name: String, description: String) {
60 if !self.available_skills.iter().any(|(n, _)| n == &name) {
61 self.available_skills.push((name, description));
62 }
63 }
64
65 pub fn add_skill_metadata(&mut self, metadata: SkillMetadata) {
67 self.add_skill(metadata.name.clone(), metadata.description.clone());
68 if !self.available_skill_metadata.iter().any(|skill| skill.name == metadata.name) {
69 self.available_skill_metadata.push(metadata);
70 }
71 }
72
73 pub fn add_skill_metadata_entries(&mut self, skills: Vec<SkillMetadata>) {
75 for skill in skills {
76 self.add_skill_metadata(skill);
77 }
78 }
79
80 pub fn add_skills(&mut self, skills: Vec<(String, String)>) {
82 for (name, description) in skills {
83 self.add_skill(name, description);
84 }
85 }
86
87 pub fn infer_capability_level(&mut self) {
89 self.capability_level = Some(crate::prompts::guidelines::infer_capability_level(&self.available_tools));
90 }
91
92 pub fn set_current_directory(&mut self, dir: PathBuf) {
94 self.current_directory = Some(dir);
95 }
96
97 pub fn load_available_skills(&mut self) {
98 let home_dir = default_codex_home_dir();
99 self.load_available_skills_with_home_dir(home_dir.as_deref());
100 }
101
102 pub async fn load_available_skills_async(&mut self) {
108 let Some(workspace) = self.workspace.clone() else {
109 return;
110 };
111 let Some(home_dir) = default_codex_home_dir() else {
112 return;
113 };
114
115 let result = tokio::task::spawn_blocking(move || collect_available_skill_metadata(&workspace, &home_dir)).await;
116 match result {
117 Ok(skills) => self.add_skill_metadata_entries(skills),
118 Err(error) => tracing::warn!(%error, "skill metadata discovery task failed"),
119 }
120 }
121
122 pub fn replace_available_skills_with_named(&mut self, names: &[String]) {
123 let home_dir = default_codex_home_dir();
124 self.replace_available_skills_with_named_and_home_dir(names, home_dir.as_deref());
125 }
126
127 fn load_available_skills_with_home_dir(&mut self, home_dir: Option<&Path>) {
128 let Some(workspace) = self.workspace.as_deref() else {
129 return;
130 };
131 let Some(home_dir) = home_dir else {
132 return;
133 };
134
135 self.add_skill_metadata_entries(collect_available_skill_metadata(workspace, home_dir));
136 }
137
138 fn replace_available_skills_with_named_and_home_dir(&mut self, names: &[String], home_dir: Option<&Path>) {
139 self.available_skills.clear();
140 self.available_skill_metadata.clear();
141
142 if names.is_empty() {
143 return;
144 }
145
146 let Some(workspace) = self.workspace.as_deref() else {
147 return;
148 };
149 let Some(home_dir) = home_dir else {
150 return;
151 };
152
153 let requested = names
154 .iter()
155 .map(|name| name.trim().to_ascii_lowercase())
156 .filter(|name| !name.is_empty())
157 .collect::<std::collections::HashSet<_>>();
158 if requested.is_empty() {
159 return;
160 }
161
162 let bundled_skills_enabled = crate::skills::bundled_skills_install_permitted_for_workspace(workspace);
163 let manager = SkillsManager::new_with_bundled_skills_enabled(home_dir.to_path_buf(), bundled_skills_enabled);
164 let outcome = manager.skills_metadata_lightweight(workspace);
165 self.add_skill_metadata_entries(
166 outcome
167 .skills
168 .into_iter()
169 .filter(is_model_catalog_eligible)
170 .filter(|skill| requested.contains(&skill.name.to_ascii_lowercase()))
171 .collect(),
172 );
173 }
174
175 pub fn from_workspace_tools(
177 workspace: impl AsRef<Path>,
178 available_tools: impl IntoIterator<Item = impl Into<String>>,
179 ) -> Self {
180 let mut context = Self {
181 workspace: Some(workspace.as_ref().to_path_buf()),
182 ..Default::default()
183 };
184
185 if let Ok(cwd) = std::env::current_dir() {
186 context.set_current_directory(cwd);
187 }
188
189 for language in snapshot_for_workspace(workspace.as_ref()).workspace_languages {
190 context.add_language(language);
191 }
192
193 for tool in available_tools {
194 context.add_tool(tool.into());
195 }
196
197 if !context.available_tools.is_empty() {
198 context.infer_capability_level();
199 }
200
201 context
202 }
203}
204
205fn collect_available_skill_metadata(workspace: &Path, home_dir: &Path) -> Vec<SkillMetadata> {
206 let bundled_skills_enabled = crate::skills::bundled_skills_install_permitted_for_workspace(workspace);
207 let manager = SkillsManager::new_with_bundled_skills_enabled(home_dir.to_path_buf(), bundled_skills_enabled);
208 manager
209 .skills_metadata_lightweight(workspace)
210 .skills
211 .into_iter()
212 .filter(is_model_catalog_eligible)
213 .collect()
214}
215
216fn default_codex_home_dir() -> Option<PathBuf> {
217 crate::skills::system::bundled_skills_home().ok()
220}
221
222#[cfg(test)]
223mod tests {
224 use super::PromptContext;
225 use crate::config::constants::tools;
226 use std::fs;
227 use std::path::PathBuf;
228 use tempfile::TempDir;
229
230 fn write_skill(skill_dir: &std::path::Path, name: &str, description: &str) {
231 fs::create_dir_all(skill_dir).expect("create skill dir");
232 fs::write(
233 skill_dir.join("SKILL.md"),
234 format!("---\nname: {name}\ndescription: {description}\n---\n# {name}\n"),
235 )
236 .expect("write skill");
237 }
238
239 #[test]
240 fn from_workspace_tools_populates_workspace_and_tools() {
241 let context = PromptContext::from_workspace_tools(
242 PathBuf::from("/tmp/vtcode"),
243 [tools::CODE_SEARCH, tools::EXEC_COMMAND],
244 );
245
246 assert_eq!(context.workspace, Some(PathBuf::from("/tmp/vtcode")));
247 assert_eq!(context.available_tools.len(), 2);
248 assert!(context.capability_level.is_some());
249 assert!(context.current_directory.is_some());
250 }
251
252 #[test]
253 fn from_workspace_tools_populates_detected_languages() {
254 let workspace = TempDir::new().expect("workspace tempdir");
255 fs::create_dir_all(workspace.path().join("src")).expect("create src");
256 fs::create_dir_all(workspace.path().join("web")).expect("create web");
257 fs::write(workspace.path().join("src/lib.rs"), "fn alpha() {}\n").expect("write rust");
258 fs::write(workspace.path().join("web/app.ts"), "const app = 1;\n").expect("write ts");
259
260 let context = PromptContext::from_workspace_tools(workspace.path(), [tools::CODE_SEARCH]);
261
262 assert_eq!(context.languages, vec!["Rust".to_string(), "TypeScript".to_string()]);
263 }
264
265 #[test]
266 fn load_available_skills_discovers_repo_and_system_skills() {
267 let workspace = TempDir::new().expect("workspace tempdir");
268 fs::create_dir(workspace.path().join(".git")).expect("create git dir");
269 fs::write(workspace.path().join("vtcode.toml"), "[skills.bundled]\nenabled = true\n")
270 .expect("grant bundled skills");
271 write_skill(&workspace.path().join(".agents/skills/repo-skill"), "repo-skill", "Repo-local skill");
272
273 let home = TempDir::new().expect("home tempdir");
274 let mut context = PromptContext::from_workspace_tools(workspace.path(), [tools::CODE_SEARCH]);
275
276 assert!(context.available_skill_metadata.is_empty());
277
278 context.load_available_skills_with_home_dir(Some(home.path()));
279
280 let skill_names = context
281 .available_skill_metadata
282 .iter()
283 .map(|skill| skill.name.as_str())
284 .collect::<Vec<_>>();
285
286 assert!(skill_names.contains(&"repo-skill"));
287 assert!(skill_names.contains(&"skill-creator"));
288 assert!(!skill_names.contains(&"cmd-review"));
289 }
290
291 #[test]
292 fn replace_available_skills_with_named_recomputes_scope() {
293 let workspace = TempDir::new().expect("workspace tempdir");
294 fs::create_dir(workspace.path().join(".git")).expect("create git dir");
295 write_skill(&workspace.path().join(".agents/skills/alpha"), "alpha", "Alpha skill");
296 write_skill(&workspace.path().join(".agents/skills/beta"), "beta", "Beta skill");
297
298 let home = TempDir::new().expect("home tempdir");
299 let mut context = PromptContext::from_workspace_tools(workspace.path(), [tools::CODE_SEARCH]);
300
301 context.replace_available_skills_with_named_and_home_dir(&["alpha".to_string()], Some(home.path()));
302 assert_eq!(
303 context
304 .available_skill_metadata
305 .iter()
306 .map(|skill| skill.name.as_str())
307 .collect::<Vec<_>>(),
308 vec!["alpha"]
309 );
310
311 context.replace_available_skills_with_named_and_home_dir(&["beta".to_string()], Some(home.path()));
312 assert_eq!(
313 context
314 .available_skill_metadata
315 .iter()
316 .map(|skill| skill.name.as_str())
317 .collect::<Vec<_>>(),
318 vec!["beta"]
319 );
320
321 context.replace_available_skills_with_named_and_home_dir(&[], Some(home.path()));
322 assert!(context.available_skill_metadata.is_empty());
323 assert!(context.available_skills.is_empty());
324 }
325}