@simplexai/localmodels-darwin-arm64 0.1.0-dev.50 → 0.1.0-dev.52

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 (40) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +38 -38
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/catalog.json +1988 -16
  5. package/modules/localmodels/catalog_recipes.py +47 -8
  6. package/modules/localmodels/contracts.py +96 -37
  7. package/modules/localmodels/deploy.py +29 -134
  8. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +132 -0
  9. package/modules/localmodels/engines.py +18 -2
  10. package/modules/localmodels/gateway_bifrost.py +9 -0
  11. package/modules/localmodels/harness_probe.py +38 -22
  12. package/modules/localmodels/library_gateway.py +132 -1
  13. package/modules/localmodels/library_model.py +5 -0
  14. package/modules/localmodels/library_poly.py +59 -0
  15. package/modules/localmodels/library_status.py +96 -31
  16. package/modules/localmodels/plan_envelope.py +234 -3
  17. package/modules/localmodels/process_identity.py +19 -9
  18. package/modules/localmodels/process_identity_darwin.py +155 -0
  19. package/modules/localmodels/remote_ops_service.py +11 -13
  20. package/modules/localmodels/runtime_cli.py +8 -8
  21. package/modules/localmodels/runtime_install.py +25 -1
  22. package/modules/localmodels/source_cli.py +9 -1
  23. package/modules/localmodels/stack.py +0 -5
  24. package/modules/localmodels/stack_binding.py +6 -2
  25. package/modules/localmodels/stack_cli.py +39 -0
  26. package/modules/localmodels/stack_compose.py +12 -43
  27. package/modules/localmodels/stack_plan.py +58 -5
  28. package/modules/localmodels/stack_suite.py +51 -12
  29. package/modules/localmodels/{strata-poly-serve-0.1.45-poly.9.txt → strata-poly-serve-0.2.20-poly.1.txt} +2 -2
  30. package/modules/localmodels/strata_poly_server.py +19 -0
  31. package/modules/localmodels/suite.py +45 -8
  32. package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/METADATA +1 -1
  33. package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/RECORD +35 -35
  34. package/package.json +1 -1
  35. package/tool.json +1 -1
  36. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +0 -75
  37. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/WHEEL +0 -0
  38. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/entry_points.txt +0 -0
  39. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/licenses/NOTICE +0 -0
  40. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -37,6 +37,7 @@ from localmodels.bifrost_config import DECISION_TIMEOUT as DECISION_TIMEOUT
37
37
  from localmodels.bifrost_config import FAST_PROVIDER as FAST_PROVIDER
38
38
  from localmodels.bifrost_config import LOG_BATCH_INTERVAL as LOG_BATCH_INTERVAL
39
39
  from localmodels.bifrost_config import STORE as STORE
40
+ from localmodels.bifrost_config import differs as _config_differs
40
41
  from localmodels.bifrost_config import read_config as read_config
41
42
  from localmodels.bifrost_config import render as render
42
43
  from localmodels.bifrost_config import render_config as render_config
@@ -65,6 +66,8 @@ PI_PROVIDER = "localmodels"
65
66
  PI_MODEL = f"{PI_PROVIDER}/{AGENT_MODEL}"
66
67
  CALLER_KEY = gateway_keys.CALLER_KEY # clients send it; loopback inference checks no key
67
68
  HEALTH_TIMEOUT_S = 180.0
69
+ # Windows cannot delete config.db while a running Bifrost holds it open: stop it before a change.
70
+ STOP_BEFORE_CONFIG_CHANGE = os.name == "nt"
68
71
 
69
72
 
70
73
  def plan_tools(
@@ -592,6 +595,12 @@ def wire(
592
595
  FAST_PROVIDER, (fast["model"], AGENT_MODEL), gw.get("context")
593
596
  )
594
597
  sheets[bifrost_datasheet.DATASHEET].update(extra[bifrost_datasheet.DATASHEET])
598
+ if (
599
+ STOP_BEFORE_CONFIG_CHANGE
600
+ and record["how"] != "unit"
601
+ and _config_differs(app, config, sheets)
602
+ ):
603
+ _stop_owned_serve(record)
595
604
  changed = _write_config(app, config, sheets)
596
605
  if changed or not _healthy_owned(record):
597
606
  _start(record, restart=changed)
@@ -13,7 +13,7 @@ import sys
13
13
  from pathlib import Path
14
14
  from typing import TYPE_CHECKING, TypedDict
15
15
 
16
- from localmodels import hosts, runtime_discovery
16
+ from localmodels import hosts, process_identity_darwin, runtime_discovery
17
17
 
18
18
  if TYPE_CHECKING:
19
19
  from localmodels import harness
@@ -64,16 +64,21 @@ def shown_pi_model(text: str) -> str | None:
64
64
 
65
65
 
66
66
  def listener_uids(addr: str, tables: tuple[str, ...] | None = None) -> set[int]:
67
- """The users whose sockets listen on ``addr``'s port: the given TCP tables (/proc's by default
68
- on Linux), lsof on macOS when no table is given."""
67
+ """The users whose sockets listen on ``addr`` (matching its host and port, plus wildcard
68
+ listeners): the given TCP tables (/proc's by default on Linux), lsof on macOS when no table
69
+ is given."""
69
70
  from localmodels.harness import HarnessError, run_tool
70
71
 
71
- port = int(addr.rpartition(":")[2])
72
+ host, port = process_identity_darwin.parse_host_port(addr)
72
73
  uids: set[int] = set()
73
74
  if tables is None and sys.platform == "win32":
74
75
  from localmodels import process_identity
75
76
 
76
- pids = process_identity.listener_pids(port)
77
+ pids = (
78
+ process_identity.listener_pids(port)
79
+ if host == "127.0.0.1"
80
+ else process_identity.listener_pids(port, host=host)
81
+ )
77
82
  if pids is None:
78
83
  raise HarnessError("cannot confirm who owns the Windows gateway listener")
79
84
  for pid in pids:
@@ -82,16 +87,17 @@ def listener_uids(addr: str, tables: tuple[str, ...] | None = None) -> set[int]:
82
87
  return uids
83
88
  if tables is None and sys.platform == "darwin":
84
89
  out = run_tool(
85
- ["/usr/sbin/lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpu"], timeout=10
90
+ ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpun"], timeout=10
86
91
  )
87
- if out.returncode not in (0, 1):
92
+ parsed = process_identity_darwin.parse_lsof_listeners(out.stdout, port, host)
93
+ if out.returncode not in (0, 1) or parsed is None:
88
94
  raise HarnessError("cannot confirm who owns the macOS gateway listener")
89
- uids = {int(line[1:]) for line in out.stdout.splitlines() if re.fullmatch(r"u\d+", line)}
90
- if out.returncode == 0 and not uids:
95
+ _, uids, _, saw_uid = parsed
96
+ if out.returncode == 0 and not saw_uid:
91
97
  raise HarnessError("cannot confirm who owns the macOS gateway listener")
92
98
  if not uids:
93
99
  try:
94
- with socket.create_connection((addr.rpartition(":")[0], port), timeout=1):
100
+ with socket.create_connection((host, port), timeout=1):
95
101
  raise HarnessError(
96
102
  "the macOS gateway port is listening, but its owner cannot be confirmed"
97
103
  )
@@ -106,7 +112,9 @@ def listener_uids(addr: str, tables: tuple[str, ...] | None = None) -> set[int]:
106
112
  for row in rows: # sl local rem st tx:rx tr:when retrnsmt uid ...
107
113
  f = row.split()
108
114
  if len(f) > 7 and f[3] == "0A" and int(f[1].rpartition(":")[2], 16) == port:
109
- uids.add(int(f[7]))
115
+ bound = process_identity_darwin.parse_proc_net_addr(f[1].rpartition(":")[0])
116
+ if bound is None or process_identity_darwin.address_conflicts(bound, host):
117
+ uids.add(int(f[7]))
110
118
  return uids
111
119
 
112
120
 
@@ -145,12 +153,12 @@ def loopback_listener_pids(port: int, proc: str = _PROC) -> set[int] | None:
145
153
  from localmodels.harness import run_tool
146
154
 
147
155
  out = run_tool(
148
- ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"], timeout=10
156
+ ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpn"], timeout=10
149
157
  )
150
- lines = out.stdout.splitlines()
151
- if out.returncode not in (0, 1) or any(not ln[1:].isdecimal() for ln in lines):
158
+ parsed = process_identity_darwin.parse_lsof_listeners(out.stdout, port, "127.0.0.1")
159
+ if out.returncode not in (0, 1) or parsed is None:
152
160
  return None
153
- return {int(ln[1:]) for ln in lines if ln[:1] == "p"}
161
+ return parsed[0]
154
162
  if not sys.platform.startswith("linux"):
155
163
  return None
156
164
  from localmodels import remote_ops_service
@@ -163,10 +171,11 @@ def loopback_listener_pids(port: int, proc: str = _PROC) -> set[int] | None:
163
171
  return _linux_socket_owner_pids(inodes, proc, uid=os.getuid())
164
172
 
165
173
 
166
- def port_holder(port: int, proc: str = _PROC) -> str | None:
167
- """Who listens on ``port``, for a refusal the operator can act on: "name (pid N)" for this
168
- user's own process, "a process of user uid N" for another user's, None when /proc shows no
169
- listener or cannot be read (Linux only; the caller then says nothing more)."""
174
+ def port_holder(port: int, proc: str = _PROC, *, host: str = "127.0.0.1") -> str | None:
175
+ """Who listens on ``port`` conflicting with ``host``, for a refusal the operator can act on:
176
+ "name (pid N)" for this user's own process, "a process of user uid N" for another user's, None
177
+ when /proc shows no matching listener or cannot be read (Linux only; the caller then says
178
+ nothing more)."""
170
179
  inodes: dict[str, int] = {}
171
180
  for table in ("net/tcp", "net/tcp6"):
172
181
  try:
@@ -176,7 +185,9 @@ def port_holder(port: int, proc: str = _PROC) -> str | None:
176
185
  for row in rows: # sl local rem st tx:rx tr:when retrnsmt uid timeout inode
177
186
  f = row.split()
178
187
  if len(f) > 9 and f[3] == "0A" and int(f[1].rpartition(":")[2], 16) == port:
179
- inodes[f[9]] = int(f[7])
188
+ bound = process_identity_darwin.parse_proc_net_addr(f[1].rpartition(":")[0])
189
+ if bound is None or process_identity_darwin.address_conflicts(bound, host):
190
+ inodes[f[9]] = int(f[7])
180
191
  if not inodes:
181
192
  return None
182
193
  for pid in sorted(_linux_socket_owner_pids(set(inodes), proc)):
@@ -391,8 +402,13 @@ def loopback_listening(port: int) -> bool:
391
402
  def bifrost_held(addr: str) -> str:
392
403
  """The refusal for a listener of this user's that the manifest does not own, naming it: a
393
404
  bifrost-http is most often another HOME's or state directory's localmodels gateway."""
394
- port = addr.rpartition(":")[2]
395
- held = port_holder(int(port)) if port.isdigit() else None
405
+ host, _, port = addr.rpartition(":")
406
+ target = host.strip("[]") or "127.0.0.1"
407
+ held = (
408
+ (port_holder(int(port)) if target == "127.0.0.1" else port_holder(int(port), host=target))
409
+ if port.isdigit()
410
+ else None
411
+ )
396
412
  other = (
397
413
  "; it is not in this tool's owned manifest, so it is most likely the localmodels "
398
414
  "gateway of another HOME or state directory"
@@ -257,6 +257,21 @@ def _pi_add(provider: str, entry: dict[str, Any], base: str) -> None:
257
257
  _write(path, models)
258
258
 
259
259
 
260
+ def _marker_for_other_file(marker: Path, path: Path) -> bool:
261
+ """Whether ``marker`` records ownership of a different existing ``models.json``."""
262
+ try:
263
+ recorded = marker.read_text(encoding="utf-8").strip()
264
+ except OSError:
265
+ return False
266
+ if not recorded:
267
+ return False
268
+ other = Path(recorded)
269
+ try:
270
+ return other.resolve() != path.resolve() and other.is_file()
271
+ except OSError:
272
+ return False
273
+
274
+
260
275
  def _pi_drop(provider: str, model_id: str) -> None:
261
276
  marker = _ours_marker(provider)
262
277
  if not marker.is_file():
@@ -266,7 +281,8 @@ def _pi_drop(provider: str, model_id: str) -> None:
266
281
  providers = models.get("providers")
267
282
  current = providers.get(provider) if isinstance(providers, dict) else None
268
283
  if not isinstance(providers, dict) or not isinstance(current, dict):
269
- marker.unlink(missing_ok=True)
284
+ if not _marker_for_other_file(marker, path):
285
+ marker.unlink(missing_ok=True)
270
286
  return
271
287
  kept = [m for m in current.get("models", []) if m.get("id") != model_id]
272
288
  if kept:
@@ -393,6 +409,113 @@ def model_facts(model: str, entry: cat.CatalogEntry, plan: Plan) -> bifrost_mode
393
409
  }
394
410
 
395
411
 
412
+ def _pi_drop_magpie_provider(profile: Path) -> None:
413
+ """Remove a dead legacy ``magpie`` provider from ``models.json`` in our private profile."""
414
+ path = profile / "models.json"
415
+ try:
416
+ models = _read(path)
417
+ except LibraryError:
418
+ return
419
+ providers = models.get("providers")
420
+ if isinstance(providers, dict) and "magpie" in providers:
421
+ del providers["magpie"]
422
+ _write(path, models)
423
+
424
+
425
+ def _clear_legacy_magpie_pi_record(tools_dir: str) -> None:
426
+ """Drop an orphaned ``magpie/...`` pi ownership entry when transitioning to Bifrost."""
427
+
428
+ def clear(doc: hosts.Owned) -> None:
429
+ pi = doc.get("pi")
430
+ if pi and str(pi.get("model") or "").startswith("magpie/"):
431
+ doc["pi"] = None
432
+
433
+ with contextlib.suppress(OSError, ValueError):
434
+ hosts.update_owned(clear, tools_dir)
435
+
436
+
437
+ def _retire_legacy_magpie(tools_dir: str) -> bool:
438
+ """Undo owned Magpie wiring before moving pi onto Bifrost (WHI-973).
439
+
440
+ Returns True when this computer had owned Magpie wiring or a started Magpie gateway.
441
+ When Magpie was already stopped (for example by ``stack down``) or its earlier plan/binary
442
+ is unavailable, ``leave_magpie`` cannot invoke the Magpie CLI; we still proceed so Bifrost
443
+ registration and pi recovery succeed rather than leaving the user stuck on a dead port.
444
+ """
445
+ from localmodels import bifrost_clients, gateway_switch
446
+
447
+ doc = hosts.load_owned(tools_dir)
448
+ had_magpie = bool(
449
+ bifrost_clients.magpie_wired(doc)
450
+ or doc["gateway"]["started"]
451
+ or doc["gateway"].get("magpie")
452
+ )
453
+ if not had_magpie:
454
+ return False
455
+ try:
456
+ gateway_switch.leave_magpie(tools_dir)
457
+ except (harness.HarnessError, OSError, ValueError):
458
+ _clear_legacy_magpie_pi_record(tools_dir)
459
+ return True
460
+
461
+
462
+ def _sync_pi_default(
463
+ profile: Path,
464
+ pi_provider: str,
465
+ gateway_model: str,
466
+ *,
467
+ stack_provider: str | None,
468
+ retired_magpie: bool = False,
469
+ ) -> None:
470
+ """Keep pi's ``settings.json`` off a dead legacy ``magpie`` default (and restore the
471
+ Quick Install default when an adopted stack LLM is reloaded after ``unpoint_pi``).
472
+ Never overwrites a user-chosen non-magpie default."""
473
+ settings_path = profile / "settings.json"
474
+ try:
475
+ settings = _read(settings_path)
476
+ except LibraryError:
477
+ return
478
+ current_provider = settings.get("defaultProvider")
479
+ current_model = settings.get("defaultModel")
480
+ was_magpie = current_provider == "magpie" or (
481
+ not current_provider
482
+ and isinstance(current_model, str)
483
+ and current_model.startswith("magpie/")
484
+ )
485
+ if was_magpie or (stack_provider is not None and not current_model):
486
+ settings["defaultProvider"] = pi_provider
487
+ settings["defaultModel"] = gateway_model
488
+ _write(settings_path, settings)
489
+ if was_magpie or retired_magpie:
490
+ _pi_drop_magpie_provider(profile)
491
+
492
+
493
+ def reconcile_pi_default(registration: Registration) -> None:
494
+ """Ensure pi's private profile is not left pointing at a dead legacy Magpie gateway when
495
+ a loaded library model is active on Bifrost (WHI-973)."""
496
+ with gateway_locked():
497
+ if ensure_instance(None) is None:
498
+ return
499
+ tools_dir = hosts.tools_dir()
500
+ retired = _retire_legacy_magpie(tools_dir)
501
+ profile = pi_profile()
502
+ pi_provider = registration.get("pi_provider") or (
503
+ gateway_bifrost.PI_PROVIDER
504
+ if registration.get("kind") in ("stack", "agent")
505
+ else PI_PROVIDER
506
+ )
507
+ stack_provider = (
508
+ registration["provider"] if registration.get("kind") in ("stack", "agent") else None
509
+ )
510
+ _sync_pi_default(
511
+ profile,
512
+ pi_provider,
513
+ registration["model"],
514
+ stack_provider=stack_provider,
515
+ retired_magpie=retired,
516
+ )
517
+
518
+
396
519
  def _register(
397
520
  model: str,
398
521
  entry: cat.CatalogEntry,
@@ -433,11 +556,19 @@ def _register(
433
556
  try:
434
557
  if listed_as not in bifrost_models.listed(record["addr"]):
435
558
  raise _fail(f"Bifrost does not list {listed_as}")
559
+ retired_magpie = _retire_legacy_magpie(hosts.tools_dir())
436
560
  facts_ = model_facts(model, entry, plan)
437
561
  base = f"http://{record['addr']}"
438
562
  pi_entry = bifrost_models.pi_provider(facts_, gateway_model, base)["models"][0]
439
563
  if not shared: # the stack's own pi entry already names localmodels-agent
440
564
  _pi_add(pi_provider, pi_entry, base)
565
+ _sync_pi_default(
566
+ pi_profile(),
567
+ pi_provider,
568
+ gateway_model,
569
+ stack_provider=stack_provider,
570
+ retired_magpie=retired_magpie,
571
+ )
441
572
  except BaseException: # roll the gateway back to what it was before this call
442
573
  with contextlib.suppress(harness.HarnessError, OSError, ValueError, LibraryError):
443
574
  apply_config(record, before, before_sheet)
@@ -15,6 +15,7 @@ STATUS_SCHEMA = "localmodels.library-status/v1"
15
15
  EVENT_SCHEMA = "localmodels.library-event/v1"
16
16
 
17
17
  ModelState = Literal["absent", "downloading", "idle", "loading", "loaded", "failed"]
18
+ Engine = Literal["llama.cpp", "polystrata", "strata"]
18
19
  Fit = Literal["gpu", "unified", "system", "none"]
19
20
  Phase = Literal["download", "verify", "load", "warm"]
20
21
  MemoryPressure = Literal["normal", "warn", "critical"]
@@ -229,6 +230,10 @@ class Row(_Row, total=False):
229
230
  license: str
230
231
  source_url: str
231
232
  prompt_tokens_per_second: float # the last load's measured prefill speed
233
+ engine: Engine # inference engine family serving this row
234
+ engine_label: str # engine, pinned build and backend for display
235
+ concurrency: int # maximum simultaneous requests served (slots / parallel)
236
+ host_ram_bytes: int # system RAM held beside VRAM by a hybrid discrete-GPU engine
232
237
  fits_now: bool # live pool currently has enough free memory to load
233
238
  load_need_bytes: int # pool-aligned memory needed to load when fits_now is False
234
239
  load_free_bytes: int # pool-aligned free memory when fits_now is False
@@ -152,6 +152,7 @@ def as_entry(recipe: suite.SuiteRecipe) -> tuple[cat.CatalogEntry, cat.QuantVari
152
152
  validated_on=tuple(recipe.get("validated_on") or ()),
153
153
  reasoning_efforts=tuple(recipe.get("reasoning_efforts") or ()),
154
154
  runtime="strata-poly",
155
+ engine=recipe.get("engine") or "",
155
156
  family=recipe.get("family") or "",
156
157
  publisher=recipe.get("publisher") or "",
157
158
  parameters=recipe.get("parameters") or "",
@@ -189,6 +190,63 @@ def _gpu_for_pool(facts: HostFacts, pool: str) -> GPU:
189
190
  return gpu
190
191
 
191
192
 
193
+ # Measured non-expert VRAM overhead (KV cache + compute buffers + CUDA context) for PolyStrata
194
+ # recipes when experts fit in VRAM: SP219 inkling-2-mini-q3-poly on 16 GB peaked at 14,498 MiB
195
+ # for 12.69 GiB of weights (~1.47 GiB overhead); 2 GiB keeps a conservative safety margin.
196
+ _VRAM_NON_EXPERT_BYTES = 2 << 30
197
+
198
+
199
+ def _ram_experts_bytes(recipe: suite.SuiteRecipe) -> int:
200
+ profile = recipe.get("profile")
201
+ raw_args = profile.get("args") if isinstance(profile, dict) else None
202
+ if not isinstance(raw_args, list):
203
+ return 0
204
+ args = [str(item) for item in raw_args]
205
+ if "--ram-experts-mib" not in args:
206
+ return 0
207
+ idx = args.index("--ram-experts-mib")
208
+ if idx + 1 >= len(args):
209
+ return 0
210
+ try:
211
+ return max(0, int(args[idx + 1]) << 20)
212
+ except ValueError:
213
+ return 0
214
+
215
+
216
+ def _calibrate_host_ram(plan: Plan, recipe: suite.SuiteRecipe, gpu: GPU) -> None:
217
+ """Discount unused ``--ram-experts-mib`` spill when ``gpu`` fits most/all weights in VRAM.
218
+
219
+ Recipes targeting 8-16 GB cards (such as ``inkling-2-mini-q3-poly``) size
220
+ ``memory_estimate_bytes`` for heavy 8 GB RAM expert offloading. On a 16 GB card where
221
+ nearly all experts stay in VRAM (~1.52 GiB host RAM actual), charging the full 8 GB spill
222
+ blocks ``library load`` at ~16.89 GB free RAM.
223
+ """
224
+ ram_experts = _ram_experts_bytes(recipe)
225
+ recipe_base = int(recipe.get("memory_estimate_bytes") or 0)
226
+ if ram_experts <= 0 or recipe_base <= ram_experts:
227
+ return
228
+ weight_bytes = sum(int(f["size_bytes"]) for f in recipe["files"] if not f.get("vision"))
229
+ if weight_bytes <= 0:
230
+ return
231
+ vram_for_weights = max(0, gpu["free_bytes"] - _VRAM_NON_EXPERT_BYTES)
232
+ spilled = min(ram_experts, max(0, weight_bytes - vram_for_weights))
233
+ saved = ram_experts - spilled
234
+ if saved <= 0:
235
+ return
236
+ plan_mem = int(str(plan["launch"]["memory_estimate_bytes"]))
237
+ calibrated = max(0, plan_mem - saved)
238
+ plan["launch"]["memory_estimate_bytes"] = calibrated
239
+ limits = plan["service"].get("limits")
240
+ if isinstance(limits, dict) and "MemoryHigh" in limits:
241
+ old_high = suite.size_bytes(limits["MemoryHigh"])
242
+ new_high = max(calibrated, old_high - saved)
243
+ limits["MemoryHigh"] = f"{(new_high + (1 << 20) - 1) >> 20}M"
244
+ if "MemoryMax" in limits:
245
+ old_max = suite.size_bytes(limits["MemoryMax"])
246
+ new_max = max(new_high + (3 << 30), old_max - saved)
247
+ limits["MemoryMax"] = f"{(new_max + (1 << 20) - 1) >> 20}M"
248
+
249
+
192
250
  def price(
193
251
  facts: HostFacts,
194
252
  recipe_id: str,
@@ -222,6 +280,7 @@ def price(
222
280
  plan = suite.build_plan(hosts.LOCAL_ID, facts, recipe, opts)
223
281
  if facts["platform"] == "win32":
224
282
  plan = suite.unbounded(plan)
283
+ _calibrate_host_ram(plan, recipe, gpu)
225
284
  need_vram = int(recipe.get("vram_bytes") or 0)
226
285
  if need_vram > gpu["total_bytes"]:
227
286
  msg = f"{recipe_id} needs {need_vram} bytes of VRAM, exceeding {gpu['total_bytes']} bytes"
@@ -7,6 +7,7 @@ from __future__ import annotations
7
7
  import datetime as dt
8
8
  import re
9
9
  import urllib.request
10
+ from collections.abc import Mapping
10
11
  from dataclasses import dataclass, field
11
12
  from typing import cast
12
13
 
@@ -33,6 +34,7 @@ from localmodels.library_model import (
33
34
  DebugInfo,
34
35
  Download,
35
36
  DownloadSource,
37
+ Engine,
36
38
  Holder,
37
39
  Host,
38
40
  LibraryError,
@@ -297,6 +299,56 @@ def _loading(job: Job) -> Load:
297
299
  return {"step": step, "done_steps": done_steps, "total_steps": total_steps}
298
300
 
299
301
 
302
+ def _apply_engine_meta(lib: Library, found: Row, model: Model, plan: Plan | None) -> None:
303
+ engine_doc = plan["engine"] if plan is not None else None
304
+ engine = _engine_kind(
305
+ model.entry.runtime, str(engine_doc.get("build") or "") if engine_doc else ""
306
+ )
307
+ found["engine"] = engine
308
+ found["engine_label"] = (
309
+ _format_engine_label(engine_doc)
310
+ if engine_doc is not None
311
+ else _fallback_engine_label(model)
312
+ )
313
+ raw_slots = plan["launch"].get("slots") if plan is not None else None
314
+ parsed_slots = int(str(raw_slots)) if raw_slots is not None else 0
315
+ found["concurrency"] = (
316
+ parsed_slots
317
+ if parsed_slots >= 1
318
+ else (1 if engine in ("polystrata", "strata") else library_pricing.posture().slots)
319
+ )
320
+ if plan is not None and engine in ("polystrata", "strata"):
321
+ host_ram = library_pricing.host_ram_bytes(plan, lib.catalog)
322
+ if host_ram > 0:
323
+ found["host_ram_bytes"] = host_ram
324
+
325
+
326
+ def _apply_record_meta(
327
+ found: Row,
328
+ model: Model,
329
+ record: Record | None,
330
+ state: str,
331
+ problem: Problem | None,
332
+ ) -> None:
333
+ if state != "absent":
334
+ if (selector := pi_model_of(model, record)) is not None:
335
+ found["pi_model"] = selector
336
+ if record is not None:
337
+ if state == "loaded" and (reg := record.get("registration")):
338
+ found["endpoint"] = {
339
+ "base_url": str(record["plan"]["endpoint"]["base_url"]),
340
+ "gateway_model": reg["model"],
341
+ }
342
+ if (speed := record.get("tokens_per_second")) is not None:
343
+ found["tokens_per_second"] = round(speed, 1)
344
+ if (prefill := record.get("prompt_tokens_per_second")) is not None:
345
+ found["prompt_tokens_per_second"] = round(prefill, 1)
346
+ if state == "idle" and (note := record.get("note")):
347
+ found["note"] = note
348
+ if state == "failed" and problem is not None:
349
+ found["error"] = problem
350
+
351
+
300
352
  def row(lib: Library, model: Model) -> Row:
301
353
  record = lib.records.get(model.id)
302
354
  priced = lib.judge(model)
@@ -353,23 +405,8 @@ def row(lib: Library, model: Model) -> Row:
353
405
  elif state == "loading" and job is not None and alive:
354
406
  found["load"] = _loading(job)
355
407
  found.update(card(model, found["vision"]))
356
- if state != "absent":
357
- if (selector := pi_model_of(model, record)) is not None:
358
- found["pi_model"] = selector
359
- if record is not None:
360
- if state == "loaded" and (reg := record.get("registration")):
361
- found["endpoint"] = {
362
- "base_url": str(record["plan"]["endpoint"]["base_url"]),
363
- "gateway_model": reg["model"],
364
- }
365
- if (speed := record.get("tokens_per_second")) is not None:
366
- found["tokens_per_second"] = round(speed, 1)
367
- if (prefill := record.get("prompt_tokens_per_second")) is not None:
368
- found["prompt_tokens_per_second"] = round(prefill, 1)
369
- if state == "idle" and (note := record.get("note")):
370
- found["note"] = note
371
- if state == "failed" and problem is not None:
372
- found["error"] = problem
408
+ _apply_engine_meta(lib, found, model, plan)
409
+ _apply_record_meta(found, model, record, state, problem)
373
410
  return found
374
411
 
375
412
 
@@ -445,6 +482,41 @@ def _pressure_label(level: object) -> MemoryPressure | None:
445
482
  return "critical"
446
483
 
447
484
 
485
+ _BACKEND_LABELS = {"cuda": "CUDA", "metal": "Metal", "cpu": "CPU"}
486
+
487
+
488
+ def _engine_kind(runtime: str, build: str = "") -> Engine:
489
+ if runtime == "strata-poly" or build.startswith("strata-poly"):
490
+ return "polystrata"
491
+ if runtime == "strata" or build.startswith("strata"):
492
+ return "strata"
493
+ return "llama.cpp"
494
+
495
+
496
+ def _format_engine_label(engine: Mapping[str, object]) -> str:
497
+ build = str(engine.get("build") or "")
498
+ if build.startswith("strata-poly-"):
499
+ label = f"PolyStrata {build.removeprefix('strata-poly-')}".strip()
500
+ elif build.startswith("strata-"):
501
+ label = f"Strata {build.removeprefix('strata-')}".strip()
502
+ else:
503
+ label = f"llama.cpp {build}".strip()
504
+ if (kind := engine.get("backend")) in _BACKEND_LABELS:
505
+ label += f" · {_BACKEND_LABELS[str(kind)]}"
506
+ return label
507
+
508
+
509
+ def _fallback_engine_label(model: Model) -> str:
510
+ tag = model.entry.engine or ""
511
+ if model.entry.runtime == "strata-poly":
512
+ version = tag.removeprefix("strata-poly-")
513
+ return f"PolyStrata {version}".strip() if version else "PolyStrata"
514
+ if model.entry.runtime == "strata":
515
+ version = tag.removeprefix("strata-")
516
+ return f"Strata {version}".strip() if version else "Strata"
517
+ return f"llama.cpp {tag}".strip() if tag else "llama.cpp"
518
+
519
+
448
520
  def host(lib: Library) -> Host:
449
521
  facts = lib.facts
450
522
  shown = library_pricing.visible(facts) # the cards the pools may use
@@ -454,20 +526,13 @@ def host(lib: Library) -> Host:
454
526
  or " ".join(str(os_info.get(k) or "") for k in ("system", "release")).strip()
455
527
  )
456
528
  engines = [p.plan["engine"] for p in lib.priced.values() if p.plan is not None]
457
- engine = next(
458
- (e for e in engines if not str(e.get("build") or "").startswith("strata")),
459
- engines[0] if engines else None,
460
- )
461
- backend = {"cuda": "CUDA", "metal": "Metal", "cpu": "CPU"}
462
- engine_label = "llama.cpp"
463
- if engine is not None:
464
- build = str(engine.get("build") or "")
465
- if build.startswith("strata-poly-"):
466
- engine_label = f"PolyStrata {build.removeprefix('strata-poly-')}".strip()
467
- else:
468
- engine_label = f"llama.cpp {build}".strip()
469
- if (kind := engine.get("backend")) in backend:
470
- engine_label += f" · {backend[str(kind)]}"
529
+ by_family: dict[Engine, str] = {}
530
+ for engine in engines:
531
+ family = _engine_kind("", str(engine.get("build") or ""))
532
+ by_family.setdefault(family, _format_engine_label(engine))
533
+ engine_order: tuple[Engine, ...] = ("llama.cpp", "polystrata", "strata")
534
+ ordered = [by_family[f] for f in engine_order if f in by_family]
535
+ engine_label = " + ".join(ordered) if ordered else "llama.cpp"
471
536
  found: Host = {
472
537
  "platform": platform_name(facts),
473
538
  "arch": ARCH.get(str(facts.get("arch")), str(facts.get("arch"))),