vtcode-core 0.104.0

Core library for VT Code - a Rust-based terminal coding agent
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
//! Skill bundle import/export
//!
//! Supports zip-based packaging of skills for distribution, version management,
//! and inline bundle injection. Follows OpenAI Skills API packaging patterns:
//! - Safe zip extraction with path traversal protection
//! - Size limits (50MB compressed, 25MB per file, 500 files max)
//! - Manifest validation after extraction
//! - Versioned storage layout

use anyhow::{Context, Result, bail};
use hashbrown::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};

/// Maximum compressed bundle size (50 MB)
pub const MAX_BUNDLE_SIZE: usize = 50 * 1024 * 1024;
/// Maximum uncompressed file size (25 MB)
pub const MAX_FILE_SIZE: usize = 25 * 1024 * 1024;
/// Maximum file count per bundle
pub const MAX_FILE_COUNT: usize = 500;

/// Result of importing a skill bundle
#[derive(Debug, Clone)]
pub struct ImportedSkillInfo {
    pub name: String,
    pub version: Option<String>,
    pub description: String,
    pub path: PathBuf,
    pub file_count: usize,
    pub total_size: u64,
}

/// Export a skill directory to a zip bundle (bytes)
///
/// Walks the skill directory and creates a zip archive.
/// The archive preserves the directory structure with the skill name as root.
pub fn export_skill_bundle(skill_root: &Path) -> Result<Vec<u8>> {
    let skill_md = skill_root.join("SKILL.md");
    if !skill_md.exists() {
        bail!("No SKILL.md found at {}", skill_root.display());
    }

    let mut buf = Vec::new();
    {
        let cursor = std::io::Cursor::new(&mut buf);
        let mut zip_writer = zip::ZipWriter::new(cursor);
        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated);

        add_dir_to_zip(&mut zip_writer, skill_root, skill_root, options)?;
        zip_writer
            .finish()
            .context("Failed to finalize zip archive")?;
    }

    info!(
        "Exported skill bundle from {}: {} bytes",
        skill_root.display(),
        buf.len()
    );
    Ok(buf)
}

fn add_dir_to_zip<W: Write + std::io::Seek>(
    zip_writer: &mut zip::ZipWriter<W>,
    root: &Path,
    dir: &Path,
    options: zip::write::SimpleFileOptions,
) -> Result<()> {
    for entry in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
        let entry = entry?;
        let path = entry.path();
        let rel = path
            .strip_prefix(root)
            .with_context(|| format!("stripping prefix from {}", path.display()))?;

        if path.is_dir() {
            let dir_name = format!("{}/", rel.to_string_lossy());
            zip_writer
                .add_directory(&dir_name, options)
                .with_context(|| format!("adding directory {dir_name}"))?;
            add_dir_to_zip(zip_writer, root, &path, options)?;
        } else {
            let name = rel.to_string_lossy().to_string();
            zip_writer
                .start_file(&name, options)
                .with_context(|| format!("starting file {name}"))?;
            let data =
                fs::read(&path).with_context(|| format!("reading file {}", path.display()))?;
            zip_writer.write_all(&data)?;
        }
    }
    Ok(())
}

/// Import a skill bundle (zip bytes) into the skill store
///
/// Extracts the zip, validates SKILL.md, and moves to versioned storage.
/// Storage layout: `<dest_store>/<skill-name>/<version>/...`
pub fn import_skill_bundle(zip_bytes: &[u8], dest_store: &Path) -> Result<ImportedSkillInfo> {
    if zip_bytes.len() > MAX_BUNDLE_SIZE {
        bail!(
            "Bundle size {} bytes exceeds maximum {} bytes",
            zip_bytes.len(),
            MAX_BUNDLE_SIZE
        );
    }

    let temp_dir = tempfile::tempdir().context("Failed to create temp directory")?;
    let temp_path = temp_dir.path();

    extract_zip_safely(zip_bytes, temp_path)?;

    let skill_md_path = find_skill_md(temp_path)?;
    let skill_root = skill_md_path.parent().unwrap_or(temp_path);

    validate_extracted_bundle(skill_root)?;

    let (manifest, _instructions) = crate::skills::manifest::parse_skill_content(
        &fs::read_to_string(&skill_md_path).context("Failed to read extracted SKILL.md")?,
    )?;

    let version = manifest
        .version
        .clone()
        .unwrap_or_else(|| "0.0.0".to_string());

    let dest_dir = dest_store.join(&manifest.name).join(&version);
    if dest_dir.exists() {
        warn!(
            "Overwriting existing skill version at {}",
            dest_dir.display()
        );
        fs::remove_dir_all(&dest_dir).context("Failed to remove existing version")?;
    }
    fs::create_dir_all(&dest_dir).context("Failed to create destination directory")?;

    let (file_count, total_size) = copy_dir_recursive(skill_root, &dest_dir)?;

    info!(
        "Imported skill '{}' v{} ({} files, {} bytes) to {}",
        manifest.name,
        version,
        file_count,
        total_size,
        dest_dir.display()
    );

    update_skill_index(dest_store, &manifest.name, &version)?;

    Ok(ImportedSkillInfo {
        name: manifest.name,
        version: Some(version),
        description: manifest.description,
        path: dest_dir,
        file_count,
        total_size,
    })
}

/// Import a skill from base64-encoded zip (inline bundle)
pub fn import_inline_bundle(base64_data: &str, dest_store: &Path) -> Result<ImportedSkillInfo> {
    use base64::Engine;
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(base64_data)
        .context("Failed to decode base64 bundle")?;
    import_skill_bundle(&bytes, dest_store)
}

/// Safely extract a zip archive with path-traversal and size protections
fn extract_zip_safely(zip_bytes: &[u8], dest: &Path) -> Result<()> {
    let cursor = std::io::Cursor::new(zip_bytes);
    let mut archive = zip::ZipArchive::new(cursor).context("Failed to open zip archive")?;

    if archive.len() > MAX_FILE_COUNT {
        bail!(
            "Zip contains {} entries, exceeds maximum {}",
            archive.len(),
            MAX_FILE_COUNT
        );
    }

    for i in 0..archive.len() {
        let mut file = archive
            .by_index(i)
            .with_context(|| format!("reading zip entry {i}"))?;
        let raw_name = file.name().to_string();

        if raw_name.contains("..") {
            bail!("Path traversal detected in zip entry: {raw_name}");
        }

        let out_path = dest.join(&raw_name);

        if !out_path.starts_with(dest) {
            bail!("Zip entry escapes destination: {}", out_path.display());
        }

        if file.is_dir() {
            fs::create_dir_all(&out_path)
                .with_context(|| format!("creating dir {}", out_path.display()))?;
        } else {
            if file.size() > MAX_FILE_SIZE as u64 {
                bail!(
                    "Zip entry '{}' ({} bytes) exceeds maximum {} bytes",
                    raw_name,
                    file.size(),
                    MAX_FILE_SIZE
                );
            }

            if let Some(parent) = out_path.parent() {
                fs::create_dir_all(parent)?;
            }

            let mut out_file = fs::File::create(&out_path)
                .with_context(|| format!("creating file {}", out_path.display()))?;
            std::io::copy(&mut file, &mut out_file)
                .with_context(|| format!("writing file {}", out_path.display()))?;
        }
    }

    Ok(())
}

/// Find SKILL.md in extracted directory (handles nested structures)
fn find_skill_md(dir: &Path) -> Result<PathBuf> {
    let direct = dir.join("SKILL.md");
    if direct.exists() {
        return Ok(direct);
    }
    let direct_lower = dir.join("skill.md");
    if direct_lower.exists() {
        return Ok(direct_lower);
    }

    for entry in fs::read_dir(dir).context("Failed to read extracted directory")? {
        let entry = entry?;
        if entry.path().is_dir() {
            let nested = entry.path().join("SKILL.md");
            if nested.exists() {
                return Ok(nested);
            }
            let nested_lower = entry.path().join("skill.md");
            if nested_lower.exists() {
                return Ok(nested_lower);
            }
        }
    }

    bail!("No SKILL.md found in extracted bundle")
}

/// Validate extracted bundle for security
fn validate_extracted_bundle(skill_root: &Path) -> Result<()> {
    let mut file_count = 0u64;
    let mut total_size = 0u64;

    validate_dir_recursive(skill_root, skill_root, &mut file_count, &mut total_size)?;

    if file_count > MAX_FILE_COUNT as u64 {
        bail!("Bundle contains {file_count} files, exceeds maximum {MAX_FILE_COUNT}");
    }

    Ok(())
}

fn validate_dir_recursive(
    root: &Path,
    dir: &Path,
    file_count: &mut u64,
    total_size: &mut u64,
) -> Result<()> {
    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();

        if path.is_symlink() {
            bail!("Symlinks not allowed in skill bundles: {}", path.display());
        }

        let canonical = path.canonicalize().unwrap_or_else(|_| path.clone());
        let root_canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
        if !canonical.starts_with(&root_canonical) {
            bail!(
                "Path traversal detected: {} escapes bundle root",
                path.display()
            );
        }

        if path.is_dir() {
            validate_dir_recursive(root, &path, file_count, total_size)?;
        } else {
            *file_count += 1;
            let size = entry.metadata()?.len();
            if size > MAX_FILE_SIZE as u64 {
                bail!(
                    "File {} ({size} bytes) exceeds maximum {MAX_FILE_SIZE} bytes",
                    path.display(),
                );
            }
            *total_size += size;
        }
    }
    Ok(())
}

/// Copy directory recursively, returning (file_count, total_bytes)
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(usize, u64)> {
    let mut count = 0usize;
    let mut size = 0u64;

    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let src_path = entry.path();
        let file_name = entry.file_name();
        let dst_path = dst.join(&file_name);

        if src_path.is_dir() {
            fs::create_dir_all(&dst_path)?;
            let (c, s) = copy_dir_recursive(&src_path, &dst_path)?;
            count += c;
            size += s;
        } else {
            fs::copy(&src_path, &dst_path)?;
            count += 1;
            size += entry.metadata()?.len();
        }
    }

    Ok((count, size))
}

/// Skill store index for tracking versions
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
pub struct SkillStoreIndex {
    pub skills: HashMap<String, SkillVersionIndex>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SkillVersionIndex {
    pub latest_version: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_version: Option<String>,
    pub versions: Vec<String>,
}

/// Update the skill index after import
fn update_skill_index(store_path: &Path, skill_name: &str, version: &str) -> Result<()> {
    let index_path = store_path.join("index.json");

    let mut index: SkillStoreIndex = if index_path.exists() {
        let content = fs::read_to_string(&index_path)?;
        serde_json::from_str(&content).unwrap_or_default()
    } else {
        SkillStoreIndex::default()
    };

    let entry = index
        .skills
        .entry(skill_name.to_string())
        .or_insert_with(|| SkillVersionIndex {
            latest_version: version.to_string(),
            default_version: None,
            versions: Vec::new(),
        });

    if !entry.versions.contains(&version.to_string()) {
        entry.versions.push(version.to_string());
    }
    entry.latest_version = version.to_string();

    fs::create_dir_all(store_path)?;
    fs::write(&index_path, serde_json::to_string_pretty(&index)?)?;

    debug!("Updated skill index at {}", index_path.display());
    Ok(())
}

/// Load the skill store index
pub fn load_skill_index(store_path: &Path) -> Result<SkillStoreIndex> {
    let index_path = store_path.join("index.json");
    if !index_path.exists() {
        return Ok(SkillStoreIndex::default());
    }
    let content = fs::read_to_string(&index_path)?;
    serde_json::from_str(&content).context("Failed to parse skill store index")
}

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

    #[test]
    fn test_skill_store_index_default() {
        let index = SkillStoreIndex::default();
        assert!(index.skills.is_empty());
    }

    #[test]
    fn test_skill_store_index_roundtrip() {
        let mut index = SkillStoreIndex::default();
        index.skills.insert(
            "test-skill".to_string(),
            SkillVersionIndex {
                latest_version: "1.0.0".to_string(),
                default_version: Some("1.0.0".to_string()),
                versions: vec!["0.9.0".to_string(), "1.0.0".to_string()],
            },
        );
        let json = serde_json::to_string(&index).expect("serialize");
        let parsed: SkillStoreIndex = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(parsed.skills["test-skill"].latest_version, "1.0.0");
        assert_eq!(parsed.skills["test-skill"].versions.len(), 2);
    }

    #[test]
    fn test_bundle_size_limit() {
        let oversized = vec![0u8; MAX_BUNDLE_SIZE + 1];
        let temp = tempfile::tempdir().expect("tempdir");
        let result = import_skill_bundle(&oversized, temp.path());
        assert!(result.is_err());
        assert!(
            result
                .expect_err("should fail")
                .to_string()
                .contains("exceeds maximum")
        );
    }
}