llmman 0.1.577

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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
//! Reusable "resolve a local OCI-store reference to servable model files"
//! logic — the CNCF ModelPack (<https://github.com/modelpack/model-spec>)
//! equivalent of `huggingface_hub.snapshot_download`.
//!
//! Originally private to `cmd::serve` (which uses it to decide whether to
//! spawn `llama-server`, `vllm`, or (Apple Silicon macOS) `mlx_lm.server`
//! as its backend for a given model), this
//! module is `pub` so it also backs `cmd::resolve` (`llmman resolve`) — a
//! standalone, scriptable entry point that other tools (e.g. a vLLM plugin
//! that wants vLLM itself, not `llmman`, to be the one serving the model)
//! can shell out to, without needing `llmman serve`'s HTTP daemon or its
//! opinions about which inference backend to launch.
//!
//! Everything here assumes the reference has already been pulled into the
//! local `OciStore` at `store_path` (see `crate::ffi::pull`) — this module
//! only resolves+extracts, it never talks to a registry itself.

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

use anyhow::{anyhow, Context};

use crate::storage::OciStore;

const HF_GGUF_MEDIA_TYPE: &str = "application/vnd.docker.ai.gguf.v3";

/// What kind of model did we find in the OCI store?
pub enum ModelPath {
    /// A GGUF file — serve with llama-server. The second field, when
    /// present, is a companion `--mmproj` projector GGUF (see
    /// [`is_mmproj_layer`]) needed for vision/audio support.
    Gguf(PathBuf, Option<PathBuf>),
    /// A safetensors directory — serve with vllm, or (Apple Silicon
    /// macOS) `mlx_lm.server` — see `cmd::serve::backend::use_mlx_for_safetensors`.
    SafeTensors(PathBuf),
    /// A latent diffusion model (image / video / audio generation) —
    /// served in-process by `crate::mediagen` from the transformer GGUF
    /// plus the sidecars pulled next to it (see
    /// `crate::hf::oci::ANNOTATION_ROLE`), or from a Diffusers pack whose
    /// pipeline it runs (`crate::mediagen::is_native_pipeline`).
    Diffusion(DiffusionPaths),
    /// A Diffusers-layout safetensors directory (a root `model_index.json`,
    /// weights in `transformer/`, `vae/`, ...) such as `nvidia/Cosmos3-Edge`
    /// — served by vLLM-Omni (`vllm serve --omni`); plain vllm cannot.
    Omni(PathBuf),
}

/// The Diffusers pipeline index that marks a [`ModelPath::Omni`] repo.
pub const DIFFUSERS_MODEL_INDEX: &str = "model_index.json";

/// The files of a resolved [`ModelPath::Diffusion`] model.
#[derive(Debug, Clone, Default)]
pub struct DiffusionPaths {
    /// The diffusion transformer GGUF (`--model`), or a Diffusers pack's
    /// `model_index.json` (its components are in `files`).
    pub model: PathBuf,
    /// Video VAE (`--vae`).
    pub vae: Option<PathBuf>,
    /// Audio VAE + vocoder (`--audio-vae`).
    pub audio_vae: Option<PathBuf>,
    /// Text embedding projection / connectors (`--text-proj`).
    pub text_proj: Option<PathBuf>,
    /// Text encoder GGUF (`--text-encoder`).
    pub text_encoder: Option<PathBuf>,
    /// Every raw layer by its `org.cncf.model.filepath` (tokenizer, configs, ...).
    pub files: std::collections::BTreeMap<String, PathBuf>,
}

impl ModelPath {
    /// The local filesystem path this variant resolved to — either a
    /// single `.gguf` file, or the model directory (parent of
    /// `config.json`) for a safetensors checkout.
    pub fn path(&self) -> &Path {
        match self {
            ModelPath::Gguf(p, _) => p,
            ModelPath::SafeTensors(p) | ModelPath::Omni(p) => p,
            ModelPath::Diffusion(d) => &d.model,
        }
    }

    /// The companion `--mmproj` projector file resolved alongside a
    /// `Gguf` model, if any — always `None` for `SafeTensors` (neither
    /// vllm nor mlx_lm.server has an equivalent separate-projector-file
    /// convention).
    pub fn mmproj(&self) -> Option<&Path> {
        match self {
            ModelPath::Gguf(_, mmproj) => mmproj.as_deref(),
            ModelPath::SafeTensors(_) | ModelPath::Diffusion(_) | ModelPath::Omni(_) => None,
        }
    }

    /// A short, stable string identifying which variant this is — used by
    /// `cmd::resolve`'s JSON output and any other consumer that wants to
    /// branch on format without matching the enum directly.
    pub fn format(&self) -> &'static str {
        match self {
            ModelPath::Gguf(..) => "gguf",
            ModelPath::SafeTensors(_) => "safetensors",
            ModelPath::Diffusion(_) => "diffusion",
            ModelPath::Omni(_) => "omni",
        }
    }
}

/// Splits an OCI digest ("sha256:abcd...") down to just its hex portion,
/// which is what the blob store's on-disk layout uses as the filename.
fn digest_hex(digest: &str) -> anyhow::Result<&str> {
    digest
        .split_once(':')
        .map(|(_, hex)| hex)
        .filter(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()))
        .ok_or_else(|| anyhow!("malformed digest: {digest}"))
}

fn layer_filepath(l: &crate::storage::oci::Descriptor) -> Option<&str> {
    l.annotations.as_ref().and_then(|a| {
        a.get("org.cncf.model.filepath")
            .or_else(|| a.get("org.opencontainers.image.title"))
            .map(|s| s.as_str())
    })
}

/// The diffusion sidecar role of a layer — see
/// `crate::hf::oci::ANNOTATION_ROLE`.
fn layer_role(l: &crate::storage::oci::Descriptor) -> Option<&str> {
    l.annotations
        .as_ref()
        .and_then(|a| a.get(crate::hf::oci::ANNOTATION_ROLE))
        .map(|s| s.as_str())
}

fn is_gguf_layer(l: &crate::storage::oci::Descriptor) -> bool {
    if l.media_type == HF_GGUF_MEDIA_TYPE {
        return true;
    }
    layer_filepath(l)
        .map(|p| p.to_lowercase().ends_with(".gguf"))
        .unwrap_or(false)
}

fn is_safetensors_layer(l: &crate::storage::oci::Descriptor) -> bool {
    layer_filepath(l)
        .map(|p| p.to_lowercase().ends_with(".safetensors"))
        .unwrap_or(false)
}

/// The layer holding the repo's *root* `model_index.json` (a Diffusers
/// pipeline index; a nested one is some vendored pipeline's, not this
/// repo's).
fn is_diffusers_index_layer(l: &crate::storage::oci::Descriptor) -> bool {
    layer_filepath(l) == Some(DIFFUSERS_MODEL_INDEX)
}

/// A Diffusers-layout repo: a root `model_index.json` next to safetensors.
fn is_diffusers_manifest(manifest: &crate::storage::oci::Manifest) -> bool {
    manifest.layers.iter().any(is_diffusers_index_layer)
        && manifest.layers.iter().any(is_safetensors_layer)
}

/// True if a (already-confirmed-GGUF) layer looks like a multimodal
/// projector rather than the main model — matched by filename containing
/// "mmproj", the de facto convention GGUF repos use, since there's no
/// media-type or metadata distinction to key off instead.
fn is_mmproj_layer(l: &crate::storage::oci::Descriptor) -> bool {
    layer_filepath(l)
        .map(|p| p.to_lowercase().contains("mmproj"))
        .unwrap_or(false)
}

// gguf_architecture/gguf_context_length_override (a GGUF metadata reader
// + --override-kv builder that let --ctx-size force a context above a
// model's own trained length) were tried and removed: llama-server's own
// capping of --ctx-size back down to a model's trained context — see
// cmd::serve::config::context_length_from_env's doc comment — is deliberate, not
// a bug to work around. Defeating that safety net via --override-kv
// produces a real NaN/incoherent-output risk for out-of-distribution
// RoPE positions that llama-server's own warning exists to prevent, for
// a use case (fitting a real agent's system prompt) that a model
// whose trained context is that tight was never going to serve well
// regardless — see docker/sandboxes' own llmmanCtxSize doc comment for the
// model-selection fix that replaced this instead.

/// Extracts a single GGUF layer to a local path, caching under
/// `cache_path` — shared by [`resolve_model`] for both the primary model
/// GGUF and, when present, a companion `--mmproj` GGUF (see
/// [`is_mmproj_layer`]), since both are extracted exactly the same way.
fn extract_gguf_layer(
    store: &OciStore,
    store_path: &Path,
    cache_path: &Path,
    layer: &crate::storage::oci::Descriptor,
) -> anyhow::Result<PathBuf> {
    let title = layer_filepath(layer).unwrap_or("model.gguf").to_owned();
    let layer_hex = digest_hex(&layer.digest)?;

    // HF blobs are stored as raw GGUF — use directly. The same goes for
    // the CNCF raw-weight layers `crate::hf::pull` writes: copying a
    // multi-GiB GGUF into the cache would double its disk footprint for
    // nothing.
    if layer.media_type == HF_GGUF_MEDIA_TYPE
        || layer.media_type == crate::hf::oci::MEDIA_TYPE_MODEL_WEIGHT_RAW
    {
        let blob_path = store_path.join("blobs").join("sha256").join(layer_hex);
        if blob_path.exists() && blob_is_gguf(&blob_path) {
            eprintln!("[llmman] using blob directly: {}", blob_path.display());
            return Ok(blob_path);
        }
    }

    // Otherwise extract from tar layer.
    if let Some(p) = cached_gguf(cache_path, layer_hex) {
        return Ok(p);
    }
    let cached_dir = cache_path.join(layer_hex);
    std::fs::create_dir_all(&cached_dir)?;
    let blob = store
        .read_blob(&layer.digest)
        .with_context(|| format!("read blob {}", layer.digest))?;
    if blob.len() >= 4 && &blob[..4] == b"GGUF" {
        let name = Path::new(&title)
            .file_name()
            .unwrap_or_else(|| std::ffi::OsStr::new("model.gguf"));
        let p = cached_dir.join(name);
        std::fs::write(&p, &blob)?;
        return Ok(p);
    }
    let mut archive = tar::Archive::new(std::io::Cursor::new(&blob));
    for entry in archive.entries()? {
        let mut entry = entry?;
        let ep = entry.path()?.to_path_buf();
        if ep.extension().and_then(|e| e.to_str()) == Some("gguf") {
            let name = ep
                .file_name()
                .unwrap_or_else(|| std::ffi::OsStr::new("model.gguf"));
            let d = cached_dir.join(name);
            entry.unpack(&d)?;
            return Ok(d);
        }
    }
    Err(anyhow!("no .gguf in tar layer {}", layer.digest))
}

/// True if the file at `path` starts with the GGUF magic.
fn blob_is_gguf(path: &Path) -> bool {
    use std::io::Read as _;
    let mut magic = [0u8; 4];
    std::fs::File::open(path)
        .and_then(|mut f| f.read_exact(&mut magic))
        .map(|()| &magic == b"GGUF")
        .unwrap_or(false)
}

/// The content-addressed blob of a raw (non-tar) layer, used as-is.
fn raw_blob_path(
    store_path: &Path,
    layer: &crate::storage::oci::Descriptor,
) -> anyhow::Result<PathBuf> {
    let p = store_path
        .join("blobs")
        .join("sha256")
        .join(digest_hex(&layer.digest)?);
    if !p.exists() {
        anyhow::bail!(
            "missing blob {} for layer {:?}",
            layer.digest,
            layer_filepath(layer)
        );
    }
    Ok(p)
}

/// A raw layer's blob under its original file name as
/// `<cache>/<digest>/<filename>`: the name carries the variant
/// (`distilled` selects the sampling schedule).
fn named_blob_path(
    store_path: &Path,
    cache_path: &Path,
    layer: &crate::storage::oci::Descriptor,
) -> anyhow::Result<PathBuf> {
    let blob = raw_blob_path(store_path, layer)?;
    let Some(name) = layer_filepath(layer).and_then(|p| Path::new(p).file_name()) else {
        return Ok(blob);
    };
    let dir = cache_path.join(digest_hex(&layer.digest)?);
    let link = dir.join(name);
    cache_layer_file(&blob, &link, layer.size)?;
    Ok(link)
}

/// Ollama's `model.Capability` values reported in `/api/show`'s
/// `capabilities` array (`ollama run` reads them to set `opts.MultiModal`).
pub const CAPABILITY_COMPLETION: &str = "completion";
pub const CAPABILITY_VISION: &str = "vision";
/// Produces embeddings instead of text; such a model has no `"completion"`.
pub const CAPABILITY_EMBEDDING: &str = "embedding";
/// Answers typed questions instead of generating text (ollama's
/// `CapabilityDecision`); such a model has no `"completion"`.
pub const CAPABILITY_DECISION: &str = "decision";
/// The chat template renders a request's `tools`.
pub const CAPABILITY_TOOLS: &str = "tools";
/// The chat template handles reasoning.
pub const CAPABILITY_THINKING: &str = "thinking";
/// Generates images (a latent diffusion model) — ollama's
/// `CapabilityImage`. Such a model has no `"completion"`.
pub const CAPABILITY_IMAGE: &str = "image";
pub const CAPABILITY_VIDEO: &str = "video";
pub const CAPABILITY_AUDIO: &str = "audio";

/// The part of ollama's `Model.Capabilities()` (server/images.go) a
/// manifest alone can answer, without extracting or opening a GGUF:
/// `"completion"` always, plus `"vision"` when a companion mmproj layer
/// is present (`projectorCapabilities`) or the CNCF config's
/// `config.capabilities.inputTypes` lists `"image"` (`configCapabilities`).
pub fn capabilities(store: &OciStore, manifest: &crate::storage::oci::Manifest) -> Vec<String> {
    // Shape written by crate::hf::oci::build_cncf_manifest.
    let config: Option<serde_json::Value> = store
        .read_blob(&manifest.config.digest)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok());
    let config_types = |key: &str| -> Vec<String> {
        config
            .as_ref()
            .and_then(|v| {
                v.get("config")?
                    .get("capabilities")?
                    .get(key)?
                    .as_array()
                    .cloned()
            })
            .unwrap_or_default()
            .iter()
            .filter_map(|t| t.as_str().map(str::to_string))
            .collect()
    };

    // A diffusion model generates media instead of text: its capabilities
    // are exactly the output types it was pulled with. A Diffusers-layout
    // repo pulled before those were recorded still generates images.
    let outputs = config_types("outputTypes");
    if outputs.iter().any(|t| t == CAPABILITY_IMAGE)
        || manifest.layers.iter().any(|l| layer_role(l).is_some())
        || is_diffusers_manifest(manifest)
    {
        let mut caps: Vec<String> = outputs
            .into_iter()
            .filter(|t| t == CAPABILITY_IMAGE || t == CAPABILITY_VIDEO || t == CAPABILITY_AUDIO)
            .collect();
        if caps.is_empty() {
            caps.push(CAPABILITY_IMAGE.to_string());
        }
        return caps;
    }

    let mut caps = vec![CAPABILITY_COMPLETION.to_string()];

    let has_mmproj = gguf_layers(manifest).is_some_and(|(_, mmproj)| mmproj.is_some());
    let config_says_image = config_types("inputTypes").iter().any(|t| t == "image");

    if has_mmproj || config_says_image {
        caps.push(CAPABILITY_VISION.to_string());
    }
    caps
}

/// `caps` (from [`capabilities`]) plus what only the GGUF header and chat
/// template say, in ollama's order: `"embedding"` for a pooling model or
/// `"decision"` for a decision model, in place of `"completion"`, then
/// `"tools"` and `"thinking"` from the template. A media, embedding or
/// decision model has no chat to equip and keeps what it has.
pub fn model_capabilities(
    mut caps: Vec<String>,
    gguf: Option<&crate::gguf::Info>,
    template: Option<&str>,
) -> Vec<String> {
    let Some(completion) = caps.iter().position(|c| c == CAPABILITY_COMPLETION) else {
        return caps;
    };
    if gguf.is_some_and(|info| info.is_embedding()) {
        caps[completion] = CAPABILITY_EMBEDDING.to_string();
        return caps;
    }
    if gguf.is_some_and(|info| info.is_decision()) {
        caps[completion] = CAPABILITY_DECISION.to_string();
        return caps;
    }
    let Some(template) = template else {
        return caps;
    };
    if crate::chat_template::handles_tools(template) {
        caps.push(CAPABILITY_TOOLS.to_string());
    }
    if crate::chat_template::thinking_controls(template).thinks {
        caps.push(CAPABILITY_THINKING.to_string());
    }
    caps
}

/// How many primary GGUF layers the manifest holds. More than one is a
/// `gguf-split` set, whose tensors are spread across the shards, so no
/// single header's tensor list describes the whole model.
pub fn gguf_shard_count(manifest: &crate::storage::oci::Manifest) -> usize {
    let layers: Vec<_> = manifest
        .layers
        .iter()
        .filter(|l| is_gguf_layer(l) && layer_role(l).is_none())
        .collect();
    let weights = layers.iter().filter(|l| !is_mmproj_layer(l)).count();
    if weights > 0 {
        return weights;
    }
    // [`gguf_layers`] falls back to the first layer when every one looks
    // like mmproj, so a lone one is the model and its header describes
    // it. Several, and which is the model is a guess — stay plural, so
    // the caller reports nothing rather than one of them.
    layers.len()
}

/// The model's parsed GGUF header: the blob as stored, or a tar layer
/// already extracted. Like [`chat_template`] it extracts nothing itself,
/// so a read-only caller never copies a checkout into the cache. `None`
/// for a checkout-layout model, or a header that will not parse.
pub fn gguf_info(
    store_path: &Path,
    cache_path: &Path,
    manifest: &crate::storage::oci::Manifest,
) -> Option<crate::gguf::Info> {
    let (primary, _) = gguf_layers(manifest)?;
    let path = raw_blob_path(store_path, primary)
        .ok()
        .filter(|p| blob_is_gguf(p))
        .or_else(|| cached_gguf(cache_path, digest_hex(&primary.digest).ok()?))?;
    crate::gguf::read_info(&path).ok()
}

/// Ollama's `api.ShowResponse.Template`: the model's chat template, read
/// without extracting anything (a read-only `/api/show` must not copy a
/// checkout into the cache). A GGUF's `tokenizer.chat_template`, from
/// the blob as stored or a tar layer already extracted; else a
/// checkout's `chat_template.jinja`, or `tokenizer_config.json`'s
/// `chat_template` (the `default` of Transformers' named templates).
pub fn chat_template(
    store: &OciStore,
    store_path: &Path,
    cache_path: &Path,
    manifest: &crate::storage::oci::Manifest,
) -> Option<String> {
    if gguf_layers(manifest).is_some() {
        return gguf_info(store_path, cache_path, manifest)?
            .str("tokenizer.chat_template")
            .map(str::to_string);
    }
    let file = |name: &str| {
        manifest
            .layers
            .iter()
            .find(|l| {
                layer_filepath(l)
                    .and_then(|p| Path::new(p).file_name())
                    .is_some_and(|f| f == name)
            })
            .and_then(|l| read_layer_text(store, l).ok())
    };
    if let Some(jinja) = file("chat_template.jinja") {
        return Some(jinja);
    }
    let config: serde_json::Value = serde_json::from_str(&file("tokenizer_config.json")?).ok()?;
    let named_default = |entry: &serde_json::Value| {
        entry.get("name").and_then(serde_json::Value::as_str) == Some("default")
    };
    match config.get("chat_template")? {
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Object(named) => named.get("default")?.as_str().map(str::to_string),
        serde_json::Value::Array(named) => named
            .iter()
            .find(|e| named_default(e))
            .or_else(|| named.first())?
            .get("template")?
            .as_str()
            .map(str::to_string),
        _ => None,
    }
}

/// A manifest layer's text: the one file of a single-file tar layer (as
/// `llmman build` writes), else the blob itself (as HuggingFace and cloud
/// pulls store docs and configs).
pub fn read_layer_text(
    store: &OciStore,
    layer: &crate::storage::oci::Descriptor,
) -> anyhow::Result<String> {
    use std::io::Read as _;
    let blob = store.read_blob(&layer.digest)?;
    if blob.len() >= 512 {
        let mut archive = tar::Archive::new(std::io::Cursor::new(&blob));
        if let Ok(entries) = archive.entries() {
            for mut entry in entries.flatten() {
                let mut s = String::new();
                if entry.read_to_string(&mut s).is_ok() && !s.is_empty() {
                    return Ok(s);
                }
            }
        }
    }
    Ok(String::from_utf8_lossy(&blob).into_owned())
}

/// The GGUF a tar layer was already extracted to, if any.
fn cached_gguf(cache_path: &Path, layer_hex: &str) -> Option<PathBuf> {
    std::fs::read_dir(cache_path.join(layer_hex))
        .ok()?
        .flatten()
        .map(|e| e.path())
        .find(|p| p.extension().and_then(|e| e.to_str()) == Some("gguf"))
}

/// The manifest's primary GGUF layer and its companion mmproj layer, if
/// any. Prefers a non-mmproj-named layer as primary so an mmproj file
/// that sorts first isn't taken for the model; falls back to the first
/// layer if every one looks like mmproj.
fn gguf_layers(
    manifest: &crate::storage::oci::Manifest,
) -> Option<(
    &crate::storage::oci::Descriptor,
    Option<&crate::storage::oci::Descriptor>,
)> {
    let layers: Vec<&crate::storage::oci::Descriptor> = manifest
        .layers
        .iter()
        .filter(|l| is_gguf_layer(l) && layer_role(l).is_none())
        .collect();
    let primary = *layers
        .iter()
        .find(|l| !is_mmproj_layer(l))
        .or(layers.first())?;
    let mmproj = layers
        .iter()
        .copied()
        .find(|l| is_mmproj_layer(l) && l.digest != primary.digest);
    Some((primary, mmproj))
}

/// Which [`ModelPath`] variant a manifest resolves to — see [`stored_format`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModelFormat {
    Gguf,
    SafeTensors,
    Diffusion,
    /// Diffusers-layout safetensors — see [`ModelPath::Omni`].
    Omni,
}

impl ModelFormat {
    /// The same vocabulary [`ModelPath::format`] reports.
    pub fn as_str(self) -> &'static str {
        match self {
            ModelFormat::Gguf => "gguf",
            ModelFormat::SafeTensors => "safetensors",
            ModelFormat::Diffusion => "diffusion",
            ModelFormat::Omni => "omni",
        }
    }
}

/// [`resolve_model`]'s classification: diffusion > GGUF > Diffusers
/// (omni) > safetensors, `None` for "no servable model layer".
pub fn manifest_format(manifest: &crate::storage::oci::Manifest) -> Option<ModelFormat> {
    if manifest.layers.iter().any(|l| layer_role(l).is_some()) {
        Some(ModelFormat::Diffusion)
    } else if gguf_layers(manifest).is_some() {
        Some(ModelFormat::Gguf)
    } else if is_diffusers_manifest(manifest) {
        Some(ModelFormat::Omni)
    } else if manifest.layers.iter().any(is_safetensors_layer) {
        Some(ModelFormat::SafeTensors)
    } else {
        None
    }
}

/// A Diffusers pack whose pipeline `crate::mediagen` runs itself.
fn is_native_diffusers(store: &OciStore, manifest: &crate::storage::oci::Manifest) -> bool {
    manifest
        .layers
        .iter()
        .find(|l| is_diffusers_index_layer(l))
        .and_then(|l| store.read_blob(&l.digest).ok())
        .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
        .and_then(|v| {
            v.get("_class_name")?
                .as_str()
                .map(crate::mediagen::is_native_pipeline)
        })
        .unwrap_or(false)
}

/// [`manifest_format`], but a Diffusers pack whose pipeline `crate::mediagen`
/// runs is [`ModelFormat::Diffusion`] rather than [`ModelFormat::Omni`].
pub fn stored_manifest_format(
    store: &OciStore,
    manifest: &crate::storage::oci::Manifest,
) -> Option<ModelFormat> {
    match manifest_format(manifest) {
        Some(ModelFormat::Omni) if is_native_diffusers(store, manifest) => {
            Some(ModelFormat::Diffusion)
        }
        f => f,
    }
}

/// The "nothing servable" error, naming the file extensions that were there.
fn no_servable_layer(model_ref: &str, manifest: &crate::storage::oci::Manifest) -> anyhow::Error {
    let exts: std::collections::HashSet<String> = manifest
        .layers
        .iter()
        .filter_map(|l| layer_filepath(l))
        .filter_map(|p| Path::new(p).extension()?.to_str().map(|e| e.to_lowercase()))
        .collect();
    if exts.is_empty() {
        anyhow!("no servable model layer found in {model_ref}")
    } else {
        anyhow!(
            "no servable model layer in {model_ref} — found {exts:?} files; \
             llmman serve supports GGUF (llama-server/ds4) and safetensors (vllm/vllm-omni/sglang/mlx)"
        )
    }
}

/// What [`resolve_model`] would resolve `model_ref` to, read off its
/// manifest without extracting anything (for `serve --pull-only`, which only
/// needs to know which engine's image to pull).
pub fn stored_format(store_path: &Path, model_ref: &str) -> anyhow::Result<ModelFormat> {
    let store = OciStore::open(store_path)?;
    let desc = store
        .find(model_ref)
        .with_context(|| format!("model not found in store: {model_ref}"))?;
    let manifest = store.read_manifest(&desc.digest)?;
    stored_manifest_format(&store, &manifest).ok_or_else(|| no_servable_layer(model_ref, &manifest))
}

/// Resolve `model_ref` (already present in the `OciStore` at `store_path`)
/// to either a `.gguf` file or an extracted safetensors directory, caching
/// any extraction under `cache_path`.
pub fn resolve_model(
    store_path: &Path,
    cache_path: &Path,
    model_ref: &str,
) -> anyhow::Result<ModelPath> {
    let store = OciStore::open(store_path)?;
    let desc = store
        .find(model_ref)
        .with_context(|| format!("model not found in store: {model_ref}"))?;
    let manifest = store.read_manifest(&desc.digest)?;

    let Some(format) = stored_manifest_format(&store, &manifest) else {
        return Err(no_servable_layer(model_ref, &manifest));
    };

    // ── Diffusers pipeline → crate::mediagen ──────────────────────────────
    if format == ModelFormat::Diffusion && manifest_format(&manifest) == Some(ModelFormat::Omni) {
        extract_safetensors_dir(store_path, cache_path, &desc.digest, &manifest)?;
        let root = cache_path.join(digest_hex(&desc.digest)?);
        let files: std::collections::BTreeMap<String, PathBuf> = manifest
            .layers
            .iter()
            .filter_map(layer_filepath)
            .filter(|p| crate::sources::is_safe_relative_path(p) && root.join(p).is_file())
            .map(|p| (p.to_string(), root.join(p)))
            .collect();
        let model = files
            .get(DIFFUSERS_MODEL_INDEX)
            .cloned()
            .ok_or_else(|| anyhow!("{model_ref}: {DIFFUSERS_MODEL_INDEX} was not extracted"))?;
        return Ok(ModelPath::Diffusion(DiffusionPaths {
            model,
            files,
            ..Default::default()
        }));
    }

    // ── diffusion → crate::mediagen ───────────────────────────────────────
    if format == ModelFormat::Diffusion {
        let (primary, _) = gguf_layers(&manifest)
            .ok_or_else(|| anyhow!("{model_ref}: diffusion model has no transformer GGUF layer"))?;
        // Every file keeps its name (see named_blob_path); a GGUF in a tar
        // layer is extracted.
        let named = |l: &crate::storage::oci::Descriptor| -> anyhow::Result<PathBuf> {
            let raw = raw_blob_path(store_path, l);
            if is_gguf_layer(l) && !raw.as_ref().is_ok_and(|p| blob_is_gguf(p)) {
                extract_gguf_layer(&store, store_path, cache_path, l)
            } else if raw.is_ok()
                && (is_gguf_layer(l) || l.media_type == crate::hf::oci::MEDIA_TYPE_MODEL_WEIGHT_RAW)
            {
                named_blob_path(store_path, cache_path, l)
            } else {
                anyhow::bail!(
                    "{model_ref}: unsupported layer {} ({})",
                    l.digest,
                    l.media_type
                )
            }
        };
        let mut paths = DiffusionPaths {
            model: named(primary)?,
            ..Default::default()
        };
        for l in &manifest.layers {
            // raw layers only: a tar layer's blob is the archive, not the file
            if let (Some(fp), true) = (layer_filepath(l), l.media_type.ends_with(".raw")) {
                paths
                    .files
                    .insert(fp.to_string(), named_blob_path(store_path, cache_path, l)?);
            }
            let Some(role) = layer_role(l) else { continue };
            let p = named(l)?;
            match role {
                "vae" => paths.vae = Some(p),
                "audio_vae" => paths.audio_vae = Some(p),
                "text_proj" => paths.text_proj = Some(p),
                "text_encoder" => paths.text_encoder = Some(p),
                // Cosmos3 sidecars its generation path does not use
                "vision_encoder" | "sound_tokenizer" => {}
                other => {
                    eprintln!("[llmman] {model_ref}: ignoring layer with unknown role {other:?}")
                }
            }
        }
        return Ok(ModelPath::Diffusion(paths));
    }

    // ── GGUF → llama-server ────────────────────────────────────────────────
    if let Some((primary, mmproj)) = gguf_layers(&manifest) {
        let primary_path = extract_gguf_layer(&store, store_path, cache_path, primary)?;
        let mmproj_path = mmproj
            .map(|l| extract_gguf_layer(&store, store_path, cache_path, l))
            .transpose()
            .context("extracting companion mmproj file")?;
        if mmproj_path.is_some() {
            eprintln!("[llmman] {model_ref}: found companion mmproj file");
        }
        return Ok(ModelPath::Gguf(primary_path, mmproj_path));
    }

    // ── safetensors → vllm / vllm-omni / mlx_lm.server ──────────────────
    let model_dir = extract_safetensors_dir(store_path, cache_path, &desc.digest, &manifest)?;
    Ok(match format {
        ModelFormat::Omni => ModelPath::Omni(model_dir),
        _ => {
            debug_assert_eq!(format, ModelFormat::SafeTensors);
            ModelPath::SafeTensors(model_dir)
        }
    })
}

/// The model directory of an extracted checkout: the parent of the
/// shallowest `config.json` or `model_index.json` (a Diffusers repo has a
/// `config.json` per component, so "first in layer order" is wrong), else
/// the checkout root.
fn safetensors_model_dir(cache_dir: &Path, rel_paths: &[&str]) -> PathBuf {
    rel_paths
        .iter()
        .filter(|p| {
            Path::new(p)
                .file_name()
                .is_some_and(|n| n == "config.json" || n == DIFFUSERS_MODEL_INDEX)
        })
        .min_by_key(|p| p.matches('/').count())
        .and_then(|p| Path::new(p).parent())
        // `join("")` would leave a trailing separator on the root case.
        .filter(|parent| !parent.as_os_str().is_empty())
        .map(|parent| cache_dir.join(parent))
        .unwrap_or_else(|| cache_dir.to_path_buf())
}

/// Extract CNCF-format safetensors layers to a cache directory and return the
/// model directory (see [`safetensors_model_dir`]).
fn extract_safetensors_dir(
    store_path: &Path,
    cache_path: &Path,
    manifest_digest: &str,
    manifest: &crate::storage::oci::Manifest,
) -> anyhow::Result<PathBuf> {
    let hex = digest_hex(manifest_digest)?;
    let cache_dir = cache_path.join(hex);

    for layer in &manifest.layers {
        // Only extract config and weight files; skip code/docs.
        let include = matches!(
            layer.media_type.as_str(),
            "application/vnd.cncf.model.weight.config.v1.raw"
                | "application/vnd.cncf.model.weight.v1.raw"
        );
        if !include {
            continue;
        }

        let Some(rel_path) = layer_filepath(layer) else {
            continue;
        };
        // The annotation came from whatever produced the manifest, so it
        // is not this process's to trust: joining "../../id_rsa" onto
        // cache_dir would escape it and overwrite an arbitrary file.
        // `crate::sources` rejects these at pack time; this covers a
        // layer already in the store, or pulled by any other path.
        if !crate::sources::is_safe_relative_path(rel_path) {
            eprintln!("[llmman] skipping layer with unsafe filepath {rel_path:?}");
            continue;
        }
        let dest = cache_dir.join(rel_path);
        if cached_layer_file_matches(&dest, layer.size) {
            continue;
        }

        let blob = raw_blob_path(store_path, layer)?;
        cache_layer_file(&blob, &dest, layer.size)
            .with_context(|| format!("cache {rel_path} from blob store"))?;
        eprintln!("[llmman] cached {rel_path}");
    }

    let rel_paths: Vec<&str> = manifest
        .layers
        .iter()
        .filter_map(layer_filepath)
        .filter(|p| crate::sources::is_safe_relative_path(p))
        .collect();
    Ok(safetensors_model_dir(&cache_dir, &rel_paths))
}

fn cached_layer_file_matches(dest: &Path, layer_size: u64) -> bool {
    dest.symlink_metadata()
        .map(|m| m.is_file() && m.len() == layer_size)
        .unwrap_or(false)
}

fn cache_layer_file(src: &Path, dest: &Path, layer_size: u64) -> anyhow::Result<()> {
    if cached_layer_file_matches(dest, layer_size) {
        return Ok(());
    }
    std::fs::create_dir_all(dest.parent().context("no parent")?)?;
    match std::fs::remove_file(dest) {
        Ok(()) => {}
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(e).with_context(|| format!("remove {}", dest.display())),
    }
    link_or_copy_file(src, dest, layer_size)
}

fn link_or_copy_file(src: &Path, dest: &Path, layer_size: u64) -> anyhow::Result<()> {
    match std::fs::hard_link(src, dest) {
        Ok(()) if cached_layer_file_matches(dest, layer_size) => Ok(()),
        Ok(()) => {
            let actual_size = dest
                .symlink_metadata()
                .with_context(|| format!("inspect hardlink {}", dest.display()))
                .map(|meta| meta.len());
            std::fs::remove_file(dest)
                .with_context(|| format!("remove invalid hardlink {}", dest.display()))?;
            let actual_size = actual_size?;
            anyhow::bail!(
                "blob {} is {actual_size} bytes, expected {layer_size}",
                src.display()
            );
        }
        Err(_) if cached_layer_file_matches(dest, layer_size) => Ok(()),
        Err(hardlink_error) => copy_file_atomic(src, dest, layer_size).with_context(|| {
            format!(
                "hardlink {} to {} failed: {hardlink_error}; copy failed",
                src.display(),
                dest.display()
            )
        }),
    }
}

fn copy_file_atomic(src: &Path, dest: &Path, layer_size: u64) -> anyhow::Result<()> {
    let tmp = cache_copy_temp_path(dest);
    let result = (|| {
        let copied = std::fs::copy(src, &tmp)
            .with_context(|| format!("copy {} to {}", src.display(), tmp.display()))?;
        if copied != layer_size {
            anyhow::bail!("copied {copied} bytes, expected {layer_size}");
        }
        match std::fs::rename(&tmp, dest) {
            Ok(()) => Ok(()),
            Err(_) if cached_layer_file_matches(dest, layer_size) => Ok(()),
            Err(e) => {
                Err(e).with_context(|| format!("rename {} to {}", tmp.display(), dest.display()))
            }
        }
    })();
    if result.is_err() || tmp.exists() {
        let _ = std::fs::remove_file(&tmp);
    }
    result
}

fn cache_copy_temp_path(dest: &Path) -> PathBuf {
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let mut tmp = dest.to_path_buf().into_os_string();
    tmp.push(format!(
        ".{}.{}.tmp",
        std::process::id(),
        COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    PathBuf::from(tmp)
}

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

    #[test]
    fn format_matches_variant() {
        assert_eq!(
            ModelPath::Gguf(PathBuf::from("/x/m.gguf"), None).format(),
            "gguf"
        );
        assert_eq!(
            ModelPath::SafeTensors(PathBuf::from("/x")).format(),
            "safetensors"
        );
    }

    #[test]
    fn path_returns_inner_pathbuf() {
        let p = ModelPath::SafeTensors(PathBuf::from("/models/foo"));
        assert_eq!(p.path(), Path::new("/models/foo"));
    }

    #[test]
    fn mmproj_is_none_unless_explicitly_set() {
        let no_mmproj = ModelPath::Gguf(PathBuf::from("/x/m.gguf"), None);
        assert_eq!(no_mmproj.mmproj(), None);

        let with_mmproj = ModelPath::Gguf(
            PathBuf::from("/x/m.gguf"),
            Some(PathBuf::from("/x/mmproj-f16.gguf")),
        );
        assert_eq!(with_mmproj.mmproj(), Some(Path::new("/x/mmproj-f16.gguf")));

        // SafeTensors (vllm/mlx) has no equivalent separate-projector-file
        // convention.
        assert_eq!(ModelPath::SafeTensors(PathBuf::from("/x")).mmproj(), None);
    }

    fn descriptor(digest: &str, filepath: &str) -> crate::storage::oci::Descriptor {
        let mut ann = std::collections::HashMap::new();
        ann.insert("org.cncf.model.filepath".to_string(), filepath.to_string());
        crate::storage::oci::Descriptor {
            media_type: "application/vnd.cncf.model.weight.v1.tar".into(),
            digest: digest.to_string(),
            size: 123,
            annotations: Some(ann),
        }
    }

    #[test]
    fn is_mmproj_layer_matches_filename_regardless_of_case_or_position() {
        assert!(is_mmproj_layer(&descriptor("sha256:a", "mmproj-F16.gguf")));
        assert!(is_mmproj_layer(&descriptor(
            "sha256:b",
            "Qwen3-VL-mmproj.gguf"
        )));
        assert!(!is_mmproj_layer(&descriptor(
            "sha256:c",
            "model.Q4_K_M.gguf"
        )));
    }

    fn manifest_with(
        layers: Vec<crate::storage::oci::Descriptor>,
    ) -> (OciStore, crate::storage::oci::Manifest) {
        // parallel tests can share a clock tick; the counter keeps their stores apart
        static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let dir = std::env::temp_dir().join(format!(
            "llmman-modelpack-caps-{}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos(),
            N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
        ));
        let store = OciStore::open(&dir).unwrap();
        let config = store
            .write_blob("application/vnd.cncf.model.config.v1+json", b"{}")
            .unwrap();
        let manifest = crate::storage::oci::Manifest {
            schema_version: 2,
            media_type: "application/vnd.oci.image.manifest.v1+json".into(),
            artifact_type: None,
            config,
            layers,
            annotations: None,
        };
        (store, manifest)
    }

    #[test]
    fn capabilities_is_completion_only_without_a_projector() {
        let (store, m) = manifest_with(vec![descriptor("sha256:a", "model.Q4_K_M.gguf")]);
        assert_eq!(capabilities(&store, &m), vec!["completion"]);
    }

    /// A GGUF header, with `pooling_type` for an embedding model.
    fn gguf_header(pooling: bool) -> crate::gguf::Info {
        use crate::gguf::Value;
        let mut info = crate::gguf::Info::default();
        info.metadata.insert(
            "general.architecture".into(),
            Value::String("gemma3".into()),
        );
        if pooling {
            info.metadata
                .insert("gemma3.pooling_type".into(), Value::U32(1));
        }
        info
    }

    const TOOLS_AND_THINKING: &str =
        "{%- if tools %}{{ tools | tojson }}{%- endif %}{%- if enable_thinking %}<think>{%- endif %}";

    /// `tools` and `thinking` follow `vision`, as in ollama.
    #[test]
    fn model_capabilities_adds_what_the_template_handles() {
        let caps = |template: Option<&str>| {
            model_capabilities(
                vec!["completion".into(), "vision".into()],
                Some(&gguf_header(false)),
                template,
            )
        };
        assert_eq!(
            caps(Some(TOOLS_AND_THINKING)),
            ["completion", "vision", "tools", "thinking"]
        );
        assert_eq!(
            caps(Some("{%- if tools %}{{ tools }}{%- endif %}")),
            ["completion", "vision", "tools"]
        );
        assert_eq!(
            caps(Some("{%- if enable_thinking %}<think>{%- endif %}")),
            ["completion", "vision", "thinking"]
        );
        assert_eq!(
            caps(Some("{{ messages[0].content }}")),
            ["completion", "vision"]
        );
        // No template: what the manifest said.
        assert_eq!(caps(None), ["completion", "vision"]);
        // No GGUF header (a checkout): the template still counts.
        assert_eq!(
            model_capabilities(vec!["completion".into()], None, Some(TOOLS_AND_THINKING)),
            ["completion", "tools", "thinking"]
        );
    }

    /// A pooling model embeds instead of completing, template or not.
    #[test]
    fn model_capabilities_reports_a_pooling_model_as_embedding() {
        assert_eq!(
            model_capabilities(
                vec!["completion".into()],
                Some(&gguf_header(true)),
                Some(TOOLS_AND_THINKING)
            ),
            ["embedding"]
        );
        assert!(gguf_header(true).is_embedding());
        assert!(!gguf_header(false).is_embedding());
    }

    /// A decision model keeps its projector's vision.
    #[test]
    fn model_capabilities_reports_a_decision_model_as_decision() {
        use crate::gguf::Value;
        let mut header = gguf_header(false);
        header
            .metadata
            .insert("gemma3.decision.type".into(), Value::String("clef".into()));
        assert_eq!(
            model_capabilities(
                vec!["completion".into(), "vision".into()],
                Some(&header),
                Some(TOOLS_AND_THINKING)
            ),
            ["decision", "vision"]
        );
        assert!(header.is_decision());
        assert!(!gguf_header(false).is_decision());
    }

    /// A media model's capabilities are what it generates.
    #[test]
    fn model_capabilities_leaves_a_media_model_alone() {
        let media = vec!["image".to_string(), "video".to_string()];
        assert_eq!(
            model_capabilities(media.clone(), None, Some(TOOLS_AND_THINKING)),
            media
        );
    }

    #[test]
    fn capabilities_adds_vision_when_a_companion_mmproj_layer_is_present() {
        // Mirrors ollama's projectorCapabilities: any projector ⇒ vision.
        let (store, m) = manifest_with(vec![
            descriptor("sha256:a", "mmproj-F16.gguf"),
            descriptor("sha256:b", "model.Q4_K_M.gguf"),
        ]);
        assert_eq!(capabilities(&store, &m), vec!["completion", "vision"]);
    }

    #[test]
    fn capabilities_a_lone_mmproj_named_gguf_is_the_model_not_a_projector() {
        let (store, m) = manifest_with(vec![descriptor("sha256:a", "mmproj-only.gguf")]);
        assert_eq!(capabilities(&store, &m), vec!["completion"]);
    }

    #[test]
    fn capabilities_two_mmproj_named_ggufs_load_with_a_projector_so_report_vision() {
        // resolve_model's fallback: first is primary, second is its mmproj.
        let (store, m) = manifest_with(vec![
            descriptor("sha256:a", "mmproj-model.gguf"),
            descriptor("sha256:b", "mmproj-F16.gguf"),
        ]);
        assert_eq!(capabilities(&store, &m), vec!["completion", "vision"]);
    }

    #[test]
    fn gguf_info_reads_the_header_of_the_stored_primary_layer() {
        let path = crate::gguf::write_test_gguf_with(&[]);
        let bytes = std::fs::read(&path).unwrap();
        let _ = std::fs::remove_file(&path);
        let (store, mut m) = manifest_with(vec![]);
        let mut d = store.write_blob(HF_GGUF_MEDIA_TYPE, &bytes).unwrap();
        d.annotations.get_or_insert_with(Default::default).insert(
            "org.cncf.model.filepath".to_string(),
            "model.gguf".to_string(),
        );
        m.layers = vec![d];
        let info = gguf_info(store.root(), Path::new("/nonexistent"), &m).expect("header");
        assert_eq!(info.architecture(), Some("llama"));
        assert_eq!(info.context_length(), Some(4096));
    }

    /// A checkout-layout model has no GGUF layer to read.
    #[test]
    fn gguf_info_is_none_without_a_gguf_layer() {
        let (store, m) = manifest_with(vec![descriptor("sha256:a", "model.safetensors")]);
        assert!(gguf_info(store.root(), Path::new("/nonexistent"), &m).is_none());
    }

    #[test]
    fn capabilities_honours_cncf_config_input_types_image() {
        // The exact shape hf::oci::build_cncf_manifest writes.
        let (store, mut m) = manifest_with(vec![descriptor("sha256:a", "model.gguf")]);
        m.config = store
            .write_blob(
                "application/vnd.cncf.model.config.v1+json",
                br#"{"descriptor":{},"modelfs":{"type":"layers","diffIds":[]},"config":{"format":"gguf","capabilities":{"inputTypes":["text","image"],"outputTypes":["text"]}}}"#,
            )
            .unwrap();
        assert_eq!(capabilities(&store, &m), vec!["completion", "vision"]);
    }

    #[test]
    fn capabilities_of_a_diffusion_model_are_its_output_types() {
        // A diffusion pull: the transformer GGUF plus role-annotated
        // sidecars, config listing what it generates. No "completion".
        let mut vae = descriptor("sha256:b", "ltx_video_vae.safetensors");
        vae.annotations.get_or_insert_with(Default::default).insert(
            crate::hf::oci::ANNOTATION_ROLE.to_string(),
            "vae".to_string(),
        );
        let mut te = descriptor("sha256:c", "gemma-3-12b-it-Q4_K_M.gguf");
        te.annotations.get_or_insert_with(Default::default).insert(
            crate::hf::oci::ANNOTATION_ROLE.to_string(),
            "text_encoder".to_string(),
        );
        let (store, mut m) =
            manifest_with(vec![descriptor("sha256:a", "ltx-Q4_K_M.gguf"), vae, te]);
        m.config = store
            .write_blob(
                "application/vnd.cncf.model.config.v1+json",
                br#"{"config":{"format":"gguf","capabilities":{"inputTypes":["text"],"outputTypes":["image","video","audio"]}}}"#,
            )
            .unwrap();
        assert_eq!(capabilities(&store, &m), vec!["image", "video", "audio"]);
        // the text encoder GGUF is a sidecar, not the model
        let (primary, mmproj) = gguf_layers(&m).unwrap();
        assert_eq!(primary.digest, "sha256:a");
        assert!(mmproj.is_none());
    }

    #[test]
    fn capabilities_ignores_input_types_at_the_document_root() {
        let (store, mut m) = manifest_with(vec![descriptor("sha256:a", "model.gguf")]);
        m.config = store
            .write_blob(
                "application/vnd.cncf.model.config.v1+json",
                br#"{"capabilities":{"inputTypes":["text","image"]}}"#,
            )
            .unwrap();
        assert_eq!(capabilities(&store, &m), vec!["completion"]);
    }

    #[test]
    fn manifest_format_follows_resolve_models_precedence() {
        let (_, m) = manifest_with(vec![
            descriptor("sha256:a", "model.Q4_K_M.gguf"),
            descriptor("sha256:b", "extra.safetensors"),
        ]);
        assert_eq!(manifest_format(&m), Some(ModelFormat::Gguf));
        let (_, m) = manifest_with(vec![
            descriptor("sha256:a", "config.json"),
            descriptor("sha256:b", "model-00001-of-00002.safetensors"),
        ]);
        assert_eq!(manifest_format(&m), Some(ModelFormat::SafeTensors));
        let mut vae = descriptor("sha256:b", "vae.safetensors");
        vae.annotations.get_or_insert_with(Default::default).insert(
            crate::hf::oci::ANNOTATION_ROLE.to_string(),
            "vae".to_string(),
        );
        let (_, m) = manifest_with(vec![descriptor("sha256:a", "ltx.gguf"), vae]);
        assert_eq!(manifest_format(&m), Some(ModelFormat::Diffusion));
        let (_, m) = manifest_with(vec![descriptor("sha256:a", "README.md")]);
        assert_eq!(manifest_format(&m), None);
    }

    #[test]
    fn gguf_shard_count_counts_only_the_primary_weights() {
        let (_, m) = manifest_with(vec![
            descriptor("sha256:a", "model-00001-of-00003.gguf"),
            descriptor("sha256:b", "model-00002-of-00003.gguf"),
            descriptor("sha256:c", "model-00003-of-00003.gguf"),
            descriptor("sha256:d", "mmproj-F16.gguf"),
        ]);
        assert_eq!(gguf_shard_count(&m), 3);
        let (_, m) = manifest_with(vec![
            descriptor("sha256:a", "model.Q4_K_M.gguf"),
            descriptor("sha256:b", "mmproj-F16.gguf"),
        ]);
        assert_eq!(gguf_shard_count(&m), 1);
        // A lone mmproj-named GGUF is the model here (see gguf_layers).
        let (_, m) = manifest_with(vec![descriptor("sha256:a", "mmproj-F16.gguf")]);
        assert_eq!(gguf_shard_count(&m), 1);
        // Several, and which one is the model is a guess.
        let (_, m) = manifest_with(vec![
            descriptor("sha256:a", "mmproj-F16.gguf"),
            descriptor("sha256:b", "mmproj-Q8.gguf"),
        ]);
        assert_eq!(gguf_shard_count(&m), 2);
    }

    /// `/api/show` reports these strings, so they are the wire contract.
    #[test]
    fn model_format_as_str_matches_model_paths_vocabulary() {
        assert_eq!(ModelFormat::Gguf.as_str(), "gguf");
        assert_eq!(ModelFormat::SafeTensors.as_str(), "safetensors");
        assert_eq!(ModelFormat::Diffusion.as_str(), "diffusion");
        assert_eq!(ModelFormat::Omni.as_str(), "omni");
    }

    /// The layers `llmman pull nvidia/Cosmos3-Edge` records (the
    /// Diffusers layout: a root pipeline index, per-component subdirs).
    fn cosmos3_layers() -> Vec<crate::storage::oci::Descriptor> {
        vec![
            descriptor("sha256:a", "config.json"),
            descriptor("sha256:b", "model_index.json"),
            descriptor("sha256:c", "scheduler/scheduler_config.json"),
            descriptor("sha256:d", "transformer/config.json"),
            descriptor(
                "sha256:e",
                "transformer/diffusion_pytorch_model-00001-of-00002.safetensors",
            ),
            descriptor("sha256:f", "vae/config.json"),
            descriptor("sha256:g", "vae/diffusion_pytorch_model.safetensors"),
            descriptor("sha256:h", "vision_encoder/model.safetensors"),
        ]
    }

    #[test]
    fn a_root_model_index_makes_a_safetensors_repo_omni() {
        let (_, m) = manifest_with(cosmos3_layers());
        assert_eq!(manifest_format(&m), Some(ModelFormat::Omni));
        // a GGUF transformer with role-annotated sidecars still wins
        let mut layers = cosmos3_layers();
        let mut vae = descriptor("sha256:z", "vae.safetensors");
        vae.annotations.get_or_insert_with(Default::default).insert(
            crate::hf::oci::ANNOTATION_ROLE.to_string(),
            "vae".to_string(),
        );
        layers.push(descriptor("sha256:y", "ltx.gguf"));
        layers.push(vae);
        let (_, m) = manifest_with(layers);
        assert_eq!(manifest_format(&m), Some(ModelFormat::Diffusion));
    }

    #[test]
    fn a_pipeline_mediagen_runs_is_diffusion_not_omni() {
        let with_index = |class: &str| {
            let (store, mut m) = manifest_with(cosmos3_layers());
            let index = store
                .write_blob(
                    "application/vnd.cncf.model.weight.config.v1.raw",
                    format!(r#"{{"_class_name": "{class}"}}"#).as_bytes(),
                )
                .unwrap();
            m.layers[1].digest = index.digest;
            stored_manifest_format(&store, &m)
        };
        assert_eq!(
            with_index("QwenImage21Pipeline"),
            Some(ModelFormat::Diffusion)
        );
        assert_eq!(with_index("Cosmos3OmniPipeline"), Some(ModelFormat::Omni));
        // an index missing from the store leaves it to vLLM-Omni
        let (store, m) = manifest_with(cosmos3_layers());
        assert_eq!(stored_manifest_format(&store, &m), Some(ModelFormat::Omni));
    }

    #[test]
    fn a_nested_model_index_or_one_without_weights_is_not_omni() {
        // A pipeline vendored inside an LLM repo does not make it one.
        let (_, m) = manifest_with(vec![
            descriptor("sha256:a", "config.json"),
            descriptor("sha256:b", "model.safetensors"),
            descriptor("sha256:c", "examples/pipeline/model_index.json"),
        ]);
        assert_eq!(manifest_format(&m), Some(ModelFormat::SafeTensors));
        // An index with nothing to serve is still nothing to serve.
        let (_, m) = manifest_with(vec![descriptor("sha256:a", "model_index.json")]);
        assert_eq!(manifest_format(&m), None);
    }

    #[test]
    fn capabilities_of_an_omni_model_are_media_even_without_recorded_outputs() {
        // Pulled before the pull recorded outputTypes: still not a chat model.
        let (store, m) = manifest_with(cosmos3_layers());
        assert_eq!(capabilities(&store, &m), vec!["image"]);
        let (store, mut m) = manifest_with(cosmos3_layers());
        m.config = store
            .write_blob(
                "application/vnd.cncf.model.config.v1+json",
                br#"{"config":{"format":"safetensors","capabilities":{"inputTypes":["text"],"outputTypes":["image","video"]}}}"#,
            )
            .unwrap();
        assert_eq!(capabilities(&store, &m), vec!["image", "video"]);
    }

    #[test]
    fn model_dir_is_the_parent_of_the_shallowest_config_json() {
        let cache = Path::new("/cache/abc");
        // Diffusers: transformer/config.json is listed before the root one.
        let dir = safetensors_model_dir(
            cache,
            &[
                "transformer/config.json",
                "vae/config.json",
                "config.json",
                "model_index.json",
            ],
        );
        assert_eq!(dir, cache);
        // A plain LLM checkout, as before.
        assert_eq!(
            safetensors_model_dir(cache, &["config.json", "model.safetensors"]),
            cache
        );
        // A repo whose only config.json is nested still resolves into it.
        assert_eq!(
            safetensors_model_dir(cache, &["sub/config.json", "sub/model.safetensors"]),
            cache.join("sub")
        );
        // A pure Diffusers repo: no root config.json, only the pipeline
        // index there and a config.json per component.
        assert_eq!(
            safetensors_model_dir(cache, &["vae/config.json", "model_index.json"]),
            cache
        );
        assert_eq!(safetensors_model_dir(cache, &["a.safetensors"]), cache);
    }

    #[test]
    fn omni_variant_reports_its_format_and_path() {
        let p = ModelPath::Omni(PathBuf::from("/cache/cosmos"));
        assert_eq!(p.format(), "omni");
        assert_eq!(p.path(), Path::new("/cache/cosmos"));
        assert_eq!(p.mmproj(), None);
    }

    #[test]
    fn extract_safetensors_dir_replaces_dest_shorter_than_layer_size() {
        let weights = b"complete-weights-bytes";
        let layer_hex = "aa".repeat(32);
        let mut layer = descriptor(&format!("sha256:{layer_hex}"), "model.safetensors");
        layer.media_type = "application/vnd.cncf.model.weight.v1.raw".into();
        layer.size = weights.len() as u64;
        let (store, manifest) = manifest_with(vec![layer]);

        let blob = store.root().join("blobs").join("sha256").join(&layer_hex);
        std::fs::create_dir_all(blob.parent().unwrap()).unwrap();
        std::fs::write(&blob, weights).unwrap();

        let cache = store.root().join("cache");
        let dest = cache.join("bb".repeat(32)).join("model.safetensors");
        std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
        std::fs::write(&dest, b"trunc").unwrap();

        let digest = format!("sha256:{}", "bb".repeat(32));
        extract_safetensors_dir(store.root(), &cache, &digest, &manifest).unwrap();
        assert_eq!(std::fs::read(&dest).unwrap(), weights);
    }

    #[test]
    fn extract_safetensors_dir_skips_dest_that_already_matches_layer_size() {
        let weights = b"complete-weights-bytes";
        let layer_hex = "aa".repeat(32);
        let mut layer = descriptor(&format!("sha256:{layer_hex}"), "model.safetensors");
        layer.media_type = "application/vnd.cncf.model.weight.v1.raw".into();
        layer.size = weights.len() as u64;
        let (store, manifest) = manifest_with(vec![layer]);

        let cache = store.root().join("cache");
        let dest = cache.join("bb".repeat(32)).join("model.safetensors");
        std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
        std::fs::write(&dest, weights).unwrap();

        let digest = format!("sha256:{}", "bb".repeat(32));
        extract_safetensors_dir(store.root(), &cache, &digest, &manifest).unwrap();
        assert_eq!(std::fs::read(&dest).unwrap(), weights);
    }

    #[cfg(unix)]
    #[test]
    fn extract_safetensors_dir_links_dest_to_blob() {
        use std::os::unix::fs::MetadataExt;

        let weights = b"complete-weights-bytes";
        let layer_hex = "aa".repeat(32);
        let mut layer = descriptor(&format!("sha256:{layer_hex}"), "model.safetensors");
        layer.media_type = "application/vnd.cncf.model.weight.v1.raw".into();
        layer.size = weights.len() as u64;
        let (store, manifest) = manifest_with(vec![layer]);

        let blob = store.root().join("blobs").join("sha256").join(&layer_hex);
        std::fs::create_dir_all(blob.parent().unwrap()).unwrap();
        std::fs::write(&blob, weights).unwrap();

        let cache = store.root().join("cache");
        let dest = cache.join("bb".repeat(32)).join("model.safetensors");
        let digest = format!("sha256:{}", "bb".repeat(32));
        extract_safetensors_dir(store.root(), &cache, &digest, &manifest).unwrap();

        let dest_meta = std::fs::metadata(&dest).unwrap();
        let blob_meta = std::fs::metadata(&blob).unwrap();
        assert_eq!(
            (dest_meta.dev(), dest_meta.ino()),
            (blob_meta.dev(), blob_meta.ino())
        );
    }

    #[cfg(unix)]
    #[test]
    fn named_blob_path_replaces_symlink_with_hardlink() {
        use std::os::unix::fs::{symlink, MetadataExt};

        let weights = b"complete-weights-bytes";
        let layer_hex = "aa".repeat(32);
        let mut layer = descriptor(&format!("sha256:{layer_hex}"), "model.safetensors");
        layer.media_type = "application/vnd.cncf.model.weight.v1.raw".into();
        layer.size = weights.len() as u64;
        let (store, _) = manifest_with(vec![layer.clone()]);

        let blob = store.root().join("blobs").join("sha256").join(&layer_hex);
        std::fs::create_dir_all(blob.parent().unwrap()).unwrap();
        std::fs::write(&blob, weights).unwrap();

        let cache = store.root().join("cache");
        let dest = cache.join(&layer_hex).join("model.safetensors");
        std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
        symlink(&blob, &dest).unwrap();

        assert_eq!(named_blob_path(store.root(), &cache, &layer).unwrap(), dest);
        assert!(!std::fs::symlink_metadata(&dest)
            .unwrap()
            .file_type()
            .is_symlink());

        let dest_meta = std::fs::metadata(&dest).unwrap();
        let blob_meta = std::fs::metadata(&blob).unwrap();
        assert_eq!(
            (dest_meta.dev(), dest_meta.ino()),
            (blob_meta.dev(), blob_meta.ino())
        );
    }

    #[test]
    fn copy_file_atomic_replaces_dest_through_temp_file() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-modelpack-copy-file-atomic-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let src = dir.join("blob");
        let dest = dir.join("model.safetensors");
        let weights = b"complete-weights-bytes";
        std::fs::write(&src, weights).unwrap();
        std::fs::write(&dest, b"trunc").unwrap();

        copy_file_atomic(&src, &dest, weights.len() as u64).unwrap();

        assert_eq!(std::fs::read(&dest).unwrap(), weights);
        assert!(
            std::fs::read_dir(&dir)
                .unwrap()
                .flatten()
                .all(|e| !e.file_name().to_string_lossy().contains(".tmp")),
            "copy temp file should not remain"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn link_or_copy_file_rejects_a_short_blob() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-modelpack-short-blob-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let src = dir.join("blob");
        let dest = dir.join("model.safetensors");
        std::fs::write(&src, b"short").unwrap();

        let error = link_or_copy_file(&src, &dest, 22).unwrap_err();
        assert!(
            error.to_string().contains("is 5 bytes, expected 22"),
            "{error:#}"
        );
        assert!(!dest.exists(), "short linked dest should be removed");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn is_gguf_layer_matches_both_mmproj_and_primary_model_files() {
        // is_mmproj_layer only narrows *within* the GGUF files a manifest
        // has — is_gguf_layer itself must still say "yes" for an mmproj
        // file, or resolve_model's gguf_layers filter would silently
        // drop it instead of finding a companion.
        assert!(is_gguf_layer(&descriptor("sha256:a", "mmproj-F16.gguf")));
        assert!(is_gguf_layer(&descriptor("sha256:b", "model.Q4_K_M.gguf")));
        assert!(!is_gguf_layer(&descriptor("sha256:c", "model.safetensors")));
    }
}