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