@nodetool-ai/huggingface 0.7.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/artifact-inspector.d.ts +48 -0
  2. package/dist/artifact-inspector.d.ts.map +1 -0
  3. package/dist/artifact-inspector.js +455 -0
  4. package/dist/artifact-inspector.js.map +1 -0
  5. package/dist/hf-auth.d.ts +36 -0
  6. package/dist/hf-auth.d.ts.map +1 -0
  7. package/dist/hf-auth.js +138 -0
  8. package/dist/hf-auth.js.map +1 -0
  9. package/dist/hf-cache.d.ts +94 -0
  10. package/dist/hf-cache.d.ts.map +1 -0
  11. package/dist/hf-cache.js +520 -0
  12. package/dist/hf-cache.js.map +1 -0
  13. package/dist/hf-download-manager.d.ts +51 -0
  14. package/dist/hf-download-manager.d.ts.map +1 -0
  15. package/dist/hf-download-manager.js +285 -0
  16. package/dist/hf-download-manager.js.map +1 -0
  17. package/dist/hf-downloader.d.ts +48 -0
  18. package/dist/hf-downloader.d.ts.map +1 -0
  19. package/dist/hf-downloader.js +140 -0
  20. package/dist/hf-downloader.js.map +1 -0
  21. package/dist/hf-file-info.d.ts +24 -0
  22. package/dist/hf-file-info.d.ts.map +1 -0
  23. package/dist/hf-file-info.js +35 -0
  24. package/dist/hf-file-info.js.map +1 -0
  25. package/dist/hf-hub-search.d.ts +51 -0
  26. package/dist/hf-hub-search.d.ts.map +1 -0
  27. package/dist/hf-hub-search.js +181 -0
  28. package/dist/hf-hub-search.js.map +1 -0
  29. package/dist/hf-models.d.ts +222 -0
  30. package/dist/hf-models.d.ts.map +1 -0
  31. package/dist/hf-models.js +1530 -0
  32. package/dist/hf-models.js.map +1 -0
  33. package/dist/index.d.ts +19 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +14 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/llama-cpp-download.d.ts +58 -0
  38. package/dist/llama-cpp-download.d.ts.map +1 -0
  39. package/dist/llama-cpp-download.js +204 -0
  40. package/dist/llama-cpp-download.js.map +1 -0
  41. package/dist/safetensor-layout.d.ts +45 -0
  42. package/dist/safetensor-layout.d.ts.map +1 -0
  43. package/dist/safetensor-layout.js +129 -0
  44. package/dist/safetensor-layout.js.map +1 -0
  45. package/dist/safetensors-inspector.d.ts +33 -0
  46. package/dist/safetensors-inspector.d.ts.map +1 -0
  47. package/dist/safetensors-inspector.js +613 -0
  48. package/dist/safetensors-inspector.js.map +1 -0
  49. package/package.json +47 -0
@@ -0,0 +1,1530 @@
1
+ /**
2
+ * Offline-first Hugging Face model discovery and typing utilities.
3
+ *
4
+ * Ported from the Python `huggingface_models.py`.
5
+ *
6
+ * The workflow implemented here follows a predictable sequence:
7
+ * 1. Enumerate cached repositories and snapshots via `HfFastCache` without hitting the hub.
8
+ * 2. Read lightweight metadata (sizes, filenames, artifacts) from the local snapshot to
9
+ * build `UnifiedModel` records for repos and individual files.
10
+ * 3. Infer model type and task:
11
+ * - Use local `model_index.json` / `config.json` parsing and artifact inspection
12
+ * so we can classify models even when offline or gated.
13
+ * 4. Provide targeted search helpers (by hf.* type, repo/file patterns, artifact hints).
14
+ * 5. Expose convenience lookups for common runtimes (llama.cpp GGUF).
15
+ *
16
+ * Wherever possible, the code avoids expensive I/O and network calls, preferring cached
17
+ * information and shallow file inspections to keep UI interactions fast and reliable.
18
+ */
19
+ import * as fs from "node:fs";
20
+ import * as fsp from "node:fs/promises";
21
+ import * as path from "node:path";
22
+ import * as os from "node:os";
23
+ import { HfFastCache } from "./hf-cache.js";
24
+ import { inspectPaths } from "./artifact-inspector.js";
25
+ // ---------------------------------------------------------------------------
26
+ // Constants
27
+ // ---------------------------------------------------------------------------
28
+ /**
29
+ * Extensions that identify repo-root single-file diffusion checkpoints we surface directly.
30
+ */
31
+ export const SINGLE_FILE_DIFFUSION_EXTENSIONS = [
32
+ ".safetensors",
33
+ ".ckpt",
34
+ ".bin",
35
+ ".pt",
36
+ ".pth",
37
+ ".svdq"
38
+ ];
39
+ /**
40
+ * Tags that hint at single-file diffusion checkpoints when hub metadata is present.
41
+ */
42
+ export const SINGLE_FILE_DIFFUSION_TAGS = new Set([
43
+ "diffusers",
44
+ "diffusers:stablediffusionpipeline",
45
+ "diffusers:stablediffusionxlpipeline",
46
+ "diffusers:stablediffusion3pipeline",
47
+ "diffusion-single-file",
48
+ "stable-diffusion",
49
+ "flux"
50
+ ]);
51
+ /** Default globs used when scanning repos for general-purpose weight files. */
52
+ export const HF_DEFAULT_FILE_PATTERNS = [
53
+ "*.safetensors",
54
+ "*.ckpt",
55
+ "*.gguf",
56
+ "*.bin",
57
+ "*.svdq"
58
+ ];
59
+ /** Extra globs for torch weights common in control/adapters. */
60
+ export const HF_PTH_FILE_PATTERNS = ["*.pth", "*.pt"];
61
+ /**
62
+ * Known repo-id allowlists for supported model families.
63
+ * These repos are recognized for offline type matching without hub metadata.
64
+ */
65
+ export const KNOWN_REPO_PATTERNS = {
66
+ flux: [
67
+ "Comfy-Org/flux1-dev",
68
+ "Comfy-Org/flux1-schnell",
69
+ "black-forest-labs/FLUX.1-dev",
70
+ "black-forest-labs/FLUX.1-schnell"
71
+ ],
72
+ flux_kontext: [
73
+ "black-forest-labs/FLUX.1-Kontext-dev",
74
+ "nunchaku-tech/nunchaku-flux-kontext"
75
+ ],
76
+ flux_canny: [
77
+ "black-forest-labs/FLUX.1-Canny-dev",
78
+ "nunchaku-tech/nunchaku-flux.1-canny-dev"
79
+ ],
80
+ flux_depth: [
81
+ "black-forest-labs/FLUX.1-Depth-dev",
82
+ "nunchaku-tech/nunchaku-flux.1-depth-dev"
83
+ ],
84
+ flux_vae: ["ffxvs/vae-flux"],
85
+ qwen_image: [
86
+ "Comfy-Org/Qwen-Image_ComfyUI",
87
+ "city96/Qwen-Image-gguf",
88
+ "nunchaku-tech/nunchaku-qwen-image"
89
+ ],
90
+ qwen_image_edit: ["Comfy-Org/Qwen-Image-Edit_ComfyUI"],
91
+ sd35: ["Comfy-Org/stable-diffusion-3.5-fp8"]
92
+ };
93
+ /**
94
+ * Map hf.* types to repo-id allowlists so type matching can succeed offline.
95
+ */
96
+ export const KNOWN_TYPE_REPO_MATCHERS = {
97
+ "hf.flux": [...KNOWN_REPO_PATTERNS.flux],
98
+ "hf.flux_fp8": [...KNOWN_REPO_PATTERNS.flux],
99
+ "hf.flux_kontext": [...KNOWN_REPO_PATTERNS.flux_kontext],
100
+ "hf.flux_canny": [...KNOWN_REPO_PATTERNS.flux_canny],
101
+ "hf.flux_depth": [...KNOWN_REPO_PATTERNS.flux_depth],
102
+ "hf.stable_diffusion_3": [...KNOWN_REPO_PATTERNS.sd35],
103
+ "hf.qwen_image": [
104
+ ...KNOWN_REPO_PATTERNS.qwen_image,
105
+ ...KNOWN_REPO_PATTERNS.qwen_image_edit
106
+ ],
107
+ "hf.qwen_image_edit": [...KNOWN_REPO_PATTERNS.qwen_image_edit],
108
+ "hf.qwen_vl": [
109
+ ...KNOWN_REPO_PATTERNS.qwen_image,
110
+ ...KNOWN_REPO_PATTERNS.qwen_image_edit
111
+ ],
112
+ "hf.unet": [
113
+ ...KNOWN_REPO_PATTERNS.flux,
114
+ ...KNOWN_REPO_PATTERNS.flux_kontext,
115
+ ...KNOWN_REPO_PATTERNS.flux_canny,
116
+ ...KNOWN_REPO_PATTERNS.flux_depth,
117
+ ...KNOWN_REPO_PATTERNS.qwen_image,
118
+ ...KNOWN_REPO_PATTERNS.qwen_image_edit,
119
+ ...KNOWN_REPO_PATTERNS.sd35
120
+ ],
121
+ "hf.vae": [
122
+ ...KNOWN_REPO_PATTERNS.flux_vae,
123
+ ...KNOWN_REPO_PATTERNS.qwen_image,
124
+ ...KNOWN_REPO_PATTERNS.qwen_image_edit
125
+ ],
126
+ "hf.clip": [
127
+ ...KNOWN_REPO_PATTERNS.sd35,
128
+ ...KNOWN_REPO_PATTERNS.qwen_image,
129
+ ...KNOWN_REPO_PATTERNS.qwen_image_edit
130
+ ],
131
+ "hf.t5": [...KNOWN_REPO_PATTERNS.sd35]
132
+ };
133
+ /**
134
+ * Base -> checkpoint variant mapping so heuristics propagate to single-file checkpoints.
135
+ */
136
+ export const _CHECKPOINT_BASES = {
137
+ "hf.stable_diffusion": "hf.stable_diffusion_checkpoint",
138
+ "hf.stable_diffusion_xl": "hf.stable_diffusion_xl_checkpoint",
139
+ "hf.stable_diffusion_3": "hf.stable_diffusion_3_checkpoint",
140
+ "hf.stable_diffusion_xl_refiner": "hf.stable_diffusion_xl_refiner_checkpoint",
141
+ "hf.flux": "hf.flux_checkpoint",
142
+ "hf.flux_kontext": "hf.flux_kontext_checkpoint",
143
+ "hf.flux_canny": "hf.flux_canny_checkpoint",
144
+ "hf.flux_depth": "hf.flux_depth_checkpoint",
145
+ "hf.qwen_image": "hf.qwen_image_checkpoint",
146
+ "hf.qwen_image_edit": "hf.qwen_image_edit_checkpoint"
147
+ };
148
+ /**
149
+ * Keyword hints across repo id/tags/paths to associate models with hf.* types.
150
+ */
151
+ export const HF_TYPE_KEYWORD_MATCHERS = {
152
+ "hf.stable_diffusion": ["stable-diffusion", "sd15"],
153
+ "hf.stable_diffusion_xl": ["sdxl", "stable-diffusion-xl"],
154
+ "hf.stable_diffusion_xl_refiner": ["refiner", "sdxl"],
155
+ "hf.stable_diffusion_3": ["sd3", "stable-diffusion-3"],
156
+ "hf.flux": ["flux"],
157
+ "hf.flux_fp8": ["flux", "fp8"],
158
+ "hf.flux_kontext": ["flux", "kontext", "nunchaku"],
159
+ "hf.flux_canny": ["flux", "canny", "nunchaku"],
160
+ "hf.flux_depth": ["flux", "depth", "nunchaku"],
161
+ "hf.qwen_image": ["qwen", "nunchaku"],
162
+ "hf.qwen_image_edit": ["qwen"],
163
+ "hf.qwen_vl": ["vl", "text_encoder", "text-encoder", "qwen"],
164
+ "hf.controlnet": ["control"],
165
+ "hf.controlnet_sdxl": ["control", "sdxl"],
166
+ "hf.controlnet_flux": ["control", "flux"],
167
+ "hf.ip_adapter": ["ip-adapter"],
168
+ "hf.lora_sd": ["lora"],
169
+ "hf.lora_sdxl": ["lora", "sdxl"],
170
+ "hf.lora_qwen_image": ["lora", "qwen"],
171
+ "hf.vae": ["vae"],
172
+ "hf.unet": ["unet"],
173
+ "hf.clip": ["clip"],
174
+ "hf.t5": ["t5"],
175
+ "hf.flux_redux": ["flux", "redux"],
176
+ "hf.real_esrgan": ["esrgan", "real-esrgan"]
177
+ };
178
+ // Copy keyword matchers to checkpoint variants.
179
+ for (const [base, ckpt] of Object.entries(_CHECKPOINT_BASES)) {
180
+ if (base in HF_TYPE_KEYWORD_MATCHERS && !(ckpt in HF_TYPE_KEYWORD_MATCHERS)) {
181
+ HF_TYPE_KEYWORD_MATCHERS[ckpt] = [...HF_TYPE_KEYWORD_MATCHERS[base]];
182
+ }
183
+ }
184
+ /**
185
+ * Map transformer architecture class names (from `config.json` `architectures` array)
186
+ * to hf.* types for offline model-type inference.
187
+ */
188
+ export const _CONFIG_MODEL_TYPE_ARCHITECTURE_MAPPING = {
189
+ // Causal language models (text generation)
190
+ LlamaForCausalLM: "hf.text_generation",
191
+ LlamaForSequenceClassification: "hf.text_classification",
192
+ MistralForCausalLM: "hf.text_generation",
193
+ Mistral3ForCausalLM: "hf.text_generation",
194
+ MixtralForCausalLM: "hf.text_generation",
195
+ GPT2LMHeadModel: "hf.text_generation",
196
+ GPT2ForSequenceClassification: "hf.text_classification",
197
+ GPTJForCausalLM: "hf.text_generation",
198
+ GPTNeoXForCausalLM: "hf.text_generation",
199
+ BloomForCausalLM: "hf.text_generation",
200
+ FalconForCausalLM: "hf.text_generation",
201
+ MPTForCausalLM: "hf.text_generation",
202
+ Qwen2ForCausalLM: "hf.text_generation",
203
+ Qwen3ForCausalLM: "hf.text_generation",
204
+ Qwen2_5ForCausalLM: "hf.text_generation",
205
+ PhiForCausalLM: "hf.text_generation",
206
+ Phi3ForCausalLM: "hf.text_generation",
207
+ Phi4ForCausalLM: "hf.text_generation",
208
+ GemmaForCausalLM: "hf.text_generation",
209
+ Gemma2ForCausalLM: "hf.text_generation",
210
+ Gemma3ForCausalLM: "hf.text_generation",
211
+ Gemma3nForCausalLM: "hf.text_generation",
212
+ CohereForCausalLM: "hf.text_generation",
213
+ OPTForCausalLM: "hf.text_generation",
214
+ // Encoder-only models (feature extraction / classification)
215
+ BertModel: "hf.feature_extraction",
216
+ BertForMaskedLM: "hf.feature_extraction",
217
+ BertForSequenceClassification: "hf.text_classification",
218
+ RobertaModel: "hf.feature_extraction",
219
+ RobertaForSequenceClassification: "hf.text_classification",
220
+ DistilBertModel: "hf.feature_extraction",
221
+ DistilBertForSequenceClassification: "hf.text_classification",
222
+ // Vision
223
+ CLIPModel: "hf.zero_shot_image_classification",
224
+ CLIPVisionModel: "hf.zero_shot_image_classification",
225
+ ViTModel: "hf.image_classification",
226
+ ViTForImageClassification: "hf.image_classification",
227
+ BlipForConditionalGeneration: "hf.image_to_text",
228
+ Blip2ForConditionalGeneration: "hf.image_to_text",
229
+ GitForCausalLM: "hf.image_to_text",
230
+ VisionEncoderDecoderModel: "hf.image_to_text",
231
+ Florence2ForConditionalGeneration: "hf.image_to_text",
232
+ // Audio
233
+ WhisperForConditionalGeneration: "hf.automatic_speech_recognition",
234
+ // Seq2Seq
235
+ T5ForConditionalGeneration: "hf.text2text_generation",
236
+ BartForConditionalGeneration: "hf.text2text_generation",
237
+ MBartForConditionalGeneration: "hf.translation",
238
+ MarianMTModel: "hf.translation",
239
+ // Vision-language
240
+ LlavaForConditionalGeneration: "hf.image_text_to_text",
241
+ Qwen2VLForConditionalGeneration: "hf.image_text_to_text",
242
+ Qwen2_5_VLForConditionalGeneration: "hf.image_text_to_text",
243
+ Qwen3VLForConditionalGeneration: "hf.image_text_to_text"
244
+ };
245
+ /**
246
+ * Map transformer `model_type` values to hf.* types when configs are parsed offline.
247
+ */
248
+ export const _CONFIG_MODEL_TYPE_MAPPING = {
249
+ whisper: "hf.automatic_speech_recognition",
250
+ "automatic-speech-recognition": "hf.automatic_speech_recognition",
251
+ "audio-classification": "hf.audio_classification",
252
+ "zero-shot-audio-classification": "hf.zero_shot_audio_classification",
253
+ "image-classification": "hf.image_classification",
254
+ "zero-shot-image-classification": "hf.zero_shot_image_classification",
255
+ "image-segmentation": "hf.image_segmentation",
256
+ "depth-estimation": "hf.depth_estimation",
257
+ detr: "hf.object_detection",
258
+ "object-detection": "hf.object_detection",
259
+ "zero-shot-object-detection": "hf.zero_shot_object_detection",
260
+ "visual-question-answering": "hf.visual_question_answering",
261
+ "question-answering": "hf.question_answering",
262
+ "table-question-answering": "hf.table_question_answering",
263
+ "text-classification": "hf.text_classification",
264
+ "zero-shot-classification": "hf.zero_shot_classification",
265
+ "token-classification": "hf.token_classification",
266
+ "feature-extraction": "hf.feature_extraction",
267
+ "fill-mask": "hf.fill_mask",
268
+ "text2text-generation": "hf.text2text_generation",
269
+ translation: "hf.translation",
270
+ "image-text-to-text": "hf.image_text_to_text",
271
+ "image-to-text": "hf.image_to_text",
272
+ "sentence-similarity": "hf.sentence_similarity",
273
+ reranker: "hf.reranker",
274
+ "real-esrgan": "hf.real_esrgan",
275
+ "flux-redux": "hf.flux_redux",
276
+ "text-generation": "hf.text_generation",
277
+ "text-to-audio": "hf.text_to_audio",
278
+ "text-to-speech": "hf.text_to_speech",
279
+ llama: "hf.text_generation",
280
+ gemma3: "hf.text_generation",
281
+ gemma3n: "hf.text_generation",
282
+ qwen2: "hf.text_generation",
283
+ qwen3: "hf.text_generation",
284
+ qwen_2_5_vl: "hf.text_generation",
285
+ mistral3: "hf.text_generation",
286
+ gpt_oss: "hf.text_generation",
287
+ phi3: "hf.text_generation",
288
+ phi4: "hf.text_generation",
289
+ gemma2: "hf.text_generation",
290
+ qwen_vl: "hf.image_text_to_text",
291
+ qwen_3_vl: "hf.image_text_to_text",
292
+ qwen2_5_vl: "hf.image_text_to_text",
293
+ glm4v: "hf.image_text_to_text",
294
+ blip: "hf.image_to_text",
295
+ "blip-2": "hf.image_to_text",
296
+ blip_2: "hf.image_to_text",
297
+ git: "hf.image_to_text",
298
+ florence2: "hf.image_to_text",
299
+ "vision-encoder-decoder": "hf.image_to_text",
300
+ vision_encoder_decoder: "hf.image_to_text",
301
+ bert: "hf.feature_extraction",
302
+ roberta: "hf.feature_extraction",
303
+ distilbert: "hf.feature_extraction",
304
+ clip: "hf.zero_shot_image_classification",
305
+ clip_vision_model: "hf.zero_shot_image_classification",
306
+ resnet: "hf.image_classification"
307
+ };
308
+ /**
309
+ * Diffusers pipeline class name -> hf.* type mapping.
310
+ */
311
+ export const CLASSNAME_TO_MODEL_TYPE = {
312
+ StableDiffusionPipeline: "hf.stable_diffusion",
313
+ StableDiffusionImg2ImgPipeline: "hf.stable_diffusion",
314
+ StableDiffusionInpaintPipeline: "hf.inpainting",
315
+ StableDiffusionXLPipeline: "hf.stable_diffusion_xl",
316
+ StableDiffusionXLImg2ImgPipeline: "hf.stable_diffusion_xl",
317
+ StableDiffusionXLInpaintPipeline: "hf.inpainting",
318
+ StableDiffusionXLRefinerPipeline: "hf.stable_diffusion_xl_refiner",
319
+ StableDiffusionXLControlNetPipeline: "hf.stable_diffusion_xl",
320
+ StableDiffusionUpscalePipeline: "hf.stable_diffusion_upscale",
321
+ StableDiffusion3Pipeline: "hf.stable_diffusion_3",
322
+ StableDiffusion3Img2ImgPipeline: "hf.stable_diffusion_3",
323
+ StableDiffusion3InpaintPipeline: "hf.inpainting",
324
+ PixArtAlphaPipeline: "hf.pixart_alpha",
325
+ FluxPipeline: "hf.flux",
326
+ FluxKontextPipeline: "hf.flux_kontext",
327
+ FluxDepthPipeline: "hf.flux_depth",
328
+ FluxReduxPipeline: "hf.flux_redux",
329
+ FluxFillPipeline: "hf.inpainting",
330
+ QwenImagePipeline: "hf.qwen_image",
331
+ QwenImageEditPlusPipeline: "hf.qwen_image_edit",
332
+ NunchakuQwenImageTransformer2DModel: "hf.qwen_image"
333
+ };
334
+ // ---------------------------------------------------------------------------
335
+ // RepoPackagingHint
336
+ // ---------------------------------------------------------------------------
337
+ /**
338
+ * Hint describing how a HF repo should be presented to the user.
339
+ *
340
+ * - `REPO_BUNDLE` means treat the repo as a single installable unit (typical diffusers).
341
+ * - `PER_FILE` exposes individual weights (gguf, adapters, quant variants).
342
+ * - `UNKNOWN` indicates insufficient signal; callers can pick a sensible default.
343
+ */
344
+ export var RepoPackagingHint;
345
+ (function (RepoPackagingHint) {
346
+ RepoPackagingHint["REPO_BUNDLE"] = "repo_bundle";
347
+ RepoPackagingHint["PER_FILE"] = "per_file";
348
+ RepoPackagingHint["UNKNOWN"] = "unknown";
349
+ })(RepoPackagingHint || (RepoPackagingHint = {}));
350
+ // ---------------------------------------------------------------------------
351
+ // Packaging heuristic constants
352
+ // ---------------------------------------------------------------------------
353
+ /** Filenames/extensions used to decide whether weights belong to a bundle or per-file list. */
354
+ export const _WEIGHT_EXTENSIONS = [
355
+ ".safetensors",
356
+ ".bin",
357
+ ".ckpt",
358
+ ".pt",
359
+ ".pth",
360
+ ".gguf",
361
+ ".ggml",
362
+ ".onnx",
363
+ ".svdq"
364
+ ];
365
+ export const _INDEX_FILENAMES = new Set([
366
+ "model.safetensors.index.json",
367
+ "pytorch_model.bin.index.json",
368
+ "model.bin.index.json",
369
+ "model.index.json"
370
+ ]);
371
+ /** Size/keyword thresholds that help spot adapters vs base weights. */
372
+ export const _SMALL_ADAPTER_MAX_BYTES = 30 * 1024 * 1024;
373
+ export const _QUANT_MARKERS = [
374
+ "gptq",
375
+ "awq",
376
+ "exl2",
377
+ "exl",
378
+ "q2",
379
+ "q3",
380
+ "q4",
381
+ "q5",
382
+ "q6",
383
+ "q8",
384
+ "svdq"
385
+ ];
386
+ export const _ADAPTER_MARKERS = [
387
+ "lora",
388
+ "adapter",
389
+ "embedding",
390
+ "textual_inversion",
391
+ "ti_",
392
+ "control",
393
+ "ip-adapter",
394
+ "style"
395
+ ];
396
+ // ---------------------------------------------------------------------------
397
+ // HF_SEARCH_TYPE_CONFIG
398
+ // ---------------------------------------------------------------------------
399
+ /**
400
+ * Static search hints per hf.* type used to build repo/file queries (offline/hub).
401
+ */
402
+ export const HF_SEARCH_TYPE_CONFIG = {
403
+ "hf.stable_diffusion_3": {
404
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS],
405
+ repo_pattern: [...KNOWN_REPO_PATTERNS.sd35]
406
+ },
407
+ "hf.flux": {
408
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS],
409
+ repo_pattern: [...KNOWN_REPO_PATTERNS.flux, "*flux*"]
410
+ },
411
+ "hf.flux_fp8": {
412
+ filename_pattern: [
413
+ "*fp8*.safetensors",
414
+ "*fp8*.ckpt",
415
+ "*fp8*.bin",
416
+ "*fp8*.pt",
417
+ "*fp8*.pth"
418
+ ],
419
+ repo_pattern: [...KNOWN_REPO_PATTERNS.flux, "*flux*"]
420
+ },
421
+ "hf.flux_kontext": {
422
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS],
423
+ repo_pattern: [
424
+ ...KNOWN_REPO_PATTERNS.flux_kontext,
425
+ "*nunchaku*flux*",
426
+ "*flux*kontext*"
427
+ ]
428
+ },
429
+ "hf.flux_canny": {
430
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS],
431
+ repo_pattern: [
432
+ ...KNOWN_REPO_PATTERNS.flux_canny,
433
+ "*nunchaku*flux*canny*",
434
+ "*flux*canny*"
435
+ ]
436
+ },
437
+ "hf.flux_depth": {
438
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS],
439
+ repo_pattern: [
440
+ ...KNOWN_REPO_PATTERNS.flux_depth,
441
+ "*nunchaku*flux*depth*",
442
+ "*flux*depth*"
443
+ ]
444
+ },
445
+ "hf.qwen_image": {
446
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS],
447
+ repo_pattern: [...KNOWN_REPO_PATTERNS.qwen_image]
448
+ },
449
+ "hf.qwen_image_edit": {
450
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS],
451
+ repo_pattern: [...KNOWN_REPO_PATTERNS.qwen_image_edit]
452
+ },
453
+ "hf.qwen_vl": {
454
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS],
455
+ repo_pattern: [
456
+ ...KNOWN_REPO_PATTERNS.qwen_image,
457
+ ...KNOWN_REPO_PATTERNS.qwen_image_edit
458
+ ]
459
+ },
460
+ "hf.controlnet": {
461
+ repo_pattern: ["*control*"],
462
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS, ...HF_PTH_FILE_PATTERNS]
463
+ },
464
+ "hf.controlnet_sdxl": {
465
+ repo_pattern: ["*control*"],
466
+ tag: ["*sdxl*"],
467
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS, ...HF_PTH_FILE_PATTERNS]
468
+ },
469
+ "hf.controlnet_flux": {
470
+ repo_pattern: ["*control*"],
471
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS, ...HF_PTH_FILE_PATTERNS]
472
+ },
473
+ "hf.ip_adapter": {
474
+ repo_pattern: ["*IP-Adapter*"],
475
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS, ...HF_PTH_FILE_PATTERNS]
476
+ },
477
+ "hf.lora_sd": { repo_pattern: ["*lora*"], pipeline_tag: [] },
478
+ "hf.lora_sdxl": {
479
+ repo_pattern: ["*lora*sdxl*", "*sdxl*lora*"]
480
+ },
481
+ "hf.lora_qwen_image": { repo_pattern: ["*lora*qwen*"], pipeline_tag: [] },
482
+ "hf.unet": {
483
+ repo_pattern: [
484
+ ...KNOWN_REPO_PATTERNS.flux,
485
+ ...KNOWN_REPO_PATTERNS.qwen_image,
486
+ ...KNOWN_REPO_PATTERNS.qwen_image_edit,
487
+ ...KNOWN_REPO_PATTERNS.sd35,
488
+ "*unet*",
489
+ "*stable-diffusion*"
490
+ ],
491
+ filename_pattern: [
492
+ "*unet*.safetensors",
493
+ "*unet*.bin",
494
+ "*unet*.ckpt",
495
+ "*flux*.safetensors",
496
+ "*flux*.bin",
497
+ "*flux*.ckpt"
498
+ ]
499
+ },
500
+ "hf.vae": {
501
+ repo_pattern: [
502
+ ...KNOWN_REPO_PATTERNS.flux_vae,
503
+ ...KNOWN_REPO_PATTERNS.qwen_image,
504
+ ...KNOWN_REPO_PATTERNS.qwen_image_edit,
505
+ "*vae*",
506
+ "*stable-diffusion*"
507
+ ],
508
+ filename_pattern: [
509
+ "*vae*.safetensors",
510
+ "*vae*.bin",
511
+ "*vae*.ckpt",
512
+ "*vae*.pt"
513
+ ]
514
+ },
515
+ "hf.clip": {
516
+ repo_pattern: [
517
+ ...KNOWN_REPO_PATTERNS.sd35,
518
+ ...KNOWN_REPO_PATTERNS.qwen_image,
519
+ ...KNOWN_REPO_PATTERNS.qwen_image_edit,
520
+ "*clip*",
521
+ "*flux*"
522
+ ],
523
+ filename_pattern: [
524
+ "*clip*.safetensors",
525
+ "*clip*.bin",
526
+ "*clip*.gguf",
527
+ "*clip*.ckpt"
528
+ ]
529
+ },
530
+ "hf.t5": {
531
+ repo_pattern: [...KNOWN_REPO_PATTERNS.sd35, "*t5*", "*flux*"],
532
+ filename_pattern: ["*t5*.safetensors", "*t5*.bin", "*t5*.gguf", "*t5*.ckpt"]
533
+ },
534
+ "hf.image_to_video": { pipeline_tag: ["image-to-video"] },
535
+ "hf.text_to_video": { pipeline_tag: ["text-to-video"] },
536
+ "hf.image_to_text": { pipeline_tag: ["image-to-text"], tag: ["*caption*"] },
537
+ "hf.inpainting": { pipeline_tag: ["image-inpainting"], tag: ["*inpaint*"] },
538
+ "hf.outpainting": { tag: ["*outpaint*"] },
539
+ "hf.flux_redux": {
540
+ repo_pattern: ["*flux*redux*"],
541
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS]
542
+ },
543
+ "hf.real_esrgan": {
544
+ repo_pattern: ["*esrgan*"],
545
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS]
546
+ }
547
+ };
548
+ // Derive checkpoint variants (single-file) from base configs.
549
+ for (const [base, ckpt] of Object.entries(_CHECKPOINT_BASES)) {
550
+ if (base in HF_SEARCH_TYPE_CONFIG && !(ckpt in HF_SEARCH_TYPE_CONFIG)) {
551
+ const baseCfg = HF_SEARCH_TYPE_CONFIG[base];
552
+ const derived = {};
553
+ for (const [k, v] of Object.entries(baseCfg)) {
554
+ derived[k] = Array.isArray(v) ? [...v] : v;
555
+ }
556
+ HF_SEARCH_TYPE_CONFIG[ckpt] = derived;
557
+ }
558
+ }
559
+ // ---------------------------------------------------------------------------
560
+ // HF_TYPE_STRUCTURAL_RULES
561
+ // ---------------------------------------------------------------------------
562
+ export const HF_TYPE_STRUCTURAL_RULES = {
563
+ "hf.unet": { file_only: true },
564
+ "hf.vae": { file_only: true },
565
+ "hf.clip": { file_only: true },
566
+ "hf.t5": { file_only: true },
567
+ "hf.qwen_vl": { file_only: true },
568
+ "hf.stable_diffusion_checkpoint": { file_only: true, checkpoint: true },
569
+ "hf.stable_diffusion_xl_checkpoint": { file_only: true, checkpoint: true },
570
+ "hf.stable_diffusion_3_checkpoint": { file_only: true, checkpoint: true },
571
+ "hf.stable_diffusion_xl_refiner_checkpoint": {
572
+ file_only: true,
573
+ checkpoint: true
574
+ },
575
+ "hf.flux_checkpoint": { file_only: true, checkpoint: true },
576
+ "hf.qwen_image_checkpoint": { checkpoint: true, nested_checkpoint: true },
577
+ "hf.qwen_image_edit_checkpoint": {
578
+ checkpoint: true,
579
+ nested_checkpoint: true
580
+ },
581
+ "hf.flux": { single_file_repo: true },
582
+ "hf.flux_fp8": { single_file_repo: true },
583
+ "hf.flux_redux": { single_file_repo: true },
584
+ "hf.stable_diffusion": { single_file_repo: true },
585
+ "hf.stable_diffusion_xl": { single_file_repo: true },
586
+ "hf.stable_diffusion_3": { single_file_repo: true },
587
+ "hf.stable_diffusion_xl_refiner": { single_file_repo: true }
588
+ };
589
+ // ---------------------------------------------------------------------------
590
+ // GENERIC_HF_TYPES & SUPPORTED_MODEL_TYPES
591
+ // ---------------------------------------------------------------------------
592
+ export const GENERIC_HF_TYPES = new Set([
593
+ "hf.text_to_image",
594
+ "hf.image_to_image",
595
+ "hf.model",
596
+ "hf.model_generic"
597
+ ]);
598
+ export const SUPPORTED_MODEL_TYPES = [
599
+ "qwen2",
600
+ "qwen3",
601
+ "qwen_2_5_vl",
602
+ "qwen_3_vl",
603
+ "mistral3",
604
+ "gpt_oss",
605
+ "llama",
606
+ "gemma3",
607
+ "gemma3n",
608
+ "phi3",
609
+ "phi4",
610
+ "gemma2"
611
+ ];
612
+ // ---------------------------------------------------------------------------
613
+ // Module-level state
614
+ // ---------------------------------------------------------------------------
615
+ /** Global HfFastCache instance for local snapshot lookups. */
616
+ const HF_FAST_CACHE = new HfFastCache();
617
+ const _DIFFUSION_COMPONENTS = new Set([
618
+ "unet",
619
+ "transformer_denoiser"
620
+ ]);
621
+ const _ARTIFACT_INSPECTION_LIMIT = 16;
622
+ const _DIFFUSION_REPO_CACHE = new Map();
623
+ // ---------------------------------------------------------------------------
624
+ // fnmatch-style glob matching
625
+ // ---------------------------------------------------------------------------
626
+ /**
627
+ * Convert a simple fnmatch-style pattern (with `*` and `?`) to a RegExp.
628
+ *
629
+ * This is intentionally minimal: supports `*` -> `.*` and `?` -> `.`.
630
+ * No support for `[...]` character classes, which are rarely used in HF patterns.
631
+ */
632
+ function _fnmatchToRegex(pattern) {
633
+ let regex = "^";
634
+ for (const ch of pattern) {
635
+ if (ch === "*") {
636
+ regex += ".*";
637
+ }
638
+ else if (ch === "?") {
639
+ regex += ".";
640
+ }
641
+ else if (".+^${}()|[]\\".includes(ch)) {
642
+ regex += "\\" + ch;
643
+ }
644
+ else {
645
+ regex += ch;
646
+ }
647
+ }
648
+ regex += "$";
649
+ return new RegExp(regex);
650
+ }
651
+ /** Case-sensitive glob check; empty pattern list means match everything. */
652
+ export function _matchesAnyPattern(value, patterns) {
653
+ if (patterns.length === 0)
654
+ return true;
655
+ return patterns.some((p) => _fnmatchToRegex(p).test(value));
656
+ }
657
+ /** Case-insensitive glob check used when filtering by repo id. */
658
+ export function _matchesAnyPatternCi(value, patterns) {
659
+ const valueLower = value.toLowerCase();
660
+ return patterns.some((p) => _fnmatchToRegex(p.toLowerCase()).test(valueLower));
661
+ }
662
+ // ---------------------------------------------------------------------------
663
+ // Packaging heuristic functions
664
+ // ---------------------------------------------------------------------------
665
+ /** Lightweight check for weight-like filenames used by packaging heuristics. */
666
+ export function _isWeightFile(fileName) {
667
+ const lower = fileName.toLowerCase();
668
+ return _WEIGHT_EXTENSIONS.some((ext) => lower.endsWith(ext));
669
+ }
670
+ /**
671
+ * Simplified bundle metadata detection (without ModelInfo).
672
+ * Returns false because we have no hub metadata in the offline-only path.
673
+ */
674
+ export function _hasBundleMetadata() {
675
+ return false;
676
+ }
677
+ /** Return True if filenames match common sharded checkpoint patterns. */
678
+ export function _hasShardedWeights(weightFiles) {
679
+ for (const name of weightFiles) {
680
+ const lower = name.toLowerCase();
681
+ if (_INDEX_FILENAMES.has(lower))
682
+ return true;
683
+ if (lower.includes("-00001-of-"))
684
+ return true;
685
+ if (lower.endsWith(".index.json"))
686
+ return true;
687
+ }
688
+ return false;
689
+ }
690
+ /** Identify multiple quantized flavors of a model (gguf/ggml/awq/gptq/etc.). */
691
+ export function _hasQuantizedVariants(weightFiles) {
692
+ let quantized = 0;
693
+ for (const name of weightFiles) {
694
+ const lower = name.toLowerCase();
695
+ if (lower.endsWith(".gguf") || lower.includes("ggml")) {
696
+ quantized++;
697
+ continue;
698
+ }
699
+ if (_QUANT_MARKERS.some((marker) => lower.includes(marker))) {
700
+ quantized++;
701
+ }
702
+ }
703
+ return quantized >= 2;
704
+ }
705
+ /** Flag repos containing small LoRA/adapter-like files instead of base weights. */
706
+ export function _hasAdapterCandidates(weightEntries) {
707
+ const adapterLike = [];
708
+ for (const [name, size] of weightEntries) {
709
+ const lower = name.toLowerCase();
710
+ if (_ADAPTER_MARKERS.some((marker) => lower.includes(marker))) {
711
+ adapterLike.push([name, size]);
712
+ continue;
713
+ }
714
+ if (lower.endsWith(".safetensors") &&
715
+ size > 0 &&
716
+ size < _SMALL_ADAPTER_MAX_BYTES &&
717
+ weightEntries.length > 1) {
718
+ adapterLike.push([name, size]);
719
+ }
720
+ }
721
+ return adapterLike.length >= 1;
722
+ }
723
+ /**
724
+ * Determine if a small set of weight files belong to the same family/variant.
725
+ *
726
+ * Useful to keep repos with a handful of shards/quantizations grouped together
727
+ * instead of forcing per-file selection.
728
+ */
729
+ export function _allSameFamily(weightFiles) {
730
+ if (weightFiles.length === 0 || weightFiles.length > 3)
731
+ return false;
732
+ const normalizedStems = new Set();
733
+ for (const name of weightFiles) {
734
+ const basename = path.basename(name);
735
+ const dotIdx = basename.lastIndexOf(".");
736
+ let stem = (dotIdx >= 0 ? basename.slice(0, dotIdx) : basename).toLowerCase();
737
+ for (const marker of _QUANT_MARKERS) {
738
+ stem = stem.replaceAll(marker, "");
739
+ }
740
+ normalizedStems.add(stem);
741
+ }
742
+ return normalizedStems.size === 1;
743
+ }
744
+ /**
745
+ * Guess whether a repo should be presented as a single bundle or per-file list.
746
+ *
747
+ * Simplified version without ModelInfo (no hub metadata).
748
+ */
749
+ export function detectRepoPackaging(_repoId, fileEntries) {
750
+ const weightEntries = fileEntries.filter(([name]) => _isWeightFile(name));
751
+ const weightFiles = weightEntries.map(([name]) => name);
752
+ const lowerWeightFiles = weightFiles.map((n) => n.toLowerCase());
753
+ if (_hasBundleMetadata())
754
+ return RepoPackagingHint.REPO_BUNDLE;
755
+ if (_hasShardedWeights(lowerWeightFiles))
756
+ return RepoPackagingHint.REPO_BUNDLE;
757
+ if (_hasQuantizedVariants(lowerWeightFiles))
758
+ return RepoPackagingHint.PER_FILE;
759
+ if (_hasAdapterCandidates(weightEntries))
760
+ return RepoPackagingHint.PER_FILE;
761
+ if (weightFiles.length === 1)
762
+ return RepoPackagingHint.REPO_BUNDLE;
763
+ if (_allSameFamily(weightFiles))
764
+ return RepoPackagingHint.REPO_BUNDLE;
765
+ if (weightFiles.length >= 4)
766
+ return RepoPackagingHint.PER_FILE;
767
+ return RepoPackagingHint.UNKNOWN;
768
+ }
769
+ // ---------------------------------------------------------------------------
770
+ // Single-file diffusion detection
771
+ // ---------------------------------------------------------------------------
772
+ /**
773
+ * Heuristically detect raw checkpoint files (e.g. Stable Diffusion .safetensors)
774
+ * that live at the repo root inside the HF cache.
775
+ *
776
+ * Excludes standard model weight files that are part of multi-file repos:
777
+ * - model.safetensors, pytorch_model.bin, model.bin, model.pt, model.pth
778
+ */
779
+ export function _isSingleFileDiffusionWeight(fileName) {
780
+ const normalized = fileName.replace(/\\/g, "/");
781
+ if (normalized.includes("/"))
782
+ return false;
783
+ const lower = normalized.toLowerCase();
784
+ if (!SINGLE_FILE_DIFFUSION_EXTENSIONS.some((ext) => lower.endsWith(ext))) {
785
+ return false;
786
+ }
787
+ const standardWeightNames = new Set([
788
+ "model.safetensors",
789
+ "pytorch_model.bin",
790
+ "model.bin",
791
+ "model.pt",
792
+ "model.pth"
793
+ ]);
794
+ return !standardWeightNames.has(lower);
795
+ }
796
+ /** Return true for files that might reveal diffusion components. */
797
+ export function _isDiffusionArtifactCandidate(fileName) {
798
+ const lower = fileName.toLowerCase();
799
+ if (lower.endsWith("model_index.json") || lower.endsWith("config.json")) {
800
+ return true;
801
+ }
802
+ return SINGLE_FILE_DIFFUSION_EXTENSIONS.some((ext) => lower.endsWith(ext));
803
+ }
804
+ /** Return true when artifact inspection identifies diffusion components. */
805
+ export async function _repoHasDiffusionArtifacts(repoId, snapshotDir, fileList) {
806
+ const cached = _DIFFUSION_REPO_CACHE.get(repoId);
807
+ if (cached !== undefined)
808
+ return cached;
809
+ if (!snapshotDir || fileList.length === 0) {
810
+ _DIFFUSION_REPO_CACHE.set(repoId, false);
811
+ return false;
812
+ }
813
+ const candidatePaths = [];
814
+ for (const fname of fileList) {
815
+ if (candidatePaths.length >= _ARTIFACT_INSPECTION_LIMIT)
816
+ break;
817
+ if (!_isDiffusionArtifactCandidate(fname))
818
+ continue;
819
+ candidatePaths.push(path.join(snapshotDir, fname));
820
+ }
821
+ if (candidatePaths.length === 0) {
822
+ _DIFFUSION_REPO_CACHE.set(repoId, false);
823
+ return false;
824
+ }
825
+ try {
826
+ const detection = inspectPaths(candidatePaths);
827
+ const matches = !!(detection && _DIFFUSION_COMPONENTS.has(detection.component ?? ""));
828
+ _DIFFUSION_REPO_CACHE.set(repoId, matches);
829
+ return matches;
830
+ }
831
+ catch {
832
+ _DIFFUSION_REPO_CACHE.set(repoId, false);
833
+ return false;
834
+ }
835
+ }
836
+ // ---------------------------------------------------------------------------
837
+ // File size helpers
838
+ // ---------------------------------------------------------------------------
839
+ function _getFileSize(filePath) {
840
+ try {
841
+ const stats = fs.lstatSync(filePath);
842
+ if (stats.isSymbolicLink()) {
843
+ try {
844
+ const resolved = fs.realpathSync(filePath);
845
+ const resolvedStats = fs.statSync(resolved);
846
+ return resolvedStats.size;
847
+ }
848
+ catch {
849
+ return 0;
850
+ }
851
+ }
852
+ return stats.size;
853
+ }
854
+ catch {
855
+ return 0;
856
+ }
857
+ }
858
+ /** Calculate total size and file entries for a repo, resolving paths. */
859
+ export function _calculateRepoStats(snapshotPath, fileList) {
860
+ let sizeOnDisk = 0;
861
+ const fileEntries = [];
862
+ for (const fileName of fileList ?? []) {
863
+ const filePath = path.join(snapshotPath, fileName);
864
+ const fileSize = _getFileSize(filePath);
865
+ sizeOnDisk += fileSize;
866
+ fileEntries.push([fileName, fileSize]);
867
+ }
868
+ return [sizeOnDisk, fileEntries];
869
+ }
870
+ // ---------------------------------------------------------------------------
871
+ // JSON helpers
872
+ // ---------------------------------------------------------------------------
873
+ function _safeLoadJson(filePath) {
874
+ try {
875
+ const content = fs.readFileSync(filePath, "utf-8");
876
+ return JSON.parse(content);
877
+ }
878
+ catch {
879
+ return {};
880
+ }
881
+ }
882
+ // ---------------------------------------------------------------------------
883
+ // Local config inference
884
+ // ---------------------------------------------------------------------------
885
+ /**
886
+ * Infer model type by reading cached config or model_index files when hub metadata
887
+ * is unavailable.
888
+ *
889
+ * The logic mirrors hub-side typing: prefer diffusers `_class_name`, fall back to
890
+ * `model_type`/`architectures` hints, and only touches local files that are already
891
+ * present in the snapshot.
892
+ */
893
+ export function _inferModelTypeFromLocalConfigs(fileEntries, snapshotDir) {
894
+ if (!snapshotDir)
895
+ return null;
896
+ const configCandidates = fileEntries
897
+ .map(([relPath]) => relPath)
898
+ .filter((relPath) => {
899
+ const lower = relPath.toLowerCase();
900
+ return (lower.endsWith("model_index.json") || lower.endsWith("config.json"));
901
+ });
902
+ if (configCandidates.length === 0)
903
+ return null;
904
+ // Sort by depth (fewer slashes first) then by length.
905
+ const sorted = [...configCandidates].sort((a, b) => {
906
+ const depthA = (a.match(/\//g) || []).length;
907
+ const depthB = (b.match(/\//g) || []).length;
908
+ if (depthA !== depthB)
909
+ return depthA - depthB;
910
+ return a.length - b.length;
911
+ });
912
+ for (const relPath of sorted) {
913
+ const configPath = path.join(snapshotDir, relPath);
914
+ const data = _safeLoadJson(configPath);
915
+ if (Object.keys(data).length === 0)
916
+ continue;
917
+ const className = data._class_name;
918
+ if (typeof className === "string") {
919
+ const mapped = CLASSNAME_TO_MODEL_TYPE[className];
920
+ if (mapped)
921
+ return mapped;
922
+ }
923
+ const modelType = typeof data.model_type === "string" ? data.model_type.toLowerCase() : "";
924
+ if (modelType) {
925
+ const mapped = _CONFIG_MODEL_TYPE_MAPPING[modelType];
926
+ if (mapped)
927
+ return mapped;
928
+ }
929
+ const architectures = data.architectures;
930
+ if (Array.isArray(architectures)) {
931
+ for (const arch of architectures) {
932
+ if (typeof arch !== "string")
933
+ continue;
934
+ const mapped = _CONFIG_MODEL_TYPE_ARCHITECTURE_MAPPING[arch];
935
+ if (mapped)
936
+ return mapped;
937
+ }
938
+ }
939
+ }
940
+ return null;
941
+ }
942
+ // ---------------------------------------------------------------------------
943
+ // Build cached repo entry
944
+ // ---------------------------------------------------------------------------
945
+ /**
946
+ * Build the repo-level `UnifiedModel` plus per-file metadata for a cached HF repo.
947
+ */
948
+ export async function _buildCachedRepoEntry(repoId, repoDir, snapshotDir, fileList) {
949
+ const repoRoot = await HF_FAST_CACHE.repoRoot(repoId, "model");
950
+ let fileEntries = [];
951
+ let sizeOnDisk = 0;
952
+ let snapshotPath = snapshotDir ?? null;
953
+ if (!snapshotPath) {
954
+ const resolved = await HF_FAST_CACHE.activeSnapshotDir(repoId, "model");
955
+ snapshotPath = resolved ?? null;
956
+ }
957
+ if (snapshotPath) {
958
+ if (fileList == null) {
959
+ fileList = await HF_FAST_CACHE.listFiles(repoId, "model");
960
+ }
961
+ [sizeOnDisk, fileEntries] = _calculateRepoStats(snapshotPath, fileList);
962
+ }
963
+ // Artifact inspection
964
+ let artifactDetection = null;
965
+ if (fileEntries.length > 0 && snapshotPath) {
966
+ const artifactPaths = fileEntries.map(([name]) => path.join(snapshotPath, name));
967
+ try {
968
+ artifactDetection = inspectPaths(artifactPaths);
969
+ }
970
+ catch {
971
+ artifactDetection = null;
972
+ }
973
+ }
974
+ const modelType = _inferModelTypeFromLocalConfigs(fileEntries, snapshotPath);
975
+ const repoModel = {
976
+ id: repoId,
977
+ type: modelType,
978
+ name: repoId,
979
+ cache_path: repoRoot ?? repoDir,
980
+ allow_patterns: null,
981
+ ignore_patterns: null,
982
+ description: null,
983
+ readme: null,
984
+ downloaded: repoRoot != null || fs.existsSync(repoDir),
985
+ repo_id: repoId,
986
+ path: null,
987
+ size_on_disk: sizeOnDisk,
988
+ artifact_family: artifactDetection?.family ?? null,
989
+ artifact_component: artifactDetection?.component ?? null,
990
+ artifact_confidence: artifactDetection?.confidence ?? null,
991
+ artifact_evidence: artifactDetection?.evidence ?? null
992
+ };
993
+ return [repoModel, fileEntries];
994
+ }
995
+ // ---------------------------------------------------------------------------
996
+ // Read all cached HF models
997
+ // ---------------------------------------------------------------------------
998
+ /**
999
+ * Enumerate all cached HF repos and return repo-level `UnifiedModel` entries.
1000
+ */
1001
+ export async function readCachedHfModels() {
1002
+ let repoList;
1003
+ try {
1004
+ repoList = await HF_FAST_CACHE.discoverRepos("model");
1005
+ }
1006
+ catch {
1007
+ return [];
1008
+ }
1009
+ const models = [];
1010
+ for (const { repoId, repoDir } of repoList) {
1011
+ const [repoModel] = await _buildCachedRepoEntry(repoId, repoDir);
1012
+ models.push(repoModel);
1013
+ }
1014
+ return models;
1015
+ }
1016
+ // ---------------------------------------------------------------------------
1017
+ // Search helpers
1018
+ // ---------------------------------------------------------------------------
1019
+ /** Get search configuration for a given hf.* type, or null if not found. */
1020
+ export function _buildSearchConfigForType(modelType) {
1021
+ const normalized = modelType.toLowerCase();
1022
+ const config = HF_SEARCH_TYPE_CONFIG[normalized];
1023
+ if (config !== undefined)
1024
+ return config;
1025
+ if (normalized.startsWith("hf.")) {
1026
+ return {
1027
+ filename_pattern: [...HF_DEFAULT_FILE_PATTERNS],
1028
+ repo_pattern: ["*"]
1029
+ };
1030
+ }
1031
+ return null;
1032
+ }
1033
+ /**
1034
+ * Infer a sensible HF pipeline tag from an hf.* type or explicit task override.
1035
+ */
1036
+ export function _derivePipelineTag(normalizedType, task) {
1037
+ if (task)
1038
+ return task.replace(/_/g, "-");
1039
+ const slug = normalizedType.startsWith("hf.")
1040
+ ? normalizedType.slice(3)
1041
+ : normalizedType;
1042
+ let effectiveSlug = slug;
1043
+ if (effectiveSlug.endsWith("_checkpoint")) {
1044
+ effectiveSlug = effectiveSlug.slice(0, -"_checkpoint".length);
1045
+ }
1046
+ const textToImageSlugs = new Set([
1047
+ "stable_diffusion",
1048
+ "stable_diffusion_xl",
1049
+ "stable_diffusion_xl_refiner",
1050
+ "stable_diffusion_3",
1051
+ "flux",
1052
+ "flux_fp8",
1053
+ "flux_kontext",
1054
+ "flux_canny",
1055
+ "flux_depth",
1056
+ "flux_redux",
1057
+ "qwen_image",
1058
+ "ip_adapter"
1059
+ ]);
1060
+ if (textToImageSlugs.has(effectiveSlug))
1061
+ return "text-to-image";
1062
+ const imageToImageSlugs = new Set([
1063
+ "qwen_image_edit",
1064
+ "image_to_image",
1065
+ "inpainting",
1066
+ "outpainting"
1067
+ ]);
1068
+ if (imageToImageSlugs.has(effectiveSlug))
1069
+ return "image-to-image";
1070
+ if (effectiveSlug === "text_to_video")
1071
+ return "text-to-video";
1072
+ if (effectiveSlug === "image_to_video")
1073
+ return "image-to-video";
1074
+ if (effectiveSlug.includes("text_to_image"))
1075
+ return "text-to-image";
1076
+ if (effectiveSlug.includes("image_to_image"))
1077
+ return "image-to-image";
1078
+ return effectiveSlug.replace(/_/g, "-");
1079
+ }
1080
+ /** Check if a repo id matches any hard-coded comfy-type mappings for a model type. */
1081
+ export function _matchesRepoForType(normalizedType, repoId, repoIdFromId) {
1082
+ const matchers = KNOWN_TYPE_REPO_MATCHERS[normalizedType];
1083
+ if (!matchers)
1084
+ return false;
1085
+ const repoLower = repoId.toLowerCase();
1086
+ const repoFromIdLower = repoIdFromId.toLowerCase();
1087
+ return matchers.some((candidate) => repoLower === candidate.toLowerCase() ||
1088
+ repoFromIdLower === candidate.toLowerCase());
1089
+ }
1090
+ /**
1091
+ * Use lightweight artifact inspection hints (family/component) to match a model type.
1092
+ */
1093
+ export function _matchesArtifactDetection(normalizedType, artifactFamily, artifactComponent) {
1094
+ const fam = (artifactFamily ?? "").toLowerCase();
1095
+ const comp = (artifactComponent ?? "").toLowerCase();
1096
+ if ([
1097
+ "hf.flux",
1098
+ "hf.flux_fp8",
1099
+ "hf.flux_kontext",
1100
+ "hf.flux_canny",
1101
+ "hf.flux_depth"
1102
+ ].includes(normalizedType)) {
1103
+ return fam.includes("flux");
1104
+ }
1105
+ if (normalizedType === "hf.stable_diffusion") {
1106
+ return (fam.startsWith("sd1") ||
1107
+ fam.startsWith("sd2") ||
1108
+ fam.includes("stable-diffusion"));
1109
+ }
1110
+ if (normalizedType === "hf.stable_diffusion_xl") {
1111
+ return fam.includes("sdxl");
1112
+ }
1113
+ if (normalizedType === "hf.stable_diffusion_xl_refiner") {
1114
+ return fam.includes("refiner") || (fam.includes("sdxl") && comp === "unet");
1115
+ }
1116
+ if (normalizedType === "hf.stable_diffusion_3") {
1117
+ return fam.includes("sd3") || fam.includes("stable-diffusion-3");
1118
+ }
1119
+ if (normalizedType === "hf.qwen_image" ||
1120
+ normalizedType === "hf.qwen_image_edit") {
1121
+ return fam.includes("qwen");
1122
+ }
1123
+ return false;
1124
+ }
1125
+ /** Semantic match for hf.* types (no structural checks here). */
1126
+ export function _matchesModelType(model, modelType) {
1127
+ let normalizedType = modelType.toLowerCase();
1128
+ let checkpointVariant = null;
1129
+ if (normalizedType.endsWith("_checkpoint")) {
1130
+ checkpointVariant = normalizedType;
1131
+ normalizedType = normalizedType.slice(0, -"_checkpoint".length);
1132
+ }
1133
+ const modelTypeLower = (model.type ?? "").toLowerCase();
1134
+ const repoId = (model.repo_id ?? "").toLowerCase();
1135
+ const repoIdFromId = model.id ? model.id.split(":")[0].toLowerCase() : "";
1136
+ const pathLower = (model.path ?? "").toLowerCase();
1137
+ function isQwenTextEncoder(p) {
1138
+ if (!p)
1139
+ return false;
1140
+ return (p.includes("text_encoders") ||
1141
+ p.includes("text_encoder") ||
1142
+ p.includes("qwen_2.5_vl"));
1143
+ }
1144
+ function isQwenVae(p) {
1145
+ if (!p)
1146
+ return false;
1147
+ return p.includes("vae");
1148
+ }
1149
+ const targetTypes = new Set([normalizedType]);
1150
+ if (checkpointVariant)
1151
+ targetTypes.add(checkpointVariant);
1152
+ if (modelTypeLower) {
1153
+ const modelTypeBase = modelTypeLower.endsWith("_checkpoint")
1154
+ ? modelTypeLower.slice(0, -"_checkpoint".length)
1155
+ : modelTypeLower;
1156
+ if (targetTypes.has(modelTypeLower) || modelTypeBase === normalizedType) {
1157
+ return !((normalizedType === "hf.qwen_image" ||
1158
+ normalizedType === "hf.qwen_image_edit") &&
1159
+ (isQwenTextEncoder(pathLower) || isQwenVae(pathLower)));
1160
+ }
1161
+ if (!GENERIC_HF_TYPES.has(modelTypeLower)) {
1162
+ const qwenFamilyTypes = new Set([
1163
+ "hf.qwen_image",
1164
+ "hf.qwen_image_checkpoint"
1165
+ ]);
1166
+ const allowedFamily = (normalizedType === "hf.qwen_image_checkpoint" ||
1167
+ normalizedType === "hf.qwen_vl" ||
1168
+ normalizedType === "hf.vae") &&
1169
+ qwenFamilyTypes.has(modelTypeLower);
1170
+ if (!allowedFamily)
1171
+ return false;
1172
+ }
1173
+ }
1174
+ if (normalizedType === "hf.qwen_image" ||
1175
+ normalizedType === "hf.qwen_image_edit") {
1176
+ if (isQwenTextEncoder(pathLower) || isQwenVae(pathLower))
1177
+ return false;
1178
+ }
1179
+ if (normalizedType === "hf.qwen_vl") {
1180
+ return isQwenTextEncoder(pathLower);
1181
+ }
1182
+ if (_matchesRepoForType(normalizedType, repoId, repoIdFromId))
1183
+ return true;
1184
+ const artifactFamily = (model.artifact_family ?? "").toLowerCase();
1185
+ const artifactComponent = (model.artifact_component ?? "").toLowerCase();
1186
+ if (artifactFamily || artifactComponent) {
1187
+ if (_matchesArtifactDetection(normalizedType, artifactFamily, artifactComponent)) {
1188
+ return true;
1189
+ }
1190
+ }
1191
+ const tags = (model.tags ?? []).map((t) => (t ?? "").toLowerCase());
1192
+ const keywords = HF_TYPE_KEYWORD_MATCHERS[normalizedType] ?? [];
1193
+ if (keywords.length > 0) {
1194
+ if (keywords.some((keyword) => repoId.includes(keyword) || tags.some((tag) => tag.includes(keyword)))) {
1195
+ return true;
1196
+ }
1197
+ if (pathLower && keywords.some((keyword) => pathLower.includes(keyword))) {
1198
+ return true;
1199
+ }
1200
+ }
1201
+ const derivedPipeline = _derivePipelineTag(normalizedType);
1202
+ return !!(derivedPipeline && model.pipeline_tag === derivedPipeline);
1203
+ }
1204
+ /**
1205
+ * Yield (repoId, repoDir, snapshotDir, fileList) for cached HF repos.
1206
+ * Returns the full list since TS does not have native async generators
1207
+ * that are universally ergonomic.
1208
+ */
1209
+ async function _iterCachedModelFiles(preResolvedRepos) {
1210
+ const repoList = preResolvedRepos ?? (await HF_FAST_CACHE.discoverRepos("model"));
1211
+ const results = [];
1212
+ for (const { repoId, repoDir } of repoList) {
1213
+ const snapshotDir = await HF_FAST_CACHE.activeSnapshotDir(repoId, "model");
1214
+ if (!snapshotDir)
1215
+ continue;
1216
+ let fileList;
1217
+ try {
1218
+ fileList = await HF_FAST_CACHE.listFiles(repoId, "model");
1219
+ }
1220
+ catch {
1221
+ continue;
1222
+ }
1223
+ results.push({ repoId, repoDir, snapshotDir, fileList });
1224
+ }
1225
+ return results;
1226
+ }
1227
+ // ---------------------------------------------------------------------------
1228
+ // Search cached models
1229
+ // ---------------------------------------------------------------------------
1230
+ /**
1231
+ * Search the local HF cache for repos/files using offline data only.
1232
+ */
1233
+ export async function searchCachedHfModels(repoPatterns, filenamePatterns) {
1234
+ const results = [];
1235
+ const cachedFiles = await _iterCachedModelFiles();
1236
+ for (const { repoId, repoDir, snapshotDir, fileList } of cachedFiles) {
1237
+ if (repoPatterns &&
1238
+ repoPatterns.length > 0 &&
1239
+ !_matchesAnyPatternCi(repoId, [...repoPatterns])) {
1240
+ continue;
1241
+ }
1242
+ const [repoModel, fileEntries] = await _buildCachedRepoEntry(repoId, repoDir, snapshotDir, fileList);
1243
+ results.push(repoModel);
1244
+ if (filenamePatterns &&
1245
+ filenamePatterns.length > 0 &&
1246
+ fileEntries.length > 0) {
1247
+ for (const [relativeName, fileSize] of fileEntries) {
1248
+ if (!_matchesAnyPattern(relativeName, [...filenamePatterns]))
1249
+ continue;
1250
+ const fileModel = {
1251
+ id: `${repoId}:${relativeName}`,
1252
+ type: repoModel.type,
1253
+ name: `${repoId}/${relativeName}`,
1254
+ repo_id: repoId,
1255
+ path: relativeName,
1256
+ cache_path: repoModel.cache_path ?? null,
1257
+ allow_patterns: null,
1258
+ ignore_patterns: null,
1259
+ description: null,
1260
+ readme: null,
1261
+ size_on_disk: fileSize,
1262
+ downloaded: repoModel.downloaded ?? null,
1263
+ pipeline_tag: repoModel.pipeline_tag ?? null,
1264
+ tags: repoModel.tags ?? null,
1265
+ has_model_index: repoModel.has_model_index ?? null,
1266
+ downloads: repoModel.downloads ?? null,
1267
+ likes: repoModel.likes ?? null,
1268
+ trending_score: repoModel.trending_score ?? null,
1269
+ artifact_family: repoModel.artifact_family ?? null,
1270
+ artifact_component: repoModel.artifact_component ?? null,
1271
+ artifact_confidence: repoModel.artifact_confidence ?? null,
1272
+ artifact_evidence: repoModel.artifact_evidence ?? null
1273
+ };
1274
+ results.push(fileModel);
1275
+ }
1276
+ }
1277
+ }
1278
+ return results;
1279
+ }
1280
+ // ---------------------------------------------------------------------------
1281
+ // Get models by hf type
1282
+ // ---------------------------------------------------------------------------
1283
+ /**
1284
+ * Return cached Hugging Face models matching a requested hf.* type.
1285
+ *
1286
+ * The search is entirely offline: build a search config, scan cached repos/files,
1287
+ * then apply the same client-side heuristics (keyword matching, repo patterns,
1288
+ * artifact hints) to label each result with the desired type.
1289
+ */
1290
+ export async function getModelsByHfType(modelType) {
1291
+ const config = _buildSearchConfigForType(modelType) ?? {};
1292
+ const repoPattern = config.repo_pattern;
1293
+ const filenamePattern = config.filename_pattern;
1294
+ function filterModels(models) {
1295
+ const rules = HF_TYPE_STRUCTURAL_RULES[modelType] ?? {};
1296
+ const fileOnly = rules.file_only ?? false;
1297
+ const checkpoint = rules.checkpoint ?? Object.values(_CHECKPOINT_BASES).includes(modelType);
1298
+ const nestedCheckpoint = rules.nested_checkpoint ?? false;
1299
+ const singleFileRepo = rules.single_file_repo ?? false;
1300
+ const seen = new Set();
1301
+ const filtered = [];
1302
+ for (const model of models) {
1303
+ if (seen.has(model.id))
1304
+ continue;
1305
+ const repoLower = (model.repo_id ?? "").toLowerCase();
1306
+ const pathValue = model.path ?? null;
1307
+ if (fileOnly && pathValue == null)
1308
+ continue;
1309
+ if (singleFileRepo) {
1310
+ if (pathValue == null && repoLower.includes("gguf"))
1311
+ continue;
1312
+ if (pathValue != null) {
1313
+ const pathLower = pathValue.toLowerCase();
1314
+ if (!_isSingleFileDiffusionWeight(pathValue) &&
1315
+ !pathLower.endsWith(".gguf")) {
1316
+ continue;
1317
+ }
1318
+ }
1319
+ }
1320
+ if (checkpoint) {
1321
+ if (!pathValue)
1322
+ continue;
1323
+ if (pathValue.includes("/") && !nestedCheckpoint)
1324
+ continue;
1325
+ }
1326
+ // For non-file-oriented types, skip file-level entries to avoid duplicates
1327
+ if (!fileOnly && !checkpoint && !singleFileRepo && pathValue != null)
1328
+ continue;
1329
+ if (!_matchesModelType(model, modelType))
1330
+ continue;
1331
+ filtered.push(model);
1332
+ seen.add(model.id);
1333
+ }
1334
+ return filtered;
1335
+ }
1336
+ const offlineModels = await searchCachedHfModels(repoPattern
1337
+ ? Array.isArray(repoPattern)
1338
+ ? repoPattern
1339
+ : [repoPattern]
1340
+ : null, filenamePattern
1341
+ ? Array.isArray(filenamePattern)
1342
+ ? filenamePattern
1343
+ : [filenamePattern]
1344
+ : null);
1345
+ return filterModels(offlineModels);
1346
+ }
1347
+ // ---------------------------------------------------------------------------
1348
+ // Delete cached model
1349
+ // ---------------------------------------------------------------------------
1350
+ /**
1351
+ * Delete a model from the Hugging Face cache.
1352
+ */
1353
+ export async function deleteCachedHfModel(modelId) {
1354
+ const repoRoot = await HF_FAST_CACHE.repoRoot(modelId, "model");
1355
+ if (!repoRoot)
1356
+ return false;
1357
+ try {
1358
+ await fsp.access(repoRoot);
1359
+ }
1360
+ catch {
1361
+ return false;
1362
+ }
1363
+ await fsp.rm(repoRoot, { recursive: true, force: true });
1364
+ await HF_FAST_CACHE.invalidate(modelId, "model");
1365
+ return true;
1366
+ }
1367
+ // ---------------------------------------------------------------------------
1368
+ // Llama.cpp cache helpers
1369
+ // ---------------------------------------------------------------------------
1370
+ /**
1371
+ * Resolve the llama.cpp native cache directory.
1372
+ */
1373
+ function _getLlamaCppCacheDir() {
1374
+ const platform = os.platform();
1375
+ if (platform === "darwin") {
1376
+ return path.join(os.homedir(), "Library", "Caches", "llama.cpp");
1377
+ }
1378
+ if (platform === "win32") {
1379
+ const localAppData = process.env.LOCALAPPDATA ?? path.join(os.homedir(), "AppData", "Local");
1380
+ return path.join(localAppData, "llama.cpp");
1381
+ }
1382
+ // Linux and others
1383
+ return path.join(os.homedir(), ".cache", "llama.cpp");
1384
+ }
1385
+ /** Build a lookup from flat GGUF filename to (repo_id, original_filename). */
1386
+ export function _buildManifestLookup(cacheDir) {
1387
+ const lookup = new Map();
1388
+ let entries;
1389
+ try {
1390
+ entries = fs.readdirSync(cacheDir);
1391
+ }
1392
+ catch {
1393
+ return lookup;
1394
+ }
1395
+ for (const entry of entries) {
1396
+ if (!entry.startsWith("manifest=") || !entry.endsWith(".json"))
1397
+ continue;
1398
+ try {
1399
+ const filePath = path.join(cacheDir, entry);
1400
+ const content = fs.readFileSync(filePath, "utf-8");
1401
+ const manifest = JSON.parse(content);
1402
+ const metadata = manifest.metadata;
1403
+ const ggufFile = manifest.ggufFile;
1404
+ const repoId = (metadata?.repo_id ?? "");
1405
+ const rfilename = (ggufFile?.rfilename ?? "");
1406
+ if (repoId && rfilename) {
1407
+ const flatName = `${repoId.replace("/", "_")}_${rfilename}`;
1408
+ lookup.set(flatName, [repoId, rfilename]);
1409
+ }
1410
+ }
1411
+ catch {
1412
+ continue;
1413
+ }
1414
+ }
1415
+ return lookup;
1416
+ }
1417
+ /**
1418
+ * Parse a flat llama.cpp GGUF filename into (repo_id, repo_name, filename).
1419
+ *
1420
+ * Resolution order:
1421
+ * 1. Exact match in manifest lookup (most reliable).
1422
+ * 2. Heuristic split on the first underscore to obtain the HuggingFace org.
1423
+ * 3. Fallback: return ("", "", entry).
1424
+ */
1425
+ export function _parseGgufFlatFilename(entry, manifestLookup) {
1426
+ // 1. Manifest lookup
1427
+ const manifestMatch = manifestLookup.get(entry);
1428
+ if (manifestMatch) {
1429
+ const [repoId, filename] = manifestMatch;
1430
+ const repo = repoId.includes("/") ? repoId.split("/")[1] : repoId;
1431
+ return [repoId, repo, filename];
1432
+ }
1433
+ // 2. Heuristic: org is before the first underscore
1434
+ const firstUs = entry.indexOf("_");
1435
+ if (firstUs < 0)
1436
+ return ["", "", entry];
1437
+ const org = entry.slice(0, firstUs);
1438
+ const rest = entry.slice(firstUs + 1); // "{repo}_{filename}"
1439
+ let idx = 0;
1440
+ while (true) {
1441
+ const us = rest.indexOf("_", idx);
1442
+ if (us < 0)
1443
+ break;
1444
+ const repoCandidate = rest.slice(0, us);
1445
+ const filenameCandidate = rest.slice(us + 1);
1446
+ const expected = `${org}_${repoCandidate}_${filenameCandidate}`;
1447
+ if (expected === entry &&
1448
+ filenameCandidate.toLowerCase().endsWith(".gguf")) {
1449
+ const repoId = `${org}/${repoCandidate}`;
1450
+ return [repoId, repoCandidate, filenameCandidate];
1451
+ }
1452
+ idx = us + 1;
1453
+ }
1454
+ // 3. Fallback
1455
+ return ["", "", entry];
1456
+ }
1457
+ /**
1458
+ * Enumerate GGUF models in the llama.cpp native cache directory.
1459
+ *
1460
+ * llama.cpp uses a flat file structure:
1461
+ * - {org}_{repo}_{filename}.gguf
1462
+ * - {org}_{repo}_{filename}.gguf.etag
1463
+ * - manifest={org}={repo}={tag}.json
1464
+ */
1465
+ export async function getLlamaCppModelsFromCache() {
1466
+ const cacheDir = _getLlamaCppCacheDir();
1467
+ try {
1468
+ const stat = await fsp.stat(cacheDir);
1469
+ if (!stat.isDirectory())
1470
+ return [];
1471
+ }
1472
+ catch {
1473
+ return [];
1474
+ }
1475
+ const manifestLookup = _buildManifestLookup(cacheDir);
1476
+ const models = [];
1477
+ let entries;
1478
+ try {
1479
+ entries = await fsp.readdir(cacheDir);
1480
+ }
1481
+ catch {
1482
+ return [];
1483
+ }
1484
+ for (const entry of entries) {
1485
+ if (!entry.toLowerCase().endsWith(".gguf"))
1486
+ continue;
1487
+ if (entry.endsWith(".etag"))
1488
+ continue;
1489
+ const filePath = path.join(cacheDir, entry);
1490
+ try {
1491
+ const stat = await fsp.stat(filePath);
1492
+ if (!stat.isFile())
1493
+ continue;
1494
+ }
1495
+ catch {
1496
+ continue;
1497
+ }
1498
+ const [repoId, repo, filename] = _parseGgufFlatFilename(entry, manifestLookup);
1499
+ let size = 0;
1500
+ try {
1501
+ const stat = await fsp.stat(filePath);
1502
+ size = stat.size;
1503
+ }
1504
+ catch {
1505
+ // ignore
1506
+ }
1507
+ models.push({
1508
+ id: repoId ? `${repoId}:${filename}` : filename,
1509
+ type: "llama_cpp_model",
1510
+ name: repoId
1511
+ ? `${repo.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())} \u2022 ${filename}`
1512
+ : filename,
1513
+ repo_id: repoId || null,
1514
+ path: filename,
1515
+ cache_path: filePath,
1516
+ size_on_disk: size,
1517
+ downloaded: true
1518
+ });
1519
+ }
1520
+ // Sort for stability
1521
+ models.sort((a, b) => {
1522
+ const repoA = a.repo_id ?? "";
1523
+ const repoB = b.repo_id ?? "";
1524
+ if (repoA !== repoB)
1525
+ return repoA.localeCompare(repoB);
1526
+ return (a.path ?? "").localeCompare(b.path ?? "");
1527
+ });
1528
+ return models;
1529
+ }
1530
+ //# sourceMappingURL=hf-models.js.map