-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathskill.rs
More file actions
672 lines (597 loc) · 21.7 KB
/
skill.rs
File metadata and controls
672 lines (597 loc) · 21.7 KB
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
use crossterm::style::Stylize;
use directories::UserDirs;
use semver::Version;
use std::fs;
use std::path::PathBuf;
const REPO: &str = "hotdata-dev/hotdata-cli";
const PRIMARY_SKILL_NAME: &str = "hotdata";
const SKILL_NAMES: &[&str] = &[
"hotdata",
"hotdata-search",
"hotdata-analytics",
"hotdata-geospatial",
];
const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
/// Agent root directories to check for symlink installation.
/// If the root dir exists, we create <root>/skills/<skill> -> ~/.agents/skills/<skill>
const AGENT_ROOTS: &[&str] = &[".claude", ".pi"];
fn home_dir() -> PathBuf {
UserDirs::new()
.expect("could not determine home directory")
.home_dir()
.to_path_buf()
}
/// The canonical store location: ~/.hotdata/skills/<skill>
fn skill_store_path(skill_name: &str) -> PathBuf {
home_dir()
.join(".hotdata")
.join("skills")
.join(skill_name)
}
/// Canonical agents layer: ~/.agents/skills/<skill>
fn agents_skill_path(skill_name: &str) -> PathBuf {
home_dir()
.join(".agents")
.join("skills")
.join(skill_name)
}
fn agents_lock_path() -> PathBuf {
home_dir().join(".agents").join(".skill-lock.json")
}
fn download_url() -> String {
format!("https://github.com/{REPO}/releases/download/v{CURRENT_VERSION}/skills.tar.gz")
}
/// Returns agent skill paths for all agent roots that exist on disk.
fn detected_agent_skill_paths(skill_name: &str) -> Vec<(String, PathBuf)> {
let home = home_dir();
AGENT_ROOTS
.iter()
.filter_map(|root| {
let root_path = home.join(root);
if root_path.exists() {
Some((root.to_string(), root_path.join("skills").join(skill_name)))
} else {
None
}
})
.collect()
}
fn parse_version_from_skill_md(content: &str) -> Option<Version> {
let content = content.strip_prefix('\u{FEFF}').unwrap_or(content);
let rest = content
.strip_prefix("---\n")
.or_else(|| content.strip_prefix("---\r\n"))?;
let inner = rest.split("\n---").next()?;
for raw_line in inner.lines() {
let line = raw_line.trim();
let Some(ver_raw) = line.strip_prefix("version:") else {
continue;
};
let ver_str = ver_raw.trim().trim_start_matches('v').trim();
if let Ok(v) = Version::parse(ver_str) {
return Some(v);
}
}
None
}
fn read_installed_version() -> Option<Version> {
let content = fs::read_to_string(skill_store_path(PRIMARY_SKILL_NAME).join("SKILL.md")).ok()?;
parse_version_from_skill_md(&content)
}
fn all_skill_stores_present() -> bool {
SKILL_NAMES
.iter()
.all(|name| skill_store_path(name).exists())
}
fn skill_auto_update_suppress_path() -> PathBuf {
home_dir()
.join(".hotdata")
.join("skills")
.join(".skill_auto_update_suppressed_for_cli")
}
fn skill_auto_update_suppressed_for_this_cli() -> bool {
let Ok(s) = fs::read_to_string(skill_auto_update_suppress_path()) else {
return false;
};
s.trim() == CURRENT_VERSION
}
fn suppress_skill_auto_update_for_this_cli() {
let path = skill_auto_update_suppress_path();
if let Some(parent) = path.parent() {
let _ = fs::create_dir_all(parent);
}
let _ = fs::write(path, format!("{CURRENT_VERSION}\n"));
}
fn clear_skill_auto_update_suppression() {
let _ = fs::remove_file(skill_auto_update_suppress_path());
}
/// If the user has previously installed agent skills (`~/.hotdata/skills/hotdata` exists) but the on-disk
/// bundle is older than this CLI or incomplete, download the matching release tarball and refresh symlinks.
/// Does nothing when skills were never installed or when [`is_managed_by_skills_agent`] is true.
/// Download failures print a warning and do not exit.
pub fn maybe_auto_update_after_cli_upgrade() {
if is_managed_by_skills_agent() {
return;
}
if !skill_store_path(PRIMARY_SKILL_NAME).exists() {
return;
}
let current = Version::parse(CURRENT_VERSION).expect("invalid package version");
let needs_refresh = match read_installed_version() {
Some(v) if v >= current && all_skill_stores_present() => false,
_ => true,
};
if !needs_refresh {
clear_skill_auto_update_suppression();
return;
}
if skill_auto_update_suppressed_for_this_cli() {
return;
}
if let Err(e) = download_and_extract() {
eprintln!(
"{}",
format!("warning: could not auto-update agent skills: {e}").yellow()
);
return;
}
let _symlinks = ensure_symlinks();
let still_needed = match read_installed_version() {
Some(v) if v >= current && all_skill_stores_present() => false,
_ => true,
};
if still_needed {
suppress_skill_auto_update_for_this_cli();
eprintln!(
"{}",
format!(
"warning: agent skills still do not match this CLI after download (release tarball may lag the binary). Automatic refresh is suppressed for CLI v{CURRENT_VERSION}; remove {} to retry, or run `hotdata skills install`.",
skill_auto_update_suppress_path().display()
)
.yellow()
);
return;
}
clear_skill_auto_update_suppression();
eprintln!(
"{}",
format!("Agent skills updated to v{current}.").green()
);
}
fn is_managed_by_skills_agent() -> bool {
let content = match fs::read_to_string(agents_lock_path()) {
Ok(c) => c,
Err(_) => return false,
};
let json: serde_json::Value = match serde_json::from_str(&content) {
Ok(v) => v,
Err(_) => return false,
};
json.get(PRIMARY_SKILL_NAME).is_some()
}
fn download_and_extract() -> Result<(), String> {
download_and_extract_from_url(&download_url())
}
fn download_and_extract_from_url(url: &str) -> Result<(), String> {
eprintln!("Downloading skill...");
// Binary download — can't route through `send_debug` (which calls
// `resp.text()` and would corrupt the gzip stream). Log the
// request line manually so `--debug` still shows the URL.
crate::util::debug_request("GET", url, &[], None);
let client = reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(120))
.build()
.map_err(|e| format!("error creating HTTP client: {e}"))?;
let resp = client
.get(url)
.send()
.map_err(|e| format!("error downloading skill: {e}"))?;
if !resp.status().is_success() {
return Err(format!("error downloading skill: HTTP {}", resp.status()));
}
let bytes = resp
.bytes()
.map_err(|e| format!("error reading response: {e}"))?;
// Extract into ~/.hotdata/skills/
let store_dir = home_dir().join(".hotdata").join("skills");
fs::create_dir_all(&store_dir).map_err(|e| format!("error creating directory: {e}"))?;
let gz = flate2::read::GzDecoder::new(std::io::Cursor::new(bytes));
let mut archive = tar::Archive::new(gz);
for entry in archive
.entries()
.map_err(|e| format!("error reading archive: {e}"))?
{
let mut entry = entry.map_err(|e| format!("error reading archive entry: {e}"))?;
let path = entry
.path()
.map_err(|e| format!("error reading entry path: {e}"))?
.into_owned();
let rel = match path.strip_prefix("skills/") {
Ok(r) if !r.as_os_str().is_empty() => r.to_path_buf(),
_ => continue,
};
let dest = store_dir.join(&rel);
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent).map_err(|e| format!("error creating directory: {e}"))?;
}
entry
.unpack(&dest)
.map_err(|e| format!("error extracting {}: {e}", rel.display()))?;
}
Ok(())
}
/// Download and install skills for `version`. Called from `run_update()` after
/// the binary has been atomically swapped so that skills match the new CLI on
/// first use. Uses the release tarball URL for `version` (not `CURRENT_VERSION`,
/// which is still the old binary at call time). Skips silently when managed by
/// a skills agent. Prints a warning on failure so the binary update is not
/// rolled back.
pub fn install_for_version(version: &Version) {
if is_managed_by_skills_agent() {
return;
}
let url = format!("https://github.com/{REPO}/releases/download/v{version}/skills.tar.gz");
if let Err(e) = download_and_extract_from_url(&url) {
eprintln!(
"{}",
format!("warning: could not update agent skills: {e}").yellow()
);
return;
}
let _symlinks = ensure_symlinks();
clear_skill_auto_update_suppression();
println!("{}", format!("Agent skills updated to v{version}.").green());
}
fn copy_dir_recursive(src: &PathBuf, dst: &PathBuf) -> Result<(), String> {
fs::create_dir_all(dst).map_err(|e| format!("error creating directory: {e}"))?;
for entry in fs::read_dir(src).map_err(|e| format!("error reading directory: {e}"))? {
let entry = entry.map_err(|e| format!("error reading entry: {e}"))?;
let dest = dst.join(entry.file_name());
if entry.file_type().map_err(|e| format!("{e}"))?.is_dir() {
copy_dir_recursive(&entry.path(), &dest)?;
} else {
fs::copy(entry.path(), &dest).map_err(|e| format!("error copying file: {e}"))?;
}
}
Ok(())
}
fn ensure_symlink_or_copy(src: &PathBuf, link_path: &PathBuf) -> Result<bool, String> {
if let Some(parent) = link_path.parent() {
fs::create_dir_all(parent)
.map_err(|e| format!("error creating {}: {e}", parent.display()))?;
}
// Remove any existing symlink or directory so we can (re)create it
if link_path.symlink_metadata().is_ok() {
if link_path.is_symlink() {
fs::remove_file(link_path).map_err(|e| format!("error removing old symlink: {e}"))?;
} else {
fs::remove_dir_all(link_path)
.map_err(|e| format!("error removing old directory: {e}"))?;
}
}
// Try symlink first, fall back to copy
#[cfg(unix)]
if std::os::unix::fs::symlink(src, link_path).is_ok() {
return Ok(true);
}
#[cfg(windows)]
if std::os::windows::fs::symlink_dir(src, link_path).is_ok() {
return Ok(true);
}
copy_dir_recursive(src, link_path)?;
Ok(false) // false = copied, not symlinked
}
fn ensure_symlinks() -> Vec<(String, PathBuf, Result<bool, String>)> {
let mut results = Vec::new();
for skill_name in SKILL_NAMES {
let store_path = skill_store_path(skill_name);
let agents_path = agents_skill_path(skill_name);
// First: ~/.agents/skills/<skill> -> ~/.hotdata/skills/<skill>
let agents_result = ensure_symlink_or_copy(&store_path, &agents_path);
results.push((
format!("~/.agents ({skill_name})"),
agents_path.clone(),
agents_result,
));
// Then: each detected agent root -> ~/.agents/skills/<skill>
for (root, link_path) in detected_agent_skill_paths(skill_name) {
let result = ensure_symlink_or_copy(&agents_path, &link_path);
results.push((format!("~/{root} ({skill_name})"), link_path, result));
}
}
results
}
pub fn install_project() {
clear_skill_auto_update_suppression();
let current = Version::parse(CURRENT_VERSION).expect("invalid package version");
// Ensure skill files exist locally first
match read_installed_version() {
Some(ref v) if *v >= current && all_skill_stores_present() => {}
Some(ref v) if *v >= current => {
println!(
"{}",
format!("Incomplete skills in ~/.hotdata/skills, downloading v{current}...")
.yellow()
);
if let Err(e) = download_and_extract() {
eprintln!("{}", e.red());
std::process::exit(1);
}
}
Some(ref v) => {
println!(
"{}",
format!("Global skill is outdated (v{v}), downloading v{current} first...")
.yellow()
);
if let Err(e) = download_and_extract() {
eprintln!("{}", e.red());
std::process::exit(1);
}
}
None => {
println!("Skill not installed globally, downloading v{current}...");
if let Err(e) = download_and_extract() {
eprintln!("{}", e.red());
std::process::exit(1);
}
}
}
let cwd = std::env::current_dir().expect("could not determine current directory");
let project_skills_root = cwd.join(".agents").join("skills");
// Always copy (not symlink) from store to .agents/skills/<skill>
if let Some(parent) = project_skills_root.parent() {
fs::create_dir_all(parent).unwrap_or_else(|e| {
eprintln!("{}", format!("error creating directory: {e}").red());
std::process::exit(1);
});
}
for skill_name in SKILL_NAMES {
let store_path = skill_store_path(skill_name);
let project_agents = project_skills_root.join(skill_name);
if project_agents.exists() {
fs::remove_dir_all(&project_agents).unwrap_or_else(|e| {
eprintln!(
"{}",
format!("error removing existing directory: {e}").red()
);
std::process::exit(1);
});
}
if let Some(parent) = project_agents.parent() {
fs::create_dir_all(parent).unwrap_or_else(|e| {
eprintln!("{}", format!("error creating directory: {e}").red());
std::process::exit(1);
});
}
copy_dir_recursive(&store_path, &project_agents).unwrap_or_else(|e| {
eprintln!("{}", e.red());
std::process::exit(1);
});
}
println!(
"{}",
format!("Skill installed to project (v{current}).").green()
);
println!("{:<20}{}", "Location:", ".agents/skills".cyan());
// For .claude and .pi in cwd: symlink (fallback copy) from .agents/skills/<skill>
for root in AGENT_ROOTS {
let root_path = cwd.join(root);
if !root_path.exists() {
continue;
}
for skill_name in SKILL_NAMES {
let project_agents = project_skills_root.join(skill_name);
let link_path = root_path.join("skills").join(skill_name);
let rel_link = link_path.strip_prefix(&cwd).unwrap_or(&link_path);
match ensure_symlink_or_copy(&project_agents, &link_path) {
Ok(true) => println!(
"{:<20}{}",
format!("./{root} ({skill_name}):"),
rel_link.display().to_string().cyan()
),
Ok(false) => println!(
"{:<20}{} (copied)",
format!("./{root} ({skill_name}):"),
rel_link.display().to_string().cyan()
),
Err(e) => eprintln!(
"{}",
format!("./{root} ({skill_name}): failed: {e}").red()
),
}
}
}
}
pub fn install() {
clear_skill_auto_update_suppression();
let current = Version::parse(CURRENT_VERSION).expect("invalid package version");
let needs_download = if is_managed_by_skills_agent() {
match read_installed_version() {
Some(ref v) if *v >= current && all_skill_stores_present() => {
println!("Managed by skills agent — already up to date (v{v}).");
false
}
Some(ref v) if *v >= current => {
println!(
"{}",
format!("Managed by skills agent — completing skill install (v{current})...")
.yellow()
);
true
}
Some(ref v) => {
println!(
"{}",
format!("Managed by skills agent — updating from v{v} to v{current}...")
.yellow()
);
true
}
None => {
println!("Installing hotdata skill v{current}...");
true
}
}
} else {
match read_installed_version() {
Some(ref v) if *v >= current && all_skill_stores_present() => {
println!("Already up to date (v{v}).");
false
}
Some(ref v) if *v >= current => {
println!(
"{}",
format!("Completing skill install (v{current})...").yellow()
);
true
}
Some(ref v) => {
println!("Updating from v{v} to v{current}...");
true
}
None => {
println!("Installing hotdata skill v{current}...");
true
}
}
};
if needs_download && let Err(e) = download_and_extract() {
eprintln!("{}", e.red());
std::process::exit(1);
}
let symlinks = ensure_symlinks();
println!(
"{}",
format!("Skill installed successfully (v{current}).").green()
);
println!(
"{:<20}{}",
"Location:",
"~/.hotdata/skills/<skill>".dark_grey()
);
for skill_name in SKILL_NAMES {
println!(
"{:<20}{}",
format!("{skill_name}:"),
skill_store_path(skill_name).display().to_string().cyan()
);
}
for (label, path, result) in &symlinks {
let status = match result {
Ok(true) => format!("{} (symlinked)", path.display().to_string().cyan()),
Ok(false) => format!("{} (copied)", path.display().to_string().cyan()),
Err(e) => format!("failed: {e}").red().to_string(),
};
println!("{:<20}{}", format!("{label}:"), status);
}
}
pub fn status() {
let current = Version::parse(CURRENT_VERSION).expect("invalid package version");
let installed_version = read_installed_version();
fn row(label: &str, value: &str) {
println!("{:<20}{}", format!("{label}:"), value);
}
let any_exist = SKILL_NAMES
.iter()
.any(|name| skill_store_path(name).exists());
let all_exist = SKILL_NAMES
.iter()
.all(|name| skill_store_path(name).exists());
if !any_exist {
row("Installed", &"No".red().to_string());
println!("\nRun 'hotdata skills install' to install.");
return;
}
if !all_exist {
row("Installed", &"Partial".yellow().to_string());
for skill_name in SKILL_NAMES {
let ok = skill_store_path(skill_name).exists();
let status = if ok {
"Yes".green().to_string()
} else {
"No".red().to_string()
};
row(&format!("{skill_name}"), &status);
}
} else {
row("Installed", &"Yes".green().to_string());
match &installed_version {
Some(v) if *v < current => {
row(
"Version",
&format!(
"{} (outdated, current is v{current})",
v.to_string().yellow()
),
);
}
Some(v) => row("Version", &v.to_string().green().to_string()),
None => row("Version", &"unknown".dark_grey().to_string()),
}
}
let home = home_dir();
for skill_name in SKILL_NAMES {
let label = format!("Agent Skills ({skill_name})");
if !skill_store_path(skill_name).exists() {
row(&label, &"—".dark_grey().to_string());
continue;
}
let mut installed_agents: Vec<String> = Vec::new();
if agents_skill_path(skill_name).exists() {
installed_agents.push("~/.agents".to_string());
}
for root in AGENT_ROOTS {
let link_path = home.join(root).join("skills").join(skill_name);
if link_path.exists() {
installed_agents.push(format!("~/{root}"));
}
}
if installed_agents.is_empty() {
row(&label, &"none".dark_grey().to_string());
} else {
row(&label, &installed_agents.join(", ").cyan().to_string());
}
}
if !all_exist {
println!("\nRun 'hotdata skills install' to install.");
} else if installed_version.is_some_and(|v| v < current) {
println!("\nRun 'hotdata skills install' to update.");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_skill_md_accepts_lf_frontmatter() {
let s = "---\nname: hotdata\nversion: 0.1.14\n---\n";
assert_eq!(
parse_version_from_skill_md(s),
Some(Version::parse("0.1.14").unwrap())
);
}
#[test]
fn parse_skill_md_accepts_crlf_opening() {
let s = "---\r\nname: hotdata\r\nversion: 0.1.14\r\n---\r\n";
assert_eq!(
parse_version_from_skill_md(s),
Some(Version::parse("0.1.14").unwrap())
);
}
#[test]
fn parse_skill_md_accepts_bom() {
let s = "\u{FEFF}---\nname: hotdata\nversion: 0.1.14\n---\n";
assert_eq!(
parse_version_from_skill_md(s),
Some(Version::parse("0.1.14").unwrap())
);
}
#[test]
fn parse_skill_md_accepts_v_prefix() {
let s = "---\nname: hotdata\nversion: v0.1.14\n---\n";
assert_eq!(
parse_version_from_skill_md(s),
Some(Version::parse("0.1.14").unwrap())
);
}
}