harn-cli 0.10.23

CLI for the Harn programming language — run, test, REPL, format, and lint
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
//! Shared helpers for `harn local …` subcommands: provider enumeration,
//! readiness snapshots, Ollama `/api/ps` loaded-model details, and PID-file
//! tracking for self-launched llama.cpp / MLX processes.

use std::path::Path;
use std::time::Duration;

use harn_vm::llm::api::OllamaPsModel;
use harn_vm::llm::readiness::{probe_provider_readiness, ProviderReadiness, ReadinessStatus};
use harn_vm::llm_config::{self, ProviderDef};
use serde::Serialize;

use crate::net;

use super::state::{read_pid_record, PidRecord};

/// Provider ids Harn treats as "local LLM runtimes" for lifecycle purposes.
/// Order is canonical for output stability.
pub(crate) const LOCAL_PROVIDERS: &[&str] = &["ollama", "llamacpp", "mlx", "local", "vllm"];

pub(crate) fn normalize_local_provider_id(provider: &str) -> String {
    let trimmed = provider.trim();
    let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
    match normalized.as_str() {
        "ollama" | "local-ollama" => "ollama".to_string(),
        "llamacpp" | "llama.cpp" | "llama-cpp" | "local-llamacpp" | "local-llama.cpp"
        | "local-llama-cpp" => "llamacpp".to_string(),
        "mlx" | "local-mlx" => "mlx".to_string(),
        "vllm" | "local-vllm" | "vllm-local" => "vllm".to_string(),
        _ => trimmed.to_string(),
    }
}

/// Per-provider runtime snapshot. Combines:
/// - provider catalog metadata (base_url, port, env override, auth style),
/// - liveness via `/v1/models` (or `/api/tags` for Ollama),
/// - currently-loaded models with memory footprint (Ollama `/api/ps` only),
/// - any harn-launched PID we are tracking.
#[derive(Debug, Clone, Serialize)]
pub(crate) struct LocalProviderSnapshot {
    pub provider: String,
    pub display_name: Option<String>,
    pub base_url: String,
    pub base_url_env: Option<String>,
    pub port: Option<u16>,
    pub reachable: bool,
    pub readiness_status: String,
    pub message: String,
    pub served_models: Vec<String>,
    pub loaded_models: Vec<LoadedModel>,
    pub pid_record: Option<PidRecord>,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct LoadedModel {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size_bytes: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size_vram_bytes: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    /// Context window the model was loaded with. Surfaced where Ollama
    /// includes it in `/api/ps` (newer daemons; older builds return None).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_length: Option<u64>,
}

pub(crate) fn local_provider_ids(filter: Option<&str>) -> Vec<String> {
    let mut ids = Vec::new();
    if let Some(name) = filter.map(str::trim).filter(|name| !name.is_empty()) {
        let id = normalize_local_provider_id(name);
        if llm_config::provider_config(&id).is_some() {
            ids.push(id);
        }
        return ids;
    }
    for id in LOCAL_PROVIDERS {
        if llm_config::provider_config(id).is_some() {
            ids.push((*id).to_string());
        }
    }
    ids
}

pub(crate) async fn snapshot_provider(
    provider: &str,
    state_dir: &Path,
) -> Result<LocalProviderSnapshot, String> {
    let provider = normalize_local_provider_id(provider);
    let def = llm_config::provider_config(&provider)
        .ok_or_else(|| format!("unknown provider: {provider}"))?;
    let base_url = llm_config::resolve_base_url(&def);

    let (reachable, status, message, served_models) = if provider == "ollama" {
        snapshot_ollama_reachability(&base_url).await
    } else {
        snapshot_openai_reachability(&provider, &base_url).await
    };

    let loaded_models = if provider == "ollama" && reachable {
        fetch_ollama_ps(&base_url).await.unwrap_or_default()
    } else {
        Vec::new()
    };

    Ok(LocalProviderSnapshot {
        provider: provider.clone(),
        display_name: def.display_name.clone(),
        base_url: base_url.clone(),
        base_url_env: def.base_url_env.clone(),
        port: port_from_base_url(&base_url),
        reachable,
        readiness_status: status,
        message,
        served_models,
        loaded_models,
        pid_record: read_pid_record(state_dir, &provider).ok().flatten(),
    })
}

async fn snapshot_openai_reachability(
    provider: &str,
    base_url: &str,
) -> (bool, String, String, Vec<String>) {
    let readiness = probe_provider_readiness(provider, None, Some(base_url)).await;
    let ProviderReadiness {
        ok,
        status,
        message,
        served_models,
        ..
    } = readiness;
    (ok, readiness_status_label(status), message, served_models)
}

async fn snapshot_ollama_reachability(base_url: &str) -> (bool, String, String, Vec<String>) {
    // `ollama_readiness` is keyed on a specific model id and returns
    // misleading messages when we just want a liveness check. Hit
    // `/api/tags` directly and collect the served set.
    match fetch_ollama_tags(base_url).await {
        Ok(served) => {
            let message = format!("Ollama is reachable at {base_url}; {} served", served.len());
            (true, "ok".to_string(), message, served)
        }
        Err(OllamaProbeError { status, message }) => (false, status, message, Vec::new()),
    }
}

#[derive(Debug)]
struct OllamaProbeError {
    status: String,
    message: String,
}

async fn fetch_ollama_tags(base_url: &str) -> Result<Vec<String>, OllamaProbeError> {
    let url = ollama_endpoint(base_url, "/api/tags").map_err(|message| OllamaProbeError {
        status: "invalid_url".to_string(),
        message,
    })?;
    let client = local_http_client().map_err(|message| OllamaProbeError {
        status: "client_error".to_string(),
        message,
    })?;
    let response = client
        .get(url.clone())
        .header("Content-Type", "application/json")
        .timeout(Duration::from_secs(4))
        .send()
        .await
        .map_err(|error| OllamaProbeError {
            status: "unreachable".to_string(),
            message: format!("Ollama daemon not reachable at {url}: {error}"),
        })?;
    if !response.status().is_success() {
        return Err(OllamaProbeError {
            status: "bad_status".to_string(),
            message: format!("Ollama /api/tags returned HTTP {}", response.status()),
        });
    }
    let body: serde_json::Value = response.json().await.map_err(|error| OllamaProbeError {
        status: "bad_response".to_string(),
        message: format!("Ollama /api/tags returned unparsable body: {error}"),
    })?;
    Ok(body
        .get("models")
        .and_then(|value| value.as_array())
        .map(|entries| {
            entries
                .iter()
                .filter_map(|entry| {
                    entry
                        .get("name")
                        .and_then(serde_json::Value::as_str)
                        .map(str::to_string)
                })
                .collect::<Vec<_>>()
        })
        .unwrap_or_default())
}

/// Build an Ollama endpoint URL, normalizing `localhost` → `127.0.0.1` (some
/// Ollama builds reject the literal hostname). One canonical helper so
/// every call site is consistent.
fn ollama_endpoint(base_url: &str, path: &str) -> Result<reqwest::Url, String> {
    let mut url = reqwest::Url::parse(base_url)
        .map_err(|error| format!("invalid Ollama base URL '{base_url}': {error}"))?;
    if url.host_str() == Some("localhost") {
        url.set_host(Some("127.0.0.1"))
            .map_err(|_| format!("invalid Ollama base URL '{base_url}'"))?;
    }
    url.set_path(path);
    Ok(url)
}

fn readiness_status_label(status: ReadinessStatus) -> String {
    match status {
        ReadinessStatus::Ok => "ok",
        ReadinessStatus::UnknownProvider => "unknown_provider",
        ReadinessStatus::Unsupported => "unsupported",
        ReadinessStatus::InvalidUrl => "invalid_url",
        ReadinessStatus::Unreachable => "unreachable",
        ReadinessStatus::BadStatus => "bad_status",
        ReadinessStatus::BadResponse => "bad_response",
        ReadinessStatus::ModelMissing => "model_missing",
        ReadinessStatus::ProviderMismatch => "provider_mismatch",
    }
    .to_string()
}

pub(crate) fn port_from_base_url(base_url: &str) -> Option<u16> {
    reqwest::Url::parse(base_url)
        .ok()
        .and_then(|url| url.port())
}

/// Best-effort `/api/ps` query so `harn local list` can show which Ollama
/// models are loaded right now plus their memory footprint. We swallow
/// errors so list/status keep working when the daemon is older or the
/// endpoint is unavailable.
pub(crate) async fn fetch_ollama_ps(base_url: &str) -> Result<Vec<LoadedModel>, String> {
    let url = ollama_endpoint(base_url, "/api/ps")?;
    let client = local_http_client()?;
    let response = client
        .get(url)
        .header("Content-Type", "application/json")
        .timeout(Duration::from_secs(4))
        .send()
        .await
        .map_err(|error| error.to_string())?;
    if !response.status().is_success() {
        return Err(format!("/api/ps returned HTTP {}", response.status()));
    }
    let body: serde_json::Value = response.json().await.map_err(|error| error.to_string())?;
    let models = body.get("models").and_then(|value| value.as_array());
    let Some(models) = models else {
        return Ok(Vec::new());
    };
    // The harn-vm `OllamaPsModel` parser is the canonical shape, so per-call
    // telemetry and per-snapshot loaded-model listings can't drift: any new
    // upstream field (e.g. context window changes) lands in one place.
    Ok(models
        .iter()
        .filter_map(|entry| {
            let ps = OllamaPsModel::from_ps_entry(entry)?;
            let name = ps.name?;
            Some(LoadedModel {
                name,
                size_bytes: ps.size_bytes,
                size_vram_bytes: ps.size_vram_bytes,
                expires_at: ps.expires_at,
                context_length: ps.context_length,
            })
        })
        .collect())
}

/// Post `keep_alive=0` to `/api/generate` for `model`. Ollama treats that as
/// "unload after this request", which matches `ollama stop <model>` from the
/// CLI. Returns Ok on 2xx, Err with the upstream message otherwise.
pub(crate) async fn ollama_unload_model(base_url: &str, model: &str) -> Result<(), String> {
    let url = ollama_endpoint(base_url, "/api/generate")?;
    let body = serde_json::json!({
        "model": model,
        "prompt": "",
        "stream": false,
        "keep_alive": 0,
    });
    let client = local_http_client()?;
    let response = client
        .post(url)
        .header("Content-Type", "application/json")
        .timeout(Duration::from_secs(8))
        .json(&body)
        .send()
        .await
        .map_err(|error| format!("Ollama unload failed: {error}"))?;
    if response.status().is_success() {
        Ok(())
    } else {
        let status = response.status();
        let detail = response.text().await.unwrap_or_default();
        Err(format!(
            "Ollama unload returned HTTP {}: {}",
            status.as_u16(),
            detail
        ))
    }
}

/// SIGTERM a child PID Harn previously launched (llama.cpp / MLX). We
/// deliberately do not retry with SIGKILL: a stuck launcher is a signal
/// for the user to investigate, not for us to silently force-kill.
#[cfg(unix)]
pub(crate) fn terminate_pid(pid: u32) -> Result<(), String> {
    use std::convert::TryFrom;
    let raw = i32::try_from(pid).map_err(|_| format!("pid {pid} is out of range"))?;
    // SAFETY: `libc::kill` is FFI; we pass a well-formed PID + SIGTERM and
    // check the return code. No memory is shared with C.
    let rc = unsafe { libc::kill(raw, libc::SIGTERM) };
    if rc == 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error().to_string())
    }
}

#[cfg(not(unix))]
pub(crate) fn terminate_pid(pid: u32) -> Result<(), String> {
    Err(format!(
        "terminating pid {pid} is not supported on this platform"
    ))
}

pub(crate) fn resolve_provider_def(provider: &str) -> Result<ProviderDef, String> {
    let provider = normalize_local_provider_id(provider);
    llm_config::provider_config(&provider)
        .ok_or_else(|| format!("unknown provider '{provider}' in Harn provider catalog"))
}

/// A fresh reqwest client for one-off lifecycle calls. We do not reuse
/// harn-vm's shared utility client because `harn local` is the only caller
/// from the CLI side and we want deterministic timeouts independent of the
/// streaming/transport client settings.
fn local_http_client() -> Result<reqwest::Client, String> {
    net::http_client_builder("cli.local.runtime")
        .connect_timeout(Duration::from_secs(2))
        .timeout(Duration::from_secs(10))
        .build()
        .map_err(|error| {
            format!(
                "failed to build HTTP client: {}",
                net::reqwest_error(&error)
            )
        })
}

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

    #[test]
    fn local_provider_ids_filters_unknown_filter() {
        let ids = local_provider_ids(Some("ollama"));
        assert_eq!(ids, vec!["ollama".to_string()]);
    }

    #[test]
    fn local_provider_ids_canonicalizes_local_runtime_aliases() {
        assert_eq!(
            local_provider_ids(Some("local-vllm")),
            vec!["vllm".to_string()]
        );
        assert_eq!(
            local_provider_ids(Some("local-llama.cpp")),
            vec!["llamacpp".to_string()]
        );
        assert_eq!(
            local_provider_ids(Some("local_ollama")),
            vec!["ollama".to_string()]
        );
        assert!(local_provider_ids(Some("not-a-provider")).is_empty());
    }

    #[test]
    fn local_provider_ids_returns_canonical_list() {
        let ids = local_provider_ids(None);
        assert!(ids.contains(&"ollama".to_string()));
        assert!(ids.contains(&"llamacpp".to_string()));
        assert!(ids.contains(&"mlx".to_string()));
    }

    #[test]
    fn port_from_base_url_recognizes_explicit_port() {
        assert_eq!(port_from_base_url("http://127.0.0.1:11434"), Some(11434));
        assert_eq!(port_from_base_url("http://localhost:8001/v1"), Some(8001));
        assert_eq!(port_from_base_url("https://api.example.com"), None);
    }

    #[test]
    fn readiness_status_label_projects_provider_mismatch() {
        assert_eq!(
            readiness_status_label(ReadinessStatus::ProviderMismatch),
            "provider_mismatch"
        );
    }
}