cc-agent-sdk 0.1.7

claude agent sdk
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! # VS Code Skills Format Export
//!
//! This module provides functionality to export skills in VS Code's SKILL.md format,
//! which includes YAML frontmatter with metadata and markdown content.

use crate::skills::error::SkillError;
use crate::skills::types::SkillPackage;
use std::fs;
use std::io::Write;
use std::path::Path;

/// VS Code Skill format configuration
#[derive(Debug, Clone)]
pub struct VsCodeExportConfig {
    /// Include dependencies in the export
    pub include_dependencies: bool,

    /// Include resource references in the export
    pub include_resources: bool,

    /// Add usage examples section
    pub include_examples: bool,

    /// Custom footer to add to the markdown
    pub footer: Option<String>,
}

impl Default for VsCodeExportConfig {
    fn default() -> Self {
        Self {
            include_dependencies: true,
            include_resources: true,
            include_examples: true,
            footer: None,
        }
    }
}

impl VsCodeExportConfig {
    /// Create a new export config with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set whether to include dependencies
    pub fn with_dependencies(mut self, include: bool) -> Self {
        self.include_dependencies = include;
        self
    }

    /// Set whether to include resources
    pub fn with_resources(mut self, include: bool) -> Self {
        self.include_resources = include;
        self
    }

    /// Set whether to include examples
    pub fn with_examples(mut self, include: bool) -> Self {
        self.include_examples = include;
        self
    }

    /// Set custom footer
    pub fn with_footer(mut self, footer: String) -> Self {
        self.footer = Some(footer);
        self
    }
}

/// Utility functions for VS Code Skills format
pub struct VsCodeUtils;

impl VsCodeUtils {
    /// Normalize a skill name to VS Code format
    ///
    /// Rules:
    /// - Lowercase only
    /// - Only alphanumeric characters and hyphens
    /// - Must start with a letter
    /// - Maximum 64 characters
    ///
    /// # Examples
    /// ```
    /// # use claude_agent_sdk::skills::vscode::VsCodeUtils;
    /// assert_eq!(VsCodeUtils::normalize_name("My Skill 123"), "my-skill-123");
    /// assert_eq!(VsCodeUtils::normalize_name("Test_API"), "test-api");
    /// ```
    pub fn normalize_name(name: &str) -> String {
        name.to_lowercase()
            .chars()
            .filter_map(|c| {
                if c.is_alphanumeric() {
                    Some(c)
                } else if c.is_whitespace() || c == '_' || c == '-' {
                    Some('-')
                } else {
                    None
                }
            })
            .collect::<String>()
            .split('-')
            .filter(|s| !s.is_empty())
            .collect::<Vec<&str>>()
            .join("-")
            .trim_start_matches(|c: char| !c.is_alphabetic())
            .to_string()
    }

    /// Validate a skill name according to VS Code rules
    pub fn validate_name(name: &str) -> Result<(), SkillError> {
        if name.is_empty() {
            return Err(SkillError::Validation("Name cannot be empty".to_string()));
        }

        if name.len() > 64 {
            return Err(SkillError::Validation(
                "Name must be 64 characters or less".to_string(),
            ));
        }

        if !name
            .chars()
            .next()
            .map(|c| c.is_alphabetic())
            .unwrap_or(false)
        {
            return Err(SkillError::Validation(
                "Name must start with a letter".to_string(),
            ));
        }

        if !name.chars().all(|c| c.is_alphanumeric() || c == '-') {
            return Err(SkillError::Validation(
                "Name can only contain lowercase letters, numbers, and hyphens".to_string(),
            ));
        }

        if !name
            .chars()
            .all(|c| c.is_lowercase() || c.is_numeric() || c == '-')
        {
            return Err(SkillError::Validation("Name must be lowercase".to_string()));
        }

        Ok(())
    }

    /// Validate description length (should be concise)
    pub fn validate_description(description: &str) -> Result<(), SkillError> {
        if description.is_empty() {
            return Err(SkillError::Validation(
                "Description cannot be empty".to_string(),
            ));
        }

        if description.len() > 200 {
            return Err(SkillError::Validation(
                "Description should be 200 characters or less for clarity".to_string(),
            ));
        }

        Ok(())
    }
}

/// Export a skill package to VS Code SKILL.md format
pub fn export_to_vscode<P: AsRef<Path>>(
    skill: &SkillPackage,
    output_path: P,
    config: &VsCodeExportConfig,
) -> Result<(), SkillError> {
    let output_path = output_path.as_ref();

    // Normalize and validate name
    let normalized_name = VsCodeUtils::normalize_name(&skill.metadata.name);
    VsCodeUtils::validate_name(&normalized_name)?;

    // Validate description
    let description = skill.metadata.description.clone();
    VsCodeUtils::validate_description(&description)?;

    // Build the SKILL.md content
    let mut content = String::new();

    // YAML Frontmatter
    content.push_str("---\n");
    content.push_str(&format!("name: {}\n", normalized_name));
    content.push_str(&format!("description: {}\n", description));

    // Add version if available
    if !skill.metadata.version.is_empty() {
        content.push_str(&format!("version: {}\n", skill.metadata.version));
    }

    // Add author if available
    if let Some(ref author) = skill.metadata.author {
        content.push_str(&format!("author: {}\n", author));
    }

    // Add tags if available
    if !skill.metadata.tags.is_empty() {
        content.push_str(&format!("tags: [{}]\n", skill.metadata.tags.join(", ")));
    }

    content.push_str("---\n\n");

    // Instructions section
    if !skill.instructions.is_empty() {
        content.push_str("# Instructions\n\n");
        content.push_str(&skill.instructions);
        content.push_str("\n\n");
    }

    // Scripts section
    if !skill.scripts.is_empty() && config.include_resources {
        content.push_str("## Scripts\n\n");
        for (i, script) in skill.scripts.iter().enumerate() {
            content.push_str(&format!("### Script {}\n\n", i + 1));
            content.push_str("```");
            // Try to detect language from shebang or extension
            if script.contains("#!/bin/bash") || script.contains("#!/bin/sh") {
                content.push_str("bash");
            } else if script.contains("#!/usr/bin/env python") {
                content.push_str("python");
            } else if script.contains("fn ") && script.contains("{") {
                content.push_str("rust");
            } else {
                content.push_str("text");
            }
            content.push('\n');
            content.push_str(script);
            content.push_str("\n```\n\n");
        }
    }

    // Dependencies section
    if !skill.metadata.dependencies.is_empty() && config.include_dependencies {
        content.push_str("## Dependencies\n\n");
        content.push_str("This skill requires the following dependencies:\n\n");
        for dep in &skill.metadata.dependencies {
            content.push_str(&format!("- {}\n", dep));
        }
        content.push('\n');
    }

    // Resources section
    if config.include_resources {
        let has_folders = !skill.resources.folders.is_empty();
        let has_tools = !skill.resources.tools.is_empty();
        let has_tests = !skill.resources.tests.is_empty();

        if has_folders || has_tools || has_tests {
            content.push_str("## Resources\n\n");

            if has_folders {
                content.push_str("### Folders\n\n");
                for folder in &skill.resources.folders {
                    content.push_str(&format!("- `{}`\n", folder.display()));
                }
                content.push('\n');
            }

            if has_tools {
                content.push_str("### Tools\n\n");
                for tool in &skill.resources.tools {
                    content.push_str(&format!("- {}\n", tool));
                }
                content.push('\n');
            }

            if has_tests {
                content.push_str("### Tests\n\n");
                for test in &skill.resources.tests {
                    content.push_str(&format!("- {}\n", test));
                }
                content.push('\n');
            }
        }
    }

    // Examples section
    if config.include_examples {
        content.push_str("## Usage Examples\n\n");
        content.push_str("### Basic Usage\n\n");
        content.push_str("```rust\n");
        content.push_str("// Import the skill\n");
        content.push_str("use claude_agent_sdk::skills::SkillPackage;\n\n");
        content.push_str("// Load the skill from the installed directory\n");
        content.push_str("let skill = SkillPackage::load(\"");
        content.push_str(&skill.metadata.name);
        content.push_str("\").unwrap();\n\n");
        content.push_str("// Use the skill with an agent\n");
        content.push_str("let agent = Agent::new()\n");
        content.push_str("    .with_skill(skill);\n");
        content.push_str("```\n\n");
    }

    // Footer
    if let Some(ref footer) = config.footer {
        content.push_str("---\n\n");
        content.push_str(footer);
        content.push('\n');
    }

    // Write to file
    let mut file = fs::File::create(output_path)
        .map_err(|e| SkillError::Io(format!("Failed to create SKILL.md file: {}", e)))?;

    file.write_all(content.as_bytes())
        .map_err(|e| SkillError::Io(format!("Failed to write SKILL.md file: {}", e)))?;

    Ok(())
}

/// Export multiple skills to a directory
pub fn export_batch_to_vscode<P: AsRef<Path>>(
    skills: &[SkillPackage],
    output_dir: P,
    config: &VsCodeExportConfig,
) -> Result<Vec<String>, SkillError> {
    let output_dir = output_dir.as_ref();

    // Create output directory if it doesn't exist
    if !output_dir.exists() {
        fs::create_dir_all(output_dir)
            .map_err(|e| SkillError::Io(format!("Failed to create output directory: {}", e)))?;
    }

    let mut exported = Vec::new();

    for skill in skills {
        let normalized_name = VsCodeUtils::normalize_name(&skill.metadata.name);
        let file_name = format!("{}.md", normalized_name);
        let file_path = output_dir.join(&file_name);

        export_to_vscode(skill, &file_path, config)?;

        exported.push(file_path.to_string_lossy().to_string());
    }

    Ok(exported)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::skills::types::{SkillMetadata, SkillResources};
    use uuid::Uuid;

    #[allow(dead_code)]
    fn create_test_skill(name: &str, description: &str) -> SkillPackage {
        SkillPackage {
            metadata: SkillMetadata {
                id: Uuid::new_v4().to_string(),
                name: name.to_string(),
                description: description.to_string(),
                version: "1.0.0".to_string(),
                author: Some("Test Author".to_string()),
                dependencies: vec!["dep1".to_string(), "dep2".to_string()],
                tags: vec!["rust".to_string(), "api".to_string()],
            },
            instructions: "This is a test skill with instructions.".to_string(),
            scripts: vec!["#!/bin/bash\necho 'Hello'".to_string()],
            resources: {
                let mut res = SkillResources::default();
                res.folders.push("/tmp/test".into());
                res.tools.push("test-tool".to_string());
                res
            },
        }
    }

    #[test]
    fn test_normalize_name_basic() {
        assert_eq!(VsCodeUtils::normalize_name("My Skill"), "my-skill");
        assert_eq!(VsCodeUtils::normalize_name("TestAPI"), "testapi");
        assert_eq!(VsCodeUtils::normalize_name("hello_world"), "hello-world");
        assert_eq!(VsCodeUtils::normalize_name("My Skill 123"), "my-skill-123");
    }

    #[test]
    fn test_normalize_name_special_chars() {
        assert_eq!(VsCodeUtils::normalize_name("Test@#$API"), "testapi");
        assert_eq!(
            VsCodeUtils::normalize_name("  multiple  spaces  "),
            "multiple-spaces"
        );
        assert_eq!(VsCodeUtils::normalize_name("Test___API"), "test-api");
    }

    #[test]
    fn test_validate_name_valid() {
        assert!(VsCodeUtils::validate_name("my-skill").is_ok());
        assert!(VsCodeUtils::validate_name("test").is_ok());
        assert!(VsCodeUtils::validate_name("my-skill-123").is_ok());
        assert!(VsCodeUtils::validate_name("a").is_ok());
    }

    #[test]
    fn test_validate_name_invalid_empty() {
        let result = VsCodeUtils::validate_name("");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_name_invalid_too_long() {
        let result = VsCodeUtils::validate_name(&"a".repeat(65));
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_name_invalid_start() {
        let result = VsCodeUtils::validate_name("123-skill");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_name_invalid_uppercase() {
        let result = VsCodeUtils::validate_name("MySkill");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_name_invalid_special_chars() {
        let result = VsCodeUtils::validate_name("my_skill");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_description_valid() {
        assert!(VsCodeUtils::validate_description("A valid description").is_ok());
    }

    #[test]
    fn test_validate_description_invalid_empty() {
        let result = VsCodeUtils::validate_description("");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_description_invalid_too_long() {
        let result = VsCodeUtils::validate_description(&"x".repeat(201));
        assert!(result.is_err());
    }

    #[test]
    fn test_export_config_default() {
        let config = VsCodeExportConfig::default();
        assert!(config.include_dependencies);
        assert!(config.include_resources);
        assert!(config.include_examples);
        assert!(config.footer.is_none());
    }

    #[test]
    fn test_export_config_builder() {
        let config = VsCodeExportConfig::new()
            .with_dependencies(false)
            .with_resources(false)
            .with_examples(false)
            .with_footer("Custom footer".to_string());

        assert!(!config.include_dependencies);
        assert!(!config.include_resources);
        assert!(!config.include_examples);
        assert_eq!(config.footer, Some("Custom footer".to_string()));
    }
}