skills 0.0.2

Manage agent skills
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
//! Implementation of the `skills pack` command.

use std::{
    fs::{self, File},
    io::{self, Read, Write},
    path::{Path, PathBuf},
};

use owo_colors::OwoColorize;
use walkdir::WalkDir;
use zip::{ZipWriter, write::SimpleFileOptions};

use crate::{
    catalog::Catalog,
    commands::{ColorChoice, init},
    config::Config,
    diagnostics::Diagnostics,
    error::{Error, Result},
    paths::display_path,
};

/// Result of packing a single skill.
struct PackResult {
    /// Skill name.
    name: String,
    /// Output path.
    path: PathBuf,
    /// Size in bytes.
    size: u64,
    /// Files included.
    files: Vec<String>,
}

/// Execute the pack command for specific skills.
#[allow(clippy::too_many_arguments)]
pub async fn run(
    color: ColorChoice,
    verbose: bool,
    skill_names: Vec<String>,
    all: bool,
    output: Option<PathBuf>,
    local: bool,
    dry_run: bool,
    force: bool,
) -> Result<()> {
    init::ensure().await?;
    let mut diagnostics = Diagnostics::new(verbose);
    let config = Config::load()?;
    let catalog = Catalog::load(&config, &mut diagnostics);
    let use_color = color.enabled();

    let output_dir = output.unwrap_or_else(|| PathBuf::from("."));

    // Ensure output directory exists
    if !output_dir.exists() {
        if dry_run {
            println!("Would create directory: {}", display_path(&output_dir));
        } else {
            fs::create_dir_all(&output_dir).map_err(|e| Error::SkillWrite {
                path: output_dir.clone(),
                source: e,
            })?;
        }
    }

    // If --all or no skills specified, pack all skills
    if all || skill_names.is_empty() {
        return pack_all(&catalog, &output_dir, dry_run, force, use_color, local, &mut diagnostics);
    }

    if skill_names.len() == 1 {
        // Single skill - use detailed output
        pack_single(&catalog, &skill_names[0], &output_dir, dry_run, force, use_color, local)
    } else {
        // Multiple skills - use summary output
        pack_multiple(&catalog, &skill_names, &output_dir, dry_run, force, use_color, local, &mut diagnostics)
    }
}

/// Execute the pack-all command.
pub async fn run_all(
    color: ColorChoice,
    verbose: bool,
    output: PathBuf,
    local: bool,
    dry_run: bool,
    force: bool,
) -> Result<()> {
    init::ensure().await?;
    let mut diagnostics = Diagnostics::new(verbose);
    let config = Config::load()?;
    let catalog = Catalog::load(&config, &mut diagnostics);
    let use_color = color.enabled();

    pack_all(&catalog, &output, dry_run, force, use_color, local, &mut diagnostics)
}

/// Pack a single skill with detailed output.
fn pack_single(
    catalog: &Catalog,
    name: &str,
    output_dir: &Path,
    dry_run: bool,
    force: bool,
    use_color: bool,
    local: bool,
) -> Result<()> {
    // Find the skill
    let skill_dir = if local {
        find_local_skill(catalog, name)?
    } else {
        find_source_skill(catalog, name)?
    };

    // Determine output path
    let output_path = output_dir.join(format!("{}.zip", name));

    // Check if output exists
    if output_path.exists() && !force {
        return Err(Error::PathExists {
            path: output_path,
        });
    }

    if dry_run {
        println!(
            "{} '{}' from {}",
            "Would pack".bold(),
            name,
            display_path(&skill_dir)
        );
        let files = collect_files(&skill_dir)?;
        println!("\nFiles:");
        for file in &files {
            println!("  - {}", file);
        }
        println!("\nDry run - no changes made.");
        return Ok(());
    }

    // Pack the skill
    let result = pack_skill(name, &skill_dir, &output_path)?;

    // Print result
    if use_color {
        println!(
            "{} '{}' from {}",
            "Packing".bold(),
            result.name.cyan(),
            display_path(&skill_dir)
        );
    } else {
        println!("Packing '{}' from {}", result.name, display_path(&skill_dir));
    }
    println!();
    println!(
        "Created: {} ({} bytes)",
        display_path(&result.path),
        result.size
    );
    for file in &result.files {
        println!("  - {}", file);
    }
    println!();
    println!(
        "Share this file or import with: skills import {}",
        result.path.file_name().unwrap_or_default().to_string_lossy()
    );

    Ok(())
}

/// Pack multiple named skills with summary output.
#[allow(clippy::too_many_arguments)]
fn pack_multiple(
    catalog: &Catalog,
    names: &[String],
    output_dir: &Path,
    dry_run: bool,
    force: bool,
    use_color: bool,
    local: bool,
    diagnostics: &mut Diagnostics,
) -> Result<()> {
    println!(
        "Packing {} skills{}...",
        names.len(),
        if dry_run { " (dry run)" } else { "" }
    );
    println!();

    let mut success_count = 0;
    let mut skip_count = 0;

    for name in names {
        let skill_dir = if local {
            match find_local_skill(catalog, name) {
                Ok(dir) => dir,
                Err(e) => {
                    diagnostics.warn(format!("Skill '{}': {}", name, e));
                    if use_color {
                        println!("  {} {} (not found)", "✗".red(), name);
                    } else {
                        println!("  ✗ {} (not found)", name);
                    }
                    skip_count += 1;
                    continue;
                }
            }
        } else {
            match find_source_skill(catalog, name) {
                Ok(dir) => dir,
                Err(e) => {
                    diagnostics.warn(format!("Skill '{}': {}", name, e));
                    if use_color {
                        println!("  {} {} (not found)", "✗".red(), name);
                    } else {
                        println!("  ✗ {} (not found)", name);
                    }
                    skip_count += 1;
                    continue;
                }
            }
        };

        let output_path = output_dir.join(format!("{}.zip", name));

        // Check if output exists
        if output_path.exists() && !force {
            if use_color {
                println!("  {} {} (already exists)", "✗".red(), name);
            } else {
                println!("  ✗ {} (already exists)", name);
            }
            skip_count += 1;
            continue;
        }

        if dry_run {
            if use_color {
                println!("  {} {}.zip", "✓".green(), name);
            } else {
                println!("  ✓ {}.zip", name);
            }
            success_count += 1;
            continue;
        }

        match pack_skill(name, &skill_dir, &output_path) {
            Ok(result) => {
                if use_color {
                    println!("  {} {}.zip ({} bytes)", "✓".green(), name, result.size);
                } else {
                    println!("  ✓ {}.zip ({} bytes)", name, result.size);
                }
                success_count += 1;
            }
            Err(e) => {
                diagnostics.warn(format!("Failed to pack '{}': {}", name, e));
                if use_color {
                    println!("  {} {} ({})", "✗".red(), name, e);
                } else {
                    println!("  ✗ {} ({})", name, e);
                }
                skip_count += 1;
            }
        }
    }

    println!();
    if dry_run {
        println!(
            "Would create {} skill archives in {}",
            success_count,
            display_path(output_dir)
        );
    } else {
        println!(
            "Created {} skill archives in {}",
            success_count,
            display_path(output_dir)
        );
    }
    if skip_count > 0 {
        println!("Skipped {} skills", skip_count);
    }

    diagnostics.print_skipped_summary();
    Ok(())
}

/// Pack all skills from sources.
fn pack_all(
    catalog: &Catalog,
    output_dir: &Path,
    dry_run: bool,
    force: bool,
    use_color: bool,
    local: bool,
    diagnostics: &mut Diagnostics,
) -> Result<()> {
    // Ensure output directory exists
    if !output_dir.exists() {
        if dry_run {
            println!("Would create directory: {}", display_path(output_dir));
        } else {
            fs::create_dir_all(output_dir).map_err(|e| Error::SkillWrite {
                path: output_dir.to_path_buf(),
                source: e,
            })?;
        }
    }

    let skills: Vec<(&String, PathBuf)> = if local {
        // Collect local skills
        catalog
            .local
            .values()
            .flat_map(|skills| skills.iter())
            .map(|(name, skill)| (name, skill.skill_dir.clone()))
            .collect()
    } else {
        // Collect source skills
        catalog
            .sources
            .iter()
            .map(|(name, skill)| (name, skill.skill_dir.clone()))
            .collect()
    };

    if skills.is_empty() {
        println!("No skills found to pack.");
        return Ok(());
    }

    println!(
        "Packing {} skills{}...",
        if local { "local" } else { "all" },
        if dry_run { " (dry run)" } else { "" }
    );
    println!();

    let mut success_count = 0;
    let mut skip_count = 0;

    for (name, skill_dir) in skills {
        let output_path = output_dir.join(format!("{}.zip", name));

        // Check if output exists
        if output_path.exists() && !force {
            if use_color {
                println!("  {} {} (already exists)", "✗".red(), name);
            } else {
                println!("  ✗ {} (already exists)", name);
            }
            skip_count += 1;
            continue;
        }

        if dry_run {
            if use_color {
                println!("  {} {}.zip", "✓".green(), name);
            } else {
                println!("  ✓ {}.zip", name);
            }
            success_count += 1;
            continue;
        }

        match pack_skill(name, &skill_dir, &output_path) {
            Ok(result) => {
                if use_color {
                    println!("  {} {}.zip ({} bytes)", "✓".green(), name, result.size);
                } else {
                    println!("  ✓ {}.zip ({} bytes)", name, result.size);
                }
                success_count += 1;
            }
            Err(e) => {
                diagnostics.warn(format!("Failed to pack '{}': {}", name, e));
                if use_color {
                    println!("  {} {} ({})", "✗".red(), name, e);
                } else {
                    println!("  ✗ {} ({})", name, e);
                }
                skip_count += 1;
            }
        }
    }

    println!();
    if dry_run {
        println!(
            "Would create {} skill archives in {}",
            success_count,
            display_path(output_dir)
        );
    } else {
        println!(
            "Created {} skill archives in {}",
            success_count,
            display_path(output_dir)
        );
    }
    if skip_count > 0 {
        println!("Skipped {} skills", skip_count);
    }

    diagnostics.print_skipped_summary();
    Ok(())
}

/// Find a source skill by name.
fn find_source_skill(catalog: &Catalog, name: &str) -> Result<PathBuf> {
    catalog
        .sources
        .get(name)
        .map(|s| s.skill_dir.clone())
        .ok_or_else(|| Error::SkillNotFound {
            name: name.to_string(),
        })
}

/// Find a local skill by name.
fn find_local_skill(catalog: &Catalog, name: &str) -> Result<PathBuf> {
    for skills in catalog.local.values() {
        if let Some(skill) = skills.get(name) {
            return Ok(skill.skill_dir.clone());
        }
    }
    Err(Error::LocalSkillNotFound {
        name: name.to_string(),
    })
}

/// Collect relative file paths in a directory.
fn collect_files(dir: &Path) -> Result<Vec<String>> {
    let mut files = Vec::new();
    for entry in WalkDir::new(dir).min_depth(1) {
        let entry = entry.map_err(|e| Error::SkillRead {
            path: dir.to_path_buf(),
            source: e
                .into_io_error()
                .unwrap_or_else(|| io::Error::other("walkdir error")),
        })?;
        if entry.file_type().is_file()
            && let Ok(rel) = entry.path().strip_prefix(dir)
        {
            files.push(rel.display().to_string());
        }
    }
    files.sort();
    Ok(files)
}

/// Pack a skill directory into a ZIP file.
fn pack_skill(name: &str, skill_dir: &Path, output_path: &Path) -> Result<PackResult> {
    let file = File::create(output_path).map_err(|e| Error::ZipCreate {
        path: output_path.to_path_buf(),
        message: e.to_string(),
    })?;

    let mut zip = ZipWriter::new(file);
    let options = SimpleFileOptions::default()
        .compression_method(zip::CompressionMethod::Deflated)
        .unix_permissions(0o644);

    let mut files = Vec::new();

    for entry in WalkDir::new(skill_dir).min_depth(1) {
        let entry = entry.map_err(|e| Error::ZipCreate {
            path: output_path.to_path_buf(),
            message: e.to_string(),
        })?;

        let path = entry.path();
        let rel_path = path.strip_prefix(skill_dir).map_err(|_| Error::ZipCreate {
            path: output_path.to_path_buf(),
            message: "failed to compute relative path".to_string(),
        })?;

        // Build archive path with skill name as root directory
        let archive_path = format!("{}/{}", name, rel_path.display());

        if entry.file_type().is_dir() {
            zip.add_directory(&archive_path, options).map_err(|e| Error::ZipCreate {
                path: output_path.to_path_buf(),
                message: e.to_string(),
            })?;
        } else if entry.file_type().is_file() {
            zip.start_file(&archive_path, options).map_err(|e| Error::ZipCreate {
                path: output_path.to_path_buf(),
                message: e.to_string(),
            })?;

            let mut f = File::open(path).map_err(|e| Error::SkillRead {
                path: path.to_path_buf(),
                source: e,
            })?;
            let mut buffer = Vec::new();
            f.read_to_end(&mut buffer).map_err(|e| Error::SkillRead {
                path: path.to_path_buf(),
                source: e,
            })?;
            zip.write_all(&buffer).map_err(|e| Error::ZipCreate {
                path: output_path.to_path_buf(),
                message: e.to_string(),
            })?;

            files.push(rel_path.display().to_string());
        }
    }

    zip.finish().map_err(|e| Error::ZipCreate {
        path: output_path.to_path_buf(),
        message: e.to_string(),
    })?;

    let size = fs::metadata(output_path)
        .map(|m| m.len())
        .unwrap_or(0);

    files.sort();

    Ok(PackResult {
        name: name.to_string(),
        path: output_path.to_path_buf(),
        size,
        files,
    })
}