krait-cli 0.1.2

Code intelligence CLI for AI agents
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
use std::path::{Path, PathBuf};

use anyhow::{bail, Context};
use tracing::{debug, info, warn};

use super::registry::{
    get_entry, resolve_download_url, resolve_server, servers_dir, ArchiveType, InstallMethod,
    ServerEntry,
};
use crate::detect::Language;

/// Ensure the LSP server binary is available. Tries all servers for the language
/// in preference order (e.g., vtsls before typescript-language-server), then
/// auto-installs the preferred one if none found.
///
/// Returns `(binary_path, server_entry)` so callers know which server was resolved.
///
/// # Errors
/// Returns an error if the server cannot be found or downloaded.
pub async fn ensure_server(language: Language) -> anyhow::Result<(PathBuf, ServerEntry)> {
    // 1. Try all entries in preference order (e.g., vtsls → typescript-language-server)
    if let Some((entry, path)) = resolve_server(language) {
        debug!("found {}: {}", entry.binary_name, path.display());
        // Check runtime prerequisite (e.g., gopls needs `go` in PATH to analyze modules).
        if let Some(cmd) = entry.requires_cmd {
            if !command_exists(cmd) {
                anyhow::bail!(
                    "{} is installed but requires `{cmd}` in PATH to function.\n  Install Go: https://go.dev/dl/",
                    entry.binary_name
                );
            }
        }
        return Ok((path, entry));
    }

    // 2. None found — download the preferred (first) entry
    let entry =
        get_entry(language).with_context(|| format!("no LSP server configured for {language}"))?;

    info!("{} not found, downloading...", entry.binary_name);
    let path = download_server(&entry).await?;
    Ok((path, entry))
}

/// Download and install an LSP server binary.
///
/// # Errors
/// Returns an error if the download or installation fails.
pub async fn download_server(entry: &ServerEntry) -> anyhow::Result<PathBuf> {
    let dir = servers_dir();
    std::fs::create_dir_all(&dir)
        .with_context(|| format!("failed to create servers directory: {}", dir.display()))?;

    match &entry.install_method {
        InstallMethod::GithubRelease { archive, .. } => {
            download_github_release(entry, &dir, *archive).await
        }
        InstallMethod::Npm {
            package,
            extra_packages,
        } => download_npm(entry, &dir, package, extra_packages).await,
        InstallMethod::GoInstall { module } => download_go(entry, &dir, module).await,
        InstallMethod::Homebrew { package } => download_homebrew(entry, package).await,
    }
}

/// Download a standalone binary from a GitHub release.
async fn download_github_release(
    entry: &ServerEntry,
    dir: &Path,
    archive: ArchiveType,
) -> anyhow::Result<PathBuf> {
    let url = resolve_download_url(entry).context("cannot resolve download URL for this server")?;

    let target = dir.join(entry.binary_name);
    let tmp = dir.join(format!(".{}.tmp", entry.binary_name));

    // Download with curl
    let download_status = tokio::process::Command::new("curl")
        .args(["-fsSL", "-o"])
        .arg(&tmp)
        .arg(&url)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .status()
        .await
        .context("failed to run curl — is curl installed?")?;

    if !download_status.success() {
        let _ = std::fs::remove_file(&tmp);
        bail!(
            "failed to download {} from {url}\n  {}",
            entry.binary_name,
            entry.install_advice
        );
    }

    // Decompress
    match archive {
        ArchiveType::Gzip => {
            let gunzip_status = tokio::process::Command::new("gunzip")
                .args(["-f"])
                .arg(&tmp)
                .status()
                .await
                .context("failed to run gunzip")?;

            if !gunzip_status.success() {
                let _ = std::fs::remove_file(&tmp);
                bail!("failed to decompress {}", entry.binary_name);
            }

            // gunzip removes .tmp extension → file is now without .tmp
            // Actually gunzip strips the .gz, but our file doesn't end in .gz
            // gunzip -f on a non-.gz file renames to remove the extension
            let decompressed = dir.join(format!(".{}", entry.binary_name));
            if decompressed.exists() {
                std::fs::rename(&decompressed, &target)?;
            } else if tmp.exists() {
                // gunzip may have decompressed in-place
                std::fs::rename(&tmp, &target)?;
            }
        }
    }

    // Make executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let perms = std::fs::Permissions::from_mode(0o755);
        std::fs::set_permissions(&target, perms).context("failed to make binary executable")?;
    }

    // Verify it can run
    let verify = tokio::process::Command::new(&target)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .await;

    match verify {
        Ok(status) if status.success() => {
            info!("installed {} to {}", entry.binary_name, target.display());
        }
        _ => {
            warn!(
                "{} downloaded but --version check failed (may still work)",
                entry.binary_name
            );
        }
    }

    Ok(target)
}

/// Install an npm package to `~/.krait/servers/npm/`.
async fn download_npm(
    entry: &ServerEntry,
    dir: &Path,
    package: &str,
    extra_packages: &[&str],
) -> anyhow::Result<PathBuf> {
    // Check if node is available
    if !command_exists("node") {
        bail!(
            "Node.js is required for {} but not found in PATH.\n  {}",
            entry.binary_name,
            entry.install_advice
        );
    }

    let npm_dir = dir.join("npm");
    std::fs::create_dir_all(&npm_dir)?;

    let mut args = vec!["install", "--prefix"];
    let npm_dir_str = npm_dir
        .to_str()
        .context("npm directory path is not valid UTF-8")?;
    args.push(npm_dir_str);
    args.push(package);
    for pkg in extra_packages {
        args.push(pkg);
    }

    let status = tokio::process::Command::new("npm")
        .args(&args)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .status()
        .await
        .context("failed to run npm — is npm installed?")?;

    if !status.success() {
        bail!(
            "npm install failed for {}.\n  {}",
            package,
            entry.install_advice
        );
    }

    let bin_path = npm_dir
        .join("node_modules")
        .join(".bin")
        .join(entry.binary_name);

    if !bin_path.exists() {
        bail!(
            "{} not found after npm install at {}",
            entry.binary_name,
            bin_path.display()
        );
    }

    info!(
        "installed {} via npm to {}",
        entry.binary_name,
        bin_path.display()
    );
    Ok(bin_path)
}

/// Install a Go binary via `go install`.
async fn download_go(entry: &ServerEntry, dir: &Path, module: &str) -> anyhow::Result<PathBuf> {
    if !command_exists("go") {
        bail!(
            "Go is required for {} but not found in PATH.\n  {}",
            entry.binary_name,
            entry.install_advice
        );
    }

    let go_dir = dir.join("go");
    std::fs::create_dir_all(&go_dir)?;

    let status = tokio::process::Command::new("go")
        .args(["install", module])
        .env("GOPATH", &go_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .status()
        .await
        .context("failed to run go install")?;

    if !status.success() {
        bail!(
            "go install failed for {}.\n  {}",
            module,
            entry.install_advice
        );
    }

    let bin_path = go_dir.join("bin").join(entry.binary_name);
    if !bin_path.exists() {
        bail!(
            "{} not found after go install at {}",
            entry.binary_name,
            bin_path.display()
        );
    }

    info!(
        "installed {} via go install to {}",
        entry.binary_name,
        bin_path.display()
    );
    Ok(bin_path)
}

/// Install a binary via Homebrew (`brew install <package>`).
///
/// Homebrew installs to its prefix (e.g. `/opt/homebrew/bin` on Apple Silicon),
/// which is already in PATH. So we just run `brew install` and then re-resolve
/// the binary from PATH.
async fn download_homebrew(entry: &ServerEntry, package: &str) -> anyhow::Result<PathBuf> {
    if !command_exists("brew") {
        bail!(
            "Homebrew is required for {} but not found in PATH.\n  {}",
            entry.binary_name,
            entry.install_advice
        );
    }

    let status = tokio::process::Command::new("brew")
        .args(["install", package])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .status()
        .await
        .context("failed to run brew install")?;

    if !status.success() {
        bail!(
            "brew install failed for {}.\n  {}",
            package,
            entry.install_advice
        );
    }

    // Homebrew puts binaries in its prefix/bin, which should be in PATH
    which::which(entry.binary_name)
        .with_context(|| format!("{} not found in PATH after brew install", entry.binary_name))
}

/// Check if a command exists in PATH.
fn command_exists(name: &str) -> bool {
    which::which(name).is_ok()
}

/// Remove all managed server binaries from `~/.krait/servers/`.
///
/// Makes all files writable first (Go module cache uses read-only permissions).
///
/// # Errors
/// Returns an error if the directory cannot be removed.
pub fn clean_servers() -> anyhow::Result<u64> {
    let dir = servers_dir();
    if !dir.exists() {
        return Ok(0);
    }

    let size = dir_size(&dir);
    // Make everything writable before removal (Go module cache is read-only by default).
    make_writable_recursive(&dir);
    std::fs::remove_dir_all(&dir).context("failed to remove servers directory")?;
    Ok(size)
}

/// Recursively make all files and directories writable.
fn make_writable_recursive(path: &Path) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(meta) = std::fs::metadata(path) {
            let mut perms = meta.permissions();
            let mode = perms.mode() | 0o200;
            perms.set_mode(mode);
            let _ = std::fs::set_permissions(path, perms);
        }
    }

    if path.is_dir() {
        if let Ok(entries) = std::fs::read_dir(path) {
            for entry in entries.filter_map(Result::ok) {
                make_writable_recursive(&entry.path());
            }
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Ok(meta) = std::fs::metadata(path) {
                let mut perms = meta.permissions();
                perms.set_mode(perms.mode() | 0o700);
                let _ = std::fs::set_permissions(path, perms);
            }
        }
    }
}

fn dir_size(path: &Path) -> u64 {
    std::fs::read_dir(path).ok().map_or(0, |entries| {
        entries
            .filter_map(Result::ok)
            .map(|e| {
                if e.path().is_dir() {
                    dir_size(&e.path())
                } else {
                    e.metadata().map_or(0, |m| m.len())
                }
            })
            .sum()
    })
}

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

    #[test]
    fn servers_dir_creates_if_missing() {
        let dir = servers_dir();
        // We don't actually create it in this test (side effect),
        // just verify the path is valid
        assert!(dir.to_str().is_some());
        assert!(dir.ends_with("servers"));
    }

    #[test]
    fn clean_empty_is_ok() {
        // Skip if servers are actually installed — we don't want to wipe them.
        let dir = servers_dir();
        if dir.exists()
            && std::fs::read_dir(&dir)
                .map(|mut e| e.next().is_some())
                .unwrap_or(false)
        {
            return;
        }
        let result = clean_servers();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn ensure_server_finds_rust_analyzer_if_installed() {
        // This test doesn't download — it just checks if RA is in PATH
        if which::which("rust-analyzer").is_err() {
            return; // skip if not installed
        }
        let (path, entry) = ensure_server(Language::Rust).await.unwrap();
        assert!(path.exists());
        assert_eq!(entry.binary_name, "rust-analyzer");
    }

    #[test]
    fn command_exists_finds_curl() {
        assert!(command_exists("curl"));
    }

    #[test]
    fn command_exists_rejects_missing() {
        assert!(!command_exists("definitely-not-a-real-binary-xyz-123"));
    }
}