knishio-cli 0.1.4

KnishIO validator orchestration CLI — Docker control, cell management, benchmarks, and health checks
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
//! Host environment detection for accel profile auto-selection.
//!
//! The public API is:
//! - [`detect`] — synchronous probe returning the resolved [`Environment`]
//! - [`print_summary`] — colored multi-line Environment block
//! - [`Accel`] — the resolved recommendation; feeds into `config::accel_files`
//!
//! Detection is intentionally fast (< ~200ms total): all probes use short
//! timeouts and run serially. Every `knishio` docker command re-detects on
//! each invocation so the output is always current.

use colored::Colorize;
use std::fmt;
use std::process::{Command, Stdio};
use std::time::Duration;

/// The resolved hardware-acceleration profile for the current host.
///
/// Variants map 1:1 to the `[docker.accel.<name>]` tables in `knishio.toml`.
/// `auto` is a CLI-level sentinel meaning "call `detect()` and use its
/// result"; by the time we hit the docker layer, a concrete variant has
/// been chosen.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Accel {
    /// Portable CPU-only stack.
    Cpu,
    /// NVIDIA GPU, containerised validator + nvidia-container-toolkit.
    Cuda,
    /// Apple Silicon via Docker Model Runner (llama.cpp-latest-metal host daemon).
    Dmr,
    /// Apple Silicon fallback: validator runs natively; Postgres in Docker only.
    MetalNative,
    /// AMD GPU via ROCm (overlay not yet shipped).
    Rocm,
    /// Cross-vendor GPU via Vulkan (overlay not yet shipped).
    Vulkan,
}

impl Accel {
    /// The toml key under `[docker.accel.<key>]`.
    pub fn config_key(self) -> &'static str {
        match self {
            Accel::Cpu => "cpu",
            Accel::Cuda => "cuda",
            Accel::Dmr => "dmr",
            Accel::MetalNative => "metal-native",
            Accel::Rocm => "rocm",
            Accel::Vulkan => "vulkan",
        }
    }

}

impl fmt::Display for Accel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.config_key())
    }
}

/// Snapshot of the host environment, populated by [`detect`].
#[derive(Debug, Clone)]
pub struct Environment {
    pub os: &'static str,
    pub arch: &'static str,
    pub cpu_brand: String,
    pub memory_gb: Option<u64>,
    pub docker: DockerStatus,
    pub gpu: Option<GpuInfo>,
    pub dmr: DmrStatus,
    pub accel: Accel,
    pub reasons: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct DockerStatus {
    pub present: bool,
    pub version: Option<String>,
}

#[derive(Debug, Clone)]
pub struct DmrStatus {
    pub client_present: bool,
    pub server_running: bool,
    pub tcp_reachable: bool,
    /// Cached model IDs visible at `/engines/v1/models`. Populated on a best-
    /// effort basis; empty when the endpoint isn't reachable.
    pub models: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct GpuInfo {
    pub vendor: GpuVendor,
    pub name: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GpuVendor {
    Apple,
    Nvidia,
    Amd,
}

// ── Public entry points ────────────────────────────────────────

/// Probe the host and return its resolved accel profile + metadata.
pub fn detect() -> Environment {
    let os = std::env::consts::OS;
    let arch = std::env::consts::ARCH;
    let cpu_brand = probe_cpu_brand(os).unwrap_or_else(|| "unknown".to_string());
    let memory_gb = probe_memory_gb(os);
    let docker = probe_docker();
    let dmr = if os == "macos" {
        probe_dmr()
    } else {
        DmrStatus {
            client_present: false,
            server_running: false,
            tcp_reachable: false,
            models: Vec::new(),
        }
    };
    let nvidia_present = probe_binary_ok("nvidia-smi", &["-L"]);
    let rocm_present = probe_binary_ok("rocminfo", &[]);
    let gpu = pick_gpu(os, &cpu_brand, nvidia_present, rocm_present);

    let mut reasons = Vec::new();
    let accel = resolve_accel(
        os,
        arch,
        &docker,
        &dmr,
        nvidia_present,
        rocm_present,
        &mut reasons,
    );

    Environment {
        os,
        arch,
        cpu_brand,
        memory_gb,
        docker,
        gpu,
        dmr,
        accel,
        reasons,
    }
}

/// Colorised multi-line Environment block written to stdout.
pub fn print_summary(env: &Environment) {
    crate::output::header("Environment");

    let info = |label: &str, value: String| {
        println!("{} {:8} {}", "".blue().bold(), label, value);
    };

    info("Host:", format!("{} ({})", env.os, env.arch));

    let cpu_line = match env.memory_gb {
        Some(gb) => format!("{} · {} GB RAM", env.cpu_brand, gb),
        None => env.cpu_brand.clone(),
    };
    info("CPU:", cpu_line);

    match &env.gpu {
        Some(gpu) => info("GPU:", format!("{} ({:?})", gpu.name, gpu.vendor)),
        None => info("GPU:", "none detected".into()),
    }

    let docker_line = if env.docker.present {
        env.docker
            .version
            .clone()
            .unwrap_or_else(|| "running".into())
    } else {
        "not available".into()
    };
    info("Docker:", docker_line);

    if env.os == "macos" {
        let dmr_line = match (&env.dmr.client_present, &env.dmr.tcp_reachable) {
            (true, true) => format!(
                "running, TCP :12434 reachable, {} cached model(s)",
                env.dmr.models.len()
            ),
            (true, false) if env.dmr.server_running => {
                "running but TCP not exposed (run: docker desktop enable model-runner --tcp=12434)"
                    .to_string()
            }
            (true, false) => "client installed, server not running".into(),
            (false, _) => "not installed".into(),
        };
        info("DMR:", dmr_line);
    }

    let arrow = "".bold();
    let accel_reason = if env.reasons.is_empty() {
        String::new()
    } else {
        format!("  ({})", env.reasons.join("; "))
    };
    println!(
        "{} {:8} {}{}",
        arrow,
        "Accel:",
        env.accel.to_string().bold().green(),
        accel_reason
    );
}

// ── Resolution logic ───────────────────────────────────────────

fn resolve_accel(
    os: &str,
    arch: &str,
    docker: &DockerStatus,
    dmr: &DmrStatus,
    nvidia_present: bool,
    rocm_present: bool,
    reasons: &mut Vec<String>,
) -> Accel {
    if !docker.present {
        reasons.push("docker not available — falling back to cpu profile anyway".into());
        return Accel::Cpu;
    }

    if os == "macos" && arch == "aarch64" {
        if dmr.tcp_reachable {
            reasons.push("Apple Silicon + DMR TCP reachable".into());
            return Accel::Dmr;
        }
        reasons.push("Apple Silicon; DMR not reachable — using metal-native fallback".into());
        return Accel::MetalNative;
    }

    if nvidia_present {
        reasons.push("nvidia-smi present".into());
        return Accel::Cuda;
    }

    if rocm_present {
        reasons.push("rocminfo present".into());
        return Accel::Rocm;
    }

    reasons.push("no accelerator detected".into());
    Accel::Cpu
}

// ── Probes ────────────────────────────────────────────────────

fn probe_cpu_brand(os: &str) -> Option<String> {
    match os {
        "macos" => run_capture("sysctl", &["-n", "machdep.cpu.brand_string"]),
        "linux" => {
            let content = std::fs::read_to_string("/proc/cpuinfo").ok()?;
            content
                .lines()
                .find(|l| l.starts_with("model name"))
                .and_then(|l| l.split_once(':'))
                .map(|(_, v)| v.trim().to_string())
        }
        _ => None,
    }
}

fn probe_memory_gb(os: &str) -> Option<u64> {
    match os {
        "macos" => {
            let bytes: u64 = run_capture("sysctl", &["-n", "hw.memsize"])?
                .trim()
                .parse()
                .ok()?;
            Some(bytes / 1024 / 1024 / 1024)
        }
        "linux" => {
            let content = std::fs::read_to_string("/proc/meminfo").ok()?;
            let line = content.lines().find(|l| l.starts_with("MemTotal:"))?;
            let kb: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
            Some(kb / 1024 / 1024)
        }
        _ => None,
    }
}

fn probe_docker() -> DockerStatus {
    let version = Command::new("docker")
        .args(["version", "--format", "{{.Server.Version}}"])
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| {
            String::from_utf8(o.stdout)
                .ok()
                .map(|s| s.trim().to_string())
        })
        .filter(|s| !s.is_empty());

    DockerStatus {
        present: version.is_some(),
        version,
    }
}

/// macOS-only DMR probe: checks `docker model version` (client present),
/// `docker model status` (server running), and finally a TCP probe of the
/// OAI-compatible endpoint (only populated when the user has explicitly
/// enabled TCP via `docker desktop enable model-runner --tcp=12434`).
fn probe_dmr() -> DmrStatus {
    let client_present = Command::new("docker")
        .args(["model", "version"])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .ok()
        .map(|s| s.success())
        .unwrap_or(false);

    if !client_present {
        return DmrStatus {
            client_present: false,
            server_running: false,
            tcp_reachable: false,
            models: Vec::new(),
        };
    }

    let server_running = Command::new("docker")
        .args(["model", "status"])
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.to_lowercase().contains("is running"))
        .unwrap_or(false);

    // Short, blocking-ish TCP probe. reqwest would be async-only and we're in
    // a sync detect path; use std::net::TcpStream with a short timeout.
    let tcp_reachable = std::net::TcpStream::connect_timeout(
        &"127.0.0.1:12434".parse().expect("static socket addr"),
        Duration::from_millis(500),
    )
    .is_ok();

    // Best-effort model list; ignored on error. Uses curl to avoid pulling an
    // HTTP client dep into the sync detection path.
    let models = if tcp_reachable {
        Command::new("curl")
            .args([
                "-s",
                "-m",
                "2",
                "http://localhost:12434/engines/v1/models",
            ])
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .and_then(|s| parse_model_ids(&s))
            .unwrap_or_default()
    } else {
        Vec::new()
    };

    DmrStatus {
        client_present,
        server_running,
        tcp_reachable,
        models,
    }
}

/// Minimal JSON parse of `{"object":"list","data":[{"id":"…"}, …]}` without
/// pulling `serde_json` just for this. Scans for `"id":"<value>"` tokens.
fn parse_model_ids(json: &str) -> Option<Vec<String>> {
    let mut out = Vec::new();
    let mut rest = json;
    while let Some(idx) = rest.find("\"id\":\"") {
        rest = &rest[idx + 6..];
        let end = rest.find('"')?;
        out.push(rest[..end].to_string());
        rest = &rest[end..];
    }
    Some(out)
}

/// Returns true iff the binary exists on PATH and, when called with `args`,
/// exits 0.
fn probe_binary_ok(bin: &str, args: &[&str]) -> bool {
    Command::new(bin)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .ok()
        .map(|s| s.success())
        .unwrap_or(false)
}

fn pick_gpu(
    os: &str,
    cpu_brand: &str,
    nvidia_present: bool,
    rocm_present: bool,
) -> Option<GpuInfo> {
    // Apple Silicon: CPU brand doubles as GPU identity (unified SoC).
    if os == "macos" && cpu_brand.contains("Apple") {
        return Some(GpuInfo {
            vendor: GpuVendor::Apple,
            name: cpu_brand.to_string(),
        });
    }
    if nvidia_present {
        // Best-effort: parse `nvidia-smi -L` first line
        let name = run_capture("nvidia-smi", &["-L"])
            .and_then(|s| s.lines().next().map(|l| l.trim().to_string()))
            .unwrap_or_else(|| "NVIDIA GPU".into());
        return Some(GpuInfo {
            vendor: GpuVendor::Nvidia,
            name,
        });
    }
    if rocm_present {
        return Some(GpuInfo {
            vendor: GpuVendor::Amd,
            name: "AMD GPU (rocminfo)".into(),
        });
    }
    None
}

fn run_capture(bin: &str, args: &[&str]) -> Option<String> {
    Command::new(bin)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| {
            String::from_utf8(o.stdout)
                .ok()
                .map(|s| s.trim().to_string())
        })
}