@simplexai/localmodels-win32-x64 0.1.0-dev.63 → 0.1.0-dev.65

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 (142) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +140 -130
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +2 -2
  5. package/modules/localmodels/app.py +15 -2
  6. package/modules/localmodels/approval.py +5 -3
  7. package/modules/localmodels/bifrost_checks.py +2 -1
  8. package/modules/localmodels/catalog.json +36 -0
  9. package/modules/localmodels/catalog.py +28 -5
  10. package/modules/localmodels/catalog_recipes.py +40 -1
  11. package/modules/localmodels/component.py +1 -1
  12. package/modules/localmodels/context_policy.py +7 -2
  13. package/modules/localmodels/custom_probe.py +5 -5
  14. package/modules/localmodels/debug_mode.py +85 -103
  15. package/modules/localmodels/deploy.py +129 -18
  16. package/modules/localmodels/deployment_lifecycle.py +167 -0
  17. package/modules/localmodels/download-mirrors.json +126 -6
  18. package/modules/localmodels/draft_spec.py +164 -0
  19. package/modules/localmodels/engine_adapters/__init__.py +4 -0
  20. package/modules/localmodels/engine_adapters/auxiliary.py +27 -0
  21. package/modules/localmodels/engine_adapters/base.py +40 -0
  22. package/modules/localmodels/engine_adapters/strata_poly.py +57 -0
  23. package/modules/localmodels/engine_adapters/suite_plan.py +394 -0
  24. package/modules/localmodels/engines-prism-b12178-03ec600.json +7 -7
  25. package/modules/localmodels/gateway.py +124 -13
  26. package/modules/localmodels/gateway_accept.py +1 -6
  27. package/modules/localmodels/gateway_cli.py +13 -24
  28. package/modules/localmodels/gateway_ops.py +185 -0
  29. package/modules/localmodels/gateway_server.py +3 -2
  30. package/modules/localmodels/harness.py +13 -16
  31. package/modules/localmodels/harness_core.py +4 -9
  32. package/modules/localmodels/harness_gateway.py +4 -3
  33. package/modules/localmodels/hosts.py +22 -34
  34. package/modules/localmodels/install.py +15 -0
  35. package/modules/localmodels/library_convert.py +5 -11
  36. package/modules/localmodels/library_custom.py +6 -6
  37. package/modules/localmodels/library_elastic.py +24 -127
  38. package/modules/localmodels/library_jobs.py +14 -5
  39. package/modules/localmodels/library_order.py +4 -3
  40. package/modules/localmodels/library_poly.py +5 -4
  41. package/modules/localmodels/library_pricing.py +80 -255
  42. package/modules/localmodels/library_serve.py +13 -14
  43. package/modules/localmodels/library_smoke.py +8 -1
  44. package/modules/localmodels/library_status.py +16 -16
  45. package/modules/localmodels/llm_rank.py +1 -1
  46. package/modules/localmodels/magpie_legacy.py +160 -0
  47. package/modules/localmodels/magpie_setup.py +6 -1
  48. package/modules/localmodels/memcalc_cli.py +2 -2
  49. package/modules/localmodels/pi_profile.py +3 -7
  50. package/modules/localmodels/plan_envelope.py +1 -1
  51. package/modules/localmodels/planning/__init__.py +3 -0
  52. package/modules/localmodels/{budget.py → planning/budget.py} +48 -30
  53. package/modules/localmodels/{stack_llm_ram.py → planning/llm_ram.py} +11 -1
  54. package/modules/localmodels/{memcalc_load.py → planning/memcalc_load.py} +1 -1
  55. package/modules/localmodels/planning/memory_pools.py +403 -0
  56. package/modules/localmodels/{sizecalc.py → planning/sizecalc.py} +1 -1
  57. package/modules/localmodels/recommend.py +1 -1
  58. package/modules/localmodels/recommend_cli.py +3 -4
  59. package/modules/localmodels/residency_host.py +1 -1
  60. package/modules/localmodels/service_control.py +4 -4
  61. package/modules/localmodels/service_deployment.py +3 -2
  62. package/modules/localmodels/service_wiring.py +17 -19
  63. package/modules/localmodels/setup_inspection.py +1 -1
  64. package/modules/localmodels/setup_inspection_harness.py +1 -1
  65. package/modules/localmodels/setup_upgrade.py +3 -12
  66. package/modules/localmodels/sizecalc_cli.py +10 -2
  67. package/modules/localmodels/speech_admission.py +1 -1
  68. package/modules/localmodels/speech_jobs.py +2 -1
  69. package/modules/localmodels/speech_model.py +2 -0
  70. package/modules/localmodels/speech_server.py +130 -9
  71. package/modules/localmodels/speech_state.py +11 -0
  72. package/modules/localmodels/speech_worker_sensevoice.py +38 -0
  73. package/modules/localmodels/speech_workers.py +5 -1
  74. package/modules/localmodels/stack.py +4 -9
  75. package/modules/localmodels/stack_arena.py +2 -2
  76. package/modules/localmodels/stack_auto.py +5 -5
  77. package/modules/localmodels/stack_aux_gpu.py +5 -3
  78. package/modules/localmodels/stack_binding.py +24 -143
  79. package/modules/localmodels/stack_capacity.py +1 -1
  80. package/modules/localmodels/stack_card.py +3 -3
  81. package/modules/localmodels/stack_cleanup.py +6 -5
  82. package/modules/localmodels/stack_client_settings.py +9 -2
  83. package/modules/localmodels/stack_compose.py +43 -6
  84. package/modules/localmodels/stack_console.py +2 -2
  85. package/modules/localmodels/stack_debug.py +1 -1
  86. package/modules/localmodels/stack_decision.py +1 -1
  87. package/modules/localmodels/stack_doctor.py +10 -7
  88. package/modules/localmodels/stack_down.py +3 -3
  89. package/modules/localmodels/stack_gpu_memory.py +1 -1
  90. package/modules/localmodels/stack_hardware.py +3 -3
  91. package/modules/localmodels/stack_hardware_text.py +1 -1
  92. package/modules/localmodels/stack_ledger.py +2 -1
  93. package/modules/localmodels/stack_lifecycle.py +7 -7
  94. package/modules/localmodels/stack_mcp.py +1 -1
  95. package/modules/localmodels/stack_memory.py +4 -4
  96. package/modules/localmodels/stack_mlx.py +1 -1
  97. package/modules/localmodels/stack_plan.py +18 -13
  98. package/modules/localmodels/stack_ports.py +2 -2
  99. package/modules/localmodels/stack_preflight.py +4 -3
  100. package/modules/localmodels/stack_remove.py +13 -6
  101. package/modules/localmodels/stack_review.py +3 -5
  102. package/modules/localmodels/stack_rollback.py +1 -1
  103. package/modules/localmodels/stack_route.py +5 -4
  104. package/modules/localmodels/stack_run.py +16 -0
  105. package/modules/localmodels/stack_suite.py +14 -6
  106. package/modules/localmodels/stack_summary.py +1 -1
  107. package/modules/localmodels/stack_try.py +10 -14
  108. package/modules/localmodels/stack_up.py +25 -39
  109. package/modules/localmodels/stack_update.py +2 -1
  110. package/modules/localmodels/stack_verify.py +4 -30
  111. package/modules/localmodels/stack_view.py +6 -4
  112. package/modules/localmodels/stack_view_apply.py +2 -2
  113. package/modules/localmodels/stack_view_llm.py +12 -7
  114. package/modules/localmodels/stack_view_text.py +2 -6
  115. package/modules/localmodels/stack_view_tick.py +2 -2
  116. package/modules/localmodels/stack_view_words.py +5 -2
  117. package/modules/localmodels/stack_warm.py +7 -4
  118. package/modules/localmodels/stack_whatif.py +1 -1
  119. package/modules/localmodels/suite.py +6 -334
  120. package/modules/localmodels/tui_views.py +28 -7
  121. package/modules/localmodels/web/index.html +595 -226
  122. package/modules/localmodels/web/sizecalc/app.js +34 -40
  123. package/modules/localmodels/web/sizecalc/calc.js +3 -3
  124. package/modules/localmodels/web/sizecalc/page.html +4 -3
  125. package/modules/localmodels/web/view/fleet.html +18 -3
  126. package/modules/localmodels/web/view/fleet.js +135 -14
  127. package/modules/localmodels/web/view/i18n.js +4 -0
  128. package/modules/localmodels/web/view/index.html +16 -0
  129. package/modules/localmodels/web/view/nav.js +49 -0
  130. package/modules/localmodels/web/view/theme.js +1 -1
  131. package/modules/localmodels/web/view/view.css +51 -15
  132. package/modules/localmodels/web/view/view.js +22 -4
  133. package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/METADATA +1 -1
  134. package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/RECORD +137 -127
  135. package/package.json +1 -1
  136. package/tool.json +1 -1
  137. package/modules/localmodels/library_vram.py +0 -123
  138. /package/modules/localmodels/{memcalc.py → planning/memcalc.py} +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/WHEEL +0 -0
  140. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/entry_points.txt +0 -0
  141. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/licenses/NOTICE +0 -0
  142. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -14,15 +14,14 @@ from typing import Any, cast
14
14
 
15
15
  from localmodels import (
16
16
  __version__,
17
- budget,
18
17
  debug_mode,
18
+ deployment_lifecycle,
19
19
  hosts,
20
20
  library_elastic,
21
21
  library_gateway,
22
22
  library_order,
23
23
  library_pricing,
24
24
  library_state,
25
- library_vram,
26
25
  metal,
27
26
  plan_envelope,
28
27
  remote_ops_common,
@@ -68,6 +67,7 @@ from localmodels.library_model import (
68
67
  )
69
68
  from localmodels.library_pricing import Model, Priced
70
69
  from localmodels.library_state import Job, Record
70
+ from localmodels.planning import budget, memory_pools
71
71
  from localmodels.probe import HostFacts
72
72
  from localmodels.records import Plan
73
73
 
@@ -147,7 +147,7 @@ def _index_owned_deployments(
147
147
  except (OSError, ValueError):
148
148
  return
149
149
  for name, owned in owned_deployments.items():
150
- if name in library_names or owned.get("removed"):
150
+ if name in library_names or deployment_lifecycle.is_removed(owned):
151
151
  continue
152
152
  owner = f"deployment:{name}"
153
153
  for dest in _extract_dests(owned.get("files") or ()):
@@ -249,7 +249,7 @@ class Library:
249
249
  if not self.healthy(str(record["plan"]["endpoint"]["base_url"])):
250
250
  continue
251
251
  pool = record["pool"]
252
- found[pool] = found.get(pool, 0) + library_pricing.memory_bytes(record["plan"])
252
+ found[pool] = found.get(pool, 0) + memory_pools.memory_bytes(record["plan"])
253
253
  return found
254
254
 
255
255
  def models(self) -> list[Model]:
@@ -337,7 +337,7 @@ def _plan_of(
337
337
  if job is not None and alive and job["pool"] != priced.pool:
338
338
  try:
339
339
  return library_pricing.price(
340
- library_pricing.capacity(lib.facts, reclaimable=lib.reclaimable()),
340
+ memory_pools.capacity(lib.facts, reclaimable=lib.reclaimable()),
341
341
  model,
342
342
  job["pool"],
343
343
  lib.base_dir,
@@ -894,7 +894,7 @@ def row(lib: Library, model: Model) -> Row:
894
894
  if plan is None
895
895
  else (0, 0, False, 0)
896
896
  )
897
- memory = library_pricing.memory_bytes(plan) if plan is not None else fallback_memory
897
+ memory = memory_pools.memory_bytes(plan) if plan is not None else fallback_memory
898
898
  if record is None and job is not None and alive:
899
899
  memory = job["memory_bytes"] or memory
900
900
  if record is not None and record["state"] != "loaded" and record.get("memory_bytes"):
@@ -951,7 +951,7 @@ def row(lib: Library, model: Model) -> Row:
951
951
  def _component_bytes(plan: Plan, pool: str) -> int:
952
952
  launch = plan.get("launch") or {}
953
953
  if pool != "system":
954
- return library_pricing.memory_bytes(plan)
954
+ return memory_pools.memory_bytes(plan)
955
955
  try:
956
956
  return suite.bounded_ram(plan)
957
957
  except (KeyError, ValueError, IndexError):
@@ -961,7 +961,7 @@ def _component_bytes(plan: Plan, pool: str) -> int:
961
961
  def pools(lib: Library, rows: list[Row]) -> list[Pool]:
962
962
  """Every pool with what holds it: loaded and loading library models, and the services this
963
963
  tool runs that are not library models (foundation components)."""
964
- holders: dict[str, list[Holder]] = {p: [] for p in library_pricing.pools(lib.facts)}
964
+ holders: dict[str, list[Holder]] = {p: [] for p in memory_pools.pools(lib.facts)}
965
965
  library_names = {r["plan"]["name"] for r in lib.records.values() if r["state"] != "idle"}
966
966
  for row_ in rows:
967
967
  if row_["state"] in ("loaded", "loading") and row_["pool"] in holders:
@@ -977,7 +977,7 @@ def pools(lib: Library, rows: list[Row]) -> list[Pool]:
977
977
  plan = record["plan"]
978
978
  if plan["name"] in library_names or not record.get("ok"):
979
979
  continue
980
- pool = library_pricing.pool_of(plan)
980
+ pool = memory_pools.pool_of(plan)
981
981
  if pool not in holders:
982
982
  if pool.startswith("gpu:"):
983
983
  continue # a card hidden from the library (CUDA_VISIBLE_DEVICES)
@@ -990,19 +990,19 @@ def pools(lib: Library, rows: list[Row]) -> list[Pool]:
990
990
  "bytes": _component_bytes(plan, pool),
991
991
  }
992
992
  )
993
- now = library_pricing.live(lib.facts, lib.reserved())
993
+ now = memory_pools.live(lib.facts, lib.reserved())
994
994
  gpu_pool_count = sum(1 for p in holders if p.startswith("gpu:"))
995
995
  found: list[Pool] = []
996
996
  for pool, held in holders.items():
997
- total = library_pricing.pool_total(lib.facts, pool)
998
- free = library_pricing.pool_free(now, pool)
997
+ total = memory_pools.pool_total(lib.facts, pool)
998
+ free = memory_pools.pool_free(now, pool)
999
999
  used = min(total, max(0, total - free))
1000
1000
  entry: Pool = {
1001
1001
  "id": pool,
1002
1002
  "total_bytes": total,
1003
1003
  "used_bytes": used,
1004
1004
  "holders": held,
1005
- "reserve_bytes": library_pricing.pool_reserve(now, pool),
1005
+ "reserve_bytes": memory_pools.pool_reserve(now, pool),
1006
1006
  }
1007
1007
  if pool == "unified" and metal.supported(now):
1008
1008
  adm = budget.admission_budget(now, "unified")
@@ -1011,7 +1011,7 @@ def pools(lib: Library, rows: list[Row]) -> list[Pool]:
1011
1011
  entry["hard_ceiling_bytes"] = adm.hard_ceiling_bytes
1012
1012
  if adm.wired_headroom_bytes is not None:
1013
1013
  entry["wired_headroom_bytes"] = adm.wired_headroom_bytes
1014
- if ext := library_vram.pool_external_holders(lib.facts, pool, gpu_pool_count):
1014
+ if ext := memory_pools.pool_external_holders(lib.facts, pool, gpu_pool_count):
1015
1015
  entry["external_holders"] = ext
1016
1016
  found.append(entry)
1017
1017
  return found
@@ -1064,7 +1064,7 @@ def _fallback_engine_label(model: Model) -> str:
1064
1064
 
1065
1065
  def host(lib: Library) -> Host:
1066
1066
  facts = lib.facts
1067
- shown = library_pricing.visible(facts) # the cards the pools may use
1067
+ shown = memory_pools.visible(facts) # the cards the pools may use
1068
1068
  os_info = facts.get("os") or {}
1069
1069
  os_label = str(
1070
1070
  os_info.get("distro")
@@ -1120,7 +1120,7 @@ def host(lib: Library) -> Host:
1120
1120
  def build(lib: Library) -> Status:
1121
1121
  models = lib.models()
1122
1122
  rows = [row(lib, m) for m in models]
1123
- now = library_pricing.live(lib.facts, lib.reserved())
1123
+ now = memory_pools.live(lib.facts, lib.reserved())
1124
1124
  candidates = [
1125
1125
  m
1126
1126
  for m, r in zip(models, rows, strict=True)
@@ -14,7 +14,6 @@ from collections.abc import Iterable, Mapping
14
14
  from dataclasses import dataclass
15
15
 
16
16
  from localmodels import engines, metal, vision
17
- from localmodels.budget import HARNESS_RAM, RAM_FLOOR, host_ram
18
17
  from localmodels.catalog import (
19
18
  USABLE_FLOOR_TOK_S,
20
19
  CatalogEntry,
@@ -29,6 +28,7 @@ from localmodels.catalog import (
29
28
  from localmodels.context_policy import AGENT, AgentPosture
30
29
  from localmodels.estimator import HardwareBudget, PhysicsRefusal, llama_host_bytes
31
30
  from localmodels.plan_envelope import PlanError
31
+ from localmodels.planning.budget import HARNESS_RAM, RAM_FLOOR, host_ram
32
32
  from localmodels.probe import HostFacts
33
33
 
34
34
  # Installed SimplexAI scores closer than this are a tie (model-scoring.md; AIHOT: 3 points or more
@@ -0,0 +1,160 @@
1
+ """The legacy Magpie gateway behind one adapter.
2
+
3
+ A stack plan's ``harness.gateway``, its ``options.gateway`` and an app gateway's
4
+ ``gateway.json`` name their gateway by kind: ``bifrost``, the gateway this tool installs, or
5
+ ``magpie``, the legacy gateway that a plan or record without a kind still means (as does any
6
+ kind that is not ``bifrost``: plans were always read that way).
7
+
8
+ ``of`` turns any of those records into a ``GatewayAdapter``: Bifrost, or ``MagpieLegacyAdapter``
9
+ where Magpie differs. What callers need to tell the two apart (the name shown, the model id a
10
+ client sends, the pinned tool, what the gateway can do) is an attribute or method here, so the
11
+ rest of localmodels asks what the gateway does rather than which one it is. What each gateway
12
+ does once installed lives in the implementation layer (``gateway._gateway``, ``gateway_ops.of``).
13
+ The few places that still decide on the kind read ``legacy``; scripts/architecture_gateway_kind.py
14
+ counts every such decision outside this module (``architecture_baselines.GATEWAY_KIND_BRANCHES``)
15
+ and the count can only go down. Removing Magpie removes ``MagpieLegacyAdapter`` and those
16
+ branches.
17
+
18
+ Standard library only (layer 0), so every layer can ask.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from collections.abc import Mapping
24
+ from typing import Any, Final, Literal
25
+
26
+ BIFROST: Final = "bifrost"
27
+ MAGPIE: Final = "magpie"
28
+ KINDS: Final = (BIFROST, MAGPIE)
29
+ GatewayTool = Literal["bifrost", "magpie"] # the tool lock's entry for each gateway
30
+
31
+
32
+ class GatewayAdapter:
33
+ """Bifrost, the gateway this tool installs. ``MagpieLegacyAdapter`` overrides what differs."""
34
+
35
+ kind: str = BIFROST
36
+ label: str = "Bifrost" # the name plans, reports and dialogs show
37
+ tool: GatewayTool = BIFROST # the tool lock entry and the plan tool that installs the binary
38
+ legacy: bool = False # Magpie: only for the branches architecture_checks still counts
39
+ # An app gateway's startup budget; None: gateway_bifrost.HEALTH_TIMEOUT_S.
40
+ health_timeout_s: float | None = None
41
+ # Bifrost keeps a request log: stack try names the LLM that answered a routed chat from it.
42
+ request_log: bool = True
43
+ # --route fastest: a decision model tiers requests between two LLMs.
44
+ routes_fastest: bool = True
45
+ # A stack plan carries gateway_keys' caller key: Magpie asks callers for one, this tool's
46
+ # Bifrost checks no key on loopback.
47
+ plan_caller_key: bool = False
48
+ # Magpie's usage CSV: stack view lists it as request events.
49
+ usage_events: bool = False
50
+ # Its private config under an app gateway root, removed when the root changes gateway.
51
+ app_config: tuple[str, ...] = ("bifrost",)
52
+ # What a stack plan warns about this gateway.
53
+ plan_warning: str | None = None
54
+ # Where the gateway serves the decision API, when not at the service API's own path: Bifrost
55
+ # serves the typesafe decision API under its own prefix.
56
+ decision_path: str | None = "/typesafe/v1/systemone"
57
+ # The model library also writes this gateway's config: changes to it take the library's
58
+ # lock (library_gateway.gateway_locked), and recheck the stack once they hold it.
59
+ shares_config: bool = True
60
+ # The provider name pi knows this gateway by, when it is not the stack's own: legacy
61
+ # Magpie's ``magpie`` provider, whose models are ``magpie/<id>``.
62
+ pi_provider: str | None = None
63
+ # File names of the gateway's binary among the tools this tool installed.
64
+ executables: frozenset[str] = frozenset({"bifrost-http", "bifrost-http.exe"})
65
+
66
+ def selected_in_pi(self, provider: object, model: object) -> bool:
67
+ """pi's default (``defaultProvider``, ``defaultModel``) is this gateway's provider."""
68
+ if self.pi_provider is None:
69
+ return False
70
+ return provider == self.pi_provider or (
71
+ not provider and isinstance(model, str) and model.startswith(self.pi_provider + "/")
72
+ )
73
+
74
+ def model(self, group: str) -> str:
75
+ """The model id a client sends to reach the stack's routing group."""
76
+ return group
77
+
78
+ def routing(self, group: str, *, tiered: bool) -> str:
79
+ """How a plan summary names the stack's routing group (``tiered``: a decision model
80
+ picks the effort or LLM)."""
81
+ return f", routed model {group}" + (" (tiered by the decision model)" if tiered else "")
82
+
83
+ def binding(self, addr: str, caller_key: str) -> dict[str, str]:
84
+ """The gateway binding the service worker forwards through (``caller_key``:
85
+ gateway_keys.CALLER_KEY). This tool's Bifrost checks no key on loopback inference."""
86
+ return {"baseUrl": f"http://{addr}/v1", "key": caller_key, "kind": self.kind}
87
+
88
+ def executable(self, platform: str) -> str:
89
+ """The binary's file name in an app gateway root (``platform``: the lock's name)."""
90
+ return "bifrost-http"
91
+
92
+ def __repr__(self) -> str:
93
+ return f"{type(self).__name__}()"
94
+
95
+
96
+ class MagpieLegacyAdapter(GatewayAdapter):
97
+ """Magpie, the legacy gateway: every way it differs from Bifrost."""
98
+
99
+ kind = MAGPIE
100
+ label = "Magpie"
101
+ tool = MAGPIE
102
+ legacy = True
103
+ health_timeout_s = 30.0
104
+ request_log = False
105
+ routes_fastest = False
106
+ plan_caller_key = True
107
+ decision_path = None
108
+ shares_config = False
109
+ pi_provider = "magpie"
110
+ executables = frozenset({"magpie", "magpie.exe"})
111
+ usage_events = True
112
+ app_config = ("home", ".config", "magpie")
113
+ plan_warning = (
114
+ "to register the local service keys, the control side uses Magpie's local"
115
+ " authenticated admin API; keys stay out of command-line arguments, diagnostic output"
116
+ " and temporary files, and are then kept in Magpie's providers.json (0600)"
117
+ )
118
+
119
+ def model(self, group: str) -> str:
120
+ return f"group/{group}"
121
+
122
+ def routing(self, group: str, *, tiered: bool) -> str:
123
+ return f", routing group {self.model(group)}"
124
+
125
+ def binding(self, addr: str, caller_key: str) -> dict[str, str]:
126
+ # Magpie's documented local client key is an app identity, not a remote gateway secret;
127
+ # the binding names no kind, as bindings did before there was a choice.
128
+ return {"baseUrl": f"http://{addr}/v1", "key": "magpie-simplex"}
129
+
130
+ def executable(self, platform: str) -> str:
131
+ return "magpie.exe" if platform == "windows" else "magpie"
132
+
133
+
134
+ BIFROST_ADAPTER: Final = GatewayAdapter()
135
+ MAGPIE_LEGACY: Final = MagpieLegacyAdapter()
136
+
137
+ # Tools that update themselves after install: the copy at the path it was installed to stays
138
+ # this tool's whatever version it has become.
139
+ SELF_UPDATING_TOOLS: Final = frozenset({MAGPIE_LEGACY.tool})
140
+
141
+
142
+ def for_kind(kind: object) -> GatewayAdapter:
143
+ """The adapter for a recorded kind: Bifrost for ``bifrost``, Magpie for anything else."""
144
+ return BIFROST_ADAPTER if kind == BIFROST else MAGPIE_LEGACY
145
+
146
+
147
+ def of(gateway: Mapping[str, Any] | None) -> GatewayAdapter:
148
+ """The adapter for a record with a ``kind``: a plan's ``harness.gateway``, a gateway view,
149
+ a service binding or ``gateway.json``. None or no kind: Magpie."""
150
+ return for_kind((gateway or {}).get("kind"))
151
+
152
+
153
+ def of_options(options: Mapping[str, Any]) -> GatewayAdapter:
154
+ """The adapter a plan's ``options`` chose; a plan from before the choice used Magpie."""
155
+ return for_kind(options.get("gateway"))
156
+
157
+
158
+ def known(kind: object) -> bool:
159
+ """Whether ``kind`` names a gateway."""
160
+ return kind in KINDS
@@ -27,6 +27,7 @@ from typing import TypedDict
27
27
  from localmodels import (
28
28
  approval,
29
29
  cli_help,
30
+ deployment_lifecycle,
30
31
  gateway,
31
32
  gateway_clients,
32
33
  harness,
@@ -502,7 +503,11 @@ def remove(purge: bool, yes: bool) -> int:
502
503
  refused while a stack deployment still uses the gateway."""
503
504
  owned = hosts.load_owned()
504
505
  members = lifecycle.stack_members()
505
- live = sorted(n for n, d in owned["deployments"].items() if n in members and not d["removed"])
506
+ live = sorted(
507
+ n
508
+ for n, d in owned["deployments"].items()
509
+ if n in members and deployment_lifecycle.holds_service(d)
510
+ )
506
511
  if live:
507
512
  print(
508
513
  f"magpie:本机还有 stack 部署({'、'.join(live)})在用这个网关;"
@@ -11,7 +11,7 @@ from pathlib import Path
11
11
  from typing import Any
12
12
 
13
13
  from localmodels import cli_help, vision
14
- from localmodels.memcalc import (
14
+ from localmodels.planning.memcalc import (
15
15
  GIB,
16
16
  KIB,
17
17
  KV_TYPES,
@@ -24,7 +24,7 @@ from localmodels.memcalc import (
24
24
  quant_bits,
25
25
  report,
26
26
  )
27
- from localmodels.memcalc_load import WeightOptions, load_model
27
+ from localmodels.planning.memcalc_load import WeightOptions, load_model
28
28
 
29
29
 
30
30
  def _gib(n: float) -> str:
@@ -15,7 +15,7 @@ from collections.abc import Mapping
15
15
  from pathlib import Path
16
16
  from typing import Any
17
17
 
18
- from localmodels import hosts, runtime_auth, runtime_discovery, runtime_io
18
+ from localmodels import hosts, magpie_legacy, runtime_auth, runtime_discovery, runtime_io
19
19
 
20
20
  RUNTIMES = ("codex", "claude", "pi")
21
21
  PROFILE_KEYS = {
@@ -360,17 +360,13 @@ class PiProfileStore:
360
360
  return
361
361
  current_provider = settings.get("defaultProvider")
362
362
  current_model = settings.get("defaultModel")
363
- was_magpie = current_provider == "magpie" or (
364
- not current_provider
365
- and isinstance(current_model, str)
366
- and current_model.startswith("magpie/")
367
- )
363
+ was_magpie = magpie_legacy.MAGPIE_LEGACY.selected_in_pi(current_provider, current_model)
368
364
  if was_magpie or (stack_provider is not None and not current_model):
369
365
  settings["defaultProvider"] = pi_provider
370
366
  settings["defaultModel"] = gateway_model
371
367
  self.write_settings(settings)
372
368
  if was_magpie or retired_magpie:
373
- self.drop_provider("magpie")
369
+ self.drop_provider(str(magpie_legacy.MAGPIE_LEGACY.pi_provider))
374
370
 
375
371
  def write_isolated_profile(
376
372
  self, provider: str, provider_entry: dict[str, Any], default_model: str
@@ -24,8 +24,8 @@ from typing import TypedDict
24
24
 
25
25
  from localmodels import catalog as cat
26
26
  from localmodels import region
27
- from localmodels.budget import gib
28
27
  from localmodels.contracts import decode
28
+ from localmodels.planning.budget import gib
29
29
  from localmodels.probe import HostFacts
30
30
  from localmodels.records import (
31
31
  Launch,
@@ -0,0 +1,3 @@
1
+ """Memory and capacity pricing as pure functions: per-model memory by context length
2
+ (``memcalc``, read by ``memcalc_load``) and weight size by device class (``sizecalc``).
3
+ See docs/local-models/architecture.md#子包."""
@@ -1,4 +1,4 @@
1
- """Hardware budgets from probe facts.
1
+ """Hardware budgets from probe facts: the placements a host offers and what each may hold.
2
2
 
3
3
  Hermes' probe_budget() reads the machine it runs on and prices only CUDA device 0. Here the same
4
4
  rules run on the controller over a host-facts document (localmodels.probe), so local and remote
@@ -34,7 +34,8 @@ HARNESS_RAM = 1 * _GIB
34
34
  _MARGIN_FLOOR = 2 << 30
35
35
  _MARGIN_FRACTION = 0.09
36
36
  _LAUNCH_HEADROOM = 1 << 30
37
- _UMA_HEADROOM_FRACTION = 0.20
37
+ # Unified memory (a Mac, an integrated CUDA device, CPU RAM) keeps this share back from models.
38
+ UMA_HEADROOM_FRACTION = 0.20
38
39
  _POOL_DISAGREEMENT_FACTOR = 1.5
39
40
  _POOL_RAM_FRACTION = 0.75
40
41
  # A card whose free memory is below this share of its total holds someone else's work.
@@ -78,6 +79,41 @@ def _margin(total: int) -> int:
78
79
  return max(_MARGIN_FLOOR, int(total * _MARGIN_FRACTION))
79
80
 
80
81
 
82
+ def uma_usable(base: int) -> int:
83
+ """What a unified-memory pool of ``base`` bytes may give models: less UMA_HEADROOM_FRACTION."""
84
+ return int(base * (1 - UMA_HEADROOM_FRACTION))
85
+
86
+
87
+ def cuda_uma_agent_bytes(base: int) -> int:
88
+ """What an agent-posture model may take of a CUDA unified-memory pool of ``base`` bytes: the
89
+ usable share less the agent safety and display reserve."""
90
+ return max(0, uma_usable(base) - AGENT_VRAM_RESERVE_BYTES)
91
+
92
+
93
+ def nvidia_cards(facts: HostFacts) -> list[GPU]:
94
+ """The NVIDIA cards CUDA can place on, in probe order: every one not in MIG mode (CUDA sees
95
+ only a MIG card's instances)."""
96
+ return [
97
+ g
98
+ for g in facts.get("gpus") or []
99
+ if g.get("vendor") == "nvidia" and g.get("mig_mode") != "enabled"
100
+ ]
101
+
102
+
103
+ def cuda_uma_live_bytes(facts: HostFacts, unified: int) -> int:
104
+ """A CUDA unified-memory pool of ``unified`` bytes as free now: device 0's free memory plus
105
+ the RAM available to a service, never more than the pool."""
106
+ cards = nvidia_cards(facts)
107
+ first_free = cards[0]["free_bytes"] if cards else 0
108
+ return min(unified, first_free + host_ram(facts)[1])
109
+
110
+
111
+ def metal_reserve_bytes(facts: HostFacts) -> int:
112
+ """What a Mac keeps back from models in unified memory: the host's soft keep (scaled by its
113
+ RAM) plus the Metal VRAM reserve."""
114
+ return metal.soft_host_keep_bytes(facts) + METAL_VRAM_RESERVE_BYTES
115
+
116
+
81
117
  def unified_pool_bytes(facts: HostFacts) -> int | None:
82
118
  """The allocator pool when the NVIDIA device is unified memory behind a carve-out, else None.
83
119
  The driver's INTEGRATED attribute decides when readable; otherwise both numeric gates hold."""
@@ -111,7 +147,7 @@ def _uma(
111
147
  lazy_reads: bool = True,
112
148
  ) -> HardwareBudget:
113
149
  return HardwareBudget(
114
- usable_vram_bytes=max(0, int(base * (1 - _UMA_HEADROOM_FRACTION))),
150
+ usable_vram_bytes=max(0, uma_usable(base)),
115
151
  total_device_bytes=total,
116
152
  ram_available_bytes=0,
117
153
  uma=True,
@@ -327,20 +363,15 @@ def placements(facts: HostFacts, *, planning: bool = True) -> list[Placement]:
327
363
  recommendation); ``planning=False`` prices free memory now (a launch)."""
328
364
  ram_total, ram_avail = host_ram(facts)
329
365
  ram_budget = ram_total if planning else ram_avail
330
- gpus = [
331
- g
332
- for g in facts.get("gpus") or []
333
- if g.get("vendor") == "nvidia" and g.get("mig_mode") != "enabled"
334
- ]
366
+ gpus = nvidia_cards(facts)
335
367
  conflicts = gpu_conflicts(facts)
336
368
 
337
369
  result: list[Placement] = []
338
370
  unified = unified_pool_bytes(facts)
339
371
  if unified is not None:
340
372
  first = gpus[0] if gpus else None
341
- live = first["free_bytes"] + ram_avail if first else ram_avail
342
373
  uma_budget = _uma(
343
- unified if planning else min(unified, live),
374
+ unified if planning else cuda_uma_live_bytes(facts, unified),
344
375
  unified,
345
376
  facts,
346
377
  gpu_name=first["name"] if first else "",
@@ -451,7 +482,7 @@ def launch_budget(capacity: Placement, facts: HostFacts, *, own_bytes: int = 0)
451
482
  total, available = host_ram(facts)
452
483
  return replace(
453
484
  capacity.budget,
454
- usable_vram_bytes=max(0, int(available * (1 - _UMA_HEADROOM_FRACTION))),
485
+ usable_vram_bytes=max(0, uma_usable(available)),
455
486
  total_device_bytes=total,
456
487
  ram_available_bytes=0,
457
488
  )
@@ -559,7 +590,7 @@ def admission_budget(
559
590
  if metal.supported(facts):
560
591
  level = facts["ram"].get("pressure_level")
561
592
  critical = metal.is_critical_pressure(facts)
562
- base_reserve = metal.soft_host_keep_bytes(facts) + METAL_VRAM_RESERVE_BYTES
593
+ base_reserve = metal_reserve_bytes(facts)
563
594
  pressured_facts, _ = metal.pressured(facts)
564
595
  kept = int(pressured_facts["ram"].get("pressure_kept_bytes") or 0)
565
596
  reserve = base_reserve + kept
@@ -603,22 +634,9 @@ def admission_budget(
603
634
  unified = unified_pool_bytes(facts)
604
635
  if unified is None:
605
636
  return None
606
- nvidia = [
607
- g
608
- for g in facts.get("gpus") or []
609
- if g.get("vendor") == "nvidia" and g.get("mig_mode") != "enabled"
610
- ]
611
- first_free = nvidia[0]["free_bytes"] if nvidia else 0
612
- _, ram_avail = host_ram(facts)
613
- usable_total = max(
614
- 0, int(unified * (1 - _UMA_HEADROOM_FRACTION)) - AGENT_VRAM_RESERVE_BYTES
615
- )
616
- raw_live = max(
617
- 0,
618
- int(min(unified, first_free + ram_avail) * (1 - _UMA_HEADROOM_FRACTION))
619
- - AGENT_VRAM_RESERVE_BYTES,
620
- )
621
- live_budget = max(0, min(usable_total, raw_live - delta_bytes))
637
+ live = cuda_uma_live_bytes(facts, unified)
638
+ usable_total = cuda_uma_agent_bytes(unified)
639
+ live_budget = max(0, min(usable_total, cuda_uma_agent_bytes(live) - delta_bytes))
622
640
  return AdmissionBudget(
623
641
  pool="unified",
624
642
  backend="cuda",
@@ -626,7 +644,7 @@ def admission_budget(
626
644
  hard_ceiling_bytes=live_budget,
627
645
  reserve_bytes=max(0, unified - usable_total),
628
646
  allows_soft_overcommit=False,
629
- physical_limit_bytes=max(0, min(unified, first_free + ram_avail) - delta_bytes),
647
+ physical_limit_bytes=max(0, live - delta_bytes),
630
648
  )
631
649
  if pool.startswith("gpu:"):
632
650
  try:
@@ -656,7 +674,7 @@ def admission_budget(
656
674
  )
657
675
  if pool == "system":
658
676
  total, avail = host_ram(facts)
659
- pool_cap = int(total * (1 - _UMA_HEADROOM_FRACTION))
677
+ pool_cap = uma_usable(total)
660
678
  used = total - avail
661
679
  usable = max(0, min(pool_cap, pool_cap - used - delta_bytes))
662
680
  return AdmissionBudget(
@@ -16,9 +16,10 @@ from collections.abc import Sequence
16
16
  from typing import cast
17
17
 
18
18
  from localmodels import catalog as cat
19
- from localmodels.budget import gib
19
+ from localmodels import draft_spec
20
20
  from localmodels.context_policy import AgentPosture
21
21
  from localmodels.estimator import llama_host_bytes
22
+ from localmodels.planning.budget import gib
22
23
  from localmodels.records import Plan
23
24
 
24
25
 
@@ -61,6 +62,15 @@ def prompt_cache_bytes(llm: Plan) -> int:
61
62
  return max(0, int(argv[argv.index("--cache-ram") + 1])) << 20
62
63
 
63
64
 
65
+ def drafter_costs_cache(llm: Plan, posture: AgentPosture) -> bool:
66
+ """Whether a unified-memory LLM carries an optional external drafter (DSpark) while its prompt
67
+ cache came out below the posture's full ``--cache-ram``. The drafter and the cache share one
68
+ pool there, so the plan without the drafter holds the larger cache; an optional speed-up never
69
+ outranks the prompt cache, and the caller re-plans with ``draft="off"``."""
70
+ full = posture.prompt_cache_mib << 20
71
+ return draft_spec.active(llm["launch"]) and 0 < prompt_cache_bytes(llm) < full
72
+
73
+
64
74
  # What a cache grown into the RAM left leaves free, so the RAM may fall this far between plan
65
75
  # and apply and the approved plan still fits: a desktop's free RAM moves by tens of MiB a minute,
66
76
  # and a cache sized to the last megabyte made every apply on one fail its RAM check (WINSTK1).
@@ -16,7 +16,7 @@ from typing import Any
16
16
 
17
17
  from localmodels import estimator, remote_ops_redirect
18
18
  from localmodels.gguf import read_gguf_header, split_parts
19
- from localmodels.memcalc import (
19
+ from localmodels.planning.memcalc import (
20
20
  MIB,
21
21
  MemcalcError,
22
22
  Model,