Skip to main content

vtcode_core/tools/skills/
mod.rs

1use crate::config::ToolDocumentationMode;
2use crate::config::types::CapabilityLevel;
3use crate::llm::provider::ToolDefinition;
4use crate::metrics::MetricsCollector;
5use crate::skills::cli_bridge::CliToolConfig;
6use crate::skills::command_skills::merge_built_in_command_skill_metadata;
7use crate::skills::discovery::{DiscoveryConfig, SkillDiscovery};
8use crate::skills::executor::{ForkSkillExecutor, SkillToolAdapter};
9use crate::skills::file_references::FileReferenceValidator;
10use crate::skills::loader::{EnhancedSkill, EnhancedSkillLoader, SkillLoaderConfig};
11use crate::skills::manager::SkillsManager;
12use crate::skills::model::{SkillErrorInfo, SkillLoadOutcome};
13use crate::skills::types::{Skill, SkillManifestMetadata, SkillVariety};
14use crate::tool_policy::ToolPolicy;
15use crate::tools::handlers::{
16    DeferredToolPolicy, SessionSurface, SessionToolsConfig, ToolModelCapabilities, ToolProfile,
17};
18use crate::tools::registry::{ToolMetadata, ToolRegistration, ToolRegistry, native_cgp_tool_factory};
19use crate::tools::traits::Tool;
20use crate::utils::file_utils::{read_file_with_context, read_file_with_context_sync};
21use anyhow::Context;
22use async_trait::async_trait;
23use hashbrown::{HashMap, HashSet};
24use serde_json::{Value, json};
25use std::path::{Path, PathBuf};
26use std::sync::Arc;
27use tokio::sync::RwLock;
28use tracing::{debug, warn};
29
30#[cfg(test)]
31use crate::tools::CgpRuntimeMode;
32use crate::tools::error_messages::skill_ops;
33use vtcode_commons::{VtCodePaths, canonicalize};
34
35type SkillMap = Arc<RwLock<HashMap<String, Skill>>>;
36type ToolDefList = Arc<RwLock<Vec<ToolDefinition>>>;
37type ToolChangeNotifier = Arc<dyn Fn(&'static str) + Send + Sync>;
38
39const SKILL_TOOL_PROMPT_PATH: &str = "skills/skill_instructions.md";
40const SKILL_ACTIVATED_STATUS: &str = "Associated tools activated and added to context.";
41const SKILL_ALREADY_ACTIVE_STATUS: &str = "Associated tools were already active.";
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum SkillActivationState {
45    Activated,
46    AlreadyActive,
47}
48
49#[derive(Clone)]
50pub struct SkillToolSessionRuntime {
51    tool_registry: Arc<ToolRegistry>,
52    active_tools: Option<ToolDefList>,
53    tool_documentation_mode: ToolDocumentationMode,
54    model_capabilities: ToolModelCapabilities,
55    deferred_tool_policy: DeferredToolPolicy,
56    anthropic_native_memory_enabled: bool,
57    tool_profile: ToolProfile,
58    on_tools_changed: Option<ToolChangeNotifier>,
59    fork_executor: Option<Arc<dyn ForkSkillExecutor>>,
60}
61
62impl SkillToolSessionRuntime {
63    pub fn new(
64        tool_registry: Arc<ToolRegistry>,
65        active_tools: Option<ToolDefList>,
66        tool_documentation_mode: ToolDocumentationMode,
67        model_capabilities: ToolModelCapabilities,
68        on_tools_changed: Option<ToolChangeNotifier>,
69    ) -> Self {
70        Self {
71            tool_registry,
72            active_tools,
73            tool_documentation_mode,
74            model_capabilities,
75            deferred_tool_policy: DeferredToolPolicy::default(),
76            anthropic_native_memory_enabled: false,
77            tool_profile: ToolProfile::default(),
78            on_tools_changed,
79            fork_executor: None,
80        }
81    }
82
83    pub fn with_fork_executor(mut self, fork_executor: Arc<dyn ForkSkillExecutor>) -> Self {
84        self.fork_executor = Some(fork_executor);
85        self
86    }
87
88    pub fn with_deferred_tool_policy(mut self, deferred_tool_policy: DeferredToolPolicy) -> Self {
89        self.deferred_tool_policy = deferred_tool_policy;
90        self
91    }
92
93    pub fn with_anthropic_native_memory_enabled(mut self, enabled: bool) -> Self {
94        self.anthropic_native_memory_enabled = enabled;
95        self
96    }
97
98    pub fn with_tool_profile(mut self, tool_profile: ToolProfile) -> Self {
99        self.tool_profile = tool_profile;
100        self
101    }
102
103    pub async fn activate_skill(
104        &self,
105        active_skills: &Arc<RwLock<HashMap<String, Skill>>>,
106        skill: Skill,
107    ) -> anyhow::Result<SkillActivationState> {
108        let skill_name = skill.name().to_string();
109        if active_skills.read().await.contains_key(skill_name.as_str()) {
110            return Ok(SkillActivationState::AlreadyActive);
111        }
112
113        if !self.tool_registry.has_tool(skill_name.as_str()).await {
114            self.tool_registry
115                .register_tool(build_traditional_skill_tool_registration_with_metrics(
116                    &skill,
117                    self.fork_executor.clone(),
118                    Some(self.tool_registry.metrics_collector()),
119                ))
120                .await
121                .with_context(|| format!("failed to register skill tool '{skill_name}'"))?;
122            self.refresh_tool_snapshot("load_skill").await;
123        }
124
125        self.tool_registry
126            .metrics_collector()
127            .record_skill_created(skill_name.clone(), skill.variety.as_str().to_string());
128        active_skills.write().await.insert(skill_name, skill);
129        Ok(SkillActivationState::Activated)
130    }
131
132    pub async fn deactivate_skill(
133        &self,
134        active_skills: &Arc<RwLock<HashMap<String, Skill>>>,
135        skill_name: &str,
136    ) -> anyhow::Result<bool> {
137        let removed = active_skills.write().await.remove(skill_name).is_some();
138        let unregistered = self.tool_registry.unregister_tool(skill_name).await?;
139        if unregistered {
140            self.refresh_tool_snapshot("unload_skill").await;
141        }
142        let settled = removed || unregistered;
143        if settled {
144            self.tool_registry
145                .metrics_collector()
146                .record_skill_deleted(skill_name.to_string());
147        }
148        Ok(settled)
149    }
150
151    async fn refresh_tool_snapshot(&self, reason: &'static str) {
152        if let Some(active_tools) = &self.active_tools {
153            let refreshed = self
154                .tool_registry
155                .model_tools(
156                    SessionToolsConfig::full_public(
157                        SessionSurface::Interactive,
158                        CapabilityLevel::CodeSearch,
159                        self.tool_documentation_mode,
160                        self.model_capabilities,
161                    )
162                    .with_planning_active(true)
163                    .with_deferred_tool_policy(self.deferred_tool_policy.clone())
164                    .with_anthropic_native_memory_enabled(self.anthropic_native_memory_enabled)
165                    .with_tool_profile(self.tool_profile),
166                )
167                .await;
168            *active_tools.write().await = refreshed;
169        }
170
171        if let Some(notifier) = &self.on_tools_changed {
172            notifier(reason);
173        }
174    }
175}
176
177fn build_skill_tool_adapter(
178    skill: Skill,
179    fork_executor: Option<Arc<dyn ForkSkillExecutor>>,
180    metrics: Option<Arc<MetricsCollector>>,
181) -> SkillToolAdapter {
182    let adapter = if skill.manifest.context.as_deref() == Some("fork") {
183        match fork_executor {
184            Some(executor) => SkillToolAdapter::with_fork_executor(skill, executor),
185            None => SkillToolAdapter::new(skill),
186        }
187    } else {
188        SkillToolAdapter::new(skill)
189    };
190    match metrics {
191        Some(collector) => adapter.with_metrics(collector),
192        None => adapter,
193    }
194}
195
196pub fn build_traditional_skill_tool_registration(
197    skill: &Skill,
198    fork_executor: Option<Arc<dyn ForkSkillExecutor>>,
199) -> ToolRegistration {
200    build_traditional_skill_tool_registration_with_metrics(skill, fork_executor, None)
201}
202
203/// Builds a traditional skill tool registration, attaching `metrics` to the
204/// adapter (and its native factory rebuilds) so executions feed the skill
205/// health report. `None` runs executions unrecorded.
206pub fn build_traditional_skill_tool_registration_with_metrics(
207    skill: &Skill,
208    fork_executor: Option<Arc<dyn ForkSkillExecutor>>,
209    metrics: Option<Arc<MetricsCollector>>,
210) -> ToolRegistration {
211    let metadata = ToolMetadata::default()
212        .with_description(skill.description())
213        .with_parameter_schema(skill_tool_parameter_schema())
214        .with_permission(ToolPolicy::Prompt)
215        .with_prompt_path(SKILL_TOOL_PROMPT_PATH);
216
217    // Traditional skills already flow through shared fork executors, so keep
218    // the trait-object bridge here and let the native CGP factory handle the
219    // ownership-first path when runtime mode is known.
220    let adapter: Arc<dyn Tool> =
221        Arc::new(build_skill_tool_adapter(skill.clone(), fork_executor.clone(), metrics.clone()));
222    let native_skill = skill.clone();
223    let native_fork_executor = fork_executor;
224
225    ToolRegistration::from_tool_with_metadata(skill.name().to_string(), CapabilityLevel::Basic, adapter, metadata)
226        .with_native_cgp_factory(native_cgp_tool_factory(move || {
227            build_skill_tool_adapter(native_skill.clone(), native_fork_executor.clone(), metrics.clone())
228        }))
229}
230
231pub fn build_skill_tool_registration(skill: &Skill) -> ToolRegistration {
232    build_traditional_skill_tool_registration(skill, None)
233}
234
235fn skill_tool_parameter_schema() -> Value {
236    json!({
237        "type": "object",
238        "properties": {},
239        "description": "Flexible input for skill execution",
240        "additionalProperties": true,
241    })
242}
243
244fn load_skill_instructions(skill: &Skill, activation_status: &str) -> String {
245    if !skill.instructions.is_empty() {
246        return skill.instructions.clone();
247    }
248
249    let skill_file = skill.path.join("SKILL.md");
250    if skill_file.exists() {
251        return match read_file_with_context_sync(&skill_file, "skill file") {
252            Ok(content) => content,
253            Err(error) => format!("Error reading skill file: {error}"),
254        };
255    }
256
257    format!("No detailed instructions available for {}. {}", skill.name(), activation_status)
258}
259
260fn build_skill_response(skill: &Skill, activation_status: &str) -> Value {
261    let instructions = load_skill_instructions(skill, activation_status);
262    let validator = FileReferenceValidator::new(skill.path.clone());
263    let resources: Vec<String> = validator
264        .list_valid_references()
265        .iter()
266        .map(|path| path.to_string_lossy().to_string())
267        .collect();
268
269    json!({
270        "name": skill.name(),
271        "variety": skill.variety,
272        "instructions": instructions,
273        "instructions_status": "These instructions are now [ACTIVE] and will persist in your system prompt for the remainder of this session.",
274        "activation_status": activation_status,
275        "resources": resources,
276        "path": skill.path,
277        "description": skill.description()
278    })
279}
280
281fn effective_codex_home(explicit_home: Option<&Path>) -> anyhow::Result<PathBuf> {
282    explicit_home
283        .map(Path::to_path_buf)
284        .map_or_else(|| crate::skills::system::bundled_skills_home().map_err(anyhow::Error::from), Ok)
285}
286
287fn find_project_root(path: &Path) -> Option<PathBuf> {
288    let mut current = Some(path);
289    while let Some(dir) = current {
290        if dir.join(".git").exists() {
291            return Some(dir.to_path_buf());
292        }
293        current = dir.parent();
294    }
295    None
296}
297
298fn build_skill_loader_config(
299    workspace_root: &Path,
300    codex_home: &Path,
301    include_bundled_system_skills: bool,
302) -> SkillLoaderConfig {
303    SkillLoaderConfig {
304        codex_home: codex_home.to_path_buf(),
305        cwd: workspace_root.to_path_buf(),
306        project_root: find_project_root(workspace_root).or_else(|| Some(workspace_root.to_path_buf())),
307        include_bundled_system_skills,
308    }
309}
310
311fn discover_session_skill_metadata(workspace_root: &Path, codex_home: &Path) -> SkillLoadOutcome {
312    let bundled_skills_permitted = crate::skills::bundled_skills_install_permitted_for_workspace(workspace_root);
313    let manager = SkillsManager::new_with_bundled_skills_enabled(codex_home.to_path_buf(), bundled_skills_permitted);
314    manager.ensure_system_skills_installed();
315    let config = build_skill_loader_config(workspace_root, codex_home, bundled_skills_permitted);
316
317    #[cfg(test)]
318    let mut discovery = crate::skills::loader::discover_skill_metadata_lightweight_hermetic(&config);
319
320    #[cfg(not(test))]
321    let mut discovery = crate::skills::loader::discover_skill_metadata_lightweight(&config);
322
323    merge_built_in_command_skill_metadata(&mut discovery.skills);
324    discovery
325}
326
327async fn discover_session_utilities(workspace_root: &Path, codex_home: &Path) -> anyhow::Result<Vec<CliToolConfig>> {
328    let mut config = DiscoveryConfig::default();
329    config.skill_paths.clear();
330    config.tool_paths = vec![
331        PathBuf::from("./tools"),
332        PathBuf::from("./vendor/tools"),
333        codex_home.join("tools"),
334    ];
335    if let Ok(paths) = VtCodePaths::resolve() {
336        config.tool_paths.push(paths.data_path("tools")?);
337        config.tool_paths.push(paths.legacy_dir().join("tools"));
338    }
339
340    let mut discovery = SkillDiscovery::with_config(config);
341    Ok(discovery.discover_all(workspace_root).await?.tools)
342}
343
344fn discovery_error_samples(errors: &[SkillErrorInfo]) -> Vec<String> {
345    errors
346        .iter()
347        .take(3)
348        .map(|error| format!("{}: {}", error.path.display(), error.message))
349        .collect()
350}
351
352fn log_discovery_warnings(operation: &'static str, errors: &[SkillErrorInfo]) {
353    if errors.is_empty() {
354        return;
355    }
356
357    warn!(
358        operation,
359        error_count = errors.len(),
360        sample = ?discovery_error_samples(errors),
361        "Session skill discovery reported warnings"
362    );
363}
364
365fn discover_skill_catalog(
366    workspace_root: &Path,
367    explicit_codex_home: Option<&Path>,
368    operation: &'static str,
369) -> anyhow::Result<(PathBuf, SkillLoadOutcome)> {
370    let codex_home = effective_codex_home(explicit_codex_home)?;
371    debug!(
372        operation,
373        workspace = %workspace_root.display(),
374        codex_home = %codex_home.display(),
375        "Running session skill discovery"
376    );
377
378    let metadata = discover_session_skill_metadata(workspace_root, &codex_home);
379    log_discovery_warnings(operation, metadata.errors.as_slice());
380    Ok((codex_home, metadata))
381}
382
383fn required_string_arg<'a>(args: &'a Value, key: &str) -> anyhow::Result<&'a str> {
384    args.get(key)
385        .and_then(Value::as_str)
386        .ok_or_else(|| anyhow::anyhow!("Missing '{key}' argument"))
387}
388
389fn unsupported_activation_error(skill_name: &str, skill: EnhancedSkill) -> anyhow::Error {
390    let message = match skill {
391        EnhancedSkill::CliTool(_) => {
392            format!("Skill '{skill_name}' is a system utility and cannot be activated via load_skill")
393        }
394        EnhancedSkill::BuiltInCommand(_) => {
395            format!(
396                "Skill '{skill_name}' is a built-in command skill and cannot be activated via load_skill; use /skills use {skill_name} instead"
397            )
398        }
399        EnhancedSkill::NativePlugin(_) => {
400            format!("Skill '{skill_name}' is a native plugin and cannot be activated via load_skill")
401        }
402        EnhancedSkill::Traditional(_) => {
403            format!("Skill '{skill_name}' is already a traditional skill")
404        }
405    };
406
407    anyhow::anyhow!(message)
408}
409
410fn resolve_skill_resource_path(skill_root: &Path, resource_path: &str) -> anyhow::Result<PathBuf> {
411    let relative_path = Path::new(resource_path);
412    if relative_path.is_absolute()
413        || relative_path.components().any(|component| {
414            matches!(
415                component,
416                std::path::Component::ParentDir | std::path::Component::RootDir | std::path::Component::Prefix(_)
417            )
418        })
419    {
420        return Err(anyhow::anyhow!("Resource path '{resource_path}' must be relative to the skill directory"));
421    }
422
423    let full_path = skill_root.join(relative_path);
424    let canonical_root =
425        canonicalize(skill_root).with_context(|| format!("Failed to resolve skill root {}", skill_root.display()))?;
426    let canonical_path = canonicalize(full_path).with_context(|| format!("Resource '{resource_path}' not found"))?;
427
428    if !canonical_path.starts_with(&canonical_root) {
429        return Err(anyhow::anyhow!("Resource '{resource_path}' escapes the skill directory"));
430    }
431
432    if !canonical_path.is_file() {
433        return Err(anyhow::anyhow!("Resource '{resource_path}' is not a readable file"));
434    }
435
436    Ok(canonical_path)
437}
438
439fn extract_metadata_keywords(metadata: Option<&SkillManifestMetadata>) -> Vec<String> {
440    let Some(meta) = metadata else {
441        return Vec::new();
442    };
443    let Some(keywords_value) = meta.get("keywords") else {
444        return Vec::new();
445    };
446    let Some(keywords_array) = keywords_value.as_array() else {
447        return Vec::new();
448    };
449    keywords_array.iter().filter_map(|v| v.as_str().map(String::from)).collect()
450}
451
452fn matches_keywords(keywords: &[String], query_lower: &str) -> bool {
453    let query_words: Vec<&str> = query_lower.split_whitespace().collect();
454    if query_words.is_empty() || keywords.is_empty() {
455        return false;
456    }
457    query_words.iter().all(|word| {
458        let normalized_word = word.replace('-', " ");
459        keywords
460            .iter()
461            .any(|kw| kw.replace('-', " ").to_lowercase().contains(normalized_word.as_str()))
462    })
463}
464
465fn matches_skill_filters(
466    name: &str,
467    description: &str,
468    variety: SkillVariety,
469    query: Option<&str>,
470    variety_filter: Option<&str>,
471    keywords: &[String],
472) -> bool {
473    let normalized_variety = format!("{variety:?}").to_lowercase();
474    if let Some(filter) = variety_filter
475        && !normalized_variety.contains(&filter.replace('_', "").to_lowercase())
476    {
477        return false;
478    }
479
480    if let Some(query) = query {
481        let query = query.to_lowercase();
482        if !name.to_lowercase().contains(query.as_str())
483            && !description.to_lowercase().contains(query.as_str())
484            && !matches_keywords(keywords, &query)
485        {
486            return false;
487        }
488    }
489
490    true
491}
492
493/// Tool to load skill instructions on demand (Progressive Disclosure)
494pub struct LoadSkillTool {
495    workspace_root: PathBuf,
496    codex_home: Option<PathBuf>,
497    active_skills: SkillMap,
498    runtime: SkillToolSessionRuntime,
499}
500
501impl LoadSkillTool {
502    pub fn new(workspace_root: PathBuf, active_skills: SkillMap, runtime: SkillToolSessionRuntime) -> Self {
503        Self::with_codex_home(workspace_root, active_skills, runtime, None)
504    }
505
506    pub fn with_codex_home(
507        workspace_root: PathBuf,
508        active_skills: SkillMap,
509        runtime: SkillToolSessionRuntime,
510        codex_home: Option<PathBuf>,
511    ) -> Self {
512        Self { workspace_root, codex_home, active_skills, runtime }
513    }
514}
515
516#[async_trait]
517impl Tool for LoadSkillTool {
518    fn name(&self) -> &str {
519        "load_skill"
520    }
521
522    fn description(&self) -> &str {
523        "Load detailed instructions for a specific traditional skill and activate its associated tool into your environment. This operation requires approval because skill content may be executable or native-backed. Use list_skills first to see what is available. Skills that list_skills reports as active are already loaded, so load_skill is only needed for inactive ones; calling it for an active skill returns the cached instructions without reloading. Returns the skill instructions and activation status."
524    }
525
526    fn parameter_schema(&self) -> Option<Value> {
527        Some(serde_json::json!({
528            "type": "object",
529            "properties": {
530                "name": {
531                    "type": "string",
532                    "description": "The name of the skill to load"
533                }
534            },
535            "required": ["name"]
536        }))
537    }
538
539    fn default_permission(&self) -> ToolPolicy {
540        // A skill may be backed by executable content or a native plugin. The
541        // approval gate must run before discovery can reach any such loader.
542        ToolPolicy::Prompt
543    }
544
545    fn is_mutating(&self) -> bool {
546        // Activation changes the session tool set and may cross into
547        // executable-backed skill implementations.
548        true
549    }
550
551    fn is_parallel_safe(&self) -> bool {
552        false
553    }
554
555    async fn execute(&self, args: Value) -> anyhow::Result<Value> {
556        let name = required_string_arg(&args, "name")?;
557
558        if let Some(skill) = self.active_skills.read().await.get(name).cloned() {
559            return Ok(build_skill_response(&skill, SKILL_ALREADY_ACTIVE_STATUS));
560        }
561
562        let (codex_home, metadata) =
563            discover_skill_catalog(&self.workspace_root, self.codex_home.as_deref(), "load_skill")?;
564
565        let mut loader = EnhancedSkillLoader::with_codex_home(self.workspace_root.clone(), codex_home.clone());
566        let skill = match loader.get_skill(name).await {
567            Ok(EnhancedSkill::Traditional(skill)) => *skill,
568            Ok(skill) => return Err(unsupported_activation_error(name, skill)),
569            Err(error) => {
570                let tools = discover_session_utilities(&self.workspace_root, &codex_home).await?;
571                if tools.iter().any(|tool| tool.name == name) {
572                    return Err(anyhow::anyhow!(
573                        "Skill '{name}' is a system utility and cannot be activated via load_skill"
574                    ));
575                }
576
577                let detail = if metadata.errors.is_empty() {
578                    String::new()
579                } else {
580                    format!(
581                        " Session discovery also reported {} issue(s); use `list_skills` to inspect warning samples.",
582                        metadata.errors.len()
583                    )
584                };
585
586                return Err(anyhow::anyhow!("Failed to load skill '{name}': {error}.{detail}"));
587            }
588        };
589
590        let activation_status = match self.runtime.activate_skill(&self.active_skills, skill.clone()).await? {
591            SkillActivationState::Activated => SKILL_ACTIVATED_STATUS,
592            SkillActivationState::AlreadyActive => SKILL_ALREADY_ACTIVE_STATUS,
593        };
594
595        Ok(build_skill_response(&skill, activation_status))
596    }
597}
598
599/// Tool to list all available skills
600pub struct ListSkillsTool {
601    workspace_root: PathBuf,
602    codex_home: Option<PathBuf>,
603    active_skills: SkillMap,
604}
605
606impl ListSkillsTool {
607    pub fn new(workspace_root: PathBuf, active_skills: SkillMap) -> Self {
608        Self::with_codex_home(workspace_root, active_skills, None)
609    }
610
611    pub fn with_codex_home(workspace_root: PathBuf, active_skills: SkillMap, codex_home: Option<PathBuf>) -> Self {
612        Self { workspace_root, codex_home, active_skills }
613    }
614}
615
616#[async_trait]
617impl Tool for ListSkillsTool {
618    fn name(&self) -> &str {
619        "list_skills"
620    }
621
622    fn description(&self) -> &str {
623        "List all available skills and system utilities. Use 'query' to filter by name, description, or routing hints, or 'variety' to filter by type ('agent_skill' or 'system_utility'). Traditional skills stay inactive until activated via 'load_skill'. Returns matching skills with names, descriptions, and types."
624    }
625
626    fn parameter_schema(&self) -> Option<Value> {
627        Some(serde_json::json!({
628            "type": "object",
629            "properties": {
630                "query": {
631                    "type": "string",
632                    "description": "Optional search term to filter skills by name, description, or routing hints (case-insensitive)"
633                },
634                "variety": {
635                    "type": "string",
636                    "enum": ["agent_skill", "system_utility", "built_in"],
637                    "description": "Optional variety to filter by"
638                }
639            },
640            "additionalProperties": false
641        }))
642    }
643
644    fn default_permission(&self) -> ToolPolicy {
645        ToolPolicy::Allow
646    }
647
648    fn is_mutating(&self) -> bool {
649        false
650    }
651
652    fn is_parallel_safe(&self) -> bool {
653        true
654    }
655
656    async fn execute(&self, args: Value) -> anyhow::Result<Value> {
657        let query = args.get("query").and_then(|v| v.as_str()).map(|s| s.to_lowercase());
658        let variety_filter = args.get("variety").and_then(|v| v.as_str());
659
660        let active_names: HashSet<String> = self.active_skills.read().await.keys().cloned().collect();
661        let (codex_home, discovery) =
662            discover_skill_catalog(&self.workspace_root, self.codex_home.as_deref(), "list_skills")?;
663
664        let mut skill_list = Vec::new();
665
666        for skill_meta in discovery.skills.iter().filter(|skill| skill.manifest.is_some()) {
667            let manifest = skill_meta.manifest.as_ref().expect("filtered to skills with manifests");
668            let keywords = extract_metadata_keywords(manifest.metadata.as_ref());
669            if !matches_skill_filters(
670                manifest.name.as_str(),
671                manifest.description.as_str(),
672                manifest.variety,
673                query.as_deref(),
674                variety_filter,
675                &keywords,
676            ) {
677                continue;
678            }
679
680            let status = if active_names.contains(manifest.name.as_str()) {
681                "active"
682            } else {
683                "dormant"
684            };
685
686            skill_list.push(json!({
687                "name": manifest.name,
688                "description": manifest.description,
689                "path": skill_meta.path,
690                "scope": skill_meta.scope,
691                "variety": manifest.variety,
692                "status": status,
693            }));
694        }
695
696        for tool in discover_session_utilities(&self.workspace_root, &codex_home).await? {
697            if !matches_skill_filters(
698                tool.name.as_str(),
699                tool.description.as_str(),
700                SkillVariety::SystemUtility,
701                query.as_deref(),
702                variety_filter,
703                &[],
704            ) {
705                continue;
706            }
707
708            skill_list.push(json!({
709                "name": tool.name,
710                "description": tool.description,
711                "variety": SkillVariety::SystemUtility,
712                "status": "dormant",
713            }));
714        }
715
716        // Sort by name for stable output
717        skill_list.sort_by(|a, b| {
718            let na = a.get("name").and_then(|v| v.as_str()).unwrap_or("");
719            let nb = b.get("name").and_then(|v| v.as_str()).unwrap_or("");
720            na.cmp(nb)
721        });
722
723        // Group by variety for "better" discovery
724        let mut grouped = HashMap::with_capacity(skill_list.len());
725        for skill in &skill_list {
726            let variety = skill.get("variety").and_then(|v| v.as_str()).unwrap_or("unknown");
727            grouped.entry(variety.to_string()).or_insert_with(Vec::new).push(skill.clone());
728        }
729
730        let mut response = serde_json::json!({
731            "count": skill_list.len(),
732            "groups": grouped,
733        });
734
735        // Add context message for queries
736        if (query.is_some() || variety_filter.is_some())
737            && let Some(response_object) = response.as_object_mut()
738        {
739            response_object.insert("filter_applied".to_string(), serde_json::json!(true));
740        }
741
742        if !discovery.errors.is_empty()
743            && let Some(response_object) = response.as_object_mut()
744        {
745            response_object.insert("discovery_errors".to_string(), serde_json::json!(discovery.errors.len()));
746            response_object.insert(
747                "discovery_error_samples".to_string(),
748                serde_json::json!(discovery_error_samples(discovery.errors.as_slice())),
749            );
750        }
751
752        Ok(response)
753    }
754}
755
756/// Tool to load a specific resource from a skill (Level 3)
757pub struct LoadSkillResourceTool {
758    skills: SkillMap,
759}
760
761impl LoadSkillResourceTool {
762    pub fn new(skills: SkillMap) -> Self {
763        Self { skills }
764    }
765}
766
767#[async_trait]
768impl Tool for LoadSkillResourceTool {
769    fn name(&self) -> &str {
770        "load_skill_resource"
771    }
772
773    fn description(&self) -> &str {
774        "Read a resource file (script, template, or doc) from an active skill's directory. The skill must already be loaded via load_skill, which is also the tool that returns skill instructions. Provide skill_name and resource_path relative to the skill root. Returns the raw file content."
775    }
776
777    fn parameter_schema(&self) -> Option<Value> {
778        Some(serde_json::json!({
779            "type": "object",
780            "properties": {
781                "skill_name": {
782                    "type": "string",
783                    "description": "The name of the skill"
784                },
785                "resource_path": {
786                    "type": "string",
787                    "description": "The relative path of the resource (e.g. 'scripts/helper.py')"
788                }
789            },
790            "required": ["skill_name", "resource_path"]
791        }))
792    }
793
794    fn default_permission(&self) -> ToolPolicy {
795        ToolPolicy::Allow
796    }
797
798    fn is_mutating(&self) -> bool {
799        false
800    }
801
802    fn is_parallel_safe(&self) -> bool {
803        true
804    }
805
806    async fn execute(&self, args: Value) -> anyhow::Result<Value> {
807        let skill_name = required_string_arg(&args, "skill_name")?;
808        let resource_path = required_string_arg(&args, "resource_path")?;
809
810        let skills = self.skills.read().await;
811        if skills.is_empty() {
812            return Err(anyhow::anyhow!(
813                "No skills are active in this session yet. Use `load_skill` (or `/skills load <name>`) first."
814            ));
815        }
816        if let Some(skill) = skills.get(skill_name) {
817            let full_path = resolve_skill_resource_path(&skill.path, resource_path)?;
818            let content = read_file_with_context(&full_path, "skill resource")
819                .await
820                .context(format!("Failed to read resource at {}", full_path.display()))?;
821
822            Ok(serde_json::json!({
823                "skill_name": skill_name,
824                "resource_path": resource_path,
825                "content": content
826            }))
827        } else {
828            Err(skill_ops::skill_not_found_error(skill_name))
829        }
830    }
831}
832
833#[cfg(test)]
834mod tests;