aigent 0.7.1

A library, CLI, and Claude plugin for managing agent skill definitions
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Skill-to-plugin assembly: packages skill directories into a Claude Code plugin.
//!
//! Takes one or more skill directories and generates a complete plugin directory
//! structure with a `plugin.json` manifest, `skills/` subdirectory containing
//! the skill files.

use std::path::{Path, PathBuf};

use crate::errors::{AigentError, Result};
use crate::fs_util::{is_regular_dir, is_regular_file};
use crate::parser::{find_skill_md, read_properties};

/// Maximum recursion depth for directory operations.
const MAX_RECURSION_DEPTH: usize = 10;

/// Assembled skill metadata collected during plugin assembly.
#[derive(Debug)]
pub struct AssembleWarning {
    /// The skill directory that caused the warning.
    pub dir: PathBuf,
    /// A human-readable warning message.
    pub message: String,
}

/// Options for plugin assembly.
#[derive(Debug)]
pub struct AssembleOptions {
    /// Output directory for the assembled plugin.
    pub output_dir: PathBuf,
    /// Override plugin name (default: derived from first skill).
    pub name: Option<String>,
    /// Run validation on assembled skills.
    pub validate: bool,
}

/// Result of a successful plugin assembly.
#[derive(Debug)]
pub struct AssembleResult {
    /// Path to the assembled plugin directory.
    pub plugin_dir: PathBuf,
    /// Number of skills included.
    pub skills_count: usize,
    /// Non-fatal warnings encountered during assembly.
    pub warnings: Vec<AssembleWarning>,
}

/// Assemble skills into a plugin directory.
///
/// Creates the output directory structure:
/// ```text
/// <output_dir>/
/// ├── plugin.json
/// ├── skills/
/// │   ├── <skill-1>/
/// │   │   └── SKILL.md
/// │   └── <skill-2>/
/// │       └── SKILL.md
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - No valid skills are found in the input directories
/// - The output directory cannot be created
/// - Skill files cannot be read or copied
pub fn assemble_plugin(skill_dirs: &[&Path], opts: &AssembleOptions) -> Result<AssembleResult> {
    if skill_dirs.is_empty() {
        return Err(AigentError::Build {
            message: "no skill directories provided".into(),
        });
    }

    // Collect valid skills.
    let mut skills: Vec<(String, PathBuf)> = Vec::new();
    let mut warnings: Vec<AssembleWarning> = Vec::new();
    for dir in skill_dirs {
        if let Some(skill_path) = find_skill_md(dir) {
            match read_properties(dir) {
                Ok(props) => {
                    // Validate skill name to prevent path traversal.
                    if is_unsafe_name(&props.name) {
                        warnings.push(AssembleWarning {
                            dir: dir.to_path_buf(),
                            message: format!(
                                "skipping: unsafe skill name '{}' (contains path separators or '..')",
                                props.name
                            ),
                        });
                        continue;
                    }
                    skills.push((props.name.clone(), skill_path));
                }
                Err(e) => {
                    warnings.push(AssembleWarning {
                        dir: dir.to_path_buf(),
                        message: format!("skipping: {e}"),
                    });
                }
            }
        } else {
            warnings.push(AssembleWarning {
                dir: dir.to_path_buf(),
                message: "no SKILL.md found".into(),
            });
        }
    }

    if skills.is_empty() {
        return Err(AigentError::Build {
            message: "no valid skills found in provided directories".into(),
        });
    }

    // Determine plugin name.
    let plugin_name = opts.name.clone().unwrap_or_else(|| skills[0].0.clone());

    // Create output directory structure.
    let out = &opts.output_dir;
    let skills_dir = out.join("skills");

    std::fs::create_dir_all(&skills_dir)?;

    // Copy each skill into skills/<name>/.
    for (name, skill_path) in &skills {
        let dest_dir = skills_dir.join(name);
        std::fs::create_dir_all(&dest_dir)?;

        // Copy the SKILL.md file.
        let dest_file = dest_dir.join("SKILL.md");
        std::fs::copy(skill_path, &dest_file)?;

        // Copy any sibling files in the same directory as SKILL.md.
        if let Some(src_dir) = skill_path.parent() {
            copy_skill_files(src_dir, &dest_dir)?;
        }
    }

    // Validate assembled skills if requested.
    if opts.validate {
        let mut all_valid = true;
        for (name, _) in &skills {
            let dest_dir = skills_dir.join(name);
            let diags = crate::validate(&dest_dir);
            if diags.iter().any(|d| d.is_error()) {
                all_valid = false;
                for d in &diags {
                    warnings.push(AssembleWarning {
                        dir: dest_dir.clone(),
                        message: format!("{name}: {d}"),
                    });
                }
            }
        }
        if !all_valid {
            return Err(AigentError::Build {
                message: "assembled skills have validation errors".into(),
            });
        }
    }

    // Generate plugin.json.
    let plugin_json = generate_plugin_json(&plugin_name, &skills)?;
    std::fs::write(out.join("plugin.json"), plugin_json)?;

    Ok(AssembleResult {
        plugin_dir: out.clone(),
        skills_count: skills.len(),
        warnings,
    })
}

/// Check whether a skill name is unsafe for use as a directory component.
///
/// Rejects names containing path separators (`/`, `\`), parent traversal (`..`),
/// or that are empty.
fn is_unsafe_name(name: &str) -> bool {
    name.is_empty()
        || name.contains('/')
        || name.contains('\\')
        || name.contains("..")
        || name == "."
}

/// Copy non-SKILL.md files from source dir to destination dir.
///
/// Copies reference files, scripts, etc. that the skill may depend on.
/// Skips hidden files and the target/ directory.
fn copy_skill_files(src: &Path, dest: &Path) -> Result<()> {
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let name = entry.file_name();
        let name_str = name.to_string_lossy();

        // Skip SKILL.md (already copied), hidden files, and target/.
        if name_str == "SKILL.md"
            || name_str == "skill.md"
            || name_str.starts_with('.')
            || name_str == "target"
        {
            continue;
        }

        let src_path = entry.path();
        let dest_path = dest.join(&name);

        if is_regular_file(&src_path) {
            std::fs::copy(&src_path, &dest_path)?;
        } else if is_regular_dir(&src_path) {
            copy_dir_recursive(&src_path, &dest_path, 0)?;
        }
    }
    Ok(())
}

/// Recursively copy a directory.
///
/// # Errors
///
/// Returns an error if the recursion depth exceeds [`MAX_RECURSION_DEPTH`].
fn copy_dir_recursive(src: &Path, dest: &Path, depth: usize) -> Result<()> {
    if depth > MAX_RECURSION_DEPTH {
        return Err(AigentError::Build {
            message: format!("exceeded maximum directory depth ({MAX_RECURSION_DEPTH})"),
        });
    }
    std::fs::create_dir_all(dest)?;
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let src_path = entry.path();
        let dest_path = dest.join(entry.file_name());

        if is_regular_file(&src_path) {
            std::fs::copy(&src_path, &dest_path)?;
        } else if is_regular_dir(&src_path) {
            copy_dir_recursive(&src_path, &dest_path, depth + 1)?;
        }
    }
    Ok(())
}

/// Generate plugin.json content from skill metadata.
///
/// Uses `serde_json` for proper escaping of all string values.
fn generate_plugin_json(name: &str, skills: &[(String, PathBuf)]) -> Result<String> {
    let json = serde_json::json!({
        "name": name,
        "description": format!("Plugin assembled from {} skill(s)", skills.len()),
        "version": "0.1.0",
    });

    serde_json::to_string_pretty(&json).map_err(|e| AigentError::Build {
        message: format!("failed to generate plugin.json: {e}"),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn make_skill(parent: &Path, name: &str, content: &str) -> PathBuf {
        let dir = parent.join(name);
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("SKILL.md"), content).unwrap();
        dir
    }

    #[test]
    fn assemble_single_skill_creates_plugin() {
        let parent = tempdir().unwrap();
        let skill = make_skill(
            parent.path(),
            "my-skill",
            "---\nname: my-skill\ndescription: Does things\n---\nBody.\n",
        );
        let out = parent.path().join("output");
        let opts = AssembleOptions {
            output_dir: out.clone(),
            name: None,
            validate: false,
        };
        let result = assemble_plugin(&[skill.as_path()], &opts).unwrap();
        assert_eq!(result.skills_count, 1);
        assert!(out.join("plugin.json").exists());
        assert!(out.join("skills/my-skill/SKILL.md").exists());
        assert!(!out.join("agents").exists());
        assert!(!out.join("hooks").exists());
    }

    #[test]
    fn assemble_multiple_skills() {
        let parent = tempdir().unwrap();
        let s1 = make_skill(
            parent.path(),
            "skill-one",
            "---\nname: skill-one\ndescription: First\n---\nBody.\n",
        );
        let s2 = make_skill(
            parent.path(),
            "skill-two",
            "---\nname: skill-two\ndescription: Second\n---\nBody.\n",
        );
        let out = parent.path().join("output");
        let opts = AssembleOptions {
            output_dir: out.clone(),
            name: Some("my-plugin".into()),
            validate: false,
        };
        let result = assemble_plugin(&[s1.as_path(), s2.as_path()], &opts).unwrap();
        assert_eq!(result.skills_count, 2);
        assert!(out.join("skills/skill-one/SKILL.md").exists());
        assert!(out.join("skills/skill-two/SKILL.md").exists());
    }

    #[test]
    fn assemble_plugin_json_has_correct_structure() {
        let parent = tempdir().unwrap();
        let skill = make_skill(
            parent.path(),
            "my-skill",
            "---\nname: my-skill\ndescription: Does things\n---\nBody.\n",
        );
        let out = parent.path().join("output");
        let opts = AssembleOptions {
            output_dir: out.clone(),
            name: Some("test-plugin".into()),
            validate: false,
        };
        assemble_plugin(&[skill.as_path()], &opts).unwrap();
        let json_str = fs::read_to_string(out.join("plugin.json")).unwrap();
        let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(json["name"], "test-plugin");
        assert_eq!(json["version"], "0.1.0");
        assert!(json.get("skills").is_none());
    }

    #[test]
    fn assemble_no_skills_returns_error() {
        let parent = tempdir().unwrap();
        let out = parent.path().join("output");
        let opts = AssembleOptions {
            output_dir: out,
            name: None,
            validate: false,
        };
        let result = assemble_plugin(&[], &opts);
        assert!(result.is_err());
    }

    #[test]
    fn assemble_copies_reference_files() {
        let parent = tempdir().unwrap();
        let skill_dir = parent.path().join("my-skill");
        fs::create_dir_all(&skill_dir).unwrap();
        fs::write(
            skill_dir.join("SKILL.md"),
            "---\nname: my-skill\ndescription: Does things\n---\nBody.\n",
        )
        .unwrap();
        fs::write(skill_dir.join("reference.md"), "Extra docs").unwrap();

        let out = parent.path().join("output");
        let opts = AssembleOptions {
            output_dir: out.clone(),
            name: None,
            validate: false,
        };
        assemble_plugin(&[skill_dir.as_path()], &opts).unwrap();
        assert!(out.join("skills/my-skill/reference.md").exists());
    }

    #[test]
    fn assemble_with_validate_rejects_invalid_skill() {
        let parent = tempdir().unwrap();
        // Missing required 'name' field.
        let skill = make_skill(
            parent.path(),
            "bad-skill",
            "---\ndescription: Missing name\n---\nBody.\n",
        );
        let out = parent.path().join("output");
        let opts = AssembleOptions {
            output_dir: out,
            name: None,
            validate: true,
        };
        let result = assemble_plugin(&[skill.as_path()], &opts);
        assert!(result.is_err());
    }

    #[test]
    fn assemble_name_defaults_to_first_skill() {
        let parent = tempdir().unwrap();
        let skill = make_skill(
            parent.path(),
            "first-skill",
            "---\nname: first-skill\ndescription: Does things\n---\nBody.\n",
        );
        let out = parent.path().join("output");
        let opts = AssembleOptions {
            output_dir: out.clone(),
            name: None,
            validate: false,
        };
        assemble_plugin(&[skill.as_path()], &opts).unwrap();
        let json_str = fs::read_to_string(out.join("plugin.json")).unwrap();
        let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(json["name"], "first-skill");
    }

    #[test]
    fn assemble_rejects_path_traversal_name() {
        let parent = tempdir().unwrap();
        let skill = make_skill(
            parent.path(),
            "evil-skill",
            "---\nname: ../../../etc/passwd\ndescription: Malicious\n---\nBody.\n",
        );
        let out = parent.path().join("output");
        let opts = AssembleOptions {
            output_dir: out,
            name: None,
            validate: false,
        };
        // Should fail because the only skill has an unsafe name.
        let result = assemble_plugin(&[skill.as_path()], &opts);
        assert!(result.is_err());
    }

    #[test]
    fn assemble_warns_on_unsafe_name_but_continues_with_others() {
        let parent = tempdir().unwrap();
        let bad = make_skill(
            parent.path(),
            "bad",
            "---\nname: ../escape\ndescription: Malicious\n---\nBody.\n",
        );
        let good = make_skill(
            parent.path(),
            "good-skill",
            "---\nname: good-skill\ndescription: Legit\n---\nBody.\n",
        );
        let out = parent.path().join("output");
        let opts = AssembleOptions {
            output_dir: out.clone(),
            name: None,
            validate: false,
        };
        let result = assemble_plugin(&[bad.as_path(), good.as_path()], &opts).unwrap();
        assert_eq!(result.skills_count, 1);
        assert!(!result.warnings.is_empty());
        assert!(result.warnings[0].message.contains("unsafe skill name"));
    }

    #[test]
    fn assembled_plugin_passes_validate_manifest() {
        let parent = tempdir().unwrap();
        let skill = make_skill(
            parent.path(),
            "my-skill",
            "---\nname: my-skill\ndescription: Does things\n---\nBody.\n",
        );
        let out = parent.path().join("output");
        let opts = AssembleOptions {
            output_dir: out.clone(),
            name: Some("test-plugin".into()),
            validate: false,
        };
        assemble_plugin(&[skill.as_path()], &opts).unwrap();
        let diags = crate::plugin::manifest::validate_manifest(&out.join("plugin.json"));
        let errors: Vec<_> = diags.iter().filter(|d| d.is_error()).collect();
        assert!(
            errors.is_empty(),
            "validate_manifest should find no errors in assembled plugin.json: {errors:?}",
        );
    }

    #[test]
    fn generate_plugin_json_escapes_special_characters() {
        let skills = vec![("skill-with-\"quotes\"".to_string(), PathBuf::from("a.md"))];
        let json_str = generate_plugin_json("name-with-\"quotes\"", &skills).unwrap();
        let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(json["name"], "name-with-\"quotes\"");
        assert!(json.get("skills").is_none());
    }

    #[test]
    fn is_unsafe_name_detects_traversal() {
        assert!(is_unsafe_name("../etc/passwd"));
        assert!(is_unsafe_name("foo/bar"));
        assert!(is_unsafe_name("foo\\bar"));
        assert!(is_unsafe_name(".."));
        assert!(is_unsafe_name("."));
        assert!(is_unsafe_name(""));
        assert!(!is_unsafe_name("my-skill"));
        assert!(!is_unsafe_name("skill_with_underscores"));
    }

    #[test]
    fn copy_dir_recursive_normal_depth() {
        let tmp = tempdir().unwrap();
        let src = tmp.path().join("src");
        let dest = tmp.path().join("dest");

        // Create a few levels of nesting (well under the limit).
        let mut current = src.clone();
        for i in 0..5 {
            current = current.join(format!("level-{i}"));
            fs::create_dir_all(&current).unwrap();
            fs::write(current.join("file.txt"), format!("level {i}")).unwrap();
        }

        copy_dir_recursive(&src, &dest, 0).unwrap();

        // Verify deepest file was copied.
        let mut check = dest.clone();
        for i in 0..5 {
            check = check.join(format!("level-{i}"));
        }
        assert!(check.join("file.txt").exists());
    }

    #[test]
    fn copy_dir_recursive_exceeds_depth_limit() {
        let tmp = tempdir().unwrap();
        let src = tmp.path().join("src");
        let dest = tmp.path().join("dest");

        // Create nesting deeper than MAX_RECURSION_DEPTH.
        let mut current = src.clone();
        for i in 0..15 {
            current = current.join(format!("level-{i}"));
            fs::create_dir_all(&current).unwrap();
        }

        let result = copy_dir_recursive(&src, &dest, 0);
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("exceeded maximum directory depth"),
            "expected depth error, got: {err_msg}"
        );
    }

    #[test]
    fn copy_dir_recursive_error_message_contains_limit() {
        let tmp = tempdir().unwrap();
        let src = tmp.path().join("src");
        let dest = tmp.path().join("dest");

        let mut current = src.clone();
        for i in 0..15 {
            current = current.join(format!("level-{i}"));
            fs::create_dir_all(&current).unwrap();
        }

        let result = copy_dir_recursive(&src, &dest, 0);
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains(&MAX_RECURSION_DEPTH.to_string()),
            "error should contain the depth limit value, got: {err_msg}"
        );
    }
}