zeptoclaw 0.5.4

Ultra-lightweight personal AI assistant
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
//! Skills management command handler.

use anyhow::{Context, Result};

use zeptoclaw::config::Config;
use zeptoclaw::skills::{EnvSpec, Skill, SkillsLoader};

use super::common::skills_loader_from_config;
use super::SkillsAction;

/// Format the `skills show` output for a skill into a string.
///
/// Extracted as a pure function to simplify unit testing.
fn format_skill_show(skill: &Skill, loader: &SkillsLoader) -> String {
    let mut lines = Vec::new();

    lines.push(format!("Name:        {}", skill.name));

    if let Some(ref v) = skill.metadata.version {
        lines.push(format!("Version:     {}", v));
    }

    if let Some(ref a) = skill.metadata.author {
        lines.push(format!("Author:      {}", a));
    }

    if let Some(ref l) = skill.metadata.license {
        lines.push(format!("License:     {}", l));
    }

    if !skill.metadata.tags.is_empty() {
        lines.push(format!("Tags:        {}", skill.metadata.tags.join(", ")));
    }

    if !skill.metadata.depends.is_empty() {
        let deps: Vec<String> = skill
            .metadata
            .depends
            .iter()
            .map(|dep| {
                let check = if loader.load_skill(dep).is_some() {
                    "\u{2713}"
                } else {
                    "\u{2717}"
                };
                format!("{} {}", dep, check)
            })
            .collect();
        lines.push(format!("Depends:     {}", deps.join(", ")));
    }

    if !skill.metadata.conflicts.is_empty() {
        let cfls: Vec<String> = skill
            .metadata
            .conflicts
            .iter()
            .map(|c| {
                if loader.load_skill(c).is_some() {
                    format!("{} (installed \u{2717})", c)
                } else {
                    format!("{} (not installed \u{2713})", c)
                }
            })
            .collect();
        lines.push(format!("Conflicts:   {}", cfls.join(", ")));
    }

    if !skill.metadata.env_needed.is_empty() {
        lines.push("Env needed:".to_string());
        let max_name_len = compute_max_name_len(&skill.metadata.env_needed);
        for env in &skill.metadata.env_needed {
            let req = if env.required { "required" } else { "optional" };
            lines.push(format!(
                "  {:<width$}   {}   {}",
                env.name,
                req,
                env.description,
                width = max_name_len
            ));
        }
    }

    let available = if loader.check_requirements(skill) {
        "yes"
    } else {
        "no"
    };
    lines.push(format!("Available:   {}", available));

    lines.push(String::new());
    lines.push("--- Content ---".to_string());
    lines.push(skill.content.clone());

    lines.join("\n")
}

/// Compute the length of the longest `name` in an `env_needed` list.
fn compute_max_name_len(env_needed: &[EnvSpec]) -> usize {
    env_needed.iter().map(|e| e.name.len()).max().unwrap_or(0)
}

/// Skills management command.
pub(crate) async fn cmd_skills(action: SkillsAction) -> Result<()> {
    let config = Config::load().with_context(|| "Failed to load configuration")?;
    let loader = skills_loader_from_config(&config);

    match action {
        SkillsAction::List { all } => {
            let disabled: std::collections::HashSet<String> = config
                .skills
                .disabled
                .iter()
                .map(|name| name.to_ascii_lowercase())
                .collect();
            let mut listed = loader.list_skills(!all);
            listed.retain(|info| !disabled.contains(&info.name.to_ascii_lowercase()));

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

            println!("Skills:");
            for info in listed {
                let ready = loader
                    .load_skill(&info.name)
                    .map(|skill| loader.check_requirements(&skill))
                    .unwrap_or(false);
                let marker = if ready {
                    "ready"
                } else {
                    "missing requirements"
                };
                println!("  - {} ({}, {})", info.name, info.source, marker);
            }
        }
        SkillsAction::Show { name } => {
            if let Some(skill) = loader.load_skill(&name) {
                let output = format_skill_show(&skill, &loader);
                println!("{}", output);
            } else {
                anyhow::bail!("Skill '{}' not found", name);
            }
        }
        SkillsAction::Create { name } => {
            let dir = loader.workspace_dir().join(&name);
            let skill_file = dir.join("SKILL.md");
            if skill_file.exists() {
                anyhow::bail!("Skill '{}' already exists at {:?}", name, skill_file);
            }

            std::fs::create_dir_all(&dir)?;
            let template = format!(
                r#"---
name: {name}
version: 1.0.0
description: Describe what this skill does.
# author: Your Name or Org
# license: MIT
# tags:
#   - category
# depends:
#   - another-skill
# conflicts:
#   - incompatible-skill
# env_needed:
#   - name: MY_API_KEY
#     description: Your API key for the service
#     required: true
metadata: {{"zeptoclaw":{{"emoji":"📚","requires":{{}}}}}}
---

# {name} Skill

Describe usage and concrete command examples.
"#
            );
            std::fs::write(&skill_file, template)?;
            println!("Created skill at {:?}", skill_file);
        }
        SkillsAction::Search { query, source } => {
            cmd_skills_search(&config, &query, &source).await?;
        }
        SkillsAction::Install { slug, github } => {
            cmd_skills_install(&config, slug.as_deref(), github.as_deref()).await?;
        }
    }

    Ok(())
}

async fn cmd_skills_search(config: &Config, query: &str, source: &str) -> Result<()> {
    let client = reqwest::Client::new();
    let mut all_results = Vec::new();

    // GitHub search
    if source == "all" || source == "github" {
        let topics = &["zeptoclaw-skill", "openclaw-skill"];
        match zeptoclaw::skills::github_source::search_github(&client, query, topics).await {
            Ok(results) => all_results.extend(results),
            Err(e) => eprintln!("GitHub search failed: {}", e),
        }
    }

    // ClawHub search (reserved — config check kept for future integration)
    if source == "all" || source == "clawhub" {
        let _ = config; // config used for future ClawHub API calls
    }

    // Sort by score descending
    all_results.sort_by(|a, b| {
        b.score
            .partial_cmp(&a.score)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    if all_results.is_empty() {
        println!("No skills found matching '{}'", query);
        return Ok(());
    }

    println!("Found {} skill(s):\n", all_results.len());
    for r in &all_results {
        let source_label = match r.source {
            zeptoclaw::skills::github_source::SkillSource::GitHub => "github",
            zeptoclaw::skills::github_source::SkillSource::ClawHub => "clawhub",
        };
        println!(
            "  {} ({}) [{}] score={:.2} stars={}",
            r.name, r.slug, source_label, r.score, r.stars
        );
        if !r.description.is_empty() {
            println!("    {}", r.description);
        }
        println!();
    }

    Ok(())
}

async fn cmd_skills_install(
    _config: &Config,
    _slug: Option<&str>,
    github: Option<&str>,
) -> Result<()> {
    if let Some(repo) = github {
        cmd_skills_install_github(repo).await
    } else {
        anyhow::bail!("Specify --github owner/repo to install a skill from GitHub")
    }
}

async fn cmd_skills_install_github(repo: &str) -> Result<()> {
    // Validate owner/repo format
    if !repo.contains('/') {
        anyhow::bail!("Expected owner/repo format, got: {}", repo);
    }

    let skills_dir = zeptoclaw::config::Config::dir().join("skills");
    std::fs::create_dir_all(&skills_dir)?;

    let repo_name = repo.split('/').nth(1).unwrap_or(repo);
    let target_dir = skills_dir.join(repo_name);

    if target_dir.exists() {
        anyhow::bail!(
            "Skill '{}' already exists at {}. Remove it first.",
            repo_name,
            target_dir.display()
        );
    }

    println!("Installing skill from github.com/{} ...", repo);

    let status = tokio::process::Command::new("git")
        .args([
            "clone",
            "--depth",
            "1",
            &format!("https://github.com/{}.git", repo),
        ])
        .arg(&target_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .status()
        .await?;

    if !status.success() {
        anyhow::bail!("git clone failed for {}", repo);
    }

    // Validate SKILL.md exists
    let skill_md = target_dir.join("SKILL.md");
    if !skill_md.exists() {
        // Clean up
        let _ = std::fs::remove_dir_all(&target_dir);
        anyhow::bail!("Repository {} has no SKILL.md — not a valid skill", repo);
    }

    // Remove .git to save space
    let _ = std::fs::remove_dir_all(target_dir.join(".git"));

    println!("Installed '{}' to {}", repo_name, target_dir.display());
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Verify the create template string contains all new field comments.
    #[test]
    fn test_create_template_contains_new_field_comments() {
        // Build the template the same way cmd_skills does (inline the pattern here).
        let name = "test-skill";
        let template = format!(
            r#"---
name: {name}
version: 1.0.0
description: Describe what this skill does.
# author: Your Name or Org
# license: MIT
# tags:
#   - category
# depends:
#   - another-skill
# conflicts:
#   - incompatible-skill
# env_needed:
#   - name: MY_API_KEY
#     description: Your API key for the service
#     required: true
metadata: {{"zeptoclaw":{{"emoji":"📚","requires":{{}}}}}}
---

# {name} Skill

Describe usage and concrete command examples.
"#
        );

        assert!(
            template.contains("# author:"),
            "template should contain '# author:'"
        );
        assert!(
            template.contains("# license:"),
            "template should contain '# license:'"
        );
        assert!(
            template.contains("# tags:"),
            "template should contain '# tags:'"
        );
        assert!(
            template.contains("# depends:"),
            "template should contain '# depends:'"
        );
        assert!(
            template.contains("# conflicts:"),
            "template should contain '# conflicts:'"
        );
        assert!(
            template.contains("# env_needed:"),
            "template should contain '# env_needed:'"
        );
        assert!(
            template.contains("version: 1.0.0"),
            "template should contain 'version: 1.0.0'"
        );
    }

    /// Verify that `compute_max_name_len` returns the correct padding value.
    #[test]
    fn test_env_spec_display_format() {
        let env_needed = vec![
            EnvSpec {
                name: "SHORT".to_string(),
                description: "A short name".to_string(),
                required: true,
            },
            EnvSpec {
                name: "MUCH_LONGER_NAME".to_string(),
                description: "A longer name".to_string(),
                required: false,
            },
            EnvSpec {
                name: "MED".to_string(),
                description: "Medium".to_string(),
                required: true,
            },
        ];

        let max_len = compute_max_name_len(&env_needed);
        assert_eq!(
            max_len,
            "MUCH_LONGER_NAME".len(),
            "max name len should be length of 'MUCH_LONGER_NAME'"
        );

        // Verify empty list returns 0.
        let empty: Vec<EnvSpec> = vec![];
        assert_eq!(
            compute_max_name_len(&empty),
            0,
            "max name len of empty list should be 0"
        );

        // Verify single-entry list returns that entry's name length.
        let single = vec![EnvSpec {
            name: "ONLY_ONE".to_string(),
            description: "desc".to_string(),
            required: true,
        }];
        assert_eq!(compute_max_name_len(&single), "ONLY_ONE".len());
    }
}