llmman 0.1.415

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
//! `llmman search` — find models on Docker Hub and Hugging Face.
//!
//! Both registries are queried at once; Docker Hub's rows come first,
//! since `docker.io/ai/` is where a bare `llmman run <name>` already
//! looks. Every NAME printed is fully qualified so it pastes straight
//! into `run`/`pull` (a bare `ai/qwen3` would resolve to hf.co).
//!
//! Docker Hub is queried through its website's search API
//! (`hub.docker.com/api/search/v4`, no credentials). Hub reports the
//! manifest media types pushed to each repo; only repos carrying a CNCF
//! ModelPack manifest are listed, since that is the format `pull` reads.
//! Repos published solely in Docker Model Runner's own format
//! (`application/vnd.docker.ai.model.config.v0.1+json`) are left out.
//! Hugging Face goes through `hf::api::search_models`, with the user's
//! token when configured.

use anyhow::{Context, Result};
use clap::{Args, ValueEnum};
use serde::Deserialize;

use crate::fmt::{human_count, relative_time_rfc3339};
use crate::hf;

/// Docker Hub's website search API; not part of the OCI registry
/// protocol, so it doesn't go through the Go shim.
const DOCKER_HUB_SEARCH_URL: &str = "https://hub.docker.com/api/search/v4";

/// Page size requested from Docker Hub, and the cap on `--limit`.
const MAX_LIMIT: u32 = 64;

/// The manifest media type of a CNCF ModelPack artifact.
const MODELPACK_MANIFEST: &str = "application/vnd.cncf.model.manifest.v1+json";

#[derive(Args, Debug)]
pub struct SearchArgs {
    /// Text to match against model names and descriptions
    #[arg(value_name = "QUERY")]
    pub query: String,

    /// Maximum number of results to show from each registry
    #[arg(
        long,
        short = 'n',
        default_value_t = 25,
        value_parser = clap::value_parser!(u32).range(1..=MAX_LIMIT as i64)
    )]
    pub limit: u32,

    /// Only search one registry instead of both
    #[arg(long, value_enum)]
    pub registry: Option<Registry>,
}

#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub enum Registry {
    /// Docker Hub (docker.io)
    #[value(alias = "docker.io", alias = "hub")]
    Docker,
    /// Hugging Face (hf.co)
    #[value(alias = "huggingface", alias = "hf.co")]
    Hf,
}

/// One table row, from either registry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hit {
    /// Fully qualified reference, ready for `llmman run`/`pull`.
    pub name: String,
    /// Docker Hub pulls; Hugging Face (last-30-day) downloads.
    pub pulls: Option<u64>,
    /// Docker Hub stars; Hugging Face likes.
    pub likes: Option<u64>,
    /// RFC 3339 timestamp of the last update, if reported.
    pub updated: Option<String>,
}

pub fn run(args: &SearchArgs) -> Result<()> {
    let query = args.query.trim();
    anyhow::ensure!(!query.is_empty(), "search query must not be empty");

    let hits = tokio::runtime::Runtime::new()
        .context("start tokio runtime")?
        .block_on(search(query, args.limit, args.registry))?;

    if hits.is_empty() {
        anyhow::bail!("no models found for {query:?}");
    }
    print!("{}", render(&hits));
    Ok(())
}

/// Docker Hub's rows first. With both registries selected, one failing
/// is a warning and the other's rows still print; both failing is an
/// error.
async fn search(query: &str, limit: u32, registry: Option<Registry>) -> Result<Vec<Hit>> {
    let client = hf::api_client()?;
    match registry {
        Some(Registry::Docker) => search_docker_hub(&client, query, limit).await,
        Some(Registry::Hf) => search_hugging_face(&client, query, limit).await,
        None => {
            let (docker, hugging_face) = tokio::join!(
                search_docker_hub(&client, query, limit),
                search_hugging_face(&client, query, limit),
            );
            match (docker, hugging_face) {
                (Ok(mut hits), Ok(more)) => {
                    hits.extend(more);
                    Ok(hits)
                }
                (Ok(hits), Err(e)) => {
                    eprintln!(
                        "[llmman] Hugging Face search failed, showing Docker Hub only: {e:#}"
                    );
                    Ok(hits)
                }
                (Err(e), Ok(hits)) => {
                    eprintln!(
                        "[llmman] Docker Hub search failed, showing Hugging Face only: {e:#}"
                    );
                    Ok(hits)
                }
                (Err(docker), Err(hugging_face)) => Err(docker
                    .context(format!("Hugging Face: {hugging_face:#}"))
                    .context("search failed on both registries")),
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Docker Hub
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct HubSearchResponse {
    #[serde(default)]
    results: Vec<HubResult>,
}

#[derive(Debug, Deserialize)]
struct HubResult {
    /// `namespace/repo`, or a bare `repo` for the official `library/`
    /// namespace.
    name: String,
    #[serde(default)]
    star_count: u64,
    /// The exact figure; `pull_count` is a display string like `"500K+"`.
    #[serde(default)]
    raw_pull_count: Option<u64>,
    #[serde(default)]
    updated_at: Option<String>,
    #[serde(default)]
    archived: bool,
    /// Every manifest/config media type pushed to the repo.
    #[serde(default)]
    media_types: Vec<String>,
}

impl HubResult {
    /// A repo can hold several formats (Docker's `ai/` models are
    /// published in both), so this is "has one", not "has only this".
    fn is_modelpack(&self) -> bool {
        self.media_types.iter().any(|t| t == MODELPACK_MANIFEST)
    }
}

/// Two Hub queries, merged: `type=model` only matches repos carrying
/// Model Runner's media type, so it misses ModelPack-only repos like
/// `ai/qwen3.8`; the unfiltered query finds those. Both are sorted by
/// pulls, since Hub's relevance order puts every `<user>/qwen` image
/// ahead of `ai/qwen3.8`. Each fetches a full page since
/// [`docker_hub_hits`] drops most rows before the cut to `limit`. One
/// failing page is tolerated.
async fn search_docker_hub(client: &reqwest::Client, query: &str, limit: u32) -> Result<Vec<Hit>> {
    let page = |kind| async move {
        let url = docker_hub_search_url(query, kind)?;
        hf::api::get_json::<HubSearchResponse>(client, url.as_str(), None).await
    };
    let (typed, untyped) = tokio::join!(page(Some("model")), page(None));
    let pages = match (typed, untyped) {
        (Ok(a), Ok(b)) => vec![a, b],
        (Ok(a), Err(_)) | (Err(_), Ok(a)) => vec![a],
        (Err(e), Err(_)) => return Err(e.context("Docker Hub model search")),
    };
    Ok(docker_hub_hits(pages, limit))
}

/// One page, most pulled first, optionally limited to a Hub `type`.
fn docker_hub_search_url(query: &str, kind: Option<&'static str>) -> Result<reqwest::Url> {
    let size = MAX_LIMIT.to_string();
    let mut params = vec![
        ("query", query),
        ("from", "0"),
        ("size", size.as_str()),
        ("sort", "pull_count"),
        ("order", "desc"),
    ];
    params.extend(kind.map(|k| ("type", k)));
    reqwest::Url::parse_with_params(DOCKER_HUB_SEARCH_URL, params)
        .context("build Docker Hub search URL")
}

/// Filters and merges Hub pages, dropping repeats, most pulled first;
/// stable, so ties keep Hub's order.
fn docker_hub_hits(pages: Vec<HubSearchResponse>, limit: u32) -> Vec<Hit> {
    let mut seen = std::collections::HashSet::new();
    let mut rows: Vec<HubResult> = pages
        .into_iter()
        .flat_map(|r| r.results)
        .filter(|r| !r.archived && r.is_modelpack())
        .filter(|r| seen.insert(r.name.clone()))
        .collect();
    rows.sort_by_key(|r| std::cmp::Reverse(r.raw_pull_count.unwrap_or(0)));
    rows.into_iter()
        .take(limit as usize)
        .map(|r| {
            // Hub omits the official namespace; a pullable reference needs it.
            let name = if r.name.contains('/') {
                format!("docker.io/{}", r.name)
            } else {
                format!("docker.io/library/{}", r.name)
            };
            Hit {
                name,
                pulls: r.raw_pull_count,
                likes: Some(r.star_count),
                updated: r.updated_at,
            }
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Hugging Face
// ---------------------------------------------------------------------------

async fn search_hugging_face(
    client: &reqwest::Client,
    query: &str,
    limit: u32,
) -> Result<Vec<Hit>> {
    let endpoint = hf::hf_endpoint("hf.co");
    let token = hf::token();
    let models = hf::api::search_models(client, &endpoint, query, limit, token.as_deref()).await?;
    Ok(models.into_iter().map(hugging_face_hit).collect())
}

fn hugging_face_hit(model: hf::api::SearchHit) -> Hit {
    Hit {
        name: format!("hf.co/{}", model.id),
        pulls: Some(model.downloads),
        likes: Some(model.likes),
        updated: model.last_modified,
    }
}

// ---------------------------------------------------------------------------
// Output
// ---------------------------------------------------------------------------

/// Same shape as `list`/`ps`: uppercase headers, 4-space gutters, columns
/// as wide as their widest cell, last column unpadded, nothing after the
/// final row.
fn render(hits: &[Hit]) -> String {
    let dash = || "-".to_string();
    let rows: Vec<[String; 4]> = hits
        .iter()
        .map(|h| {
            [
                h.name.clone(),
                h.pulls.map(human_count).unwrap_or_else(dash),
                h.likes.map(|n| n.to_string()).unwrap_or_else(dash),
                h.updated
                    .as_deref()
                    .map(relative_time_rfc3339)
                    .unwrap_or_else(dash),
            ]
        })
        .collect();

    let headers = ["NAME", "PULLS", "LIKES", "UPDATED"];
    let widths: Vec<usize> = (0..headers.len())
        .map(|c| {
            rows.iter()
                .map(|r| r[c].len())
                .max()
                .unwrap_or(0)
                .max(headers[c].len())
        })
        .collect();

    let line = |cells: [&str; 4]| {
        format!(
            "{:<w0$}    {:<w1$}    {:<w2$}    {}\n",
            cells[0],
            cells[1],
            cells[2],
            cells[3],
            w0 = widths[0],
            w1 = widths[1],
            w2 = widths[2],
        )
    };
    let mut out = line(headers);
    for r in &rows {
        out.push_str(&line([&r[0], &r[1], &r[2], &r[3]]));
    }
    out
}

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

    /// Relevance order buries `ai/qwen3.8` under `<user>/qwen` images;
    /// both pages must ask for pull-count order.
    #[test]
    fn docker_hub_search_url_sorts_by_pulls() {
        for (kind, suffix) in [(Some("model"), "&type=model"), (None, "")] {
            let url = docker_hub_search_url("qwen", kind).unwrap();
            assert_eq!(
                url.as_str(),
                format!(
                    "{DOCKER_HUB_SEARCH_URL}?query=qwen&from=0&size=64\
                     &sort=pull_count&order=desc{suffix}"
                )
            );
        }
    }

    /// A `type=model` page and an unfiltered page, plus rows that must
    /// not print: Model Runner-only, archived, a container image, a raw
    /// Hugging Face mirror, one repeated across pages, and one past
    /// `limit`. ModelPack-only `ai/qwen3.8` appears only on the
    /// unfiltered page and must print, ranked by pulls among the first
    /// page's rows.
    #[test]
    fn docker_hub_rows_become_pullable_references() {
        let typed = r#"{"total": 4, "results": [
            {"name": "ai/qwen3", "short_description": "Qwen3 LLM", "star_count": 210,
             "pull_count": "500K+", "raw_pull_count": 614283,
             "updated_at": "2026-08-17T14:03:18.618971Z", "archived": false,
             "media_types": ["application/vnd.cncf.model.manifest.v1+json",
                             "application/vnd.docker.ai.model.config.v0.1+json"],
             "content_types": ["model"]},
            {"name": "ai/qwen2.5", "star_count": 13, "raw_pull_count": 163532,
             "media_types": ["application/vnd.docker.ai.model.config.v0.1+json"],
             "content_types": ["model"]},
            {"name": "ai/qwen3-embedding", "star_count": 1, "raw_pull_count": 74850,
             "media_types": ["application/vnd.cncf.model.manifest.v1+json",
                             "application/vnd.docker.ai.model.config.v0.1+json"],
             "content_types": ["model"]},
            {"name": "ai/old", "archived": true, "star_count": 0,
             "media_types": ["application/vnd.cncf.model.manifest.v1+json",
                             "application/vnd.docker.ai.model.config.v0.1+json"],
             "content_types": ["model"]}
        ]}"#;
        let untyped = r#"{"total": 6, "results": [
            {"name": "ai/qwen3", "star_count": 210, "raw_pull_count": 614283,
             "media_types": ["application/vnd.cncf.model.manifest.v1+json",
                             "application/vnd.docker.ai.model.config.v0.1+json"],
             "content_types": ["model"]},
            {"name": "library/nginx", "star_count": 99999, "raw_pull_count": 9999999,
             "media_types": ["application/vnd.docker.distribution.manifest.v2+json"],
             "content_types": ["image"]},
            {"name": "ai/qwen3.8", "star_count": 4, "raw_pull_count": 98764,
             "media_types": ["application/vnd.cncf.model.manifest.v1+json"],
             "content_types": ["unrecognized"]},
            {"name": "someone/qwen3.8-27b", "star_count": 0, "raw_pull_count": 90000,
             "media_types": ["application/vnd.huggingface.model.v1"],
             "content_types": ["unrecognized"]},
            {"name": "official-thing", "star_count": 1,
             "media_types": ["application/vnd.cncf.model.manifest.v1+json"]},
            {"name": "ai/third", "star_count": 0,
             "media_types": ["application/vnd.cncf.model.manifest.v1+json"]}
        ]}"#;
        let typed: HubSearchResponse = serde_json::from_str(typed).unwrap();
        let untyped: HubSearchResponse = serde_json::from_str(untyped).unwrap();
        let hits = docker_hub_hits(vec![typed, untyped], 4);
        let names: Vec<&str> = hits.iter().map(|h| h.name.as_str()).collect();
        // A bare name is the official `library/` namespace. Rows with no
        // pull count sort last, keeping Hub's order among themselves.
        assert_eq!(
            names,
            [
                "docker.io/ai/qwen3",
                "docker.io/ai/qwen3.8",
                "docker.io/ai/qwen3-embedding",
                "docker.io/library/official-thing"
            ]
        );
        assert_eq!(
            hits[0],
            Hit {
                name: "docker.io/ai/qwen3".into(),
                pulls: Some(614283),
                likes: Some(210),
                updated: Some("2026-08-17T14:03:18.618971Z".into()),
            }
        );
        assert_eq!(hits[3].pulls, None);
        assert_eq!(hits[3].updated, None);
    }

    #[test]
    fn hugging_face_rows_become_pullable_references() {
        let body = r#"[
            {"id": "unsloth/Qwen3-8B-GGUF", "likes": 989, "downloads": 12853002,
             "lastModified": "2025-07-31T10:27:38.000Z"},
            {"id": "someone/bare"}
        ]"#;
        let models: Vec<hf::api::SearchHit> = serde_json::from_str(body).unwrap();
        let hits: Vec<Hit> = models.into_iter().map(hugging_face_hit).collect();
        assert_eq!(
            hits[0],
            Hit {
                name: "hf.co/unsloth/Qwen3-8B-GGUF".into(),
                pulls: Some(12853002),
                likes: Some(989),
                updated: Some("2025-07-31T10:27:38.000Z".into()),
            }
        );
        assert_eq!(hits[1].pulls, Some(0));
        assert_eq!(hits[1].updated, None);
    }

    #[test]
    fn render_aligns_columns_and_dashes_missing_values() {
        let hits = vec![
            Hit {
                name: "docker.io/ai/qwen3".into(),
                pulls: Some(614_283),
                likes: Some(210),
                updated: None,
            },
            Hit {
                name: "hf.co/unsloth/Qwen3-8B-GGUF".into(),
                pulls: Some(12_853_002),
                likes: Some(989),
                updated: None,
            },
        ];
        let out = render(&hits);
        assert_eq!(
            out,
            "NAME                           PULLS     LIKES    UPDATED\n\
             docker.io/ai/qwen3             614.3K    210      -\n\
             hf.co/unsloth/Qwen3-8B-GGUF    12.9M     989      -\n"
        );
    }
}