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