llmman 0.1.689

Run any agent on any model, models stored as OCI images
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
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
//! Helpers shared by the per-integration launchers.

use std::path::{Path, PathBuf};

use anyhow::Context;

/// Launchers that hand the daemon's real client key to another process must
/// not send it to a remote cleartext endpoint. Call this before anything
/// probes or starts the daemon; loopback HTTP and remote HTTPS remain valid.
pub(super) fn check_daemon_key_transport(integration: &str) -> anyhow::Result<()> {
    check_daemon_key_transport_to(
        integration,
        crate::auth::client_key().is_some(),
        crate::daemon::connects_securely(),
        &crate::daemon::server(),
    )
}

fn check_daemon_key_transport_to(
    integration: &str,
    has_client_key: bool,
    connects_securely: bool,
    server: &str,
) -> anyhow::Result<()> {
    anyhow::ensure!(
        !has_client_key || connects_securely,
        "{integration} needs a local llmman serve, or one over TLS: LLMMAN_HOST points at \
         {server}, and the daemon API key would cross the network in cleartext."
    );
    Ok(())
}

/// `NO_PROXY`/`no_proxy` for a child handed the daemon's key over loopback,
/// so an inherited proxy never sees it. Inherited entries are kept.
pub(super) fn daemon_no_proxy_env(server: &str) -> Vec<(&'static str, String)> {
    if !crate::daemon::connects_over_loopback() {
        return Vec::new();
    }
    no_proxy_env(
        server,
        std::env::var("NO_PROXY").ok().as_deref(),
        std::env::var("no_proxy").ok().as_deref(),
    )
}

/// Tools read either spelling, so both get the host; a spelling that is
/// unset or empty inherits the other's entries.
fn no_proxy_env(
    server: &str,
    upper: Option<&str>,
    lower: Option<&str>,
) -> Vec<(&'static str, String)> {
    let Some(host) = reqwest::Url::parse(server).ok().and_then(|url| {
        url.host_str()
            .map(|h| h.trim_matches(['[', ']']).to_string())
    }) else {
        return Vec::new();
    };
    [("NO_PROXY", upper, lower), ("no_proxy", lower, upper)]
        .into_iter()
        .map(|(name, own, other)| {
            let inherited = [own, other]
                .into_iter()
                .flatten()
                .map(|list| list.trim().trim_end_matches(','))
                .find(|list| !list.is_empty());
            let value = match inherited {
                Some(list)
                    if list
                        .split(',')
                        .any(|e| e.trim().eq_ignore_ascii_case(&host)) =>
                {
                    list.to_string()
                }
                Some(list) => format!("{list},{host}"),
                None => host.clone(),
            };
            (name, value)
        })
        .collect()
}

/// Writes `contents` to `path`, and its directory, unless it already holds
/// exactly that.
pub(super) fn write_if_changed(path: &Path, contents: &str) -> anyhow::Result<()> {
    if std::fs::read_to_string(path).ok().as_deref() == Some(contents) {
        return Ok(());
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
    }
    std::fs::write(path, contents).with_context(|| format!("write {}", path.display()))
}

pub(super) fn write_yaml_merged(
    path: &Path,
    label: &str,
    merge: impl FnOnce(&serde_json::Value) -> serde_json::Value,
) -> anyhow::Result<()> {
    write_structured_merged(
        path,
        label,
        ("YAML", "yml.bak"),
        |text| Ok(yaml_serde::from_str(text)?),
        |value| Ok(yaml_serde::to_string(value)?),
        |raw, backup| {
            if !backup.exists() {
                return true;
            }
            yaml_serde::from_str::<serde_json::Value>(raw)
                .and_then(|value| yaml_serde::to_string(&value))
                .is_ok_and(|canonical| canonical != raw)
        },
        merge,
    )
}

/// Renders `s` as a double-quoted YAML scalar, escaping backslashes and
/// double quotes — enough to keep any value we generate (a model name, a
/// URL) a literal string regardless of YAML keywords or metacharacters
/// it might contain.
pub(super) fn yaml_quote(s: &str) -> String {
    format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
}

/// The value of the last `long` or `short` flag before a `--`, as a word or
/// `=`-joined, the forms `has_flag` takes; yargs keeps the last too.
/// Nothing after a second `--` counts, as in `has_forwarded_model_flag`.
pub(super) fn forwarded_value<'a>(
    extra_args: &'a [String],
    long: &str,
    short: &str,
) -> Option<&'a str> {
    let mut found = None;
    let mut args = super::before_terminator(extra_args)
        .iter()
        .map(String::as_str);
    while let Some(a) = args.next() {
        if a == long || a == short {
            found = args.next().or(found);
        } else if let Some(v) = [long, short]
            .iter()
            .find_map(|f| a.strip_prefix(*f).and_then(|rest| rest.strip_prefix('=')))
        {
            found = Some(v);
        }
    }
    found.filter(|v| !v.is_empty())
}

/// The value of the last `--model`/`-m` after `--`; see [`forwarded_value`].
pub(super) fn forwarded_model(extra_args: &[String]) -> Option<&str> {
    forwarded_value(extra_args, "--model", "-m")
}

/// A leading `~` is `home`, as Qwen Code's `Storage.resolvePath` reads
/// it; a quoted export leaves it for the program to expand.
pub(super) fn expand_tilde(dir: &str, home: &Path) -> PathBuf {
    match dir.strip_prefix('~') {
        Some(rest) if rest.is_empty() || rest.starts_with(['/', '\\']) => {
            home.join(rest.trim_start_matches(['/', '\\']))
        }
        _ => PathBuf::from(dir),
    }
}

/// Rewrites the JSON object at `path` through `merge`, leaving a file it
/// does not understand alone and saying so under `label`.
///
/// The settings files these integrations read are the user's as much as
/// llmman's, so: comments survive a parse (`strip_json_comments`) and the
/// text carrying them is kept as `.bak` before the first rewrite that
/// would drop them; a rendering that already matches is not written at
/// all; and the write is atomic, since a half-written settings file is
/// worse than a stale one. A leading BOM is stripped because a
/// node-based reader tolerates one and `serde_json` does not.
pub(super) fn write_json_merged(
    path: &Path,
    label: &str,
    merge: impl FnOnce(&serde_json::Value) -> serde_json::Value,
) -> anyhow::Result<()> {
    write_structured_merged(
        path,
        label,
        ("JSON", "json.bak"),
        |text| {
            let text = text.trim_start_matches('\u{feff}').trim();
            Ok(serde_json::from_str(&strip_json_comments(text))?)
        },
        |value| {
            let mut out = serde_json::to_string_pretty(value)?;
            out.push('\n');
            Ok(out)
        },
        |raw, backup| !backup.exists() || strip_json_comments(raw) != raw,
        merge,
    )
}

/// Parse, merge, back up, and atomically rewrite a user-owned structured
/// settings file. Format-specific parsing and rendering stay at the call site.
fn write_structured_merged(
    path: &Path,
    label: &str,
    format: (&str, &str),
    parse: impl FnOnce(&str) -> anyhow::Result<serde_json::Value>,
    serialize: impl FnOnce(&serde_json::Value) -> anyhow::Result<String>,
    should_backup: impl FnOnce(&str, &Path) -> bool,
    merge: impl FnOnce(&serde_json::Value) -> serde_json::Value,
) -> anyhow::Result<()> {
    let raw = match std::fs::read_to_string(path) {
        Ok(raw) => Some(raw),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(e).with_context(|| format!("read {}", path.display())),
    };
    let existing = match raw.as_deref().map(str::trim) {
        None | Some("") => serde_json::json!({}),
        Some(text) => match parse(text) {
            Ok(value) if value.is_object() => value,
            _ => {
                eprintln!(
                    "[llmman] {label}: {} is not a {} object; leaving it alone",
                    path.display(),
                    format.0
                );
                return Ok(());
            }
        },
    };
    let merged = merge(&existing);
    if merged == existing {
        return Ok(());
    }
    let dir = path.parent().context("settings path has no directory")?;
    std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
    if let Some(raw) = &raw {
        let backup = path.with_extension(format.1);
        if should_backup(raw, &backup) {
            std::fs::copy(path, &backup)
                .with_context(|| format!("back up {} to {}", path.display(), backup.display()))?;
        }
    }
    let out = serialize(&merged)?;
    crate::fsutil::write_atomic(path, out.as_bytes())
        .with_context(|| format!("write {}", path.display()))
}

/// `//` and `/* */` comments outside strings replaced by spaces, so a
/// parse error still points at the right place; what `strip-json-comments`
/// does for Qwen Code before `JSON.parse`.
fn strip_json_comments(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    let mut chars = raw.chars().peekable();
    let mut in_string = false;
    let mut escaped = false;
    while let Some(c) = chars.next() {
        if in_string {
            out.push(c);
            if escaped {
                escaped = false;
            } else if c == '\\' {
                escaped = true;
            } else if c == '"' {
                in_string = false;
            }
            continue;
        }
        match c {
            '"' => {
                in_string = true;
                out.push(c);
            }
            '/' if chars.peek() == Some(&'/') => {
                out.push(' ');
                while chars.peek().is_some_and(|&n| n != '\n') {
                    chars.next();
                    out.push(' ');
                }
            }
            '/' if chars.peek() == Some(&'*') => {
                chars.next();
                out.push_str("  ");
                let mut prev = ' ';
                for n in chars.by_ref() {
                    out.push(if n == '\n' { '\n' } else { ' ' });
                    if prev == '*' && n == '/' {
                        break;
                    }
                    prev = n;
                }
            }
            _ => out.push(c),
        }
    }
    out
}

/// The object at `key` in `parent`, put there if absent or not an object.
pub(super) fn object_under<'a>(
    parent: &'a mut serde_json::Map<String, serde_json::Value>,
    key: &str,
) -> &'a mut serde_json::Map<String, serde_json::Value> {
    let slot = parent.entry(key).or_insert_with(|| serde_json::json!({}));
    if !slot.is_object() {
        *slot = serde_json::json!({});
    }
    slot.as_object_mut().expect("set to an object just above")
}

/// The explicit agent directory understood by both Pi and OMP.
pub(super) fn configured_pi_agent_dir() -> anyhow::Result<Option<PathBuf>> {
    let Some(dir) = std::env::var("PI_CODING_AGENT_DIR")
        .ok()
        .filter(|dir| !dir.trim().is_empty())
    else {
        return Ok(None);
    };
    let dir = dir.trim();
    if !dir.starts_with('~') {
        return Ok(Some(PathBuf::from(dir)));
    }
    let home = crate::config::home_dir().context("no home directory")?;
    Ok(Some(expand_tilde(dir, &home)))
}

/// The model entry Pi and OMP are told about: its display name, what it can
/// take in, whether it thinks, and how much it can hold. Every example in
/// Pi's own `models.md`
/// declares these, and what it assumes for an entry that omits them is
/// not written down, so they are stated rather than left to it.
pub(super) fn pi_model_entry(
    model: &str,
    reasons: bool,
    vision: bool,
    context_window: Option<u64>,
) -> serde_json::Value {
    let input: &[&str] = if vision {
        &["text", "image"]
    } else {
        &["text"]
    };
    let mut entry = serde_json::json!({
        "id": model,
        "name": model,
        "input": input,
    });
    if reasons {
        entry["reasoning"] = serde_json::json!(true);
    }
    if let Some(context) = context_window {
        entry["contextWindow"] = serde_json::json!(context);
    }
    entry
}

/// Merge one model into a named provider while retaining unrelated providers,
/// provider options, and models. OMP also retains unowned fields on the
/// matching model; Pi rebuilds its matching entry from daemon metadata.
pub(super) fn provider_models_merged(
    existing: &serde_json::Value,
    provider_name: &str,
    entry: &serde_json::Value,
    preserve_existing_model_fields: bool,
    configure: impl FnOnce(&mut serde_json::Map<String, serde_json::Value>),
) -> serde_json::Value {
    let mut root = existing.clone();
    let Some(root_map) = root.as_object_mut() else {
        return serde_json::json!({});
    };
    let provider = object_under(object_under(root_map, "providers"), provider_name);
    let old_models = provider
        .get("models")
        .and_then(serde_json::Value::as_array)
        .cloned()
        .unwrap_or_default();
    let mut replaced = false;
    let mut models = Vec::with_capacity(old_models.len() + 1);
    for old in old_models {
        if old.get("id") != entry.get("id") {
            models.push(old);
            continue;
        }
        if replaced {
            continue;
        }
        let mut merged = if preserve_existing_model_fields {
            old
        } else {
            serde_json::json!({})
        };
        if let (Some(merged), Some(update)) = (merged.as_object_mut(), entry.as_object()) {
            merged.extend(update.clone());
        } else {
            merged = entry.clone();
        }
        models.push(merged);
        replaced = true;
    }
    if !replaced {
        models.push(entry.clone());
    }
    configure(provider);
    provider.insert("models".into(), serde_json::json!(models));
    root
}

#[cfg(test)]
mod tests {
    use super::super::{pair_context_window, served_context_window};
    use super::*;

    #[test]
    fn no_proxy_adds_the_daemon_host_to_what_is_inherited() {
        let server = "http://127.0.0.1:17434";
        for (upper, lower, want_upper, want_lower) in [
            (None, None, "127.0.0.1", "127.0.0.1"),
            (Some("a.test"), None, "a.test,127.0.0.1", "a.test,127.0.0.1"),
            (None, Some("b.test"), "b.test,127.0.0.1", "b.test,127.0.0.1"),
            (
                Some("a.test,"),
                Some("b.test"),
                "a.test,127.0.0.1",
                "b.test,127.0.0.1",
            ),
            (Some(""), Some(" "), "127.0.0.1", "127.0.0.1"),
            (
                Some("a.test"),
                Some(""),
                "a.test,127.0.0.1",
                "a.test,127.0.0.1",
            ),
            (
                Some("a.test, 127.0.0.1"),
                None,
                "a.test, 127.0.0.1",
                "a.test, 127.0.0.1",
            ),
        ] {
            assert_eq!(
                no_proxy_env(server, upper, lower),
                [
                    ("NO_PROXY", want_upper.to_string()),
                    ("no_proxy", want_lower.to_string())
                ],
                "{upper:?} {lower:?}"
            );
        }
    }

    #[test]
    fn no_proxy_names_the_host_without_brackets_or_port() {
        let env = no_proxy_env("http://[::1]:17434", Some("a.test"), None);
        assert_eq!(env[0], ("NO_PROXY", "a.test,::1".to_string()));
        let env = no_proxy_env("http://host.docker.internal:17434", None, None);
        assert_eq!(env[1], ("no_proxy", "host.docker.internal".to_string()));
        assert!(no_proxy_env("not a url", None, None).is_empty());
    }

    #[test]
    fn a_real_daemon_key_never_crosses_remote_cleartext() {
        let remote_http = "http://192.0.2.1:17434";
        let error = check_daemon_key_transport_to("agent", true, false, remote_http)
            .unwrap_err()
            .to_string();
        assert!(error.contains("agent"));
        assert!(error.contains(remote_http));
        assert!(error.contains("cleartext"));

        assert!(check_daemon_key_transport_to("agent", false, false, remote_http).is_ok());
        assert!(check_daemon_key_transport_to("agent", true, true, remote_http).is_ok());
    }

    /// Regression test for a real CodeRabbit finding: an unquoted model
    /// value in generated YAML could be misparsed as a non-string
    /// (`null`, `true`, ...) or broken outright by metacharacters.
    #[test]
    fn yaml_quote_escapes_keywords_and_metacharacters() {
        assert_eq!(yaml_quote("qwen3.5:0.8b"), "\"qwen3.5:0.8b\"");
        assert_eq!(yaml_quote("null"), "\"null\"");
        assert_eq!(yaml_quote("true"), "\"true\"");
        assert_eq!(
            yaml_quote(r#"a "quoted" \ value"#),
            r#""a \"quoted\" \\ value""#
        );
    }

    /// The last forwarded model wins, in either spelling; none is none.
    #[test]
    fn forwarded_model_takes_the_last_spelling() {
        let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert_eq!(forwarded_model(&args(&["--model", "b"])), Some("b"));
        assert_eq!(forwarded_model(&args(&["-m=b", "--model", "c"])), Some("c"));
        assert_eq!(forwarded_model(&args(&["--model=b", "-m", "c"])), Some("c"));
        assert_eq!(forwarded_model(&args(&["-p", "x"])), None);
        assert_eq!(forwarded_model(&args(&["--model"])), None);
        assert_eq!(forwarded_model(&args(&["--model="])), None);
        // After a second `--` it is not a flag.
        assert_eq!(forwarded_model(&args(&["--", "--model", "c"])), None);
        assert_eq!(
            forwarded_model(&args(&["--model", "b", "--", "--model", "c"])),
            Some("b")
        );
    }

    #[test]
    fn forwarded_value_reads_either_spelling_of_any_flag() {
        let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        let cd = |a: &[&str]| forwarded_value(&args(a), "--cd", "-C").map(str::to_owned);
        assert_eq!(cd(&["-C", "/b"]).as_deref(), Some("/b"));
        assert_eq!(cd(&["--cd=/b", "--cd", "/c"]).as_deref(), Some("/c"));
        assert_eq!(cd(&["exec", "-C=/b", "hi"]).as_deref(), Some("/b"));
        assert_eq!(cd(&["--cdx=/b", "-Cx=/c"]), None);
        assert_eq!(cd(&["--", "-C", "/b"]), None);
    }

    /// Comments go, as `strip-json-comments` takes them out for Qwen Code,
    /// and nothing else moves: not a `//` inside a string, not a column.
    #[test]
    fn strip_json_comments_keeps_strings_and_columns() {
        let raw =
            "{\n  // note\n  \"url\": \"http://h//v1\", /* block\n  */ \"q\": \"a\\\"//b\"\n}\n";
        let stripped = strip_json_comments(raw);
        assert_eq!(stripped.chars().count(), raw.chars().count());
        assert_eq!(stripped.lines().count(), raw.lines().count());
        let v: serde_json::Value = serde_json::from_str(&stripped).unwrap();
        assert_eq!(v["url"], "http://h//v1");
        assert_eq!(v["q"], "a\"//b");
        assert_eq!(strip_json_comments("{\"a\": 1}"), "{\"a\": 1}");
    }

    /// A leading `~` is the home directory; anything else is as given.
    #[test]
    fn expand_tilde_reads_the_forms_qwen_code_reads() {
        let home = Path::new("/h");
        assert_eq!(expand_tilde("~/alt", home), PathBuf::from("/h/alt"));
        assert_eq!(expand_tilde("~", home), PathBuf::from("/h"));
        assert_eq!(expand_tilde("/abs", home), PathBuf::from("/abs"));
        assert_eq!(expand_tilde("~user/x", home), PathBuf::from("~user/x"));
    }

    #[test]
    fn pi_model_entry_declares_what_the_daemon_serves() {
        let entry = pi_model_entry("qwen3.5:0.8b", true, true, Some(32768));
        assert_eq!(entry["id"], "qwen3.5:0.8b");
        assert_eq!(entry["name"], "qwen3.5:0.8b");
        assert_eq!(entry["input"], serde_json::json!(["text", "image"]));
        assert_eq!(entry["reasoning"], true);
        assert_eq!(entry["contextWindow"], 32768);

        // A text-only model that does not think, and no window to
        // declare: pi keeps its own default rather than being told a guess.
        let plain = pi_model_entry("smol", false, false, None);
        assert_eq!(plain["input"], serde_json::json!(["text"]));
        assert_eq!(plain.get("reasoning"), None);
        assert_eq!(plain.get("contextWindow"), None);
    }

    /// The entry — pi's and omp's alike — carries the window `launch`
    /// resolved, not the raw trained context. Which file it lands in is
    /// covered by `write_omp_config_in_dir`'s own tests; this pins where
    /// the number comes from.
    #[test]
    fn pi_model_entry_declares_the_resolved_window_not_the_trained_context() {
        // A pair's larger half, as `pair_context_window` resolves it —
        // a figure no trained context could have produced.
        let pair = pair_context_window(Some(32_768), Some(200_000));
        assert_eq!(pair, Some(200_000));
        let entry = pi_model_entry("gemma4", false, false, pair);
        assert_eq!(entry["contextWindow"], 200_000);

        // And the daemon's clamp travels: a model trained past
        // DEFAULT_CTX_SIZE is served only the default, so it declares
        // only the default.
        let default = u64::from(crate::cmd::serve::DEFAULT_CTX_SIZE);
        let served = served_context_window(None, Some(1 << 20));
        assert_eq!(served, Some(default));
        let entry = pi_model_entry("big", false, false, served);
        assert_eq!(entry["contextWindow"], default);
    }
}