1use hashbrown::HashMap;
7use serde::{Deserialize, Deserializer, Serialize};
8use serde_json::Value as JsonValue;
9use std::path::PathBuf;
10
11pub use crate::model::{SkillErrorInfo, SkillMetadata, SkillScope};
12
13pub type SkillManifestMetadata = HashMap<String, JsonValue>;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
17#[serde(rename_all = "snake_case")]
18pub enum SkillVariety {
19 #[default]
21 AgentSkill,
22 SystemUtility,
24 BuiltIn,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct SkillNetworkPolicy {
31 #[serde(default)]
32 pub allowed_domains: Vec<String>,
33 #[serde(default)]
34 pub denied_domains: Vec<String>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
39pub struct SkillPermissionProfile {
40 #[serde(
41 default,
42 skip_serializing_if = "Option::is_none",
43 deserialize_with = "deserialize_boxed_file_system_permissions_opt"
44 )]
45 pub file_system: Option<Box<SkillFileSystemPermissions>>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
50pub struct SkillFileSystemPermissions {
51 #[serde(default, skip_serializing_if = "Vec::is_empty")]
52 pub read: Vec<PathBuf>,
53 #[serde(default, skip_serializing_if = "Vec::is_empty")]
54 pub write: Vec<PathBuf>,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub struct SkillManifest {
60 pub name: String,
62 pub description: String,
64 pub version: Option<String>,
66 #[serde(skip_serializing_if = "Option::is_none")]
68 #[serde(rename = "default-version")]
69 #[serde(alias = "default_version")]
70 pub default_version: Option<String>,
71 #[serde(skip_serializing_if = "Option::is_none")]
73 #[serde(rename = "latest-version")]
74 #[serde(alias = "latest_version")]
75 pub latest_version: Option<String>,
76 pub author: Option<String>,
78 #[serde(skip_serializing_if = "Option::is_none")]
80 pub license: Option<String>,
81 #[serde(skip_serializing_if = "Option::is_none")]
83 pub model: Option<String>,
84 #[serde(skip_serializing_if = "Option::is_none")]
86 pub mode: Option<bool>,
87 #[serde(skip_serializing_if = "Option::is_none")]
89 #[serde(rename = "vtcode-native")]
90 #[serde(alias = "vtcode_native")]
91 pub vtcode_native: Option<bool>,
92 #[serde(skip_serializing_if = "Option::is_none")]
94 #[serde(rename = "allowed-tools")]
95 #[serde(alias = "allowed_tools")]
96 pub allowed_tools: Option<String>,
97 #[serde(skip_serializing_if = "Option::is_none")]
99 #[serde(rename = "disable-model-invocation")]
100 #[serde(alias = "disable_model_invocation")]
101 pub disable_model_invocation: Option<bool>,
102 #[serde(skip_serializing_if = "Option::is_none")]
104 #[serde(rename = "when-to-use")]
105 #[serde(alias = "when_to_use")]
106 pub when_to_use: Option<String>,
107 #[serde(skip_serializing_if = "Option::is_none")]
109 #[serde(rename = "when-not-to-use")]
110 #[serde(alias = "when_not_to_use")]
111 pub when_not_to_use: Option<String>,
112 #[serde(skip_serializing_if = "Option::is_none")]
114 #[serde(rename = "argument-hint")]
115 #[serde(alias = "argument_hint")]
116 pub argument_hint: Option<String>,
117 #[serde(skip_serializing_if = "Option::is_none")]
119 #[serde(rename = "user-invocable")]
120 #[serde(alias = "user_invocable")]
121 pub user_invocable: Option<bool>,
122 #[serde(skip_serializing_if = "Option::is_none")]
124 pub context: Option<String>,
125 #[serde(skip_serializing_if = "Option::is_none")]
127 pub agent: Option<String>,
128 #[serde(skip_serializing_if = "Option::is_none")]
130 pub hooks: Option<JsonValue>,
131 #[serde(skip_serializing_if = "Option::is_none")]
133 #[serde(rename = "requires-container")]
134 #[serde(alias = "requires_container")]
135 pub requires_container: Option<bool>,
136 #[serde(skip_serializing_if = "Option::is_none")]
138 #[serde(rename = "disallow-container")]
139 #[serde(alias = "disallow_container")]
140 pub disallow_container: Option<bool>,
141 #[serde(skip_serializing_if = "Option::is_none")]
143 pub compatibility: Option<String>,
144 #[serde(default)]
146 pub variety: SkillVariety,
147 #[serde(skip_serializing_if = "Option::is_none")]
149 pub metadata: Option<SkillManifestMetadata>,
150 #[serde(skip_serializing_if = "Option::is_none")]
152 pub tools: Option<Vec<String>>,
153 #[serde(skip_serializing_if = "Option::is_none")]
155 #[serde(rename = "network")]
156 #[serde(alias = "network_policy")]
157 pub network_policy: Option<Box<SkillNetworkPolicy>>,
158 #[serde(
160 default,
161 skip_serializing_if = "Option::is_none",
162 alias = "permission_profile",
163 deserialize_with = "deserialize_boxed_permission_profile_opt"
164 )]
165 pub permissions: Option<Box<SkillPermissionProfile>>,
166}
167
168impl SkillPermissionProfile {
169 fn is_empty(&self) -> bool {
170 self.file_system.is_none()
171 }
172
173 fn into_boxed_if_non_empty(self) -> Option<Box<Self>> {
174 (!self.is_empty()).then_some(Box::new(self))
175 }
176}
177
178impl SkillFileSystemPermissions {
179 fn is_empty(&self) -> bool {
180 self.read.is_empty() && self.write.is_empty()
181 }
182
183 fn into_boxed_if_non_empty(self) -> Option<Box<Self>> {
184 (!self.is_empty()).then_some(Box::new(self))
185 }
186}
187
188fn deserialize_boxed_permission_profile_opt<'de, D>(
189 deserializer: D,
190) -> Result<Option<Box<SkillPermissionProfile>>, D::Error>
191where
192 D: Deserializer<'de>,
193{
194 Option::<SkillPermissionProfile>::deserialize(deserializer)
195 .map(|value| value.and_then(SkillPermissionProfile::into_boxed_if_non_empty))
196}
197
198fn deserialize_boxed_file_system_permissions_opt<'de, D>(
199 deserializer: D,
200) -> Result<Option<Box<SkillFileSystemPermissions>>, D::Error>
201where
202 D: Deserializer<'de>,
203{
204 Option::<SkillFileSystemPermissions>::deserialize(deserializer)
205 .map(|value| value.and_then(SkillFileSystemPermissions::into_boxed_if_non_empty))
206}
207
208impl Default for SkillManifest {
209 fn default() -> Self {
210 Self {
211 name: String::new(),
212 description: String::new(),
213 version: None,
214 default_version: None,
215 latest_version: None,
216 author: None,
217 license: None,
218 model: None,
219 mode: None,
220 vtcode_native: None,
221 allowed_tools: None,
222 disable_model_invocation: None,
223 when_to_use: None,
224 when_not_to_use: None,
225 argument_hint: None,
226 user_invocable: None,
227 context: None,
228 agent: None,
229 hooks: None,
230 requires_container: None,
231 disallow_container: None,
232 compatibility: None,
233 variety: SkillVariety::AgentSkill,
234 metadata: None,
235 tools: None,
236 network_policy: None,
237 permissions: None,
238 }
239 }
240}
241
242impl SkillManifest {
243 pub fn validate(&self) -> anyhow::Result<()> {
245 self.validate_name()?;
246 self.validate_description()?;
247 self.validate_optional_fields()?;
248 Ok(())
249 }
250
251 fn validate_name(&self) -> anyhow::Result<()> {
253 if self.name.is_empty() {
254 anyhow::bail!("name is required and must not be empty");
255 }
256
257 if self.name.len() > 64 {
258 anyhow::bail!("name exceeds maximum length: {} characters (max 64)", self.name.len());
259 }
260
261 if !self.name.chars().all(|c| c.is_lowercase() || c.is_numeric() || c == '-') {
263 anyhow::bail!(
264 "name contains invalid characters: '{}'\nMust contain only lowercase letters, numbers, and hyphens",
265 self.name
266 );
267 }
268
269 if self.name.contains("--") {
271 anyhow::bail!("name contains consecutive hyphens: '{}'\nHyphens must not appear consecutively", self.name);
272 }
273
274 if self.name.starts_with('-') {
276 anyhow::bail!("name starts with hyphen: '{}'\nMust not start with a hyphen", self.name);
277 }
278
279 if self.name.ends_with('-') {
281 anyhow::bail!("name ends with hyphen: '{}'\nMust not end with a hyphen", self.name);
282 }
283
284 if self.name.contains("anthropic") || self.name.contains("claude") {
286 anyhow::bail!("name contains reserved word: '{}'\nMust not contain 'anthropic' or 'claude'", self.name);
287 }
288
289 Ok(())
290 }
291
292 fn validate_description(&self) -> anyhow::Result<()> {
294 if self.description.is_empty() {
295 anyhow::bail!("description is required and must not be empty");
296 }
297
298 if self.description.len() > 1024 {
299 anyhow::bail!("description exceeds maximum length: {} characters (max 1024)", self.description.len());
300 }
301
302 Ok(())
303 }
304
305 fn validate_optional_fields(&self) -> anyhow::Result<()> {
307 if self.hooks.is_some() {
308 anyhow::bail!("hooks are not supported in VT Code skills");
309 }
310
311 if let Some(allowed_tools) = &self.allowed_tools {
313 let tools: Vec<&str> = allowed_tools.split_whitespace().collect();
314
315 if tools.len() > 16 {
316 anyhow::bail!("allowed-tools exceeds maximum tool count: {} tools (max 16)", tools.len());
317 }
318
319 if tools.is_empty() {
320 anyhow::bail!("allowed-tools must not be empty if specified");
321 }
322 }
323
324 if let Some(license) = &self.license
326 && license.len() > 512
327 {
328 anyhow::bail!("license exceeds maximum length: {} characters (max 512)", license.len());
329 }
330
331 if let Some(compatibility) = &self.compatibility
333 && (compatibility.is_empty() || compatibility.len() > 500)
334 {
335 anyhow::bail!(
336 "compatibility must be between 1-500 characters if provided, got {} characters",
337 compatibility.len()
338 );
339 }
340
341 Ok(())
342 }
343
344 pub(crate) fn validate_directory_name_match(&self, skill_path: &std::path::Path) -> anyhow::Result<()> {
347 let tool_json = skill_path.join("tool.json");
350 if tool_json.exists() {
351 return Ok(());
352 }
353
354 let parent_dir = skill_path
355 .parent()
356 .ok_or_else(|| anyhow::anyhow!("Cannot determine parent directory of: {skill_path:?}"))?;
357
358 let dir_name = parent_dir
359 .file_name()
360 .and_then(|name| name.to_str())
361 .ok_or_else(|| anyhow::anyhow!("Cannot extract directory name from: {parent_dir:?}"))?;
362
363 if dir_name != self.name {
364 anyhow::bail!(
365 "Skill name '{}' does not match directory name '{}'\nPer Agent Skills spec, the name field must match the parent directory name",
366 self.name,
367 dir_name
368 );
369 }
370
371 Ok(())
372 }
373}
374
375#[derive(Debug, Clone, PartialEq, Eq)]
377pub enum ResourceType {
378 Markdown,
380 Script,
382 Reference,
384 Asset,
386 Other(String),
388}
389
390#[derive(Debug, Clone)]
392pub struct SkillResource {
393 pub path: String,
395 pub resource_type: ResourceType,
397 pub content: Option<Vec<u8>>,
399}
400
401#[derive(Debug, Clone)]
403pub struct Skill {
404 pub manifest: SkillManifest,
406
407 pub path: PathBuf,
409
410 pub scope: SkillScope,
412
413 pub instructions: String,
415
416 pub variety: SkillVariety,
418
419 resources: HashMap<String, SkillResource>,
421}
422
423impl Skill {
424 pub fn new(manifest: SkillManifest, path: PathBuf, instructions: String) -> anyhow::Result<Self> {
426 manifest.validate()?;
427 let path_str = path.to_string_lossy();
428 let scope = if path.starts_with(PathBuf::from("/etc/codex/skills")) {
429 SkillScope::Admin
430 } else if path_str.contains("/skills/.system/")
431 || path_str.ends_with("/skills/.system")
432 || path_str.contains("\\skills\\.system\\")
433 {
434 SkillScope::System
435 } else if path_str.contains("/.agents/skills/") || path_str.contains("\\.agents\\skills\\") {
436 SkillScope::Repo
437 } else {
438 SkillScope::User
439 };
440 Ok(Skill {
441 variety: manifest.variety,
442 manifest,
443 path,
444 scope,
445 instructions,
446 resources: HashMap::new(),
447 })
448 }
449
450 pub fn with_scope(
452 manifest: SkillManifest,
453 path: PathBuf,
454 scope: SkillScope,
455 instructions: String,
456 ) -> anyhow::Result<Self> {
457 manifest.validate()?;
458 Ok(Skill {
459 variety: manifest.variety,
460 manifest,
461 path,
462 scope,
463 instructions,
464 resources: HashMap::new(),
465 })
466 }
467
468 pub fn add_resource(&mut self, path: String, resource: SkillResource) {
470 self.resources.insert(path, resource);
471 }
472
473 pub fn name(&self) -> &str {
475 &self.manifest.name
476 }
477
478 pub fn description(&self) -> &str {
480 &self.manifest.description
481 }
482
483 fn instruction_tokens(&self) -> usize {
485 self.instructions.len() / 4
487 }
488
489 pub fn has_resource(&self, path: &str) -> bool {
491 self.resources.contains_key(path)
492 }
493
494 pub fn get_resource(&self, path: &str) -> Option<&SkillResource> {
496 self.resources.get(path)
497 }
498
499 pub fn list_resources(&self) -> Vec<&str> {
501 self.resources.keys().map(|s| s.as_str()).collect()
502 }
503}
504
505#[derive(Debug, Clone)]
507pub enum SkillContext {
508 MetadataOnly(SkillManifest, PathBuf),
510 WithInstructions(Skill),
512 Full(Skill),
514}
515
516impl SkillContext {
517 pub fn manifest(&self) -> &SkillManifest {
519 match self {
520 SkillContext::MetadataOnly(m, _) => m,
521 SkillContext::WithInstructions(s) => &s.manifest,
522 SkillContext::Full(s) => &s.manifest,
523 }
524 }
525
526 pub fn path(&self) -> &PathBuf {
528 match self {
529 SkillContext::MetadataOnly(_, p) => p,
530 SkillContext::WithInstructions(s) => &s.path,
531 SkillContext::Full(s) => &s.path,
532 }
533 }
534
535 pub fn skill(&self) -> Option<&Skill> {
537 match self {
538 SkillContext::MetadataOnly(_, _) => None,
539 SkillContext::WithInstructions(s) => Some(s),
540 SkillContext::Full(s) => Some(s),
541 }
542 }
543
544 fn tokens(&self) -> usize {
546 match self {
547 SkillContext::MetadataOnly(_, _) => 100,
548 SkillContext::WithInstructions(s) => 100 + s.instruction_tokens(),
549 SkillContext::Full(s) => 100 + s.instruction_tokens() + (s.resources.len() * 50),
550 }
551 }
552}
553
554#[derive(Debug, Clone)]
556pub struct SkillRegistryEntry {
557 skill: Skill,
558 enabled: bool,
559 load_time: std::time::SystemTime,
560}
561
562#[cfg(test)]
563mod tests {
564 use super::*;
565
566 #[test]
567 fn test_manifest_validation_valid() {
568 let m = SkillManifest {
569 name: "my-skill".to_string(),
570 description: "A test skill".to_string(),
571 ..Default::default()
572 };
573 m.validate().unwrap();
574 }
575
576 #[test]
577 fn test_manifest_validation_invalid_name_length() {
578 let m = SkillManifest {
579 name: "a".repeat(65),
580 description: "Valid description".to_string(),
581 ..Default::default()
582 };
583 assert!(m.validate().is_err());
584 }
585
586 #[test]
587 fn test_manifest_validation_reserved_word() {
588 let m = SkillManifest {
589 name: "anthropic-skill".to_string(),
590 description: "Valid description".to_string(),
591 ..Default::default()
592 };
593 assert!(m.validate().is_err());
594 }
595
596 #[test]
597 fn test_skill_context_tokens() {
598 let manifest = SkillManifest {
599 name: "test".to_string(),
600 description: "Test".to_string(),
601 ..Default::default()
602 };
603
604 let meta_ctx = SkillContext::MetadataOnly(manifest.clone(), PathBuf::from("/test"));
605 assert_eq!(meta_ctx.tokens(), 100);
606 }
607
608 #[test]
609 fn test_compatibility_validation() {
610 let m = SkillManifest {
612 name: "test-skill".to_string(),
613 description: "Test description".to_string(),
614 compatibility: Some("Designed for VT Code".to_string()),
615 ..Default::default()
616 };
617 m.validate().unwrap();
618
619 let m = SkillManifest {
621 name: "test-skill".to_string(),
622 description: "Test description".to_string(),
623 compatibility: Some("".to_string()),
624 ..Default::default()
625 };
626 assert!(m.validate().is_err());
627
628 let m = SkillManifest {
630 name: "test-skill".to_string(),
631 description: "Test description".to_string(),
632 compatibility: Some("a".repeat(501)),
633 ..Default::default()
634 };
635 assert!(m.validate().is_err());
636 }
637
638 #[test]
639 fn test_allowed_tools_string_format() {
640 let m = SkillManifest {
642 name: "test-skill".to_string(),
643 description: "Test description".to_string(),
644 allowed_tools: Some("Read Write Bash".to_string()),
645 ..Default::default()
646 };
647 m.validate().unwrap();
648
649 let m = SkillManifest {
651 name: "test-skill".to_string(),
652 description: "Test description".to_string(),
653 allowed_tools: Some("".to_string()),
654 ..Default::default()
655 };
656 assert!(m.validate().is_err());
657
658 let tools = (0..17).map(|i| format!("Tool{i}")).collect::<Vec<_>>().join(" ");
660 let m = SkillManifest {
661 name: "test-skill".to_string(),
662 description: "Test description".to_string(),
663 allowed_tools: Some(tools),
664 ..Default::default()
665 };
666 assert!(m.validate().is_err());
667 }
668
669 #[test]
670 fn test_hooks_rejected() {
671 let m = SkillManifest {
672 name: "test-skill".to_string(),
673 description: "Test description".to_string(),
674 hooks: Some(serde_json::json!({
675 "pre_tool_use": [
676 { "command": "echo pre" }
677 ]
678 })),
679 ..Default::default()
680 };
681 assert!(m.validate().is_err());
682 }
683
684 #[test]
685 fn test_metadata_field() {
686 let mut metadata = HashMap::new();
687 metadata.insert("author".to_string(), serde_json::json!("Test Author"));
688 metadata.insert("version".to_string(), serde_json::json!("1.0.0"));
689
690 let m = SkillManifest {
691 name: "test-skill".to_string(),
692 description: "Test description".to_string(),
693 version: Some("1.0.0".to_string()),
694 author: Some("Test Author".to_string()),
695 metadata: Some(metadata),
696 tools: None,
697 ..Default::default()
698 };
699 m.validate().unwrap();
700 }
701
702 #[test]
703 fn empty_permissions_deserialize_to_none() {
704 let manifest: SkillManifest = serde_json::from_str(
705 r#"{
706 "name": "test-skill",
707 "description": "Test description",
708 "permissions": {},
709 "network": {}
710 }"#,
711 )
712 .expect("manifest should deserialize");
713
714 assert!(manifest.permissions.is_none());
715 assert!(manifest.network_policy.is_some());
716 }
717
718 #[test]
719 fn empty_file_system_permissions_deserialize_to_none() {
720 let manifest: SkillManifest = serde_json::from_str(
721 r#"{
722 "name": "test-skill",
723 "description": "Test description",
724 "permissions": {
725 "file_system": {}
726 }
727 }"#,
728 )
729 .expect("manifest should deserialize");
730
731 assert!(manifest.permissions.is_none());
732 }
733
734 #[test]
735 fn boxed_skill_fields_are_smaller_than_inline_options() {
736 use std::mem::size_of;
737
738 assert!(size_of::<Option<Box<SkillNetworkPolicy>>>() < size_of::<Option<SkillNetworkPolicy>>());
739 assert!(size_of::<Option<Box<SkillPermissionProfile>>>() < size_of::<Option<SkillPermissionProfile>>());
740 assert!(size_of::<Option<Box<SkillFileSystemPermissions>>>() < size_of::<Option<SkillFileSystemPermissions>>());
741 }
742}