@simplexai/localmodels-darwin-x64 0.1.0-dev.104 → 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 (81) hide show
  1. package/README.md +1 -1
  2. package/bootstrap.identity +1 -1
  3. package/bootstrap.sha256 +80 -78
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +204 -86
  6. package/modules/localmodels/apple_sensors.py +23 -0
  7. package/modules/localmodels/approval.py +25 -2
  8. package/modules/localmodels/catalog.json +454 -31
  9. package/modules/localmodels/catalog.py +11 -0
  10. package/modules/localmodels/catalog_recipes.py +61 -3
  11. package/modules/localmodels/cli_help.py +10 -0
  12. package/modules/localmodels/cli_parser.py +313 -230
  13. package/modules/localmodels/component.py +20 -2
  14. package/modules/localmodels/custom_probe.py +4 -2
  15. package/modules/localmodels/deploy.py +11 -1
  16. package/modules/localmodels/engine_adapters/suite_plan.py +21 -21
  17. package/modules/localmodels/host_sensors.py +25 -2
  18. package/modules/localmodels/hosts.py +26 -5
  19. package/modules/localmodels/library_cli.py +34 -16
  20. package/modules/localmodels/library_custom.py +9 -1
  21. package/modules/localmodels/library_direct.py +41 -1
  22. package/modules/localmodels/library_jobs.py +23 -4
  23. package/modules/localmodels/library_model.py +146 -1
  24. package/modules/localmodels/library_order.py +175 -69
  25. package/modules/localmodels/library_poly.py +42 -11
  26. package/modules/localmodels/library_presentation.py +485 -0
  27. package/modules/localmodels/library_pricing.py +3 -1
  28. package/modules/localmodels/library_serve.py +208 -3
  29. package/modules/localmodels/library_state.py +47 -10
  30. package/modules/localmodels/library_status.py +29 -16
  31. package/modules/localmodels/llm_rank.py +9 -3
  32. package/modules/localmodels/plan_envelope.py +11 -2
  33. package/modules/localmodels/probe.py +34 -7
  34. package/modules/localmodels/quant_formats.py +9 -2
  35. package/modules/localmodels/records.py +19 -2
  36. package/modules/localmodels/remote_ops_verify.py +91 -24
  37. package/modules/localmodels/runtime_index.py +303 -0
  38. package/modules/localmodels/setup_inspection.py +22 -3
  39. package/modules/localmodels/speech_cli.py +20 -14
  40. package/modules/localmodels/speech_serve.py +9 -2
  41. package/modules/localmodels/speech_server.py +3 -0
  42. package/modules/localmodels/stack_args.py +270 -139
  43. package/modules/localmodels/stack_auto.py +90 -5
  44. package/modules/localmodels/stack_cli.py +117 -116
  45. package/modules/localmodels/stack_compose.py +5 -1
  46. package/modules/localmodels/stack_debug.py +14 -4
  47. package/modules/localmodels/stack_down.py +2 -0
  48. package/modules/localmodels/stack_hardware.py +14 -12
  49. package/modules/localmodels/stack_mlx.py +8 -1
  50. package/modules/localmodels/stack_picks.py +19 -20
  51. package/modules/localmodels/stack_plan.py +3 -2
  52. package/modules/localmodels/stack_review.py +28 -7
  53. package/modules/localmodels/stack_suite.py +11 -9
  54. package/modules/localmodels/stack_up.py +2 -0
  55. package/modules/localmodels/stack_view.py +180 -35
  56. package/modules/localmodels/stack_view_demo.py +2 -0
  57. package/modules/localmodels/stack_view_gpu.py +36 -2
  58. package/modules/localmodels/stack_view_schema.py +26 -3
  59. package/modules/localmodels/stack_view_slots.py +3 -1
  60. package/modules/localmodels/stack_view_telemetry.py +90 -4
  61. package/modules/localmodels/stack_view_tick.py +246 -40
  62. package/modules/localmodels/stack_view_words.py +7 -0
  63. package/modules/localmodels/stack_whatif_html.py +9 -12
  64. package/modules/localmodels/suite.py +129 -2
  65. package/modules/localmodels/telemetry_math.py +458 -18
  66. package/modules/localmodels/transport.py +8 -1
  67. package/modules/localmodels/tts_cli.py +24 -20
  68. package/modules/localmodels/tts_serve.py +9 -2
  69. package/modules/localmodels/tts_sidecar.py +3 -0
  70. package/modules/localmodels/web/whatif/app.js +1 -1
  71. package/modules/localmodels/web/whatif/sim.js +8 -14
  72. package/modules/localmodels/win_probe.py +89 -16
  73. package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/METADATA +1 -1
  74. package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/RECORD +76 -74
  75. package/package.json +1 -1
  76. package/tool.json +1 -1
  77. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/WHEEL +0 -0
  78. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/entry_points.txt +0 -0
  79. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/licenses/LICENSE +0 -0
  80. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/licenses/NOTICE +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -26,9 +26,10 @@ from concurrent.futures import ThreadPoolExecutor
26
26
  from typing import TypedDict
27
27
 
28
28
  try:
29
- from localmodels import metal_probe, win_probe
29
+ from localmodels import metal_probe, process_identity, win_probe
30
30
  except ImportError:
31
31
  import metal_probe # type: ignore[import-not-found,no-redef]
32
+ import process_identity # type: ignore[import-not-found,no-redef]
32
33
  import win_probe # type: ignore[import-not-found,no-redef]
33
34
 
34
35
 
@@ -182,6 +183,7 @@ class HostFacts(RequiredHostFacts, total=False):
182
183
  shared_libraries: dict[str, bool] # HOST_LIBRARIES: can the loader find each one
183
184
  metal: dict[str, object] | None # metal_probe.py on Apple Silicon (2026-10-29; metal.Metal)
184
185
  gpu_processes: list[win_probe.GpuAppMemory] # Windows WDDM per-app local VRAM (CIM)
186
+ wddm_shared_spill_bytes: int # Windows WDDM total SharedUsage spill bytes (CIM)
185
187
 
186
188
 
187
189
  SCHEMA = "localmodels.host-facts/v1"
@@ -673,6 +675,25 @@ def _user() -> str:
673
675
  return os.environ.get("USER", "")
674
676
 
675
677
 
678
+ def _probe_port_candidates(ports: Sequence[int]) -> list[int]:
679
+ """Loopback ports worth probing with HTTP /props. On Windows, pre-filter with
680
+ ``process_identity.listener_pids`` so closed ports do not stall ~2 s each on SYN retries;
681
+ fail open when the listener table cannot be queried."""
682
+ unique = list(dict.fromkeys(ports))
683
+ if sys.platform != "win32":
684
+ return unique
685
+ active: list[int] = []
686
+ for port in unique:
687
+ try:
688
+ owners = process_identity.listener_pids(port)
689
+ except (OSError, AttributeError):
690
+ active.append(port)
691
+ continue
692
+ if owners is None or owners:
693
+ active.append(port)
694
+ return active
695
+
696
+
676
697
  def collect(
677
698
  ports: Sequence[int] = SERVICE_PORTS,
678
699
  models_dir: str = "~/.local/share/localmodels/models",
@@ -690,10 +711,12 @@ def collect(
690
711
  smi = _nvidia_smi() or "nvidia-smi"
691
712
  _mark_mig(smi, gpus)
692
713
  _mark_details(smi, gpus)
693
- with ThreadPoolExecutor(max_workers=16) as pool: # Windows refuses a closed port after ~2 s
694
- servers = [
695
- s for s in pool.map(probe_llama_server, dict.fromkeys([*ports, *SERVICE_PORTS])) if s
696
- ]
714
+ candidates = _probe_port_candidates([*ports, *SERVICE_PORTS])
715
+ if candidates:
716
+ with ThreadPoolExecutor(max_workers=16) as pool:
717
+ servers = [s for s in pool.map(probe_llama_server, candidates) if s]
718
+ else:
719
+ servers = []
697
720
  is_linux = sys.platform.startswith("linux")
698
721
  vendor = _gpu_vendor_class()
699
722
  facts: HostFacts = {
@@ -731,8 +754,12 @@ def collect(
731
754
  }
732
755
  if facts["platform"] == "darwin" and facts["arch"] == "arm64":
733
756
  facts["metal"] = metal_probe.metal_device_with_telemetry()
734
- if facts["platform"] == "win32" and gpus and (gpu_procs := win_probe.gpu_process_memory()):
735
- facts["gpu_processes"] = gpu_procs
757
+ if facts["platform"] == "win32" and gpus:
758
+ gpu_procs, wddm_spill = win_probe.gpu_memory_snapshot()
759
+ if gpu_procs:
760
+ facts["gpu_processes"] = gpu_procs
761
+ if wddm_spill is not None:
762
+ facts["wddm_shared_spill_bytes"] = wddm_spill
736
763
  return facts
737
764
 
738
765
 
@@ -95,10 +95,17 @@ QUANT_BITS = {f.name: f.bits for f in FORMATS}
95
95
  EXL_PREFIXES = ("EXL2-", "EXL3-")
96
96
 
97
97
 
98
+ _METHOD_PREFIXES = ("GSQ-RCO-", "UD-")
99
+
100
+
98
101
  def normalize(name: str) -> str:
99
- """Upper case without an Unsloth dynamic ``UD-`` prefix: "ud-q4_k_m" reads "Q4_K_M"."""
102
+ """Upper case without known quant-method prefixes (``UD-``, ``GSQ-RCO-``):
103
+ ``"ud-q4_k_m"`` reads ``"Q4_K_M"`` and ``"gsq-rco-iq3_s"`` reads ``"IQ3_S"``."""
100
104
  key = name.strip().upper()
101
- return key[3:] if key.startswith("UD-") else key
105
+ for prefix in _METHOD_PREFIXES:
106
+ if key.startswith(prefix):
107
+ return key[len(prefix) :]
108
+ return key
102
109
 
103
110
 
104
111
  def lookup(name: str) -> QuantFormat | None:
@@ -124,6 +124,16 @@ class ServicePlan(RequiredService, Launch, total=False):
124
124
  health_path: str
125
125
 
126
126
 
127
+ class PlanEndpoint(TypedDict, total=False):
128
+ base_url: str
129
+ model: str
130
+ contract: str
131
+ health_path: str
132
+ slots_path: str | None
133
+ metrics_path: str | None
134
+ metrics_requires_auth: bool
135
+
136
+
127
137
  class RequiredPlan(TypedDict):
128
138
  schema: str
129
139
  name: str
@@ -137,7 +147,7 @@ class RequiredPlan(TypedDict):
137
147
  placement: dict[str, object]
138
148
  launch: dict[str, object]
139
149
  service: ServicePlan
140
- endpoint: dict[str, str]
150
+ endpoint: PlanEndpoint
141
151
  warnings: list[str]
142
152
 
143
153
 
@@ -161,9 +171,16 @@ class ProgressEvent(Event, total=False):
161
171
  ready: bool
162
172
  state: str
163
173
  health: str | None
174
+ seconds: float
175
+ health_wait_ms: int
176
+ touch_ms: int
177
+
178
+
179
+ class _StepRecordOptional(TypedDict, total=False):
180
+ duration_ms: int
164
181
 
165
182
 
166
- class StepRecord(TypedDict):
183
+ class StepRecord(_StepRecordOptional):
167
184
  step: str
168
185
  ok: bool
169
186
  result: ProgressEvent | None
@@ -39,6 +39,13 @@ except ImportError: # run as a bare file from this directory
39
39
  EMBEDDING_DIMENSIONS = {"qwen3-embedding-0.6b": 1024}
40
40
  LIMIT_UNIT = " apple" # repeated to size inputs; /tokenize gives the real count
41
41
  LIMIT_MARGIN = 32 # tokens either side of the limit: room for the special tokens added
42
+ HEALTH_POLL_INTERVAL_S = (
43
+ 0.25 # fast /health polling avoids ±3s quantization error on engine_load_ms
44
+ )
45
+
46
+
47
+ def _health_extra(health_wait_ms: int | None) -> dict[str, int]:
48
+ return {"health_wait_ms": health_wait_ms} if health_wait_ms is not None else {}
42
49
 
43
50
 
44
51
  def _restarts(p: remote_ops_common.ServiceParams) -> int:
@@ -76,17 +83,17 @@ def _evaluate_chat_answer(content: str, reasoning: str, *, smoke: bool) -> tuple
76
83
  )
77
84
 
78
85
 
79
- def act_verify(p: remote_ops_common.VerifyParams) -> None:
80
- """Readiness is a real generation, never /health alone (Hermes' touch generation)."""
81
- paths = remote_ops_common.paths(p)
86
+ def _wait_for_health(root: str, p: remote_ops_common.VerifyParams, paths: dict[str, str]) -> int:
87
+ """Poll /health every HEALTH_POLL_INTERVAL_S until ready and return wait time in ms."""
82
88
  base_restarts = _restarts(p) if p["service_kind"] == "systemd-user" else 0
83
- root = f"http://127.0.0.1:{p['port']}"
84
- deadline = time.monotonic() + p.get("timeout_s", 900)
89
+ health_started = time.monotonic()
90
+ deadline = health_started + p.get("timeout_s", 900)
85
91
  health_path = str((p.get("health") or {}).get("path") or "/health")
92
+ last_progress: float | None = None
86
93
  while True:
87
94
  try:
88
95
  if _health_ready(root, health_path, p):
89
- break
96
+ return max(0, round((time.monotonic() - health_started) * 1000))
90
97
  except (urllib.error.URLError, OSError, ValueError):
91
98
  pass
92
99
  if p["service_kind"] == "systemd-user":
@@ -111,16 +118,26 @@ def act_verify(p: remote_ops_common.VerifyParams) -> None:
111
118
  raise RuntimeError(
112
119
  "the process exited. Log tail:\n" + remote_ops_common.log_tail(paths)
113
120
  )
114
- if time.monotonic() > deadline:
121
+ now = time.monotonic()
122
+ if now > deadline:
115
123
  raise RuntimeError(
116
124
  "timed out waiting for the model to load. Log tail:\n"
117
125
  + remote_ops_common.log_tail(paths)
118
126
  )
119
- remote_ops_common.emit("progress", phase="loading")
120
- time.sleep(3)
127
+ if last_progress is None or now - last_progress >= remote_ops_common.PROGRESS_EVERY_S:
128
+ remote_ops_common.emit("progress", phase="loading")
129
+ last_progress = now
130
+ time.sleep(HEALTH_POLL_INTERVAL_S)
131
+
132
+
133
+ def act_verify(p: remote_ops_common.VerifyParams) -> None:
134
+ """Readiness is a real generation, never /health alone (Hermes' touch generation)."""
135
+ paths = remote_ops_common.paths(p)
136
+ root = f"http://127.0.0.1:{p['port']}"
137
+ health_wait_ms = _wait_for_health(root, p, paths)
121
138
  contract = p.get("contract")
122
139
  if contract in CONTRACTS:
123
- CONTRACTS[contract](root, p)
140
+ CONTRACTS[contract](root, p, health_wait_ms)
124
141
  return
125
142
  started = time.monotonic()
126
143
  smoke = bool(p.get("smoke"))
@@ -154,7 +171,16 @@ def act_verify(p: remote_ops_common.VerifyParams) -> None:
154
171
  seen = _picture_answer(root, p)
155
172
  extra["picture_answer"] = seen[:200]
156
173
  ok, failure = PICTURE_EXPECT in seen.lower(), f"the picture answer lacks {PICTURE_EXPECT!r}"
157
- _report(ok, answer, started, failure, timings=resp.get("timings"), **extra, **_released(ok, p))
174
+ _report(
175
+ ok,
176
+ answer,
177
+ started,
178
+ failure,
179
+ timings=resp.get("timings"),
180
+ health_wait_ms=health_wait_ms,
181
+ **extra,
182
+ **_released(ok, p),
183
+ )
158
184
 
159
185
 
160
186
  def _released(ok: bool, p: remote_ops_common.VerifyParams) -> dict[str, int]:
@@ -237,7 +263,9 @@ def _picture_answer(root: str, p: remote_ops_common.VerifyParams) -> str:
237
263
  return content + " " + reasoning
238
264
 
239
265
 
240
- def _verify_decision(root: str, p: remote_ops_common.VerifyParams) -> None:
266
+ def _verify_decision(
267
+ root: str, p: remote_ops_common.VerifyParams, health_wait_ms: int | None = None
268
+ ) -> None:
241
269
  """Readiness of a System One model is a probability for an unambiguous question."""
242
270
  started = time.monotonic()
243
271
  body = {
@@ -255,7 +283,14 @@ def _verify_decision(root: str, p: remote_ops_common.VerifyParams) -> None:
255
283
  if not 0 <= noul <= 1:
256
284
  raise ValueError("System One probability outside [0, 1]")
257
285
  failure = f"noul for the checkout outage is {noul:.3f}, should be above 0.5"
258
- _report(noul > 0.5, f"noul={noul:.3f}", started, failure, usage=resp.get("usage"))
286
+ _report(
287
+ noul > 0.5,
288
+ f"noul={noul:.3f}",
289
+ started,
290
+ failure,
291
+ usage=resp.get("usage"),
292
+ **_health_extra(health_wait_ms),
293
+ )
259
294
 
260
295
 
261
296
  def _finite(values: object) -> list[float]:
@@ -270,8 +305,14 @@ def _finite(values: object) -> list[float]:
270
305
 
271
306
 
272
307
  def _report(ok: bool, answer: str, started: float, failure: str, **extra: object) -> None:
308
+ elapsed = max(0.0, time.monotonic() - started)
273
309
  remote_ops_common.emit(
274
- "result", ready=ok, answer=answer, seconds=round(time.monotonic() - started, 2), **extra
310
+ "result",
311
+ ready=ok,
312
+ answer=answer,
313
+ seconds=round(elapsed, 2),
314
+ touch_ms=max(0, round(elapsed * 1000)),
315
+ **extra,
275
316
  )
276
317
  if not ok:
277
318
  raise RuntimeError("readiness check failed: " + failure)
@@ -322,7 +363,9 @@ def _input_limit(
322
363
  return f" limit={limit}: {served} served, {refused} refused"
323
364
 
324
365
 
325
- def _verify_embedding(root: str, p: remote_ops_common.VerifyParams) -> None:
366
+ def _verify_embedding(
367
+ root: str, p: remote_ops_common.VerifyParams, health_wait_ms: int | None = None
368
+ ) -> None:
326
369
  """Finite unit vectors of one width; a paraphrase lands nearer than an unrelated sentence."""
327
370
  started = time.monotonic()
328
371
  texts = [
@@ -363,10 +406,18 @@ def _verify_embedding(root: str, p: remote_ops_common.VerifyParams) -> None:
363
406
  root + "/v1/embeddings", p["api_key"], {**body, "input": [text]}, timeout=300
364
407
  ),
365
408
  )
366
- _report(all(abs(n - 1) < 1e-2 for n in norms) and near > far, answer, started, answer)
409
+ _report(
410
+ all(abs(n - 1) < 1e-2 for n in norms) and near > far,
411
+ answer,
412
+ started,
413
+ answer,
414
+ **_health_extra(health_wait_ms),
415
+ )
367
416
 
368
417
 
369
- def _verify_rerank(root: str, p: remote_ops_common.VerifyParams) -> None:
418
+ def _verify_rerank(
419
+ root: str, p: remote_ops_common.VerifyParams, health_wait_ms: int | None = None
420
+ ) -> None:
370
421
  """The known relevant document, not placed first, must rank first. llama-server returns the
371
422
  results sorted by score and cut to ``top_n``, so ask for every document."""
372
423
  started, docs = time.monotonic(), remote_ops_common.RERANK_DOCS
@@ -409,10 +460,13 @@ def _verify_rerank(root: str, p: remote_ops_common.VerifyParams) -> None:
409
460
  f"top={best}{limit}",
410
461
  started,
411
462
  f"document {best} ranked first",
463
+ **_health_extra(health_wait_ms),
412
464
  )
413
465
 
414
466
 
415
- def verify_stt(root: str, p: remote_ops_common.VerifyParams) -> None:
467
+ def verify_stt(
468
+ root: str, p: remote_ops_common.VerifyParams, health_wait_ms: int | None = None
469
+ ) -> None:
416
470
  """A pinned recording transcribes to text containing its known phrase."""
417
471
  fx = p.get("fixture") or {}
418
472
  dest = os.path.join(remote_ops_common.expand(p["deploy_dir"]), str(fx["name"]))
@@ -435,10 +489,18 @@ def verify_stt(root: str, p: remote_ops_common.VerifyParams) -> None:
435
489
  raise ValueError("missing transcription text")
436
490
  expect = str(fx["expect"]).lower()
437
491
  ok = expect in " ".join(text.lower().split())
438
- _report(ok, text.strip()[:120], started, f"the transcript lacks {expect!r}")
492
+ _report(
493
+ ok,
494
+ text.strip()[:120],
495
+ started,
496
+ f"the transcript lacks {expect!r}",
497
+ **_health_extra(health_wait_ms),
498
+ )
439
499
 
440
500
 
441
- def _verify_tts(root: str, p: remote_ops_common.VerifyParams) -> None:
501
+ def _verify_tts(
502
+ root: str, p: remote_ops_common.VerifyParams, health_wait_ms: int | None = None
503
+ ) -> None:
442
504
  """Each fixture sentence (Chinese and English: both G2P paths) comes back as audible 16-bit
443
505
  mono WAV of a sentence's length. Whether it says the words is a round trip through STT."""
444
506
  started, heard = time.monotonic(), []
@@ -460,14 +522,19 @@ def _verify_tts(root: str, p: remote_ops_common.VerifyParams) -> None:
460
522
  answer,
461
523
  started,
462
524
  "the synthesized audio is empty, silent or of implausible length: " + answer,
525
+ **_health_extra(health_wait_ms),
463
526
  )
464
527
 
465
528
 
466
- CONTRACTS = {
529
+ def _verify_health(
530
+ _root: str, _p: remote_ops_common.VerifyParams, health_wait_ms: int | None = None
531
+ ) -> None:
532
+ remote_ops_common.emit("result", ready=True, touch_ms=0, **_health_extra(health_wait_ms))
533
+
534
+
535
+ CONTRACTS: dict[str, Callable[[str, remote_ops_common.VerifyParams, int | None], None]] = {
467
536
  "systemone": _verify_decision,
468
- "health": lambda root, p: remote_ops_common.emit(
469
- "result", ready=True
470
- ), # behind a front that checks it
537
+ "health": _verify_health, # behind a front that checks it
471
538
  "embedding": _verify_embedding,
472
539
  "rerank": _verify_rerank,
473
540
  "stt": verify_stt,
@@ -0,0 +1,303 @@
1
+ """Atomic runtime index projection (``$LOCALMODELS_STATE/runtime-index.json``).
2
+
3
+ Provides a single, zero-Python-startup disk contract (``localmodels.runtime-index/v1``)
4
+ that external consumers (such as the Linger Go daemon) can read directly to discover
5
+ installed/loaded LLM models, loopback health/slots/metrics endpoints, ``pi_spec`` metadata,
6
+ and active speech/TTS sidecar endpoints.
7
+
8
+ Locking invariant: ``.runtime-index.lock`` is a strict leaf lock. Every state mutator first
9
+ commits its own authoritative state file (library model record or sidecar ``runtime.json``)
10
+ and then calls ``refresh()``, which acquires ``.runtime-index.lock``, re-reads all current
11
+ state files from disk, and atomically replaces ``runtime-index.json``. Concurrent writers
12
+ can therefore never overwrite newer state with a stale snapshot and cannot deadlock.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import datetime as dt
18
+ import json
19
+ import logging
20
+ import os
21
+ from collections.abc import Mapping
22
+ from pathlib import Path
23
+ from typing import Any, Literal, TypedDict
24
+
25
+ from localmodels import (
26
+ __version__,
27
+ catalog,
28
+ hosts,
29
+ library_direct,
30
+ library_state,
31
+ speech_state,
32
+ tts_state,
33
+ )
34
+ from localmodels.library_model import PiSpec
35
+ from localmodels.library_state import Record
36
+
37
+ SCHEMA: Literal["localmodels.runtime-index/v1"] = "localmodels.runtime-index/v1"
38
+ _LOG = logging.getLogger("localmodels.runtime_index")
39
+
40
+
41
+ class _ModelIndexRequired(TypedDict):
42
+ id: str
43
+ state: str
44
+ pool: str | None
45
+ engine: str | None
46
+ pi_model: str
47
+
48
+
49
+ class ModelIndexEntry(_ModelIndexRequired, total=False):
50
+ base_url: str
51
+ health_url: str
52
+ slots_url: str | None
53
+ metrics_url: str | None
54
+ metrics_requires_auth: bool
55
+ api_key_file: str | None
56
+ pid_file: str | None
57
+ pi_spec: PiSpec
58
+
59
+
60
+ class SidecarIndexEntry(TypedDict):
61
+ runtime_file: str
62
+ base_url: str
63
+ health_url: str
64
+ status_url: str
65
+ api_key_file: str | None
66
+
67
+
68
+ class SidecarsIndex(TypedDict):
69
+ speech: SidecarIndexEntry | None
70
+ tts: SidecarIndexEntry | None
71
+
72
+
73
+ class RuntimeIndex(TypedDict):
74
+ schema: Literal["localmodels.runtime-index/v1"]
75
+ updated_at: str
76
+ tool_version: str
77
+ models: list[ModelIndexEntry]
78
+ sidecars: SidecarsIndex
79
+
80
+
81
+ def state_root(state_dir: Path | None = None) -> Path:
82
+ return hosts.state_dir() if state_dir is None else state_dir
83
+
84
+
85
+ def index_path(state_dir: Path | None = None) -> Path:
86
+ return state_root(state_dir) / "runtime-index.json"
87
+
88
+
89
+ def lock_path(state_dir: Path | None = None) -> Path:
90
+ return state_root(state_dir) / ".runtime-index.lock"
91
+
92
+
93
+ def _rfc3339_utc_now() -> str:
94
+ return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
95
+
96
+
97
+ def _join_origin(base_url: str, path: str) -> str:
98
+ origin = base_url.rstrip("/").removesuffix("/v1")
99
+ suffix = path if path.startswith("/") else "/" + path
100
+ return origin + suffix
101
+
102
+
103
+ def _pi_model_of(record: Record) -> str:
104
+ if direct := record.get("pi_model"):
105
+ return str(direct)
106
+ if (reg := record.get("registration")) is not None and (pm := reg.get("pi_model")):
107
+ return str(pm)
108
+ plan = record["plan"]
109
+ served = str(plan["endpoint"].get("model") or plan["model"]["model_id"])
110
+ return library_direct.pi_model(record["id"], served)
111
+
112
+
113
+ def _engine_of(record: Record, catalog_by_id: Mapping[str, catalog.CatalogEntry]) -> str | None:
114
+ plan = record["plan"]
115
+ launch_runtime = str(plan.get("launch", {}).get("runtime") or "")
116
+ build = str(plan.get("engine", {}).get("build") or "")
117
+ entry = catalog_by_id.get(record["catalog_id"])
118
+ runtime = launch_runtime or (entry.runtime if entry is not None else "")
119
+ if not runtime and isinstance(ce := record.get("catalog_entry"), Mapping):
120
+ runtime = str(ce.get("runtime") or "")
121
+ if runtime == "strata-poly" or build.startswith("strata-poly"):
122
+ return "polystrata"
123
+ if runtime == "strata" or build.startswith("strata"):
124
+ return "strata"
125
+ if runtime == "mlx-lm" or build.startswith("mlx-lm"):
126
+ return "mlx-lm"
127
+ if build or plan.get("engine", {}).get("binary"):
128
+ return "llama.cpp"
129
+ return None
130
+
131
+
132
+ def _loaded_endpoint_fields(
133
+ record: Record,
134
+ engine: str | None,
135
+ catalog_by_id: Mapping[str, catalog.CatalogEntry],
136
+ ) -> dict[str, Any]:
137
+ plan = record["plan"]
138
+ ep = plan["endpoint"]
139
+ svc = plan["service"]
140
+ argv = [str(a) for a in (svc.get("argv") or ())]
141
+ base_url = str(ep.get("base_url") or "")
142
+ health_path = str(ep.get("health_path") or svc.get("health_path") or "/health")
143
+ if "slots_path" in ep:
144
+ slots_path = ep["slots_path"]
145
+ else:
146
+ slots_path = "/slots" if "--slots" in argv else None
147
+ if "metrics_path" in ep:
148
+ metrics_path = ep["metrics_path"]
149
+ else:
150
+ metrics_path = (
151
+ "/metrics" if (engine in ("polystrata", "strata") or "--metrics" in argv) else None
152
+ )
153
+ if "metrics_requires_auth" in ep:
154
+ metrics_requires_auth = bool(ep["metrics_requires_auth"])
155
+ else:
156
+ env = svc.get("env") or {}
157
+ keyed = (
158
+ "--api-key-file" in argv
159
+ or "STRATA_API_KEY" in env
160
+ or any("auth_proxy" in arg for arg in argv)
161
+ )
162
+ metrics_requires_auth = bool(metrics_path and keyed)
163
+ deploy_dir = str(svc.get("deploy_dir") or "")
164
+ expanded = Path(os.path.expanduser(deploy_dir)) if deploy_dir else None
165
+ return {
166
+ "base_url": base_url,
167
+ "health_url": _join_origin(base_url, health_path) if base_url else "",
168
+ "slots_url": _join_origin(base_url, slots_path) if (base_url and slots_path) else None,
169
+ "metrics_url": (
170
+ _join_origin(base_url, metrics_path) if (base_url and metrics_path) else None
171
+ ),
172
+ "metrics_requires_auth": metrics_requires_auth,
173
+ "api_key_file": str(expanded / "api-key") if expanded is not None else None,
174
+ "pid_file": str(expanded / "server.pid") if expanded is not None else None,
175
+ "pi_spec": library_direct.pi_spec_for_record(record, catalog_by_id=catalog_by_id),
176
+ }
177
+
178
+
179
+ def _model_entry(
180
+ record: Record,
181
+ catalog_by_id: Mapping[str, catalog.CatalogEntry],
182
+ ) -> ModelIndexEntry:
183
+ engine = _engine_of(record, catalog_by_id)
184
+ entry: ModelIndexEntry = {
185
+ "id": record["id"],
186
+ "state": record["state"],
187
+ "pool": record.get("pool") or None,
188
+ "engine": engine,
189
+ "pi_model": _pi_model_of(record),
190
+ }
191
+ if record["state"] == "loaded":
192
+ loaded = _loaded_endpoint_fields(record, engine, catalog_by_id)
193
+ entry["base_url"] = loaded["base_url"]
194
+ entry["health_url"] = loaded["health_url"]
195
+ entry["slots_url"] = loaded["slots_url"]
196
+ entry["metrics_url"] = loaded["metrics_url"]
197
+ entry["metrics_requires_auth"] = loaded["metrics_requires_auth"]
198
+ entry["api_key_file"] = loaded["api_key_file"]
199
+ entry["pid_file"] = loaded["pid_file"]
200
+ entry["pi_spec"] = loaded["pi_spec"]
201
+ return entry
202
+
203
+
204
+ def _sidecar_entry(
205
+ runtime_file: Path,
206
+ record: Mapping[str, Any] | None,
207
+ status_path: str,
208
+ ) -> SidecarIndexEntry | None:
209
+ if record is None or not record.get("running") or record.get("state") == "stopped":
210
+ return None
211
+ raw_url = record.get("base_url")
212
+ if not isinstance(raw_url, str) or not raw_url.strip():
213
+ return None
214
+ base = raw_url.strip().rstrip("/")
215
+ raw_key = record.get("key_file")
216
+ api_key_file = raw_key if isinstance(raw_key, str) and raw_key else None
217
+ return {
218
+ "runtime_file": str(runtime_file),
219
+ "base_url": base,
220
+ "health_url": f"{base}/health",
221
+ "status_url": f"{base}{status_path}",
222
+ "api_key_file": api_key_file,
223
+ }
224
+
225
+
226
+ def _load_catalog_by_id(records: list[Record]) -> dict[str, catalog.CatalogEntry]:
227
+ needs_catalog = any(
228
+ r["state"] == "loaded"
229
+ or (
230
+ not str(r["plan"].get("engine", {}).get("build") or "")
231
+ and not str(r["plan"].get("launch", {}).get("runtime") or "")
232
+ )
233
+ for r in records
234
+ )
235
+ if not needs_catalog:
236
+ return {}
237
+ try:
238
+ return {entry.id: entry for entry in catalog.load_catalog_file()}
239
+ except (OSError, ValueError):
240
+ return {}
241
+
242
+
243
+ def build(state_dir: Path | None = None) -> RuntimeIndex:
244
+ """Build the ``localmodels.runtime-index/v1`` snapshot from current on-disk state."""
245
+ records = sorted(library_state.records(state_dir), key=lambda r: r["id"])
246
+ catalog_by_id = _load_catalog_by_id(records)
247
+ speech_entry = _sidecar_entry(
248
+ speech_state.runtime_path(state_dir),
249
+ speech_state.load_runtime_record(state_dir),
250
+ "/v1/speech/status",
251
+ )
252
+ tts_entry = _sidecar_entry(
253
+ tts_state.runtime_path(state_dir),
254
+ tts_state.load_runtime_record(state_dir),
255
+ "/v1/tts/status",
256
+ )
257
+ return {
258
+ "schema": SCHEMA,
259
+ "updated_at": _rfc3339_utc_now(),
260
+ "tool_version": __version__,
261
+ "models": [_model_entry(record, catalog_by_id) for record in records],
262
+ "sidecars": {
263
+ "speech": speech_entry,
264
+ "tts": tts_entry,
265
+ },
266
+ }
267
+
268
+
269
+ def write(state_dir: Path | None = None) -> Path:
270
+ """Atomically rebuild and persist ``$LOCALMODELS_STATE/runtime-index.json`` under leaf lock;
271
+ raises what reading the state or writing the file raised."""
272
+ with hosts.file_lock(lock_path(state_dir)):
273
+ snapshot = build(state_dir)
274
+ return hosts.save_private(index_path(state_dir), snapshot)
275
+
276
+
277
+ def refresh(state_dir: Path | None = None) -> Path | None:
278
+ """``write``, after the caller committed its own state: the index is a projection of that
279
+ state, so a failure to rebuild it is logged and leaves the committed operation's outcome (and
280
+ any error it is about to raise) untouched. None: the index was not refreshed this time."""
281
+ try:
282
+ return write(state_dir)
283
+ except (OSError, ValueError, KeyError, TypeError) as exc:
284
+ reason = exc.strerror if isinstance(exc, OSError) and exc.strerror else ""
285
+ _LOG.warning(
286
+ "runtime-index.json not refreshed (%s%s)",
287
+ type(exc).__name__,
288
+ f": {reason}" if reason else "",
289
+ )
290
+ return None
291
+
292
+
293
+ def load(state_dir: Path | None = None) -> RuntimeIndex | None:
294
+ """Read ``runtime-index.json`` if present and valid; otherwise return ``None``."""
295
+ try:
296
+ raw = json.loads(index_path(state_dir).read_text(encoding="utf-8"))
297
+ except (OSError, ValueError):
298
+ return None
299
+ if not isinstance(raw, dict) or raw.get("schema") != SCHEMA:
300
+ return None
301
+ if not isinstance(raw.get("models"), list) or not isinstance(raw.get("sidecars"), dict):
302
+ return None
303
+ return raw # type: ignore[return-value]