@simplexai/localmodels-linux-x64 0.1.0-dev.48 → 0.1.0-dev.50

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 (83) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +82 -72
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/budget.py +40 -14
  5. package/modules/localmodels/catalog.json +473 -36
  6. package/modules/localmodels/debug_mode.py +25 -0
  7. package/modules/localmodels/deploy.py +3 -0
  8. package/modules/localmodels/download-mirrors.json +47 -0
  9. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +13 -1
  10. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +79 -0
  11. package/modules/localmodels/engines.py +31 -6
  12. package/modules/localmodels/gateway.py +23 -6
  13. package/modules/localmodels/gateway_bifrost.py +6 -2
  14. package/modules/localmodels/harness.py +8 -2
  15. package/modules/localmodels/harness_gateway.py +78 -17
  16. package/modules/localmodels/harness_probe.py +5 -1
  17. package/modules/localmodels/hosts.py +52 -5
  18. package/modules/localmodels/library_floor.py +76 -0
  19. package/modules/localmodels/library_jobs.py +60 -7
  20. package/modules/localmodels/library_model.py +38 -2
  21. package/modules/localmodels/library_poly.py +272 -0
  22. package/modules/localmodels/library_pricing.py +251 -79
  23. package/modules/localmodels/library_serve.py +27 -4
  24. package/modules/localmodels/library_state.py +16 -0
  25. package/modules/localmodels/library_status.py +46 -18
  26. package/modules/localmodels/library_vram.py +123 -0
  27. package/modules/localmodels/llm_rank.py +42 -1
  28. package/modules/localmodels/magpie_windows.py +312 -0
  29. package/modules/localmodels/probe.py +39 -37
  30. package/modules/localmodels/process_identity.py +26 -33
  31. package/modules/localmodels/process_identity_darwin.py +189 -0
  32. package/modules/localmodels/process_identity_linux.py +62 -30
  33. package/modules/localmodels/recommend.py +3 -1
  34. package/modules/localmodels/remote_ops.py +11 -0
  35. package/modules/localmodels/remote_ops_download.py +30 -5
  36. package/modules/localmodels/remote_ops_service.py +15 -46
  37. package/modules/localmodels/reuse.py +13 -6
  38. package/modules/localmodels/runtime_io.py +32 -18
  39. package/modules/localmodels/service_probe.py +1 -1
  40. package/modules/localmodels/setup_inspection.py +97 -80
  41. package/modules/localmodels/setup_inspection_harness.py +147 -0
  42. package/modules/localmodels/setup_text.py +24 -0
  43. package/modules/localmodels/setup_upgrade.py +155 -0
  44. package/modules/localmodels/stack.py +3 -1
  45. package/modules/localmodels/stack_auto.py +6 -2
  46. package/modules/localmodels/stack_clients.py +1 -1
  47. package/modules/localmodels/stack_compose.py +5 -1
  48. package/modules/localmodels/stack_down.py +25 -16
  49. package/modules/localmodels/stack_hardware.py +17 -3
  50. package/modules/localmodels/stack_picks.py +28 -13
  51. package/modules/localmodels/stack_remove.py +3 -1
  52. package/modules/localmodels/stack_route.py +5 -1
  53. package/modules/localmodels/stack_suite.py +29 -8
  54. package/modules/localmodels/stack_view_access.py +238 -58
  55. package/modules/localmodels/stack_view_hub.py +12 -7
  56. package/modules/localmodels/stack_view_serve.py +13 -6
  57. package/modules/localmodels/strata-poly-serve-0.2.19-poly.1.txt +428 -0
  58. package/modules/localmodels/strata_poly_server.py +14 -2
  59. package/modules/localmodels/suite.py +19 -3
  60. package/modules/localmodels/tool_archive.py +4 -0
  61. package/modules/localmodels/transport.py +3 -1
  62. package/modules/localmodels/tui.py +4 -1
  63. package/modules/localmodels/tui_dialogs.py +42 -9
  64. package/modules/localmodels/tui_modals.py +63 -16
  65. package/modules/localmodels/tui_screen.py +80 -53
  66. package/modules/localmodels/tui_views.py +36 -6
  67. package/modules/localmodels/vision.py +4 -2
  68. package/modules/localmodels/web/index.html +996 -300
  69. package/modules/localmodels/web/sizecalc/app.js +616 -88
  70. package/modules/localmodels/web/sizecalc/page.html +239 -106
  71. package/modules/localmodels/web/view/fleet.js +25 -2
  72. package/modules/localmodels/web/view/nav.js +19 -3
  73. package/modules/localmodels/web/view/view.css +110 -22
  74. package/modules/localmodels/web/view/view.js +40 -22
  75. package/modules/localmodels/win_probe.py +204 -0
  76. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/METADATA +1 -1
  77. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/RECORD +79 -69
  78. package/package.json +1 -1
  79. package/tool.json +1 -1
  80. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/WHEEL +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/entry_points.txt +0 -0
  82. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/NOTICE +0 -0
  83. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -12,7 +12,7 @@ import os
12
12
  import re
13
13
  import threading
14
14
  import time
15
- from collections.abc import Callable, Iterator
15
+ from collections.abc import Callable, Iterator, Mapping
16
16
  from contextlib import contextmanager
17
17
  from pathlib import Path
18
18
  from typing import Any, Literal, TypedDict, TypeVar
@@ -346,6 +346,15 @@ class OwnedBifrost(_OwnedBifrostSince20261110):
346
346
  binary: str
347
347
 
348
348
 
349
+ class OwnedMagpie(TypedDict):
350
+ """A private ``magpie serve`` instance this tool launched for its own gateway-home."""
351
+
352
+ addr: str
353
+ binary: str
354
+ gateway_home: str
355
+ tools_dir: str
356
+
357
+
349
358
  class _OwnedGatewaySince20261031(TypedDict, total=False):
350
359
  caller_keys: list[str] # ids of the Magpie gateway keys (callers' keys) this tool added
351
360
  # The Magpie search APIs this tool added for the web search service the stack used to run:
@@ -353,6 +362,7 @@ class _OwnedGatewaySince20261031(TypedDict, total=False):
353
362
  search: str # the searxng search API URL
354
363
  search_you: bool # Magpie's You.com search API, the free fallback after it
355
364
  bifrost: OwnedBifrost # since 2026-11-02: the Bifrost gateway this tool runs
365
+ magpie: OwnedMagpie # since 2026-11-20: private magpie serve launched for this gateway-home
356
366
 
357
367
 
358
368
  class OwnedGateway(_OwnedGatewaySince20261031):
@@ -424,12 +434,37 @@ def empty_owned() -> Owned:
424
434
  }
425
435
 
426
436
 
427
- def tools_dir(given: str | Path = TOOLS_DIR) -> str:
437
+ def _strip_trailing_sep(path: str) -> str:
438
+ cleaned = path.rstrip("/\\")
439
+ return cleaned if cleaned and not cleaned.endswith(":") else path
440
+
441
+
442
+ def _is_default_tools_dir(given: str | Path, env: Mapping[str, str] | None = None) -> bool:
443
+ raw = str(given)
444
+ if raw.replace("\\", "/").rstrip("/") == TOOLS_DIR:
445
+ return True
446
+ norm_given = os.path.normcase(os.path.normpath(os.path.expanduser(raw)))
447
+ norm_default = os.path.normcase(os.path.normpath(os.path.expanduser(TOOLS_DIR)))
448
+ if norm_given == norm_default:
449
+ return True
450
+ if env is not None:
451
+ home = env.get("HOME") or env.get("USERPROFILE")
452
+ if home:
453
+ env_default = os.path.normcase(
454
+ os.path.normpath(os.path.join(home, TOOLS_DIR.removeprefix("~/")))
455
+ )
456
+ if norm_given == env_default:
457
+ return True
458
+ return False
459
+
460
+
461
+ def tools_dir(given: str | Path = TOOLS_DIR, *, env: Mapping[str, str] | None = None) -> str:
428
462
  """The tools root: ``LOCALMODELS_TOOLS_DIR`` overrides the default ``TOOLS_DIR``."""
429
- if str(given) == TOOLS_DIR and (
430
- override := os.environ.get("LOCALMODELS_TOOLS_DIR", "").strip()
463
+ environ = os.environ if env is None else env
464
+ if (override := environ.get("LOCALMODELS_TOOLS_DIR", "").strip()) and _is_default_tools_dir(
465
+ given, env=env
431
466
  ):
432
- return override
467
+ return _strip_trailing_sep(override)
433
468
  return str(given)
434
469
 
435
470
 
@@ -520,6 +555,18 @@ def own_gateway(
520
555
  update_owned(change, tools_dir)
521
556
 
522
557
 
558
+ def own_magpie(tools_dir: str | Path, record: OwnedMagpie | None) -> None:
559
+ """Record or clear the private ``magpie serve`` instance launched by this tool."""
560
+
561
+ def change(doc: Owned) -> None:
562
+ if record is None:
563
+ doc["gateway"].pop("magpie", None)
564
+ else:
565
+ doc["gateway"]["magpie"] = record
566
+
567
+ update_owned(change, tools_dir)
568
+
569
+
523
570
  def forget_search(tools_dir: str | Path, field: Literal["search", "search_you"]) -> None:
524
571
  """Forget a Magpie search API this tool added for the web search service it used to run."""
525
572
 
@@ -0,0 +1,76 @@
1
+ """Floor metadata for library models that do not fit this computer's pools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from localmodels import budget, context_policy, library_pricing, metal, suite, vision
6
+ from localmodels.estimator import agent_footprint_bytes, eager
7
+ from localmodels.library_pricing import Model
8
+ from localmodels.probe import HostFacts
9
+
10
+
11
+ def floor_metadata(
12
+ facts: HostFacts,
13
+ model: Model,
14
+ shortfall_bytes: int = 0,
15
+ *,
16
+ memory_kind: str = "",
17
+ ) -> tuple[int, int, bool, int]:
18
+ """Estimated floor memory, context window, vision flag and download bytes when a model does
19
+ not fit this computer's pools (``plan is None``), using the same agent posture.
20
+
21
+ Honors per-entry posture overrides (such as ``ubatch``), accounts for Metal and CUDA UMA
22
+ unified memory, and avoids mixing host RAM shortfalls (``memory_kind == "ram"``) into VRAM
23
+ floor bytes.
24
+ """
25
+ if model.entry.runtime == "strata-poly":
26
+ recipe = suite.recipe(model.entry.id)
27
+ window = int(recipe.get("context") or model.entry.n_ctx_train)
28
+ active = model.entry.agent_posture(
29
+ context_policy.posture_for(library_pricing.posture(), "cuda")
30
+ )
31
+ vision_on = bool(recipe.get("vision")) and active.vision != "off"
32
+ download = sum(
33
+ int(f["size_bytes"]) for f in recipe["files"] if vision_on or not f.get("vision")
34
+ )
35
+ floor_bytes = int(recipe.get("min_vram_free_bytes") or recipe.get("vram_bytes") or 0)
36
+ effective_shortfall = 0 if memory_kind == "ram" else shortfall_bytes
37
+ return max(effective_shortfall, floor_bytes), window, vision_on, download
38
+ metal_unified = metal.supported(facts)
39
+ cuda_uma = not metal_unified and budget.unified_pool_bytes(facts) is not None
40
+ active = model.entry.agent_posture(
41
+ context_policy.posture_for(library_pricing.posture(), "metal" if metal_unified else "cuda")
42
+ )
43
+ profile = eager(model.entry.profile(model.variant))
44
+ window = profile.n_ctx_train if 0 < profile.n_ctx_train < active.floor else active.floor
45
+ vision_on = vision.llama_reader_enabled(model.entry.mmproj, active.vision)
46
+ mtp = bool(model.entry.mtp_capable and model.entry.agent_mtp and active.mtp_draft_depth > 0)
47
+ core = agent_footprint_bytes(
48
+ profile,
49
+ window,
50
+ slots=active.slots,
51
+ kv_types=active.kv_types[-1],
52
+ ubatch=active.ubatch,
53
+ mtp=mtp,
54
+ )
55
+ if metal_unified or cuda_uma:
56
+ vision_extra = (
57
+ vision.llama_device_bytes(model.entry.mmproj, "gpu")
58
+ if vision_on and model.entry.mmproj is not None
59
+ else 0
60
+ )
61
+ host_side = (
62
+ context_policy.cache_floor_bytes(active, profile)
63
+ + context_policy.metal_host_bytes(profile, active)
64
+ if metal_unified
65
+ else 0
66
+ )
67
+ floor_bytes = core + vision_extra + host_side
68
+ else:
69
+ floor_bytes = core
70
+ download = sum(f.size_bytes for f in model.variant.files)
71
+ if vision_on and model.entry.mmproj is not None:
72
+ download += model.entry.mmproj.size_bytes
73
+ if model.entry.mtp_head is not None:
74
+ download += model.entry.mtp_head.size_bytes
75
+ effective_shortfall = 0 if memory_kind == "ram" else shortfall_bytes
76
+ return max(effective_shortfall, floor_bytes), window, vision_on, download
@@ -21,6 +21,7 @@ from pathlib import Path
21
21
  from localmodels import (
22
22
  app,
23
23
  deploy_steps,
24
+ frontend,
24
25
  hosts,
25
26
  library_gateway,
26
27
  library_pricing,
@@ -147,6 +148,11 @@ def delete_weights(files: list[str], keep: set[str]) -> list[str]:
147
148
  return deleted
148
149
 
149
150
 
151
+ KEEP_FAILED_DOWNLOAD_CODES = frozenset(
152
+ ("DOWNLOAD_FAILED", "NETWORK_UNAVAILABLE", "DISK_INSUFFICIENT")
153
+ )
154
+
155
+
150
156
  def _code(message: str) -> str:
151
157
  text = message.lower()
152
158
  if "sha256 mismatch" in text:
@@ -173,16 +179,24 @@ def _download_telemetry(phase: str, event: dict[str, object]) -> tuple[str | Non
173
179
 
174
180
 
175
181
  class _Counter:
176
- """Bytes of the whole model: the files already verified count as done; each progress event
177
- moves its file's counter for the phase it reports."""
182
+ """Bytes of the whole model: the files already verified (or partially downloaded on disk)
183
+ count as done; each progress event moves its file's counter for the phase it reports."""
178
184
 
179
185
  def __init__(self, model: str, plan: Plan, handle: JobHandle) -> None:
180
186
  self.model, self.handle = model, handle
181
187
  self.sizes = {os.path.basename(f["dest"]): f["size_bytes"] for f in plan["files"]}
182
188
  self.done = {
183
- os.path.basename(f["dest"]): f["size_bytes"]
189
+ os.path.basename(f["dest"]): (
190
+ f["size_bytes"]
191
+ if plan_envelope.verified_in_place(f)
192
+ else min(
193
+ f["size_bytes"],
194
+ remote_ops_download.kept_bytes(
195
+ os.path.expanduser(f["dest"]) + ".part", f["size_bytes"]
196
+ ),
197
+ )
198
+ )
184
199
  for f in plan["files"]
185
- if plan_envelope.verified_in_place(f)
186
200
  }
187
201
 
188
202
  @property
@@ -250,7 +264,9 @@ def fetch(
250
264
  """The plan's engine (when it is a pinned release) and weights, as stack apply fetches them;
251
265
  ``only`` limits the weights to the files this job claims. Progress counts the whole model."""
252
266
  counter = _Counter(model, plan, handle)
253
- progress(model, "download", sum(counter.done.values()), counter.total)
267
+ initial_done = sum(counter.done.values())
268
+ handle.update("download", initial_done, counter.total)
269
+ progress(model, "download", initial_done, counter.total)
254
270
  files = [f for f in plan["files"] if only is None or os.path.expanduser(f["dest"]) in only]
255
271
  steps: tuple[Action, ...] = ("download",) if files else ()
256
272
  if engine and plan["engine"]["source"] == "release":
@@ -264,6 +280,11 @@ def fetch(
264
280
  if result.returncode != 0 or outcome.get("event") != "result":
265
281
  message = str(outcome.get("message") or result.stderr.strip()[-500:] or "failed")
266
282
  raise LibraryError(_code(message), message, failed=True)
283
+ if engine and (reqs := plan["launch"].get("frontend_requirements")):
284
+ try:
285
+ frontend.install(str(plan["launch"]["frontend_base_dir"]), str(reqs))
286
+ except frontend.FrontendError as exc:
287
+ raise LibraryError("DOWNLOAD_FAILED", str(exc), failed=True) from None
267
288
  progress(model, "verify", counter.total, counter.total)
268
289
 
269
290
 
@@ -319,7 +340,28 @@ def _refuse_download(lib: library_status.Library, model: Model) -> library_prici
319
340
  lib.facts, priced, library_pricing.base_free(lib.base_dir)
320
341
  )
321
342
  if reason is not None:
322
- error = LibraryError(reason["code"], f"{model.id} cannot be downloaded here")
343
+ code = reason["code"]
344
+ if code == "DRIVER_UPDATE_REQUIRED":
345
+ req = reason.get("required_cuda") or "required CUDA"
346
+ det = reason.get("detected_cuda")
347
+ detail = f"{model.id} requires NVIDIA driver supporting CUDA {req}" + (
348
+ f" (detected {det})" if det else ""
349
+ )
350
+ elif code == "RUNTIME_DEPENDENCY_MISSING":
351
+ missing = reason.get("missing_libraries")
352
+ if missing:
353
+ detail = f"{model.id} requires missing runtime libraries: {', '.join(missing)}"
354
+ elif req_glibc := reason.get("required_glibc"):
355
+ det_glibc = reason.get("detected_glibc") or "unknown"
356
+ detail = f"{model.id} requires glibc {req_glibc}+ (detected {det_glibc})"
357
+ else:
358
+ detail = f"{model.id} is missing required runtime dependencies"
359
+ elif code == "GPU_UNSUPPORTED":
360
+ vendor = reason.get("gpu_vendor") or "unknown"
361
+ detail = f"{model.id} requires an NVIDIA or Apple Silicon GPU (detected: {vendor})"
362
+ else:
363
+ detail = f"{model.id} cannot be downloaded here"
364
+ error = LibraryError(code, detail)
323
365
  if "need_bytes" in reason:
324
366
  error.fields = {"need_bytes": reason["need_bytes"], "have_bytes": reason["have_bytes"]}
325
367
  raise error
@@ -405,7 +447,8 @@ def download(
405
447
  others = claimed_elsewhere(model.id)
406
448
  mine = [f for f in files if os.path.realpath(f) not in others]
407
449
  job = library_state.acquire("download", model.id, priced.pool, memory, mine, files)
408
- with library_state.held([job]):
450
+ claims = [job]
451
+ with library_state.held(claims):
409
452
  handle = library_state.JobHandle(job)
410
453
  try:
411
454
  _fetch_and_commit(model, plan, handle, priced.pool, memory, base_dir, mine, files)
@@ -416,6 +459,16 @@ def download(
416
459
  if library_state.load(model.id) is None:
417
460
  _give_up(model.id, job, handle)
418
461
  raise LibraryError("CANCELLED", "the download was cancelled") from None
462
+ except LibraryError as exc:
463
+ if exc.code in KEEP_FAILED_DOWNLOAD_CODES:
464
+ with library_state.locked():
465
+ if library_state.load(model.id) is None and library_state.current(job):
466
+ if library_state.cancelled(job):
467
+ _give_up(model.id, job, handle)
468
+ raise LibraryError("CANCELLED", "the download was cancelled") from None
469
+ library_state.fail_job(handle.job, {"code": exc.code, "detail": exc.detail})
470
+ claims.clear()
471
+ raise
419
472
  if not autoload:
420
473
  return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
421
474
  try:
@@ -31,6 +31,9 @@ ERROR_CODES = (
31
31
  "MEMORY_INSUFFICIENT",
32
32
  "DISK_INSUFFICIENT",
33
33
  "PLATFORM_UNSUPPORTED",
34
+ "GPU_UNSUPPORTED",
35
+ "DRIVER_UPDATE_REQUIRED",
36
+ "RUNTIME_DEPENDENCY_MISSING",
34
37
  "LOAD_NO_ROOM",
35
38
  "DOWNLOAD_FAILED",
36
39
  "CHECKSUM_MISMATCH",
@@ -51,6 +54,9 @@ REFUSALS = frozenset(
51
54
  "MEMORY_INSUFFICIENT",
52
55
  "DISK_INSUFFICIENT",
53
56
  "PLATFORM_UNSUPPORTED",
57
+ "GPU_UNSUPPORTED",
58
+ "DRIVER_UPDATE_REQUIRED",
59
+ "RUNTIME_DEPENDENCY_MISSING",
54
60
  "LOAD_NO_ROOM",
55
61
  "MODEL_FILES_MISSING",
56
62
  )
@@ -114,6 +120,12 @@ class Holder(TypedDict):
114
120
  bytes: int
115
121
 
116
122
 
123
+ class ExternalHolder(TypedDict):
124
+ name: str
125
+ bytes: int
126
+ pids: list[int]
127
+
128
+
117
129
  class _Pool(TypedDict):
118
130
  id: str # gpu:N | system | unified
119
131
  total_bytes: int
@@ -123,15 +135,26 @@ class _Pool(TypedDict):
123
135
 
124
136
  class Pool(_Pool, total=False):
125
137
  reserve_bytes: int
138
+ external_holders: list[ExternalHolder]
126
139
 
127
140
 
128
141
  class _Reason(TypedDict):
129
- code: str # MEMORY_INSUFFICIENT | DISK_INSUFFICIENT | PLATFORM_UNSUPPORTED
142
+ code: str # MEMORY_INSUFFICIENT | DISK_INSUFFICIENT | PLATFORM_UNSUPPORTED | GPU_UNSUPPORTED | DRIVER_UPDATE_REQUIRED | RUNTIME_DEPENDENCY_MISSING
130
143
 
131
144
 
132
145
  class Reason(_Reason, total=False):
133
146
  need_bytes: int
134
147
  have_bytes: int
148
+ memory_kind: Literal["vram", "ram", "unified"]
149
+ reclaimable_desktop_vram: bool
150
+ reclaim_bytes: int
151
+ gpu_vendor: Literal["amd", "intel", "none", "unknown"]
152
+ required_cuda: str
153
+ detected_cuda: str
154
+ driver_version: str
155
+ missing_libraries: list[str]
156
+ required_glibc: str
157
+ detected_glibc: str
135
158
 
136
159
 
137
160
  class _Availability(TypedDict):
@@ -213,7 +236,16 @@ class Row(_Row, total=False):
213
236
  note: Note # idle only, when autoload was skipped
214
237
 
215
238
 
216
- class Status(TypedDict):
239
+ class _DebugInfo(TypedDict):
240
+ mode: Literal["tiny", "simulate"]
241
+ source: Literal["env", "state_config", "user_config"]
242
+
243
+
244
+ class DebugInfo(_DebugInfo, total=False):
245
+ config_path: str
246
+
247
+
248
+ class _Status(TypedDict):
217
249
  schema: str
218
250
  tool_version: str
219
251
  observed_at: str
@@ -222,6 +254,10 @@ class Status(TypedDict):
222
254
  models: list[Row]
223
255
 
224
256
 
257
+ class Status(_Status, total=False):
258
+ debug: DebugInfo
259
+
260
+
225
261
  def library_id(catalog_id: str, quant: str) -> str:
226
262
  """The stable library id: the catalog id and its variant."""
227
263
  return f"{catalog_id}:{quant}"
@@ -0,0 +1,272 @@
1
+ """PolyStrata (``strata-poly``) LLM recipes for the model library.
2
+
3
+ Validated ``strata-poly`` chat recipes that declare model-card metadata (``display_name``,
4
+ ``description``, ``family``, ``publisher``, ``parameters``) join ``localmodels library`` on
5
+ supported NVIDIA Linux and Windows hosts alongside ``llama.cpp`` models. Pricing runs
6
+ ``suite.build_plan`` so CUDA 13 driver checks, glibc checks, vision reader placement and host
7
+ RAM ceilings stay identical to ``stack plan``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from localmodels import (
13
+ budget,
14
+ catalog_recipes,
15
+ deploy,
16
+ engines,
17
+ hosts,
18
+ plan_envelope,
19
+ stack_suite,
20
+ suite,
21
+ vision,
22
+ )
23
+ from localmodels import catalog as cat
24
+ from localmodels.context_policy import AgentPosture
25
+ from localmodels.estimator import PhysicsRefusal
26
+ from localmodels.library_model import Reason, split_id
27
+ from localmodels.probe import GPU, HostFacts
28
+ from localmodels.records import Plan
29
+
30
+
31
+ def strata_ids() -> set[str]:
32
+ """Every catalog component id of a Strata/PolyStrata runtime."""
33
+ return {
34
+ c["id"] for c in catalog_recipes.components() if c["runtime"] in ("strata", "strata-poly")
35
+ }
36
+
37
+
38
+ def engine_blocker(exc: plan_envelope.PlanError) -> Reason | None:
39
+ """Structured unavailability reason for CUDA driver or runtime library refusals."""
40
+ if isinstance(exc, engines.CudaDriverError):
41
+ reason: Reason = {"code": "DRIVER_UPDATE_REQUIRED"}
42
+ if exc.required_cuda:
43
+ reason["required_cuda"] = exc.required_cuda
44
+ if exc.detected_cuda:
45
+ reason["detected_cuda"] = exc.detected_cuda
46
+ if exc.driver_version:
47
+ reason["driver_version"] = exc.driver_version
48
+ return reason
49
+ if isinstance(exc, engines.EngineUnavailableError):
50
+ reason = {"code": "RUNTIME_DEPENDENCY_MISSING"}
51
+ if exc.missing_libraries:
52
+ reason["missing_libraries"] = list(exc.missing_libraries)
53
+ if exc.required_glibc:
54
+ reason["required_glibc"] = exc.required_glibc
55
+ if exc.detected_glibc:
56
+ reason["detected_glibc"] = exc.detected_glibc
57
+ return reason
58
+ return None
59
+
60
+
61
+ def is_library_recipe(recipe: suite.SuiteRecipe) -> bool:
62
+ """True when a ``strata-poly`` LLM component carries complete model-card metadata."""
63
+ return (
64
+ recipe["runtime"] == "strata-poly"
65
+ and recipe["task"] == "llm"
66
+ and bool(recipe.get("display_name"))
67
+ and bool(recipe.get("description"))
68
+ )
69
+
70
+
71
+ def _validated_for(recipe: suite.SuiteRecipe, platform: str) -> bool:
72
+ if recipe.get("status") != "validated" or not stack_suite.built_for(recipe, platform):
73
+ return False
74
+ scope = recipe.get("validated_on")
75
+ if not scope:
76
+ return True
77
+ # Decision 48: Linux CUDA evidence also validates native Windows x64 CUDA builds.
78
+ return platform in scope or (platform == "win32" and "linux" in scope)
79
+
80
+
81
+ def eligible(recipe: suite.SuiteRecipe, platform: str) -> bool:
82
+ """Whether ``recipe`` should be shown by ``library status`` on ``platform``."""
83
+ return is_library_recipe(recipe) and _validated_for(recipe, platform)
84
+
85
+
86
+ def in_library(recipe_id: str, facts: HostFacts) -> bool:
87
+ """Whether ``recipe_id`` is exposed as a downloadable model in the library on this host."""
88
+ return any(
89
+ r["id"] == recipe_id and eligible(r, facts["platform"]) for r in suite.recipes("llm")
90
+ )
91
+
92
+
93
+ def is_poly_plan(plan: Plan) -> bool:
94
+ """True when ``plan`` deploys a ``strata-poly`` server."""
95
+ if str(plan["engine"].get("build") or "").startswith("strata-poly"):
96
+ return True
97
+ return str(plan["launch"].get("frontend_requirements") or "").startswith("strata-poly")
98
+
99
+
100
+ def as_entry(recipe: suite.SuiteRecipe) -> tuple[cat.CatalogEntry, cat.QuantVariant]:
101
+ """Build a ``CatalogEntry`` + ``QuantVariant`` view of a ``strata-poly`` recipe so
102
+ ``library_status`` and ``library_gateway`` render its model card without special cases."""
103
+ alias = recipe.get("alias") or recipe["id"]
104
+ weight_files = tuple(
105
+ cat.AssetFile(
106
+ path=f"{alias}.gguf" if i == 0 else str(f.get("local_name") or f["path"]),
107
+ size_bytes=int(f["size_bytes"]),
108
+ local=str(f.get("local_name") or "") or None,
109
+ revision=str(f.get("revision") or recipe["revision"]),
110
+ sha256=str(f["sha256"]),
111
+ )
112
+ for i, f in enumerate(recipe["files"])
113
+ if not f.get("vision")
114
+ )
115
+ vision_files = [f for f in recipe["files"] if f.get("vision")]
116
+ mmproj = (
117
+ cat.AssetFile(
118
+ path=str(vision_files[0]["path"]),
119
+ size_bytes=int(vision_files[0]["size_bytes"]),
120
+ local=str(vision_files[0].get("local_name") or "") or None,
121
+ revision=str(vision_files[0].get("revision") or recipe["revision"]),
122
+ sha256=str(vision_files[0]["sha256"]),
123
+ )
124
+ if vision_files
125
+ else None
126
+ )
127
+ variant = cat.QuantVariant(
128
+ quant=recipe["version"],
129
+ files=weight_files,
130
+ validated=recipe.get("status") == "validated",
131
+ )
132
+ quality_doc = recipe.get("quality")
133
+ score = int(quality_doc["score"]) if isinstance(quality_doc, dict) else 0
134
+ entry = cat.CatalogEntry(
135
+ id=recipe["id"],
136
+ display_name=recipe.get("display_name") or alias,
137
+ description=recipe.get("description") or "",
138
+ repo=recipe["repo"],
139
+ variants=(variant,),
140
+ n_ctx_train=int(recipe.get("context") or 65536),
141
+ full_layers=0,
142
+ recurrent_layers=0,
143
+ per_layer_f16=0,
144
+ moe=bool(recipe.get("moe", True)),
145
+ mmproj=mmproj,
146
+ quality=score,
147
+ license=recipe.get("license") or "",
148
+ license_url=recipe.get("license_url") or "",
149
+ status=recipe.get("status") or "",
150
+ tasks=tuple(recipe.get("tasks") or ("llm",)),
151
+ evidence=tuple(recipe.get("evidence") or ()),
152
+ validated_on=tuple(recipe.get("validated_on") or ()),
153
+ reasoning_efforts=tuple(recipe.get("reasoning_efforts") or ()),
154
+ runtime="strata-poly",
155
+ family=recipe.get("family") or "",
156
+ publisher=recipe.get("publisher") or "",
157
+ parameters=recipe.get("parameters") or "",
158
+ active_parameters=recipe.get("active_parameters") or "",
159
+ )
160
+ return entry, variant
161
+
162
+
163
+ def shown_entries(facts: HostFacts) -> list[tuple[cat.CatalogEntry, cat.QuantVariant]]:
164
+ """Every ``strata-poly`` library model visible on this host."""
165
+ platform = facts["platform"]
166
+ return [as_entry(r) for r in suite.recipes("llm") if eligible(r, platform)]
167
+
168
+
169
+ def find_entry(model_id: str) -> tuple[cat.CatalogEntry, cat.QuantVariant] | None:
170
+ """Resolve ``id:QUANT`` (or bare ``id``) to a ``strata-poly`` library model, or None."""
171
+ catalog_id, quant = split_id(model_id)
172
+ for recipe in suite.recipes("llm"):
173
+ if recipe["id"] == catalog_id and is_library_recipe(recipe):
174
+ if not quant or quant == recipe["version"]:
175
+ return as_entry(recipe)
176
+ return None
177
+
178
+
179
+ def _gpu_for_pool(facts: HostFacts, pool: str) -> GPU:
180
+ if not pool.startswith("gpu:"):
181
+ raise plan_envelope.PlanError(f"PolyStrata recipes need a discrete NVIDIA GPU, not {pool}")
182
+ index = int(pool.split(":", 1)[1])
183
+ gpu = next(
184
+ (g for g in facts.get("gpus") or [] if g["index"] == index and g.get("vendor") == "nvidia"),
185
+ None,
186
+ )
187
+ if gpu is None:
188
+ raise plan_envelope.PlanError(f"this computer has no NVIDIA GPU for pool {pool}")
189
+ return gpu
190
+
191
+
192
+ def price(
193
+ facts: HostFacts,
194
+ recipe_id: str,
195
+ pool: str,
196
+ base_dir: str,
197
+ port: int,
198
+ posture: AgentPosture,
199
+ *,
200
+ require_live: bool = False,
201
+ ) -> Plan:
202
+ """Price one ``strata-poly`` library model on discrete pool ``pool``."""
203
+ if facts["platform"] not in ("linux", "win32"):
204
+ raise plan_envelope.PlanError(
205
+ "PolyStrata recipes run on Linux and Windows NVIDIA GPUs only"
206
+ )
207
+ gpu = _gpu_for_pool(facts, pool)
208
+ recipe = suite.recipe(recipe_id)
209
+ if not stack_suite.built_for(recipe, facts["platform"]):
210
+ raise plan_envelope.PlanError(f"{recipe_id} has no engine build for {facts['platform']}")
211
+ spec = recipe.get("vision") or {}
212
+ reader = vision.strata_mode(posture.vision, gpu["total_bytes"], bool(spec))
213
+ reserve = stack_suite.poly_reserve_mib(recipe, gpu, 0)
214
+ opts = suite.SuiteOptions(
215
+ base_dir=base_dir,
216
+ hf_endpoint=deploy.hf_endpoint(),
217
+ gpu=gpu,
218
+ port=port,
219
+ vram_reserve_mib=reserve,
220
+ vision_reader=reader,
221
+ )
222
+ plan = suite.build_plan(hosts.LOCAL_ID, facts, recipe, opts)
223
+ if facts["platform"] == "win32":
224
+ plan = suite.unbounded(plan)
225
+ need_vram = int(recipe.get("vram_bytes") or 0)
226
+ if need_vram > gpu["total_bytes"]:
227
+ msg = f"{recipe_id} needs {need_vram} bytes of VRAM, exceeding {gpu['total_bytes']} bytes"
228
+ raise deploy.AgentMemoryError(
229
+ msg, PhysicsRefusal(need_vram, gpu["total_bytes"], msg), "GPU memory"
230
+ )
231
+ min_free = int(recipe.get("min_vram_free_bytes") or need_vram)
232
+ if require_live and min_free > gpu["free_bytes"]:
233
+ msg = (
234
+ f"{recipe_id} needs at least {min_free} bytes of free VRAM now, "
235
+ f"only {gpu['free_bytes']} bytes free"
236
+ )
237
+ raise deploy.AgentMemoryError(
238
+ msg, PhysicsRefusal(min_free, gpu["free_bytes"], msg), "GPU memory"
239
+ )
240
+ if not require_live and min_free > gpu["free_bytes"]:
241
+ msg = (
242
+ f"{recipe_id} needs at least {min_free} bytes of loadable VRAM, "
243
+ f"only {gpu['free_bytes']} bytes available"
244
+ )
245
+ raise deploy.AgentMemoryError(
246
+ msg, PhysicsRefusal(min_free, gpu["free_bytes"], msg), "GPU memory"
247
+ )
248
+ min_total_ram = int(recipe.get("min_ram_total_bytes") or 0)
249
+ total_ram = facts["ram"]["total_bytes"]
250
+ if min_total_ram > total_ram:
251
+ msg = (
252
+ f"{recipe_id} recommends at least {min_total_ram} bytes of system memory, "
253
+ f"this host has {total_ram} bytes"
254
+ )
255
+ raise deploy.AgentMemoryError(
256
+ msg, PhysicsRefusal(min_total_ram, total_ram, msg), "system memory"
257
+ )
258
+ needed_ram = suite.bounded_ram(plan) + budget.HARNESS_RAM + budget.RAM_FLOOR
259
+ _, avail_ram = budget.host_ram(facts)
260
+ if needed_ram > avail_ram:
261
+ msg = (
262
+ f"{recipe_id} needs {needed_ram} bytes of system memory, "
263
+ f"exceeding {avail_ram} bytes available"
264
+ )
265
+ raise deploy.AgentMemoryError(
266
+ msg, PhysicsRefusal(needed_ram, avail_ram, msg), "system memory"
267
+ )
268
+ # PolyStrata's expert cache fills free VRAM up to the recipe's full-VRAM footprint.
269
+ full_vram = int(str(plan["launch"].get("vram_bytes") or 0))
270
+ if full_vram > gpu["free_bytes"]:
271
+ plan["launch"]["vram_bytes"] = gpu["free_bytes"]
272
+ return plan