@simplexai/localmodels-linux-arm64 0.1.0-dev.103 → 0.1.0-dev.105

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 (172) hide show
  1. package/LICENSE +201 -0
  2. package/{modules/simplex_localmodels-0.1.0.dev103.dist-info/licenses/NOTICE → NOTICE} +42 -13
  3. package/README.md +10 -0
  4. package/bootstrap.identity +1 -1
  5. package/bootstrap.sha256 +159 -158
  6. package/modules/localmodels/__init__.py +1 -1
  7. package/modules/localmodels/__main__.py +204 -86
  8. package/modules/localmodels/apple_sensors.py +23 -0
  9. package/modules/localmodels/approval.py +25 -2
  10. package/modules/localmodels/catalog.json +584 -158
  11. package/modules/localmodels/catalog.py +18 -3
  12. package/modules/localmodels/catalog_recipes.py +64 -6
  13. package/modules/localmodels/cli_help.py +10 -0
  14. package/modules/localmodels/cli_parser.py +313 -230
  15. package/modules/localmodels/component.py +21 -3
  16. package/modules/localmodels/console.py +1 -1
  17. package/modules/localmodels/context_policy.py +6 -5
  18. package/modules/localmodels/custom_probe.py +4 -2
  19. package/modules/localmodels/debug_cli.py +0 -12
  20. package/modules/localmodels/debug_mode.py +0 -6
  21. package/modules/localmodels/decode_calibration.json +3 -4
  22. package/modules/localmodels/decode_calibration.py +5 -2
  23. package/modules/localmodels/deploy.py +11 -1
  24. package/modules/localmodels/deployment_lifecycle.py +1 -1
  25. package/modules/localmodels/download-mirrors.json +1 -1
  26. package/modules/localmodels/engine_adapters/base.py +11 -1
  27. package/modules/localmodels/engine_adapters/strata_poly.py +65 -3
  28. package/modules/localmodels/engine_adapters/suite_plan.py +61 -24
  29. package/modules/localmodels/engines-b11583.json +6 -26
  30. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +3 -15
  31. package/modules/localmodels/engines-b12757-mix-ef2df21.json +3 -15
  32. package/modules/localmodels/engines-prism-b12178-03ec600.json +3 -15
  33. package/modules/localmodels/engines-speechcpp-v0.11.3.json +4 -20
  34. package/modules/localmodels/engines-strata-0.1.47.json +1 -5
  35. package/modules/localmodels/engines-strata-0.1.49.2.json +1 -5
  36. package/modules/localmodels/engines-strata-0.1.59.1.json +1 -5
  37. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +6 -30
  38. package/modules/localmodels/engines-strata-poly-0.2.20-poly.9.json +129 -0
  39. package/modules/localmodels/engines-whisper-b5454.json +6 -30
  40. package/modules/localmodels/engines.json +13 -61
  41. package/modules/localmodels/estimator.py +10 -5
  42. package/modules/localmodels/gpu_specs.py +1 -1
  43. package/modules/localmodels/host_sensors.py +25 -2
  44. package/modules/localmodels/hosts.py +38 -21
  45. package/modules/localmodels/kokoro-tts-0.6.1.txt +1 -1
  46. package/modules/localmodels/library_cli.py +34 -16
  47. package/modules/localmodels/library_custom.py +9 -1
  48. package/modules/localmodels/library_direct.py +41 -1
  49. package/modules/localmodels/library_elastic.py +135 -6
  50. package/modules/localmodels/library_jobs.py +23 -4
  51. package/modules/localmodels/library_kept.py +9 -1
  52. package/modules/localmodels/library_model.py +174 -2
  53. package/modules/localmodels/library_order.py +175 -69
  54. package/modules/localmodels/library_poly.py +150 -21
  55. package/modules/localmodels/library_presentation.py +485 -0
  56. package/modules/localmodels/library_pricing.py +15 -4
  57. package/modules/localmodels/library_serve.py +342 -70
  58. package/modules/localmodels/library_smoke.py +63 -5
  59. package/modules/localmodels/library_state.py +48 -10
  60. package/modules/localmodels/library_status.py +37 -17
  61. package/modules/localmodels/llm_rank.py +22 -11
  62. package/modules/localmodels/metal.py +1 -2
  63. package/modules/localmodels/plan_envelope.py +40 -13
  64. package/modules/localmodels/planning/budget.py +14 -12
  65. package/modules/localmodels/planning/memory_pools.py +7 -1
  66. package/modules/localmodels/privacy_acceptance.py +6 -5
  67. package/modules/localmodels/probe.py +34 -7
  68. package/modules/localmodels/py.typed +0 -0
  69. package/modules/localmodels/quant_formats.py +10 -3
  70. package/modules/localmodels/recommend_cli.py +1 -1
  71. package/modules/localmodels/records.py +19 -2
  72. package/modules/localmodels/remote_ops_launchd.py +8 -1
  73. package/modules/localmodels/remote_ops_verify.py +91 -24
  74. package/modules/localmodels/runtime_index.py +303 -0
  75. package/modules/localmodels/runtime_process.py +1 -1
  76. package/modules/localmodels/service_deployment.py +2 -4
  77. package/modules/localmodels/service_probe.py +59 -13
  78. package/modules/localmodels/setup_inspection.py +94 -73
  79. package/modules/localmodels/setup_text.py +7 -56
  80. package/modules/localmodels/sidecar_downloads.py +34 -0
  81. package/modules/localmodels/sidecar_http.py +61 -5
  82. package/modules/localmodels/sidecar_state.py +52 -2
  83. package/modules/localmodels/speech_admission.py +20 -4
  84. package/modules/localmodels/speech_catalog.py +23 -0
  85. package/modules/localmodels/speech_cli.py +30 -16
  86. package/modules/localmodels/speech_jobs.py +42 -17
  87. package/modules/localmodels/speech_serve.py +9 -2
  88. package/modules/localmodels/speech_server.py +185 -81
  89. package/modules/localmodels/speech_state.py +4 -1
  90. package/modules/localmodels/speech_workers.py +11 -0
  91. package/modules/localmodels/stack.py +1 -1
  92. package/modules/localmodels/stack_args.py +276 -145
  93. package/modules/localmodels/stack_auto.py +91 -6
  94. package/modules/localmodels/stack_aux_gpu.py +1 -1
  95. package/modules/localmodels/stack_cleanup.py +21 -18
  96. package/modules/localmodels/stack_cli.py +120 -115
  97. package/modules/localmodels/stack_compose.py +16 -5
  98. package/modules/localmodels/stack_debug.py +15 -6
  99. package/modules/localmodels/stack_decision.py +4 -4
  100. package/modules/localmodels/stack_doctor.py +2 -2
  101. package/modules/localmodels/stack_down.py +2 -0
  102. package/modules/localmodels/stack_events.py +1 -1
  103. package/modules/localmodels/stack_gpu_memory.py +1 -1
  104. package/modules/localmodels/stack_hardware.py +17 -15
  105. package/modules/localmodels/stack_mcp.py +1 -2
  106. package/modules/localmodels/stack_mlx.py +8 -1
  107. package/modules/localmodels/stack_picks.py +20 -21
  108. package/modules/localmodels/stack_plan.py +12 -11
  109. package/modules/localmodels/stack_ports.py +31 -4
  110. package/modules/localmodels/stack_review.py +28 -7
  111. package/modules/localmodels/stack_rollback.py +1 -1
  112. package/modules/localmodels/stack_run.py +1 -1
  113. package/modules/localmodels/stack_suite.py +72 -21
  114. package/modules/localmodels/stack_up.py +2 -0
  115. package/modules/localmodels/stack_view.py +180 -35
  116. package/modules/localmodels/stack_view_agent.py +1 -1
  117. package/modules/localmodels/stack_view_demo.py +2 -0
  118. package/modules/localmodels/stack_view_gpu.py +36 -2
  119. package/modules/localmodels/stack_view_schema.py +26 -3
  120. package/modules/localmodels/stack_view_serve.py +0 -2
  121. package/modules/localmodels/stack_view_slots.py +3 -1
  122. package/modules/localmodels/stack_view_telemetry.py +90 -4
  123. package/modules/localmodels/stack_view_tick.py +246 -40
  124. package/modules/localmodels/stack_view_words.py +9 -2
  125. package/modules/localmodels/stack_warm.py +2 -2
  126. package/modules/localmodels/stack_whatif.py +524 -41
  127. package/modules/localmodels/stack_whatif_html.py +900 -0
  128. package/modules/localmodels/startlux-decide-83fe6c7d.txt +2 -2
  129. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.7.txt → strata-poly-serve-0.2.20-poly.9.txt} +1 -1
  130. package/modules/localmodels/strata_poly_server.py +114 -3
  131. package/modules/localmodels/suite.py +265 -6
  132. package/modules/localmodels/telemetry_math.py +458 -18
  133. package/modules/localmodels/transport.py +8 -1
  134. package/modules/localmodels/tts_admission.py +2 -17
  135. package/modules/localmodels/tts_catalog.py +29 -1
  136. package/modules/localmodels/tts_cli.py +45 -22
  137. package/modules/localmodels/tts_http.py +10 -4
  138. package/modules/localmodels/tts_jobs.py +49 -19
  139. package/modules/localmodels/tts_serve.py +9 -2
  140. package/modules/localmodels/tts_server.py +1 -1
  141. package/modules/localmodels/tts_sidecar.py +69 -28
  142. package/modules/localmodels/tts_state.py +7 -2
  143. package/modules/localmodels/vision.py +5 -3
  144. package/modules/localmodels/web/view/ASSET-SOURCES.md +4 -7
  145. package/modules/localmodels/web/view/view.css +0 -1
  146. package/modules/localmodels/web/view/view.js +2 -5
  147. package/modules/localmodels/web/whatif/app.js +730 -0
  148. package/modules/localmodels/web/whatif/page.html +1172 -0
  149. package/modules/localmodels/web/whatif/sim.js +297 -0
  150. package/modules/localmodels/win_probe.py +89 -16
  151. package/modules/localmodels/windows_job.py +179 -11
  152. package/modules/simplex_localmodels-0.1.0.dev105.dist-info/METADATA +14 -0
  153. package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/RECORD +151 -145
  154. package/modules/simplex_localmodels-0.1.0.dev105.dist-info/licenses/LICENSE +201 -0
  155. package/modules/simplex_localmodels-0.1.0.dev105.dist-info/licenses/NOTICE +126 -0
  156. package/package.json +11 -2
  157. package/tool.json +1 -1
  158. package/modules/localmodels/engines-strata-poly-0.2.20-poly.7.json +0 -94
  159. package/modules/localmodels/fixtures/stack-research-demo-plan.json +0 -1059
  160. package/modules/localmodels/stack_research.py +0 -716
  161. package/modules/localmodels/stack_research_demo.py +0 -125
  162. package/modules/localmodels/stack_research_plan.py +0 -146
  163. package/modules/localmodels/web/index.html +0 -2605
  164. package/modules/localmodels/web/sizecalc/app.js +0 -1306
  165. package/modules/localmodels/web/sizecalc/calc.js +0 -269
  166. package/modules/localmodels/web/sizecalc/page.html +0 -520
  167. package/modules/localmodels/web/view/logo-claude.svg +0 -3
  168. package/modules/localmodels/web/view/logo-codex.png +0 -0
  169. package/modules/simplex_localmodels-0.1.0.dev103.dist-info/METADATA +0 -9
  170. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/WHEEL +0 -0
  171. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/entry_points.txt +0 -0
  172. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -19,10 +19,13 @@ from pathlib import Path
19
19
 
20
20
  from localmodels import (
21
21
  app,
22
+ chat_template,
22
23
  custom_hub,
23
24
  draft_spec,
24
25
  hosts,
25
26
  library_jobs,
27
+ library_kept,
28
+ library_poly,
26
29
  library_pricing,
27
30
  library_serve,
28
31
  library_state,
@@ -91,6 +94,12 @@ def _strip_flags(argv: list[str], names: set[str], valued: set[str]) -> list[str
91
94
  return out
92
95
 
93
96
 
97
+ def _unwrap_launcher(argv: list[str]) -> list[str]:
98
+ if len(argv) >= 3 and Path(argv[1].replace("\\", "/")).name == chat_template.SLOT_CACHE:
99
+ return argv[2:]
100
+ return argv
101
+
102
+
94
103
  def _build_smoke_plan(
95
104
  record: Record,
96
105
  facts: HostFacts,
@@ -114,11 +123,11 @@ def _build_smoke_plan(
114
123
  deploy_dir = f"{base}/deployments/{smoke_name}"
115
124
  api_key_file = f"{deploy_dir}/api-key"
116
125
 
117
- argv = list(plan["service"]["argv"])
126
+ argv = _unwrap_launcher(list(plan["service"]["argv"]))
118
127
  argv = _strip_flags(
119
128
  argv,
120
- names={"--jinja", "--no-warmup", "--mmproj-offload"},
121
- valued={"--mmproj", "--chat-template-file", "--reasoning-budget"},
129
+ names={"--jinja", "--no-warmup", "--mmproj-offload", "--no-mmproj-offload"},
130
+ valued={"--mmproj", "--chat-template-file", "--reasoning-budget", "--slot-save-path"},
122
131
  )
123
132
  argv = _replace_flag(argv, ("-c", "--ctx-size"), "-c", str(ctx))
124
133
  argv = _replace_flag(argv, ("-np", "--parallel"), "-np", "1")
@@ -223,16 +232,65 @@ def _restore_verification(model_id: str, prior: VerificationRecord | None) -> No
223
232
  library_state.save(current)
224
233
 
225
234
 
226
- def smoke_test(model_id: str, base_dir: str, *, ctx: int = 4096) -> Row:
227
- """Run an isolated ephemeral smoke-test at ``ctx`` tokens and persist ``verification``."""
235
+ def _validate_smoke_target(model_id: str, ctx: int) -> library_pricing.Model:
228
236
  if isinstance(ctx, bool) or ctx <= 0:
229
237
  raise LibraryError("INVALID_STATE", "--ctx must be a positive integer")
230
238
  model = library_pricing.find(model_id, library_pricing.entries())
239
+ if model.entry.runtime != "llama.cpp":
240
+ raise LibraryError(
241
+ "INVALID_STATE",
242
+ f"smoke-test supports llama.cpp models only ({model.id} uses {model.entry.runtime})",
243
+ )
244
+ if library_kept.retired(model.entry):
245
+ raise LibraryError(
246
+ "INVALID_STATE",
247
+ f"this version no longer ships {model.id}; remove it and download a current model",
248
+ )
249
+ return model
250
+
251
+
252
+ def _record_runtime_issue(record: Record) -> str | None:
253
+ custom = record.get("custom")
254
+ if custom is not None and (fmt := custom.get("format")) not in (None, "gguf"):
255
+ return str(fmt)
256
+ plan = record["plan"]
257
+ if library_poly.is_poly_plan(plan):
258
+ return "strata-poly"
259
+ launch_runtime = str(plan["launch"].get("runtime") or "")
260
+ if launch_runtime and launch_runtime != "llama.cpp":
261
+ return launch_runtime
262
+ build = str(plan["engine"].get("build") or "")
263
+ if build.startswith("strata"):
264
+ return "strata"
265
+ if build.startswith("mlx"):
266
+ return "mlx-lm"
267
+ source = str(plan["engine"].get("source") or "")
268
+ if source in ("python", "venv"):
269
+ return source
270
+ argv = _unwrap_launcher(list(plan["service"]["argv"]))
271
+ binary = str(plan["engine"].get("binary") or "")
272
+ if not argv or (binary and argv[0] != binary):
273
+ return "an unsupported launcher"
274
+ return None
275
+
276
+
277
+ def _validate_smoke_record(model_id: str, record: Record) -> None:
278
+ if issue := _record_runtime_issue(record):
279
+ raise LibraryError(
280
+ "INVALID_STATE",
281
+ f"smoke-test supports llama.cpp models only ({model_id} uses {issue})",
282
+ )
283
+
284
+
285
+ def smoke_test(model_id: str, base_dir: str, *, ctx: int = 4096) -> Row:
286
+ """Run an isolated ephemeral smoke-test at ``ctx`` tokens and persist ``verification``."""
287
+ model = _validate_smoke_target(model_id, ctx)
231
288
  with library_state.locked():
232
289
  library_state.refuse_busy(model.id, "smoke_test")
233
290
  record = library_state.load(model.id)
234
291
  if record is None:
235
292
  raise LibraryError("INVALID_STATE", f"{model.id} is not downloaded")
293
+ _validate_smoke_record(model.id, record)
236
294
  if missing := library_jobs.files_missing(record["plan"]):
237
295
  raise LibraryError("MODEL_FILES_MISSING", "missing: " + ", ".join(missing))
238
296
  facts = library_jobs.probe()
@@ -15,6 +15,7 @@ import contextlib
15
15
  import json
16
16
  import os
17
17
  import re
18
+ import threading
18
19
  import uuid
19
20
  from collections.abc import Iterator
20
21
  from contextlib import contextmanager
@@ -23,7 +24,7 @@ from typing import Literal, TypedDict
23
24
 
24
25
  from localmodels import hosts, process_identity
25
26
  from localmodels.contracts import decode
26
- from localmodels.library_model import LibraryError, Note, Problem
27
+ from localmodels.library_model import LibraryError, LoadBreakdownMs, Note, Problem
27
28
  from localmodels.plan_envelope import utc_now
28
29
  from localmodels.records import Plan
29
30
 
@@ -144,6 +145,13 @@ class Record(_RecordRequired, total=False):
144
145
  custom: CustomMeta # custom hub model metadata (absent for curated models)
145
146
  verification: VerificationRecord # smoke-test verification state (custom models)
146
147
  catalog_entry: dict[str, object] # schema-3 entry snapshot for custom models
148
+ loaded_at: str | None # RFC3339 UTC timestamp when the active load became ready
149
+ load_duration_ms: int | None # total load duration in ms for the active load
150
+ load_breakdown_ms: LoadBreakdownMs | None # per-phase timing breakdown in ms
151
+ cold_load: bool | None # whether the active load was cold (None when indeterminate)
152
+ warm_first_s: float | None # wall seconds of warm_llm() first request
153
+ warm_second_s: float | None # wall seconds of warm_llm() second request
154
+ ever_loaded: bool # True once the model has completed at least one load on this host
147
155
 
148
156
 
149
157
  class _JobSince20261113(TypedDict, total=False):
@@ -178,8 +186,19 @@ class Job(_JobSince20261113):
178
186
  updated_at: str
179
187
 
180
188
 
181
- def root() -> Path:
182
- return hosts.state_dir() / "library"
189
+ _HELD_LOCKS = threading.local()
190
+
191
+
192
+ def _held_locks() -> set[str]:
193
+ held: set[str] | None = getattr(_HELD_LOCKS, "keys", None)
194
+ if held is None:
195
+ held = set()
196
+ _HELD_LOCKS.keys = held
197
+ return held
198
+
199
+
200
+ def root(state_dir: Path | None = None) -> Path:
201
+ return (hosts.state_dir() if state_dir is None else state_dir) / "library"
183
202
 
184
203
 
185
204
  def _file(model: str) -> str:
@@ -199,10 +218,20 @@ def pid_path(model: str) -> Path:
199
218
 
200
219
 
201
220
  @contextmanager
202
- def locked() -> Iterator[None]:
203
- """The one lock every state transition holds, briefly."""
204
- with hosts.file_lock(root() / ".lock"):
221
+ def locked(state_dir: Path | None = None) -> Iterator[None]:
222
+ """The one lock every state transition holds, briefly (re-entrant per thread)."""
223
+ lock_file = root(state_dir) / ".lock"
224
+ resolved = os.path.realpath(lock_file)
225
+ held = _held_locks()
226
+ if resolved in held:
205
227
  yield
228
+ return
229
+ with hosts.file_lock(lock_file):
230
+ held.add(resolved)
231
+ try:
232
+ yield
233
+ finally:
234
+ held.discard(resolved)
206
235
 
207
236
 
208
237
  def load(model: str) -> Record | None:
@@ -213,9 +242,9 @@ def load(model: str) -> Record | None:
213
242
  return None
214
243
 
215
244
 
216
- def records() -> list[Record]:
245
+ def records(state_dir: Path | None = None) -> list[Record]:
217
246
  found = []
218
- for path in sorted((root() / "models").glob("*.json")):
247
+ for path in sorted((root(state_dir) / "models").glob("*.json")):
219
248
  try:
220
249
  found.append(decode(json.loads(path.read_text(encoding="utf-8")), Record))
221
250
  except (OSError, ValueError):
@@ -335,6 +364,14 @@ def fail_job(job: Job, error: Problem) -> None:
335
364
  path.unlink(missing_ok=True)
336
365
 
337
366
 
367
+ def _may_persist_job(job: Job) -> bool:
368
+ """Under ``locked()``: True only while ``job`` still owns its model slot and is active."""
369
+ found = read_job(job["model"])
370
+ if found is None or found.get("id") != job.get("id"):
371
+ return False
372
+ return not found.get("error") and not cancelled(job)
373
+
374
+
338
375
  class JobHandle:
339
376
  """This process's job: progress written for ``status``, at most once a second."""
340
377
 
@@ -415,8 +452,9 @@ class JobHandle:
415
452
  if changed or now - self._written >= JOB_WRITE_EVERY_S or done >= total:
416
453
  self._written = now
417
454
  self.job["updated_at"] = utc_now()
418
- with contextlib.suppress(OSError):
419
- hosts.save_private(job_path(self.job["model"]), self.job)
455
+ with contextlib.suppress(OSError), locked():
456
+ if _may_persist_job(self.job):
457
+ hosts.save_private(job_path(self.job["model"]), self.job)
420
458
 
421
459
 
422
460
  def refuse_busy(model: str, kind: str) -> None:
@@ -20,6 +20,7 @@ from localmodels import (
20
20
  library_direct,
21
21
  library_elastic,
22
22
  library_order,
23
+ library_presentation,
23
24
  library_pricing,
24
25
  library_state,
25
26
  metal,
@@ -64,6 +65,8 @@ from localmodels.library_model import (
64
65
  VerificationFailureKind,
65
66
  VerificationMeta,
66
67
  VerificationStatus,
68
+ apply_load_lifecycle,
69
+ disambiguate_row_names,
67
70
  sanitize_problem,
68
71
  )
69
72
  from localmodels.library_pricing import Model, Priced
@@ -380,8 +383,11 @@ def card(model: Model, vision_on: bool) -> Row:
380
383
  }
381
384
  if HUB_REPO.fullmatch(entry.repo):
382
385
  found["source_url"] = f"https://huggingface.co/{entry.repo}"
383
- if vision_on:
384
- found["capabilities"] = ["vision"]
386
+ caps = [c for c in entry.capabilities if c != "vision" or vision_on]
387
+ if vision_on and "vision" not in caps:
388
+ caps = ["vision", *caps]
389
+ if caps:
390
+ found["capabilities"] = caps
385
391
  return cast(Row, {k: v for k, v in found.items() if v})
386
392
 
387
393
 
@@ -483,16 +489,20 @@ def _apply_engine_meta(lib: Library, found: Row, model: Model, plan: Plan | None
483
489
  )
484
490
  raw_slots = plan["launch"].get("slots") if plan is not None else None
485
491
  parsed_slots = int(str(raw_slots)) if raw_slots is not None else 0
486
- found["concurrency"] = (
487
- parsed_slots
488
- if parsed_slots >= 1
489
- else (
490
- 2
491
- if engine == "polystrata"
492
- else (1 if engine == "strata" else library_pricing.posture().slots)
493
- )
494
- )
495
- if plan is not None and engine in ("polystrata", "strata"):
492
+ if parsed_slots >= 1:
493
+ concurrency = parsed_slots
494
+ elif engine == "polystrata":
495
+ recipe = next((r for r in suite.recipes("llm") if r["id"] == model.entry.id), None)
496
+ concurrency = suite.effective_parallel(recipe, ()) if recipe is not None else 1
497
+ else:
498
+ concurrency = 1 if engine == "strata" else library_pricing.posture().slots
499
+ found["concurrency"] = concurrency
500
+ if (
501
+ plan is not None
502
+ and engine in ("polystrata", "strata")
503
+ and found["pool"] != "unified"
504
+ and memory_pools.pool_of(plan) != "unified"
505
+ ):
496
506
  host_ram = library_pricing.host_ram_bytes(plan, lib.catalog)
497
507
  if host_ram > 0:
498
508
  found["host_ram_bytes"] = host_ram
@@ -568,6 +578,8 @@ def _apply_record_meta(
568
578
  record: Record | None,
569
579
  state: str,
570
580
  problem: Problem | None,
581
+ *,
582
+ now_utc: dt.datetime,
571
583
  ) -> None:
572
584
  if state != "absent":
573
585
  if (selector := pi_model_of(model, record)) is not None:
@@ -575,6 +587,7 @@ def _apply_record_meta(
575
587
  if record is not None:
576
588
  if state == "loaded":
577
589
  _apply_loaded_endpoint(found, model, record)
590
+ apply_load_lifecycle(found, record, now_utc=now_utc)
578
591
  if (speed := record.get("tokens_per_second")) is not None:
579
592
  found["tokens_per_second"] = round(speed, 1)
580
593
  if (prefill := record.get("prompt_tokens_per_second")) is not None:
@@ -908,7 +921,8 @@ def _apply_storage(
908
921
  found["storage"] = storage
909
922
 
910
923
 
911
- def row(lib: Library, model: Model) -> Row:
924
+ def row(lib: Library, model: Model, *, now_utc: dt.datetime | None = None) -> Row:
925
+ observed_now = dt.datetime.now(dt.timezone.utc) if now_utc is None else now_utc
912
926
  record = lib.records.get(model.id)
913
927
  priced = lib.judge(model)
914
928
  state, problem = _state(lib, model.id, record)
@@ -969,7 +983,8 @@ def row(lib: Library, model: Model) -> Row:
969
983
  found["load"] = _loading(job)
970
984
  found.update(card(model, found["vision"]))
971
985
  _apply_engine_meta(lib, found, model, plan)
972
- _apply_record_meta(found, model, record, state, problem)
986
+ library_presentation.apply_row_meta(lib.facts, found, model, plan)
987
+ _apply_record_meta(found, model, record, state, problem, now_utc=observed_now)
973
988
  _apply_custom_meta(found, record, job, alive)
974
989
  _apply_storage(lib, found, model, record, job, plan, state)
975
990
  return found
@@ -1145,8 +1160,10 @@ def host(lib: Library) -> Host:
1145
1160
 
1146
1161
 
1147
1162
  def build(lib: Library) -> Status:
1163
+ observed_now = dt.datetime.now(dt.timezone.utc)
1148
1164
  models = lib.models()
1149
- rows = [row(lib, m) for m in models]
1165
+ rows = [row(lib, m, now_utc=observed_now) for m in models]
1166
+ disambiguate_row_names(rows)
1150
1167
  now = memory_pools.live(lib.facts, lib.reserved())
1151
1168
  candidates = [
1152
1169
  m
@@ -1156,14 +1173,17 @@ def build(lib: Library) -> Status:
1156
1173
  and r.get("fits_now") is True
1157
1174
  and r.get("origin") != "custom"
1158
1175
  ]
1159
- chosen = library_pricing.recommend(now, candidates, lib.base_dir)
1176
+ best_pick = library_pricing.smartest(now, lib.base_dir)
1177
+ best_id = f"{best_pick[0]}:{best_pick[1]}" if best_pick is not None else None
1178
+ chosen = next((m.id for m in candidates if m.id == best_id), None) if best_id else None
1160
1179
  for r in rows:
1161
1180
  r["recommended"] = r["id"] == chosen
1162
1181
  rows = library_order.order_rows(lib.facts, models, rows)
1182
+ library_presentation.enrich_status_rows(lib.facts, rows, best_id)
1163
1183
  status_doc: Status = {
1164
1184
  "schema": STATUS_SCHEMA,
1165
1185
  "tool_version": __version__,
1166
- "observed_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
1186
+ "observed_at": observed_now.isoformat(timespec="seconds"),
1167
1187
  "host": host(lib),
1168
1188
  "pools": pools(lib, rows),
1169
1189
  "models": rows,
@@ -1,6 +1,6 @@
1
1
  """Which catalog LLM is the default for a budget: a gate, then an order.
2
2
 
3
- The gate is the agent posture — since roadmap decision 26 a window of at least 64K for the
3
+ The gate is the agent posture — a window of at least 64K for the
4
4
  posture's slots, weights and KV resident. Gated entries are ordered by ``quality.score``, which
5
5
  for scored entries is the installed SimplexAI score (docs/local-models/model-scoring.md),
6
6
  then by predicted decode speed; ``choose`` applies the user's scenario (``--prefer``).
@@ -12,6 +12,7 @@ from __future__ import annotations
12
12
 
13
13
  from collections.abc import Iterable, Mapping
14
14
  from dataclasses import dataclass
15
+ from typing import Literal
15
16
 
16
17
  from localmodels import engines, metal, vision
17
18
  from localmodels.catalog import (
@@ -26,7 +27,7 @@ from localmodels.catalog import (
26
27
  validated_here,
27
28
  )
28
29
  from localmodels.context_policy import AGENT, AgentPosture
29
- from localmodels.estimator import HardwareBudget, PhysicsRefusal, llama_host_bytes
30
+ from localmodels.estimator import Backend, HardwareBudget, PhysicsRefusal, llama_host_bytes
30
31
  from localmodels.plan_envelope import PlanError
31
32
  from localmodels.planning.budget import HARNESS_RAM, RAM_FLOOR, host_ram
32
33
  from localmodels.probe import HostFacts
@@ -35,7 +36,7 @@ from localmodels.probe import HostFacts
35
36
  # rarely swap): a challenger with another engine must beat the llama.cpp pick by at least this.
36
37
  TIE_BAND = 3
37
38
  # Scores within this band are statistically indistinguishable (AIHOT: under 1 point is a coin
38
- # flip; roadmap decision 71): break ties by decode speed, and let prefer_over_llama recipes win.
39
+ # flip): break ties by decode speed, and let prefer_over_llama recipes win.
39
40
  COIN_FLIP = 1
40
41
  # --prefer fast: the fastest fitting model whose score is within this many points of the best.
41
42
  FAST_QUALITY_BAND = 5
@@ -70,14 +71,20 @@ def strata_bar(llama_score: int, options: Mapping[str, object]) -> int:
70
71
 
71
72
 
72
73
  def strata_recipe_bar(
73
- llama_score: int, options: Mapping[str, object], *, prefer_over_llama: bool = False
74
+ llama_score: int,
75
+ options: Mapping[str, object],
76
+ *,
77
+ prefer_over_llama: bool = False,
78
+ allow_poly_fastest: bool = False,
74
79
  ) -> int:
75
80
  """The installed score one Strata/PolyStrata recipe must reach to replace the llama.cpp pick:
76
81
  a recipe marked ``prefer_over_llama`` (such as PolyStrata Inkling 2 Mini on CUDA 13+, which
77
82
  offers higher-precision quants and faster decode/prefill on NVIDIA cards) wins within
78
- ``COIN_FLIP`` against llama.cpp under ``smartest``, while keeping ``--prefer fastest`` on
79
- llama.cpp when one fits."""
83
+ ``COIN_FLIP`` against llama.cpp under ``smartest`` and ``concurrent``, and may compete under
84
+ ``--prefer fastest`` when ``allow_poly_fastest`` is set (full-VRAM resident, >= 2 slots)."""
80
85
  if options.get("prefer") == "fastest" and llama_score >= 0:
86
+ if allow_poly_fastest and prefer_over_llama:
87
+ return 0
81
88
  return 1 << 30
82
89
  if prefer_over_llama:
83
90
  return max(0, llama_score - COIN_FLIP)
@@ -90,12 +97,12 @@ PRODUCT_DEFAULTS = {
90
97
 
91
98
 
92
99
  # The installed SimplexAI score at which a validated model takes over from the Mac ladder
93
- # (roadmap decision 40, 2026-11-09: intelligence first): 50 is the AIHOT reference-model mean.
100
+ # (intelligence first): 50 is the reference-model mean.
94
101
  # A 24 GB Mac with the memory free holds Qwen3.8-27B UD-IQ3_S (52); one under desktop load, and
95
102
  # every 16 GB Mac, stays on the ladder rather than a lower-scored model such as Qwen3.6-35B-A3B.
96
103
  MAC_DEFAULT_YIELD_SCORE = 50
97
104
 
98
- # The Mac small-memory ladder (roadmap decisions 57, 61 and 68, user-selected; replaces decision
105
+ # The Mac small-memory ladder (user-selected; replaces earlier
99
106
  # 39's LFM3-1.7B): on every Apple Silicon Mac of MAC_LADDER_MIN_BYTES or more, while no validated
100
107
  # model scoring MAC_DEFAULT_YIELD_SCORE or more fits, --llm auto tries Ornith 1.5 9B Q4_K_M first
101
108
  # (fits 16 GB idle Macs and busy 24 GB+ Macs from ~12.5 GiB available), then falls back to
@@ -209,7 +216,7 @@ def agent_ready(
209
216
  budget: HardwareBudget,
210
217
  posture: AgentPosture = AGENT,
211
218
  ) -> bool:
212
- """The gate every recommended LLM passes before it is ranked (roadmap decision 21): the
219
+ """The gate every recommended LLM passes before it is ranked: the
213
220
  agent posture fits this budget, a window of at least ``posture.floor`` (64K) shared by
214
221
  ``posture.slots`` concurrent requests with weights and KV resident. Long context is a
215
222
  precondition of agent work, so a model that cannot hold it is never the default."""
@@ -336,7 +343,11 @@ def automatic_fit(
336
343
 
337
344
 
338
345
  def rank_key(
339
- entry: CatalogEntry, variant: QuantVariant, budget: HardwareBudget, *, backend: str = "auto"
346
+ entry: CatalogEntry,
347
+ variant: QuantVariant,
348
+ budget: HardwareBudget,
349
+ *,
350
+ backend: Backend | Literal["auto"] = "auto",
340
351
  ) -> tuple[int, float]:
341
352
  """How gated LLMs are ordered: agent capability (``quality.score``) first, predicted decode
342
353
  tok/s second. Time to first token has no separate estimator: prefill and decode are both
@@ -395,7 +406,7 @@ def recommended_entry(
395
406
  budget: HardwareBudget,
396
407
  entries: tuple[CatalogEntry, ...],
397
408
  *,
398
- backend: str = "auto",
409
+ backend: Backend | Literal["auto"] = "auto",
399
410
  ladder: tuple[str, ...] = (),
400
411
  ) -> tuple[CatalogEntry, str] | None:
401
412
  """Pick among resident entries that pass ``agent_ready`` (64K shared by two requests).
@@ -28,8 +28,7 @@ METAL_UUID = "metal-0" # service_probe.METAL_UUID labels the processes it finds
28
28
  # HARNESS_RAM (a test keeps them equal; importing them here would cycle through deploy).
29
29
  HOST_KEEP_BYTES = 2 * GIB
30
30
  # Apple's default recommendedMaxWorkingSetSize (iogpu.wired_limit_mb unset) as Macs reported it:
31
- # (total, working set). M4 16 GB and M6 24 GB read 74.0% (evidence/2026-10-30-macos-metal,
32
- # evidence/2026-11-05-macmini-64k); oMLX 0.7.4 records 107.5 GiB on a 128 GiB MacBook
31
+ # (total, working set). M4 16 GB and M6 24 GB read 74.0% (measured on Apple Silicon Macs); oMLX 0.7.4 records 107.5 GiB on a 128 GiB MacBook
33
32
  # (omlx/cluster/node_role.py); macOS 27 on the 256 GB M5 Ultra read 222.7 GiB (MT1). A simulated
34
33
  # Mac interpolates the share linearly in between; a real one uses its own probe reading, which
35
34
  # also shows a raised sysctl (local-119: 249036 MiB set, the same value read, 2026-11-09).
@@ -5,6 +5,8 @@ argv; this module adds where the deployment lives, its service identity, endpoin
5
5
 
6
6
  from __future__ import annotations
7
7
 
8
+ import contextlib
9
+ import contextvars
8
10
  import datetime as dt
9
11
  import functools
10
12
  import hashlib
@@ -17,13 +19,13 @@ import time
17
19
  import urllib.error
18
20
  import urllib.parse
19
21
  import urllib.request
20
- from collections.abc import Callable, Mapping, Sequence
22
+ from collections.abc import Callable, Iterator, Mapping, Sequence
21
23
  from dataclasses import dataclass
22
24
  from pathlib import Path
23
25
  from typing import TypedDict
24
26
 
25
27
  from localmodels import catalog as cat
26
- from localmodels import region
28
+ from localmodels import deployment_lifecycle, region
27
29
  from localmodels.contracts import decode
28
30
  from localmodels.planning.budget import gib
29
31
  from localmodels.probe import HostFacts
@@ -32,6 +34,7 @@ from localmodels.records import (
32
34
  ModelSpec,
33
35
  PinnedFile,
34
36
  Plan,
37
+ PlanEndpoint,
35
38
  ReleaseEngine,
36
39
  ReusableFile,
37
40
  ServicePlan,
@@ -324,13 +327,6 @@ def service_name(base_dir: str, name: str) -> str:
324
327
  return f"localmodels-{root_tag(base_dir)}-{name}"
325
328
 
326
329
 
327
- def _same_dir(a: str, b: str) -> bool:
328
- def norm(path: str) -> str:
329
- return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
330
-
331
- return norm(a) == norm(b)
332
-
333
-
334
330
  def resolved_name(model_id: str, port: int, base_dir: str, taken: Mapping[str, str]) -> str:
335
331
  """The deployment name under ``base_dir``. ``taken`` maps each recorded deployment's name to
336
332
  its directory. A name another base directory already uses gets this directory's tag, so two
@@ -339,9 +335,9 @@ def resolved_name(model_id: str, port: int, base_dir: str, taken: Mapping[str, s
339
335
  root = f"{base_dir.rstrip('/')}/deployments"
340
336
  tag = hashlib.sha256(os.path.normpath(os.path.expanduser(base_dir)).encode()).hexdigest()[:6]
341
337
  tagged = f"{plain}-{tag}"
342
- if tagged in taken and _same_dir(taken[tagged], f"{root}/{tagged}"):
338
+ if tagged in taken and deployment_lifecycle.same_dir(taken[tagged], f"{root}/{tagged}"):
343
339
  return tagged
344
- if plain in taken and not _same_dir(taken[plain], f"{root}/{plain}"):
340
+ if plain in taken and not deployment_lifecycle.same_dir(taken[plain], f"{root}/{plain}"):
345
341
  return tagged
346
342
  return plain
347
343
 
@@ -410,10 +406,33 @@ def port_holder(facts: HostFacts, port: int) -> str | None:
410
406
  return None
411
407
 
412
408
 
409
+ _PORTS_ASSUMED_FREE: contextvars.ContextVar[bool] = contextvars.ContextVar(
410
+ "localmodels_ports_assumed_free", default=False
411
+ )
412
+
413
+
414
+ @contextlib.contextmanager
415
+ def assume_ports_free() -> Iterator[None]:
416
+ """Plan as if every loopback port were free (stack_ports.port_state and loopback_listening,
417
+ require_free_port): how setup inspect tells what else, if anything, blocks a host whose plan
418
+ was refused only for busy or unconfirmed ports. Never used for a plan that is applied."""
419
+ token = _PORTS_ASSUMED_FREE.set(True)
420
+ try:
421
+ yield
422
+ finally:
423
+ _PORTS_ASSUMED_FREE.reset(token)
424
+
425
+
426
+ def ports_assumed_free() -> bool:
427
+ return _PORTS_ASSUMED_FREE.get()
428
+
429
+
413
430
  def require_free_port(
414
431
  facts: HostFacts, port: int, *, role: str = "", fix: str = "pick a free port"
415
432
  ) -> None:
416
433
  """Refuse a port another server answers on, naming that server and how to get past it."""
434
+ if ports_assumed_free():
435
+ return
417
436
  if (holder := port_holder(facts, port)) is not None:
418
437
  raise PlanError(
419
438
  f"port {port} for {role} already has a server ({holder}); it is not part of this "
@@ -439,7 +458,7 @@ def plan_envelope(
439
458
  placement: dict[str, object],
440
459
  launch: dict[str, object],
441
460
  service: Launch,
442
- endpoint: dict[str, str],
461
+ endpoint: PlanEndpoint,
443
462
  warnings: list[str],
444
463
  ) -> Plan:
445
464
  """The deployment-plan/v1 document every planner writes; each prices its own parts."""
@@ -458,6 +477,14 @@ def plan_envelope(
458
477
  svc[key] = service[key]
459
478
  if "autostart" in service:
460
479
  svc["autostart"] = service["autostart"]
480
+ full_endpoint: PlanEndpoint = {
481
+ "base_url": f"http://{host}:{where.port}/v1",
482
+ "health_path": "/health",
483
+ "slots_path": None,
484
+ "metrics_path": None,
485
+ "metrics_requires_auth": False,
486
+ **endpoint,
487
+ }
461
488
  return {
462
489
  "schema": PLAN_SCHEMA,
463
490
  "name": where.name,
@@ -474,6 +501,6 @@ def plan_envelope(
474
501
  "placement": placement,
475
502
  "launch": launch,
476
503
  "service": svc,
477
- "endpoint": {"base_url": f"http://{host}:{where.port}/v1", **endpoint},
504
+ "endpoint": full_endpoint,
478
505
  "warnings": warnings,
479
506
  }
@@ -22,11 +22,15 @@ from __future__ import annotations
22
22
 
23
23
  import re
24
24
  from dataclasses import dataclass, replace
25
- from typing import Literal
26
25
 
27
26
  from localmodels import gpu_specs, metal
28
27
  from localmodels.context_policy import RUNTIME_OVERHEAD_BYTES
29
- from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES, METAL_VRAM_RESERVE_BYTES, HardwareBudget
28
+ from localmodels.estimator import (
29
+ AGENT_VRAM_RESERVE_BYTES,
30
+ METAL_VRAM_RESERVE_BYTES,
31
+ HardwareBudget,
32
+ )
33
+ from localmodels.estimator import Backend as Backend
30
34
  from localmodels.probe import GPU, ComputeProcess, HostFacts
31
35
 
32
36
  _GIB = 1 << 30
@@ -38,7 +42,9 @@ _LAUNCH_HEADROOM = 1 << 30
38
42
  # Unified memory (a Mac, an integrated CUDA device, CPU RAM) keeps this share back from models.
39
43
  UMA_HEADROOM_FRACTION = 0.20
40
44
  _POOL_DISAGREEMENT_FACTOR = 1.5
41
- _POOL_RAM_FRACTION = 0.75
45
+ # Without the driver's INTEGRATED attribute, a CUDA pool at least this share of physical RAM (and
46
+ # well above nvidia-smi's total) is unified memory behind a carve-out (unified_pool_bytes).
47
+ _UNIFIED_POOL_MIN_RAM_SHARE = 0.75
42
48
  # A card whose free memory is below this share of its total holds someone else's work.
43
49
  BUSY_GPU_FRACTION = 0.10 # another program holding more of a card than this needs consent
44
50
  IDLE_USED_BYTES = 1 << 30 # what an idle card's driver context may hold
@@ -56,16 +62,12 @@ _SERVING_IMAGE_RE = re.compile(
56
62
  )
57
63
  # A Windows GPU context named like one of these is another inference server. Any other one (the
58
64
  # desktop, a game, a browser, an app that uses CUDA) is not a conflict: only the free memory
59
- # decides whether a model fits beside it (roadmap decision 60).
65
+ # decides whether a model fits beside it.
60
66
  _SERVING_PROCESS_RE = re.compile(
61
67
  _SERVING_IMAGE_RE.pattern + r"|lm.?studio|lms\b|kobold", re.IGNORECASE
62
68
  )
63
69
 
64
70
 
65
- # The device a placement runs on; engine_adapters.llama_cpp.backend_for keys its hooks on it.
66
- Backend = Literal["cuda", "metal", "cpu"]
67
-
68
-
69
71
  @dataclass(frozen=True)
70
72
  class Placement:
71
73
  """Where one model would run: one card, every card split by layer, or the host's unified pool."""
@@ -135,7 +137,7 @@ def unified_pool_bytes(facts: HostFacts) -> int | None:
135
137
  smi_total > 0
136
138
  and total >= int(smi_total * _POOL_DISAGREEMENT_FACTOR)
137
139
  and ram_total > 0
138
- and total >= int(ram_total * _POOL_RAM_FRACTION)
140
+ and total >= int(ram_total * _UNIFIED_POOL_MIN_RAM_SHARE)
139
141
  ):
140
142
  return total
141
143
  return None
@@ -219,7 +221,7 @@ def gpu_conflicts(facts: HostFacts) -> dict[str, list[str]]:
219
221
  def foreign_work(proc: ComputeProcess, facts: HostFacts) -> bool:
220
222
  """A compute process this tool does not own that holds a card for someone else: any such
221
223
  process, its owner known or not, except on Windows, where only an inference server counts
222
- (``_SERVING_PROCESS_RE``); every other WDDM context is the desktop's (roadmap decision 60)."""
224
+ (``_SERVING_PROCESS_RE``); every other WDDM context is the desktop's."""
223
225
  if proc["owned"] is True:
224
226
  return False
225
227
  return facts.get("platform") != "win32" or bool(_SERVING_PROCESS_RE.search(proc["name"]))
@@ -232,7 +234,7 @@ def holders(facts: HostFacts) -> dict[str, list[str]]:
232
234
  found: dict[str, list[str]] = {}
233
235
  # A desktop always draws on its card (WDDM's desktop, Xorg, gnome-shell, browsers, games);
234
236
  # with no foreign compute work there, that memory is the desktop's, and the plan prices only
235
- # what is free (roadmap decision 60). Inside a container other namespaces' processes are
237
+ # what is free. Inside a container other namespaces' processes are
236
238
  # invisible, so memory held there still counts as someone's work.
237
239
  desktop = facts.get("services") is not None and facts.get("environment") != "container"
238
240
  for g in facts.get("gpus") or []:
@@ -312,7 +314,7 @@ def idle_cards(facts: HostFacts, need_bytes: int) -> list[GPU]:
312
314
 
313
315
  def sharing_cards(facts: HostFacts, need_bytes: int) -> list[GPU]:
314
316
  """NVIDIA cards with ``need_bytes`` free, only for an explicit sharing consent. Who else uses
315
- a card, known or not, does not matter there: the free memory decides (roadmap decision 60)."""
317
+ a card, known or not, does not matter there: the free memory decides."""
316
318
  nvidia = [g for g in facts.get("gpus") or [] if g["vendor"] == "nvidia"]
317
319
  unified_uuid = (
318
320
  nvidia[0]["uuid"] if len(nvidia) > 1 and unified_pool_bytes(facts) is not None else None