@simplexai/localmodels-win32-x64 0.1.0-dev.59 → 0.1.0-dev.61

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 (134) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +126 -107
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +107 -44
  5. package/modules/localmodels/apple_sensors.py +431 -0
  6. package/modules/localmodels/auth_proxy.py +185 -19
  7. package/modules/localmodels/bifrost_admin.py +30 -0
  8. package/modules/localmodels/bifrost_checks.py +2 -2
  9. package/modules/localmodels/bifrost_config.py +132 -9
  10. package/modules/localmodels/bifrost_models.py +1 -1
  11. package/modules/localmodels/catalog.json +509 -54
  12. package/modules/localmodels/catalog.py +21 -4
  13. package/modules/localmodels/catalog_add.py +42 -11
  14. package/modules/localmodels/catalog_license.py +2 -0
  15. package/modules/localmodels/catalog_recipes.py +2 -0
  16. package/modules/localmodels/cli_parser.py +6 -2
  17. package/modules/localmodels/context_policy.py +40 -4
  18. package/modules/localmodels/custom_hub.py +983 -0
  19. package/modules/localmodels/custom_hub_http.py +579 -0
  20. package/modules/localmodels/custom_probe.py +451 -0
  21. package/modules/localmodels/debug_mode.py +13 -0
  22. package/modules/localmodels/debug_stub_server.py +156 -1
  23. package/modules/localmodels/deploy.py +38 -7
  24. package/modules/localmodels/deploy_steps.py +5 -0
  25. package/modules/localmodels/download-mirrors.json +20 -0
  26. package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
  27. package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
  28. package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
  29. package/modules/localmodels/engines-whisper-b5454.json +120 -1
  30. package/modules/localmodels/engines.py +38 -8
  31. package/modules/localmodels/estimator.py +60 -7
  32. package/modules/localmodels/gateway.py +48 -3
  33. package/modules/localmodels/gateway_app_bifrost.py +18 -18
  34. package/modules/localmodels/gateway_bifrost.py +102 -16
  35. package/modules/localmodels/gateway_cli.py +14 -80
  36. package/modules/localmodels/gateway_server.py +88 -16
  37. package/modules/localmodels/gguf.py +6 -0
  38. package/modules/localmodels/gpu_specs.py +35 -1
  39. package/modules/localmodels/harness.py +1 -2
  40. package/modules/localmodels/hf_repo.py +12 -4
  41. package/modules/localmodels/host_sensors.py +704 -0
  42. package/modules/localmodels/install.py +4 -4
  43. package/modules/localmodels/library_cli.py +181 -3
  44. package/modules/localmodels/library_custom.py +831 -0
  45. package/modules/localmodels/library_elastic.py +35 -7
  46. package/modules/localmodels/library_gateway.py +94 -32
  47. package/modules/localmodels/library_jobs.py +76 -11
  48. package/modules/localmodels/library_kept.py +50 -6
  49. package/modules/localmodels/library_model.py +254 -2
  50. package/modules/localmodels/library_pricing.py +83 -4
  51. package/modules/localmodels/library_serve.py +178 -60
  52. package/modules/localmodels/library_smoke.py +315 -0
  53. package/modules/localmodels/library_state.py +77 -1
  54. package/modules/localmodels/library_status.py +126 -4
  55. package/modules/localmodels/npm_transport.py +4 -58
  56. package/modules/localmodels/nvml_ctypes.py +431 -0
  57. package/modules/localmodels/plan_envelope.py +14 -6
  58. package/modules/localmodels/recommend_cli.py +2 -1
  59. package/modules/localmodels/records.py +1 -0
  60. package/modules/localmodels/remote_ops.py +120 -665
  61. package/modules/localmodels/remote_ops_common.py +729 -0
  62. package/modules/localmodels/remote_ops_download.py +396 -241
  63. package/modules/localmodels/remote_ops_mirrors.py +26 -65
  64. package/modules/localmodels/remote_ops_prepare.py +43 -35
  65. package/modules/localmodels/remote_ops_ranges.py +98 -65
  66. package/modules/localmodels/remote_ops_remove.py +30 -22
  67. package/modules/localmodels/remote_ops_service.py +103 -95
  68. package/modules/localmodels/remote_ops_verify.py +113 -65
  69. package/modules/localmodels/runtime-lock.json +19 -19
  70. package/modules/localmodels/runtime_cli.py +15 -5
  71. package/modules/localmodels/runtime_io.py +54 -1
  72. package/modules/localmodels/service_control.py +32 -1
  73. package/modules/localmodels/service_wiring.py +2 -3
  74. package/modules/localmodels/service_worker.py +6 -2
  75. package/modules/localmodels/services_cli.py +35 -27
  76. package/modules/localmodels/source_byok.py +3 -5
  77. package/modules/localmodels/speech-sv.txt +93 -0
  78. package/modules/localmodels/speech_admission.py +437 -0
  79. package/modules/localmodels/speech_catalog.py +170 -0
  80. package/modules/localmodels/speech_cli.py +273 -0
  81. package/modules/localmodels/speech_jobs.py +772 -0
  82. package/modules/localmodels/speech_model.py +404 -0
  83. package/modules/localmodels/speech_serve.py +287 -0
  84. package/modules/localmodels/speech_server.py +837 -0
  85. package/modules/localmodels/speech_state.py +697 -0
  86. package/modules/localmodels/speech_worker_sensevoice.py +255 -0
  87. package/modules/localmodels/speech_workers.py +783 -0
  88. package/modules/localmodels/stack.py +0 -33
  89. package/modules/localmodels/stack_auto.py +5 -3
  90. package/modules/localmodels/stack_aux_gpu.py +45 -4
  91. package/modules/localmodels/stack_capacity.py +77 -8
  92. package/modules/localmodels/stack_cli.py +16 -1
  93. package/modules/localmodels/stack_compose.py +1 -1
  94. package/modules/localmodels/stack_down.py +24 -1
  95. package/modules/localmodels/stack_hardware.py +57 -88
  96. package/modules/localmodels/stack_hardware_text.py +4 -59
  97. package/modules/localmodels/stack_lifecycle.py +2 -2
  98. package/modules/localmodels/stack_memory.py +14 -3
  99. package/modules/localmodels/stack_suite.py +9 -10
  100. package/modules/localmodels/stack_summary.py +4 -4
  101. package/modules/localmodels/stack_view.py +77 -53
  102. package/modules/localmodels/stack_view_demo.py +36 -5
  103. package/modules/localmodels/stack_view_events.py +147 -12
  104. package/modules/localmodels/stack_view_gpu.py +97 -17
  105. package/modules/localmodels/stack_view_llm.py +16 -1
  106. package/modules/localmodels/stack_view_measure.py +4 -1
  107. package/modules/localmodels/stack_view_schema.py +54 -8
  108. package/modules/localmodels/stack_view_serve.py +40 -3
  109. package/modules/localmodels/stack_view_slots.py +89 -10
  110. package/modules/localmodels/stack_view_telemetry.py +163 -0
  111. package/modules/localmodels/stack_view_text.py +5 -2
  112. package/modules/localmodels/stack_view_tick.py +658 -0
  113. package/modules/localmodels/stack_view_words.py +4 -0
  114. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.5.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
  115. package/modules/localmodels/suite.py +3 -1
  116. package/modules/localmodels/telemetry_math.py +538 -0
  117. package/modules/localmodels/transport.py +3 -2
  118. package/modules/localmodels/tui_views.py +2 -2
  119. package/modules/localmodels/web/view/view.js +1 -1
  120. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
  121. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +123 -104
  122. package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/NOTICE +9 -0
  123. package/package.json +1 -1
  124. package/tool.json +1 -1
  125. package/modules/localmodels/bifrost_datasheet.py +0 -53
  126. package/modules/localmodels/bifrost_provider.py +0 -88
  127. package/modules/localmodels/bifrost_unit.py +0 -99
  128. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +0 -94
  129. package/modules/localmodels/gateway_switch.py +0 -51
  130. package/modules/localmodels/library_floor.py +0 -78
  131. package/modules/localmodels/service_stop.py +0 -52
  132. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
  133. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
  134. /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,831 @@
1
+ """State-mutating custom Hub download and isolated registration for ``localmodels library custom``.
2
+
3
+ Downloads community GGUF models from Hugging Face or ModelScope into an isolated directory tree
4
+ ``<base_dir>/models/custom/<hub>/<owner>/<repo>/<rev>/<rel_path>``, enforces a hard 1.1x disk
5
+ headroom check (never bypassable) and memory admission (bypassable with ``force_memory``), pins
6
+ custom models to the newest bundled llama.cpp engine lock, and leaves downloaded models in
7
+ ``state: "idle"`` with ``verification.status: "untested"`` and ``standby_on_restart: True``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import re
14
+ import urllib.parse
15
+ from collections.abc import Mapping
16
+ from pathlib import Path
17
+ from typing import Any, cast
18
+
19
+ from localmodels import (
20
+ budget,
21
+ catalog_add,
22
+ custom_hub,
23
+ custom_probe,
24
+ deploy,
25
+ engines,
26
+ gguf,
27
+ hosts,
28
+ library_gateway,
29
+ library_jobs,
30
+ library_pricing,
31
+ library_state,
32
+ library_status,
33
+ plan_envelope,
34
+ remote_ops,
35
+ )
36
+ from localmodels.gguf import GGUFHeader
37
+ from localmodels.library_model import (
38
+ CustomHub,
39
+ LibraryError,
40
+ Row,
41
+ split_id,
42
+ )
43
+ from localmodels.library_state import CustomMeta, Job, JobHandle, Record
44
+ from localmodels.probe import HostFacts
45
+ from localmodels.records import Plan, ReusableFile
46
+
47
+ CUSTOM_ENGINE_TAG = "b12588-mix-c0c3de8"
48
+ _SAFE_SEGMENT_RE = re.compile(r"[^a-z0-9._-]+")
49
+ _REV_SAFE_RE = re.compile(r"[^a-zA-Z0-9._-]+")
50
+
51
+
52
+ def _slug(value: str) -> str:
53
+ cleaned = _SAFE_SEGMENT_RE.sub("-", value.strip().lower()).strip(".-_")
54
+ return cleaned or "model"
55
+
56
+
57
+ def _safe_rel_path(raw: str) -> str:
58
+ parts = [part for part in raw.replace("\\", "/").split("/") if part and part != "."]
59
+ if not parts or any(part == ".." for part in parts):
60
+ raise LibraryError("INVALID_REPO_SPEC", f"unsafe file path in repository: {raw!r}")
61
+ return "/".join(parts)
62
+
63
+
64
+ def _custom_local_name(hub: CustomHub, repo_id: str, revision: str, rel_path: str) -> str:
65
+ hub_short = "hf" if hub == "huggingface" else "ms"
66
+ owner, _, name = repo_id.partition("/")
67
+ rev_short = _REV_SAFE_RE.sub("-", (revision or "main").strip())[:12].strip("-") or "main"
68
+ return f"custom/{hub_short}/{_slug(owner)}/{_slug(name)}/{rev_short}/{_safe_rel_path(rel_path)}"
69
+
70
+
71
+ def _parse_download_payload(
72
+ payload: Mapping[str, object],
73
+ ) -> tuple[
74
+ CustomHub,
75
+ str,
76
+ str | None,
77
+ str,
78
+ list[str] | None,
79
+ str,
80
+ bool,
81
+ bool,
82
+ str | None,
83
+ ]:
84
+ raw_hub = str(payload.get("hub") or "").strip().lower()
85
+ if raw_hub not in ("huggingface", "modelscope"):
86
+ raise LibraryError(
87
+ "INVALID_REPO_SPEC", f"hub must be huggingface or modelscope, got {raw_hub!r}"
88
+ )
89
+ raw_repo = payload.get("repo_id")
90
+ if not isinstance(raw_repo, str) or not raw_repo.strip():
91
+ raise LibraryError("INVALID_REPO_SPEC", "repo_id is required")
92
+ raw_rev = payload.get("revision")
93
+ if raw_rev is not None and not isinstance(raw_rev, str):
94
+ raise LibraryError("INVALID_REPO_SPEC", "revision must be a string")
95
+ revision = raw_rev.strip() or None if isinstance(raw_rev, str) else None
96
+ raw_variant = payload.get("variant_id")
97
+ if not isinstance(raw_variant, str) or not raw_variant.strip():
98
+ raise LibraryError("INVALID_REPO_SPEC", "variant_id is required")
99
+ raw_files = payload.get("files")
100
+ explicit_files: list[str] | None = None
101
+ if raw_files is not None:
102
+ if not isinstance(raw_files, list) or not all(
103
+ isinstance(item, str) and item.strip() for item in raw_files
104
+ ):
105
+ raise LibraryError("INVALID_REPO_SPEC", "files must be a list of non-empty paths")
106
+ explicit_files = [item.strip() for item in raw_files]
107
+ raw_mmproj = payload.get("mmproj", "auto")
108
+ if raw_mmproj is None:
109
+ mmproj_opt = "none"
110
+ elif isinstance(raw_mmproj, str) and raw_mmproj.strip():
111
+ mmproj_opt = raw_mmproj.strip()
112
+ else:
113
+ raise LibraryError("INVALID_REPO_SPEC", "mmproj must be 'auto', 'none', or a file path")
114
+ force_memory = payload.get("force_memory", False)
115
+ if not isinstance(force_memory, bool):
116
+ raise LibraryError("INVALID_REPO_SPEC", "force_memory must be a boolean")
117
+ replace = payload.get("replace", False)
118
+ if not isinstance(replace, bool):
119
+ raise LibraryError("INVALID_REPO_SPEC", "replace must be a boolean")
120
+ raw_token = payload.get("token")
121
+ if raw_token is not None and not isinstance(raw_token, str):
122
+ raise LibraryError("INVALID_REPO_SPEC", "token must be a string")
123
+ token = raw_token.strip() or None if isinstance(raw_token, str) else None
124
+ return (
125
+ cast(CustomHub, raw_hub),
126
+ raw_repo.strip(),
127
+ revision,
128
+ raw_variant.strip(),
129
+ explicit_files,
130
+ mmproj_opt,
131
+ force_memory,
132
+ replace,
133
+ token,
134
+ )
135
+
136
+
137
+ def _resolve_repo(
138
+ hub: CustomHub, repo_id: str, revision: str | None, token: str | None
139
+ ) -> tuple[custom_hub.FetchedRepo, custom_hub.TreeInspection]:
140
+ spec = custom_hub.parse_repo_spec(repo_id, hub=hub, revision=revision)
141
+ outcome = custom_hub.fetch_repo(spec, token=token)
142
+ if isinstance(outcome, custom_hub.HubGated):
143
+ code = "HUB_AUTH_REQUIRED" if outcome.http_status == 401 else "HUB_FORBIDDEN"
144
+ raise LibraryError(
145
+ code,
146
+ f"{outcome.hub} repository {outcome.repo_id} requires authentication or license access",
147
+ hub=outcome.hub,
148
+ repo_id=outcome.repo_id,
149
+ )
150
+ if isinstance(outcome, custom_hub.HubNotFound):
151
+ raise LibraryError(
152
+ "HUB_REPO_NOT_FOUND",
153
+ f"{outcome.hub} repository {outcome.repo_id} was not found",
154
+ hub=outcome.hub,
155
+ repo_id=outcome.repo_id,
156
+ )
157
+ inspected = custom_hub.inspect_tree(outcome)
158
+ if not inspected.compatible or not inspected.variants:
159
+ raise LibraryError(
160
+ "HUB_FORMAT_UNSUPPORTED",
161
+ f"{outcome.repo_id} has no runnable GGUF files ({inspected.reason or 'unsupported'})",
162
+ )
163
+ return outcome, inspected
164
+
165
+
166
+ def _select_variant_and_files(
167
+ fetched: custom_hub.FetchedRepo,
168
+ inspected: custom_hub.TreeInspection,
169
+ variant_id: str,
170
+ explicit_files: list[str] | None,
171
+ mmproj_opt: str,
172
+ ) -> tuple[
173
+ custom_hub.GgufVariantGroup, tuple[custom_hub.RepoFile, ...], custom_hub.RepoFile | None
174
+ ]:
175
+ wanted = variant_id.lower()
176
+ variant = next(
177
+ (
178
+ v
179
+ for v in inspected.variants
180
+ if wanted in (v.variant_id.lower(), v.quant.lower(), v.label.lower())
181
+ ),
182
+ None,
183
+ )
184
+ if variant is None:
185
+ raise LibraryError(
186
+ "INVALID_REPO_SPEC",
187
+ f"variant {variant_id!r} was not found in {fetched.repo_id}",
188
+ )
189
+ if explicit_files:
190
+ by_path = {f.path: f for f in fetched.files}
191
+ chosen: list[custom_hub.RepoFile] = []
192
+ for path in explicit_files:
193
+ found = by_path.get(path)
194
+ if found is None:
195
+ raise LibraryError(
196
+ "INVALID_REPO_SPEC",
197
+ f"requested file {path!r} was not found in {fetched.repo_id}",
198
+ )
199
+ chosen.append(found)
200
+ weight_files = tuple(chosen)
201
+ else:
202
+ weight_files = variant.files
203
+
204
+ mmproj_file: custom_hub.RepoFile | None = None
205
+ lower_opt = mmproj_opt.lower()
206
+ if lower_opt == "none":
207
+ mmproj_file = None
208
+ elif lower_opt == "auto":
209
+ if variant.mmproj_file:
210
+ by_path = {f.path: f for f in fetched.files}
211
+ mmproj_file = by_path.get(variant.mmproj_file)
212
+ else:
213
+ by_path = {f.path: f for f in fetched.files}
214
+ mmproj_file = by_path.get(mmproj_opt)
215
+ if mmproj_file is None:
216
+ raise LibraryError(
217
+ "INVALID_REPO_SPEC",
218
+ f"requested mmproj file {mmproj_opt!r} was not found in {fetched.repo_id}",
219
+ )
220
+ return variant, weight_files, mmproj_file
221
+
222
+
223
+ def _select_pool_and_engine(
224
+ facts: HostFacts, base_dir: str
225
+ ) -> tuple[str, str, int, dict[str, object]]:
226
+ """Return ``(pool_id, placement_id, memory_ceiling_bytes, release_engine_dict)``."""
227
+ pool_map = library_pricing.pools(facts)
228
+ preferred = [p for p in pool_map if p != "system"]
229
+ if not preferred:
230
+ vendor = str(facts.get("gpu_vendor_class") or "none")
231
+ raise LibraryError(
232
+ "GPU_UNSUPPORTED",
233
+ f"custom GGUF models require an NVIDIA or Apple Silicon GPU (detected: {vendor})",
234
+ )
235
+ pool_id = max(
236
+ preferred,
237
+ key=lambda p: (
238
+ library_pricing.pool_free(facts, p),
239
+ library_pricing.pool_total(facts, p),
240
+ ),
241
+ )
242
+ placement_id = pool_map[pool_id]
243
+ adm = budget.admission_budget(facts, pool_id)
244
+ total = library_pricing.pool_total(facts, pool_id)
245
+ ceiling = adm.hard_ceiling_bytes if adm is not None and adm.hard_ceiling_bytes > 0 else total
246
+ backend = "metal" if pool_id == "unified" and facts.get("platform") == "darwin" else "cuda"
247
+ lock_path = engines.engine_lock_path(CUSTOM_ENGINE_TAG)
248
+ try:
249
+ build = engines.select_engine_build(facts, backend, lock_path)
250
+ except engines.CudaDriverError as exc:
251
+ raise LibraryError("DRIVER_UPDATE_REQUIRED", str(exc)) from None
252
+ except engines.EngineUnavailableError as exc:
253
+ raise LibraryError("RUNTIME_DEPENDENCY_MISSING", str(exc)) from None
254
+ except plan_envelope.PlanError as exc:
255
+ raise LibraryError("RUNTIME_DEPENDENCY_MISSING", str(exc)) from None
256
+ engine_doc = cast(dict[str, object], engines.release_engine(build, base_dir))
257
+ return pool_id, placement_id, ceiling, engine_doc
258
+
259
+
260
+ def _catalog_entry_dict(
261
+ *,
262
+ catalog_id: str,
263
+ quant: str,
264
+ fetched: custom_hub.FetchedRepo,
265
+ weight_files: tuple[custom_hub.RepoFile, ...],
266
+ mmproj_file: custom_hub.RepoFile | None,
267
+ local_names: Mapping[str, str],
268
+ sha_overrides: Mapping[str, str],
269
+ header: GGUFHeader | None,
270
+ ) -> dict[str, object]:
271
+ file_rows: list[dict[str, Any]] = [
272
+ {
273
+ "path": f.path,
274
+ "size_bytes": f.size_bytes,
275
+ "local": local_names[f.path],
276
+ "revision": f.revision or fetched.revision,
277
+ "sha256": sha_overrides.get(f.path, f.sha256 or ""),
278
+ }
279
+ for f in weight_files
280
+ ]
281
+ family = custom_hub.infer_family(
282
+ fetched.repo_id, fetched.tags, header.architecture if header else None
283
+ )
284
+ display = fetched.title or fetched.repo_id.rsplit("/", 1)[-1]
285
+ if header is not None:
286
+ try:
287
+ entry: dict[str, Any] = catalog_add.entry_from_header(
288
+ header,
289
+ model_id=catalog_id,
290
+ repo=fetched.repo_id,
291
+ quant=quant,
292
+ files=file_rows,
293
+ license_name=fetched.license or "unknown",
294
+ license_url=fetched.url,
295
+ tasks=["llm"],
296
+ status="candidate",
297
+ quality=0,
298
+ display_name=display,
299
+ description=f"Custom model from {fetched.hub}: {fetched.repo_id}",
300
+ evidence=[],
301
+ )
302
+ except (ValueError, KeyError, TypeError, OverflowError):
303
+ header = None
304
+ if header is None:
305
+ entry = {
306
+ "id": catalog_id,
307
+ "display_name": display,
308
+ "description": f"Custom model from {fetched.hub}: {fetched.repo_id}",
309
+ "repo": fetched.repo_id,
310
+ "license": fetched.license or "unknown",
311
+ "license_url": fetched.url,
312
+ "status": "candidate",
313
+ "tasks": ["llm"],
314
+ "evidence": [],
315
+ "variants": [{"quant": quant, "files": file_rows}],
316
+ "n_ctx_train": 32768,
317
+ "full_layers": 32,
318
+ "recurrent_layers": 0,
319
+ "per_layer_f16": 262144,
320
+ "moe": False,
321
+ "architecture": "",
322
+ "quality": 0,
323
+ }
324
+ entry["engine"] = CUSTOM_ENGINE_TAG
325
+ entry["runtime"] = "llama.cpp"
326
+ entry["family"] = family
327
+ entry["publisher"] = fetched.owner
328
+ if mmproj_file is not None:
329
+ entry["mmproj"] = {
330
+ "path": mmproj_file.path,
331
+ "size_bytes": mmproj_file.size_bytes,
332
+ "local": local_names[mmproj_file.path],
333
+ "revision": mmproj_file.revision or fetched.revision,
334
+ "sha256": sha_overrides.get(mmproj_file.path, mmproj_file.sha256 or ""),
335
+ }
336
+ return cast(dict[str, object], entry)
337
+
338
+
339
+ def _build_download_plan(
340
+ *,
341
+ facts: HostFacts,
342
+ base_dir: str,
343
+ catalog_id: str,
344
+ quant: str,
345
+ fetched: custom_hub.FetchedRepo,
346
+ weight_files: tuple[custom_hub.RepoFile, ...],
347
+ mmproj_file: custom_hub.RepoFile | None,
348
+ local_names: Mapping[str, str],
349
+ sha_overrides: Mapping[str, str],
350
+ pool_id: str,
351
+ placement_id: str,
352
+ engine_doc: dict[str, object],
353
+ est_memory: int,
354
+ n_ctx_train: int,
355
+ ) -> Plan:
356
+ base = base_dir.rstrip("/")
357
+ models_dir = f"{base}/models"
358
+ all_files = (*weight_files, *((mmproj_file,) if mmproj_file is not None else ()))
359
+ planned_files: list[ReusableFile] = [
360
+ {
361
+ "repo": fetched.repo_id,
362
+ "path": f.path,
363
+ "revision": f.revision or fetched.revision,
364
+ "size_bytes": f.size_bytes,
365
+ "sha256": sha_overrides.get(f.path, f.sha256 or ""),
366
+ "local_name": local_names[f.path],
367
+ "dest": f"{models_dir}/{local_names[f.path]}",
368
+ "url": f.download_url,
369
+ }
370
+ for f in all_files
371
+ ]
372
+ model_alias = gguf.model_id_from_stem(Path(weight_files[0].path).name.removesuffix(".gguf"))
373
+ where = plan_envelope.deployment(
374
+ catalog_id,
375
+ deploy.DEFAULT_PORT,
376
+ base,
377
+ "127.0.0.1",
378
+ hosts.deployment_dirs(hosts.LOCAL_ID),
379
+ )
380
+ gpus = {g["index"]: g for g in facts.get("gpus") or []}
381
+ gpu_idx = library_pricing.gpu_index(pool_id)
382
+ placement_gpus = (
383
+ [
384
+ {
385
+ "index": gpu_idx,
386
+ "uuid": gpus[gpu_idx]["uuid"],
387
+ "name": gpus[gpu_idx]["name"],
388
+ }
389
+ ]
390
+ if gpu_idx is not None and gpu_idx in gpus
391
+ else []
392
+ )
393
+ mem_key = "unified_bytes" if pool_id == "unified" else "vram_bytes"
394
+ launch: dict[str, object] = {
395
+ "window": min(n_ctx_train, 65536) if n_ctx_train > 0 else 32768,
396
+ "spilled": False,
397
+ "spill_bytes": 0,
398
+ "reasons": [],
399
+ "mtp_prefill": False,
400
+ "slots": 1,
401
+ "kv_types": ["q8_0", "q8_0"],
402
+ "posture": "agent",
403
+ mem_key: est_memory,
404
+ "vram_bytes": est_memory,
405
+ }
406
+ if mmproj_file is not None:
407
+ launch["vision"] = True
408
+ launch["vision_reader"] = "gpu"
409
+ argv = [
410
+ str(engine_doc["binary"]),
411
+ "-m",
412
+ planned_files[0]["dest"],
413
+ "-a",
414
+ model_alias,
415
+ "--host",
416
+ "127.0.0.1",
417
+ "--port",
418
+ str(deploy.DEFAULT_PORT),
419
+ "--api-key-file",
420
+ where.api_key_file,
421
+ ]
422
+ return plan_envelope.plan_envelope(
423
+ hosts.LOCAL_ID,
424
+ facts,
425
+ where,
426
+ model={
427
+ "id": catalog_id,
428
+ "display_name": fetched.title or fetched.repo_id.rsplit("/", 1)[-1],
429
+ "repo": fetched.repo_id,
430
+ "quant": quant,
431
+ "model_id": model_alias,
432
+ "validated": False,
433
+ },
434
+ files=planned_files,
435
+ engine=cast(Any, engine_doc),
436
+ placement={"id": placement_id, "label": pool_id, "pooled": False, "gpus": placement_gpus},
437
+ launch=launch,
438
+ service={"argv": argv, "env": {}, "autostart": False},
439
+ endpoint={"model": model_alias},
440
+ warnings=[],
441
+ )
442
+
443
+
444
+ def _auth_headers_for_plan(
445
+ plan: Plan, token: str | None, *, hub: CustomHub
446
+ ) -> dict[str, str] | None:
447
+ if not token:
448
+ return None
449
+ hosts_seen: dict[str, str] = {}
450
+ for f in plan["files"]:
451
+ allowed = custom_hub.token_for_endpoint(hub, f["url"], token)
452
+ if not allowed:
453
+ continue
454
+ host = (urllib.parse.urlsplit(f["url"]).hostname or "").lower()
455
+ if host:
456
+ hosts_seen[host] = f"Bearer {allowed}"
457
+ return hosts_seen or None
458
+
459
+
460
+ def _safe_memory_bytes(header: GGUFHeader | None, weights_bytes: int, mmproj_bytes: int) -> int:
461
+ if header is not None:
462
+ try:
463
+ return custom_probe.physics_memory_bytes(header, weights_bytes, mmproj_bytes)
464
+ except (ValueError, KeyError, TypeError, OverflowError):
465
+ pass
466
+ return custom_probe.rough_memory_bytes(weights_bytes, mmproj_bytes)
467
+
468
+
469
+ def _read_receipt_sha256(dest: str) -> str:
470
+ receipt = Path(os.path.expanduser(dest) + ".sha256")
471
+ try:
472
+ return receipt.read_text(encoding="utf-8").strip()
473
+ except OSError:
474
+ return ""
475
+
476
+
477
+ def _read_local_header(first_dest: str) -> GGUFHeader | None:
478
+ path = Path(os.path.expanduser(first_dest))
479
+ try:
480
+ return gguf.read_gguf_header(path)
481
+ except (OSError, ValueError):
482
+ return None
483
+
484
+
485
+ def _cleanup_aborted(model_id: str, job: Job, handle: JobHandle, base_dir: str) -> None:
486
+ gone = library_jobs.leftovers(handle.job)
487
+ library_jobs.delete_weights(gone, library_jobs.in_use(model_id))
488
+ library_jobs.prune_empty_custom_dirs(gone, base_dir)
489
+ if library_state.current(job):
490
+ library_state.clear_job(model_id)
491
+
492
+
493
+ def _check_disk_and_memory(
494
+ custom_model_id: str,
495
+ plan: Plan,
496
+ base_dir: str,
497
+ pool_id: str,
498
+ est_memory: int,
499
+ ceiling: int,
500
+ *,
501
+ force_memory: bool,
502
+ ) -> None:
503
+ missing = library_pricing.missing_bytes(plan)
504
+ disk_need = int(missing * custom_probe.DISK_HEADROOM_MULTIPLIER)
505
+ disk_have = library_pricing.base_free(base_dir)
506
+ if disk_need > disk_have:
507
+ raise LibraryError(
508
+ "DISK_INSUFFICIENT",
509
+ f"{custom_model_id} needs {disk_need} bytes free disk (1.1x missing bytes), "
510
+ f"only {disk_have} bytes available",
511
+ need_bytes=disk_need,
512
+ have_bytes=disk_have,
513
+ can_force=False,
514
+ )
515
+ if ceiling > 0 and est_memory > ceiling and not force_memory:
516
+ raise LibraryError(
517
+ "MEMORY_INSUFFICIENT",
518
+ f"{custom_model_id} needs ~{est_memory} bytes, exceeding {pool_id} ceiling "
519
+ f"{ceiling} bytes",
520
+ need_bytes=est_memory,
521
+ have_bytes=ceiling,
522
+ can_force=True,
523
+ )
524
+
525
+
526
+ def _build_custom_meta(
527
+ fetched: custom_hub.FetchedRepo,
528
+ variant_id: str,
529
+ shard_count: int,
530
+ mmproj_file: custom_hub.RepoFile | None,
531
+ *,
532
+ force_memory: bool,
533
+ header: GGUFHeader | None,
534
+ ) -> CustomMeta:
535
+ meta: CustomMeta = {
536
+ "hub": fetched.hub,
537
+ "repo_id": fetched.repo_id,
538
+ "format": "gguf",
539
+ "variant_id": variant_id,
540
+ "shard_count": shard_count,
541
+ "standby_on_restart": True,
542
+ "accepted_risk": force_memory,
543
+ }
544
+ if fetched.revision:
545
+ meta["revision"] = fetched.revision
546
+ if fetched.url:
547
+ meta["url"] = fetched.url
548
+ if mmproj_file is not None:
549
+ meta["mmproj_file"] = mmproj_file.path
550
+ meta["mmproj_bytes"] = mmproj_file.size_bytes
551
+ if header is not None:
552
+ meta["has_chat_template"] = "tokenizer.chat_template" in header.metadata
553
+ return meta
554
+
555
+
556
+ def download_custom(payload: Mapping[str, object], base_dir: str) -> Row:
557
+ """Execute ``localmodels library custom download --config-stdin --base-dir <dir> --jsonl``."""
558
+ (
559
+ hub,
560
+ repo_id,
561
+ revision,
562
+ variant_id,
563
+ explicit_files,
564
+ mmproj_opt,
565
+ force_memory,
566
+ replace,
567
+ token,
568
+ ) = _parse_download_payload(payload)
569
+ fetched, inspected = _resolve_repo(hub, repo_id, revision, token)
570
+ variant, weight_files, mmproj_file = _select_variant_and_files(
571
+ fetched, inspected, variant_id, explicit_files, mmproj_opt
572
+ )
573
+ custom_model_id = custom_hub.make_custom_model_id(
574
+ fetched.hub, fetched.repo_id, variant.variant_id
575
+ )
576
+ catalog_id, quant_slug = split_id(custom_model_id)
577
+
578
+ facts = library_jobs.probe()
579
+ if problem := library_pricing.platform_problem(facts):
580
+ raise LibraryError("PLATFORM_UNSUPPORTED", problem)
581
+ pool_id, placement_id, ceiling, engine_doc = _select_pool_and_engine(facts, base_dir)
582
+
583
+ weights_bytes = sum(f.size_bytes for f in weight_files)
584
+ mmproj_bytes = mmproj_file.size_bytes if mmproj_file is not None else 0
585
+ resolved_token = custom_hub.resolve_token(fetched.hub, token, hub_explicit=True)
586
+ header_token = custom_hub.token_for_endpoint(
587
+ fetched.hub, weight_files[0].download_url, resolved_token
588
+ )
589
+ remote_header, _ = custom_hub.read_remote_gguf_header(
590
+ weight_files[0].download_url, token=header_token
591
+ )
592
+ est_memory = _safe_memory_bytes(remote_header, weights_bytes, mmproj_bytes)
593
+
594
+ all_files = (*weight_files, *((mmproj_file,) if mmproj_file is not None else ()))
595
+ local_names = {
596
+ f.path: _custom_local_name(fetched.hub, fetched.repo_id, fetched.revision, f.path)
597
+ for f in all_files
598
+ }
599
+ provisional_entry = _catalog_entry_dict(
600
+ catalog_id=catalog_id,
601
+ quant=quant_slug,
602
+ fetched=fetched,
603
+ weight_files=weight_files,
604
+ mmproj_file=mmproj_file,
605
+ local_names=local_names,
606
+ sha_overrides={},
607
+ header=remote_header,
608
+ )
609
+ plan = _build_download_plan(
610
+ facts=facts,
611
+ base_dir=base_dir,
612
+ catalog_id=catalog_id,
613
+ quant=quant_slug,
614
+ fetched=fetched,
615
+ weight_files=weight_files,
616
+ mmproj_file=mmproj_file,
617
+ local_names=local_names,
618
+ sha_overrides={},
619
+ pool_id=pool_id,
620
+ placement_id=placement_id,
621
+ engine_doc=engine_doc,
622
+ est_memory=est_memory,
623
+ n_ctx_train=remote_header.n_ctx_train if remote_header is not None else 32768,
624
+ )
625
+ _check_disk_and_memory(
626
+ custom_model_id,
627
+ plan,
628
+ base_dir,
629
+ pool_id,
630
+ est_memory,
631
+ ceiling,
632
+ force_memory=force_memory,
633
+ )
634
+
635
+ files = library_jobs.dests(plan)
636
+ custom_meta = _build_custom_meta(
637
+ fetched,
638
+ variant.variant_id,
639
+ len(weight_files),
640
+ mmproj_file,
641
+ force_memory=force_memory,
642
+ header=remote_header,
643
+ )
644
+ library_jobs.cancel_on_sigterm()
645
+ old_dests: list[str] = []
646
+ with library_state.locked():
647
+ library_state.refuse_busy(custom_model_id, "download")
648
+ existing = library_state.load(custom_model_id)
649
+ if existing is not None:
650
+ if not replace:
651
+ raise LibraryError("INVALID_STATE", f"{custom_model_id} is already downloaded")
652
+ if existing["state"] != "idle":
653
+ raise LibraryError(
654
+ "INVALID_STATE",
655
+ f"{custom_model_id} is {existing['state']}; unload it before replacing",
656
+ )
657
+ old_dests = library_jobs.dests(existing["plan"])
658
+ others = library_jobs.claimed_elsewhere(custom_model_id)
659
+ mine = [f for f in files if os.path.realpath(f) not in others]
660
+ job = library_state.acquire(
661
+ "download",
662
+ custom_model_id,
663
+ pool_id,
664
+ est_memory,
665
+ mine,
666
+ files,
667
+ custom=custom_meta,
668
+ catalog_entry=provisional_entry,
669
+ base_dir=base_dir,
670
+ )
671
+
672
+ auth_headers = _auth_headers_for_plan(plan, resolved_token, hub=fetched.hub)
673
+ claims = [job]
674
+ with library_state.held(claims):
675
+ handle = library_state.JobHandle(job)
676
+ try:
677
+ with library_jobs.watch_cancel(job):
678
+ library_jobs.fetch(
679
+ custom_model_id,
680
+ plan,
681
+ handle,
682
+ library_jobs.executor(),
683
+ set(mine),
684
+ auth_headers=auth_headers,
685
+ shard_count=len(weight_files),
686
+ )
687
+ _commit_custom_record(
688
+ custom_model_id=custom_model_id,
689
+ catalog_id=catalog_id,
690
+ quant_slug=quant_slug,
691
+ fetched=fetched,
692
+ weight_files=weight_files,
693
+ mmproj_file=mmproj_file,
694
+ local_names=local_names,
695
+ facts=facts,
696
+ base_dir=base_dir,
697
+ pool_id=pool_id,
698
+ placement_id=placement_id,
699
+ engine_doc=engine_doc,
700
+ plan=plan,
701
+ custom_meta=custom_meta,
702
+ remote_header=remote_header,
703
+ est_memory=est_memory,
704
+ job=job,
705
+ handle=handle,
706
+ old_dests=old_dests,
707
+ )
708
+ except KeyboardInterrupt:
709
+ with library_state.locked():
710
+ if library_state.load(custom_model_id) is None or replace:
711
+ _cleanup_aborted(custom_model_id, job, handle, base_dir)
712
+ raise LibraryError("CANCELLED", "the download was cancelled") from None
713
+ except LibraryError as exc:
714
+ safe_detail = custom_hub.redact_secrets(
715
+ remote_ops.redact_text(exc.detail), extra_token=resolved_token
716
+ )
717
+ with library_state.locked():
718
+ if library_state.current(job):
719
+ if library_state.cancelled(job):
720
+ _cleanup_aborted(custom_model_id, job, handle, base_dir)
721
+ raise LibraryError("CANCELLED", "the download was cancelled") from None
722
+ if (
723
+ exc.code in library_jobs.KEEP_FAILED_DOWNLOAD_CODES
724
+ and library_state.load(custom_model_id) is None
725
+ ):
726
+ library_state.fail_job(
727
+ handle.job, {"code": exc.code, "detail": safe_detail}
728
+ )
729
+ claims.clear()
730
+ else:
731
+ _cleanup_aborted(custom_model_id, job, handle, base_dir)
732
+ raise LibraryError(exc.code, safe_detail, failed=exc.failed, **exc.fields) from None
733
+ except Exception as exc:
734
+ with library_state.locked():
735
+ if library_state.current(job):
736
+ _cleanup_aborted(custom_model_id, job, handle, base_dir)
737
+ safe_detail = custom_hub.redact_secrets(
738
+ remote_ops.redact_text(str(exc)), extra_token=resolved_token
739
+ )
740
+ raise LibraryError("DOWNLOAD_FAILED", safe_detail, failed=True) from None
741
+
742
+ return library_status.model_row(
743
+ library_status.Library.read(library_jobs.probe(), base_dir), custom_model_id
744
+ )
745
+
746
+
747
+ def _commit_custom_record(
748
+ *,
749
+ custom_model_id: str,
750
+ catalog_id: str,
751
+ quant_slug: str,
752
+ fetched: custom_hub.FetchedRepo,
753
+ weight_files: tuple[custom_hub.RepoFile, ...],
754
+ mmproj_file: custom_hub.RepoFile | None,
755
+ local_names: Mapping[str, str],
756
+ facts: HostFacts,
757
+ base_dir: str,
758
+ pool_id: str,
759
+ placement_id: str,
760
+ engine_doc: dict[str, object],
761
+ plan: Plan,
762
+ custom_meta: CustomMeta,
763
+ remote_header: GGUFHeader | None,
764
+ est_memory: int,
765
+ job: Job,
766
+ handle: JobHandle,
767
+ old_dests: list[str],
768
+ ) -> None:
769
+ local_header = _read_local_header(plan["files"][0]["dest"]) or remote_header
770
+ sha_overrides: dict[str, str] = {}
771
+ for f in plan["files"]:
772
+ if not f["sha256"]:
773
+ computed = _read_receipt_sha256(f["dest"])
774
+ if computed:
775
+ sha_overrides[f["path"]] = computed
776
+ if local_header is not None:
777
+ custom_meta = {
778
+ **custom_meta,
779
+ "has_chat_template": "tokenizer.chat_template" in local_header.metadata,
780
+ }
781
+ weights_bytes = sum(f.size_bytes for f in weight_files)
782
+ mmproj_bytes = mmproj_file.size_bytes if mmproj_file is not None else 0
783
+ est_memory = _safe_memory_bytes(local_header, weights_bytes, mmproj_bytes)
784
+ final_entry = _catalog_entry_dict(
785
+ catalog_id=catalog_id,
786
+ quant=quant_slug,
787
+ fetched=fetched,
788
+ weight_files=weight_files,
789
+ mmproj_file=mmproj_file,
790
+ local_names=local_names,
791
+ sha_overrides=sha_overrides,
792
+ header=local_header,
793
+ )
794
+ final_plan = _build_download_plan(
795
+ facts=facts,
796
+ base_dir=base_dir,
797
+ catalog_id=catalog_id,
798
+ quant=quant_slug,
799
+ fetched=fetched,
800
+ weight_files=weight_files,
801
+ mmproj_file=mmproj_file,
802
+ local_names=local_names,
803
+ sha_overrides=sha_overrides,
804
+ pool_id=pool_id,
805
+ placement_id=placement_id,
806
+ engine_doc=engine_doc,
807
+ est_memory=est_memory,
808
+ n_ctx_train=local_header.n_ctx_train if local_header is not None else 32768,
809
+ )
810
+ selector = library_gateway.pi_model(custom_model_id, str(final_plan["endpoint"]["model"]))
811
+ record: Record = library_state.new_record(
812
+ custom_model_id, catalog_id, quant_slug, pool_id, final_plan, selector
813
+ )
814
+ record["memory_bytes"] = est_memory
815
+ record["base_dir"] = base_dir
816
+ record["custom"] = custom_meta
817
+ record["verification"] = {"status": "untested"}
818
+ record["catalog_entry"] = final_entry
819
+ with library_state.locked():
820
+ found = library_state.read_job(custom_model_id)
821
+ if found is None or found.get("id") != job["id"] or library_state.cancelled(job):
822
+ _cleanup_aborted(custom_model_id, job, handle, base_dir)
823
+ raise LibraryError("CANCELLED", "the download was cancelled")
824
+ library_state.save(record)
825
+ library_state.clear_job(custom_model_id)
826
+ if old_dests:
827
+ new_real = {os.path.realpath(p) for p in library_jobs.dests(final_plan)}
828
+ stale = [p for p in old_dests if os.path.realpath(p) not in new_real]
829
+ if stale:
830
+ library_jobs.delete_weights(stale, library_jobs.in_use(custom_model_id))
831
+ library_jobs.prune_empty_custom_dirs(stale, base_dir)