@simplexai/localmodels-linux-x64 0.1.0-dev.36 → 0.1.0-dev.38

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 (134) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +132 -110
  3. package/kit.py +1 -0
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +9 -3
  6. package/modules/localmodels/bifrost_checks.py +9 -6
  7. package/modules/localmodels/bifrost_config.py +203 -0
  8. package/modules/localmodels/bifrost_datasheet.py +12 -2
  9. package/modules/localmodels/budget.py +13 -2
  10. package/modules/localmodels/catalog.json +137 -2
  11. package/modules/localmodels/catalog.py +70 -321
  12. package/modules/localmodels/catalog_add.py +2 -8
  13. package/modules/localmodels/catalog_recipes.py +352 -0
  14. package/modules/localmodels/cli_parser.py +4 -1
  15. package/modules/localmodels/console.py +5 -4
  16. package/modules/localmodels/contracts.py +13 -3
  17. package/modules/localmodels/debug_cli.py +158 -0
  18. package/modules/localmodels/debug_mode.py +727 -0
  19. package/modules/localmodels/debug_stub_server.py +192 -0
  20. package/modules/localmodels/decode_calibration.json +1 -1
  21. package/modules/localmodels/decode_calibration.py +34 -17
  22. package/modules/localmodels/gateway.py +21 -155
  23. package/modules/localmodels/gateway_accept.py +201 -0
  24. package/modules/localmodels/gateway_bifrost.py +30 -193
  25. package/modules/localmodels/gateway_cli.py +15 -6
  26. package/modules/localmodels/gateway_foundations.py +2 -4
  27. package/modules/localmodels/gateway_probe.py +0 -1
  28. package/modules/localmodels/gateway_server.py +2 -3
  29. package/modules/localmodels/gpu_specs.py +12 -0
  30. package/modules/localmodels/guard.py +2 -7
  31. package/modules/localmodels/harness.py +16 -129
  32. package/modules/localmodels/harness_cleanup.py +135 -0
  33. package/modules/localmodels/harness_gateway.py +16 -14
  34. package/modules/localmodels/harness_probe.py +12 -4
  35. package/modules/localmodels/hosts.py +25 -2
  36. package/modules/localmodels/http_local.py +59 -0
  37. package/modules/localmodels/install.py +23 -8
  38. package/modules/localmodels/library_gateway.py +20 -9
  39. package/modules/localmodels/library_jobs.py +125 -28
  40. package/modules/localmodels/library_model.py +10 -0
  41. package/modules/localmodels/library_pricing.py +29 -22
  42. package/modules/localmodels/library_serve.py +17 -1
  43. package/modules/localmodels/library_state.py +15 -2
  44. package/modules/localmodels/library_status.py +30 -0
  45. package/modules/localmodels/llm_rank.py +185 -39
  46. package/modules/localmodels/probe.py +108 -174
  47. package/modules/localmodels/process_identity.py +120 -154
  48. package/modules/localmodels/process_windows.py +86 -0
  49. package/modules/localmodels/recommend.py +6 -3
  50. package/modules/localmodels/recommend_cli.py +14 -6
  51. package/modules/localmodels/remote_ops.py +65 -0
  52. package/modules/localmodels/remote_ops_service.py +14 -2
  53. package/modules/localmodels/runtime_args.py +10 -3
  54. package/modules/localmodels/runtime_auth.py +5 -9
  55. package/modules/localmodels/runtime_cli.py +128 -129
  56. package/modules/localmodels/runtime_discovery.py +84 -0
  57. package/modules/localmodels/runtime_install.py +101 -0
  58. package/modules/localmodels/runtime_releases.py +302 -0
  59. package/modules/localmodels/search_server.py +5 -1
  60. package/modules/localmodels/service_stop.py +8 -108
  61. package/modules/localmodels/service_upgrade.py +394 -63
  62. package/modules/localmodels/services_cli.py +24 -14
  63. package/modules/localmodels/setup_inspection.py +97 -9
  64. package/modules/localmodels/setup_text.py +7 -0
  65. package/modules/localmodels/sizecalc.py +0 -1
  66. package/modules/localmodels/stack.py +45 -235
  67. package/modules/localmodels/stack_arena.py +732 -0
  68. package/modules/localmodels/stack_args.py +21 -12
  69. package/modules/localmodels/stack_auto.py +384 -3
  70. package/modules/localmodels/stack_aux_gpu.py +4 -3
  71. package/modules/localmodels/stack_capacity.py +138 -0
  72. package/modules/localmodels/stack_cleanup.py +9 -4
  73. package/modules/localmodels/stack_cli.py +288 -0
  74. package/modules/localmodels/stack_compose.py +63 -30
  75. package/modules/localmodels/stack_console.py +9 -6
  76. package/modules/localmodels/stack_hardware.py +95 -265
  77. package/modules/localmodels/stack_hardware_text.py +263 -0
  78. package/modules/localmodels/stack_journal.py +3 -9
  79. package/modules/localmodels/stack_ledger.py +48 -18
  80. package/modules/localmodels/stack_lifecycle.py +33 -312
  81. package/modules/localmodels/stack_llm_ram.py +16 -6
  82. package/modules/localmodels/stack_mcp.py +729 -0
  83. package/modules/localmodels/stack_memory.py +0 -2
  84. package/modules/localmodels/stack_picks.py +62 -15
  85. package/modules/localmodels/stack_plan.py +19 -1
  86. package/modules/localmodels/stack_preflight.py +11 -19
  87. package/modules/localmodels/stack_progress.py +9 -1
  88. package/modules/localmodels/stack_remove.py +373 -0
  89. package/modules/localmodels/stack_route.py +101 -17
  90. package/modules/localmodels/stack_run.py +29 -0
  91. package/modules/localmodels/stack_suite.py +21 -10
  92. package/modules/localmodels/stack_summary.py +14 -0
  93. package/modules/localmodels/stack_try.py +238 -24
  94. package/modules/localmodels/stack_try_client.py +53 -15
  95. package/modules/localmodels/stack_try_docs.py +2 -2
  96. package/modules/localmodels/stack_view.py +24 -171
  97. package/modules/localmodels/stack_view_access.py +114 -1
  98. package/modules/localmodels/stack_view_agent.py +3 -13
  99. package/modules/localmodels/stack_view_hub.py +9 -10
  100. package/modules/localmodels/stack_view_llm.py +1 -1
  101. package/modules/localmodels/stack_view_sandbox.py +2 -2
  102. package/modules/localmodels/stack_view_schema.py +183 -0
  103. package/modules/localmodels/stack_view_serve.py +7 -1
  104. package/modules/localmodels/stack_view_service.py +1 -2
  105. package/modules/localmodels/stack_view_text.py +13 -9
  106. package/modules/localmodels/stack_warm.py +48 -4
  107. package/modules/localmodels/stack_warm_store.py +517 -0
  108. package/modules/localmodels/tools.json +32 -18
  109. package/modules/localmodels/transport.py +38 -13
  110. package/modules/localmodels/tui.py +28 -4
  111. package/modules/localmodels/tui_dialogs.py +136 -0
  112. package/modules/localmodels/tui_modals.py +279 -0
  113. package/modules/localmodels/tui_screen.py +113 -154
  114. package/modules/localmodels/tui_views.py +134 -203
  115. package/modules/localmodels/web/index.html +510 -101
  116. package/modules/localmodels/web/sizecalc/app.js +363 -10
  117. package/modules/localmodels/web/sizecalc/page.html +27 -3
  118. package/modules/localmodels/web/view/fleet.html +11 -2
  119. package/modules/localmodels/web/view/fleet.js +191 -17
  120. package/modules/localmodels/web/view/i18n.js +3 -2
  121. package/modules/localmodels/web/view/index.html +1 -1
  122. package/modules/localmodels/web/view/nav.js +22 -3
  123. package/modules/localmodels/web/view/view.css +63 -18
  124. package/modules/localmodels/web/view/view.js +169 -32
  125. package/modules/localmodels/windows_job.py +69 -0
  126. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/METADATA +1 -1
  127. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/RECORD +128 -106
  128. package/package.json +1 -1
  129. package/tool.json +1 -1
  130. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  131. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/WHEEL +0 -0
  132. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/entry_points.txt +0 -0
  133. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/NOTICE +0 -0
  134. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -1,9 +1,6 @@
1
1
  #!/usr/bin/env python3
2
- """Read-only host facts, stdlib-only on the target host (Python 3.8+).
3
- Delivered as ``ssh HOST python3 - < probe.py``; budgets and policy belong to the controller.
4
- Bounded nvidia-smi, engine --version/--help and loopback /props or /models; no service changes.
2
+ """Read-only host facts, stdlib-only on the target host (Python 3.8+); budgets live on controller.
5
3
  Ported from hermes_cli/local_runtime/hardware.py (MIT, Copyright (c) 2025 Nous Research).
6
- service_probe.py adds holders; bandwidth_probe.py measures memory bandwidth only on request.
7
4
  """
8
5
 
9
6
  from __future__ import annotations
@@ -48,15 +45,12 @@ class GPUBase(TypedDict):
48
45
 
49
46
 
50
47
  class GPU(GPUBase, total=False):
51
- # NVIDIA only. Generation is the most the card and its slot share (an idle link trains down,
52
- # so not the current one); width is the negotiated one, which a narrow slot caps.
53
- pcie_gen: int
54
- pcie_width: int
55
- mig_mode: str # enabled | disabled; absent where the card or driver has no MIG
56
- # Since 2026-10-28, each absent where the driver does not report it (_mark_details).
48
+ pcie_gen: int # max shared by card and slot
49
+ pcie_width: int # negotiated link width
50
+ mig_mode: str # enabled | disabled
57
51
  compute_capability: str # e.g. "8.9"
58
- reserved_bytes: int # held by the driver and firmware, outside used and free
59
- display_active: bool # a display is driven from the card, so its free memory moves
52
+ reserved_bytes: int # held by driver/firmware outside used and free
53
+ display_active: bool # driving a display, so free memory can shift
60
54
 
61
55
 
62
56
  class CudaPool(TypedDict):
@@ -148,9 +142,7 @@ class Services(TypedDict):
148
142
 
149
143
 
150
144
  class MemoryBandwidth(TypedDict):
151
- """Host-memory copy speed from bandwidth_probe.py, run only on request."""
152
-
153
- measured_gbps: float # bytes / seconds / 1e9
145
+ measured_gbps: float # bytes / seconds / 1e9; copy speed from bandwidth_probe.py
154
146
  method: str
155
147
  bytes: int # read + write traffic over the timed copies
156
148
  seconds: float
@@ -180,7 +172,6 @@ class RequiredHostFacts(TypedDict):
180
172
 
181
173
 
182
174
  class HostFacts(RequiredHostFacts, total=False):
183
- # Added 2026-10-23 under the same schema id: facts cached before then still decode.
184
175
  environment: str # bare | container | wsl | unknown
185
176
  cgroup_memory: CgroupMemory | None
186
177
  services: Services
@@ -203,17 +194,10 @@ _ENGINE_GLOBS = (
203
194
  "/usr/local/bin/llama-server",
204
195
  "/opt/homebrew/bin/llama-server",
205
196
  )
206
- # Older builds print "version: 11370 (bed0a856)"; the 0.5 line prints
207
- # "version: 0.5.0-dev (build 11370, commit bed0a8566)", where a source build without git history
208
- # reports build 1 and has no comparable release number.
209
197
  _VERSION_RE = re.compile(r"version:\s*(\d+)\s*\(([0-9a-f]+)\)")
210
198
  _SEMVER_RE = re.compile(r"version:\s*([\w.\-]+)\s*\(build\s*(\d+),\s*commit\s*([0-9a-f]+)\)")
211
- # Ports the plans and the 24GB+64GB baseline use, plus llama-server's default (8080 up to b11549,
212
- # 9931 from b11550, ggml-org/llama.cpp#30159); the controller adds every catalog port.
213
199
  SERVICE_PORTS = (8080, 9931, 18100, 18321, 18331, 18351, 18352, 18370)
214
200
  _CONTAINER_CGROUP_RE = re.compile(r"docker|kubepods|containerd|libpod|lxc|crio")
215
- # System libraries a pinned engine build may need that minimal images lack (engine locks name
216
- # them in host_libraries); upstream llama.cpp and whisper.cpp Linux builds link GCC's OpenMP.
217
201
  HOST_LIBRARIES = ("libgomp.so.1",)
218
202
  DETAIL_FIELDS = ("compute_cap", "memory.reserved", "display_active") # nvidia-smi names
219
203
  _UNLIMITED = 1 << 60 # cgroup v1 reports "no limit" as a page-aligned LONG_MAX
@@ -240,16 +224,15 @@ def _run(
240
224
 
241
225
 
242
226
  def _arch() -> str:
243
- machine = platform.machine().lower()
244
- return {"x86_64": "x64", "amd64": "x64", "aarch64": "arm64"}.get(machine, machine)
227
+ m = platform.machine().lower()
228
+ return {"x86_64": "x64", "amd64": "x64", "aarch64": "arm64"}.get(m, m)
245
229
 
246
230
 
247
231
  def _distro() -> str:
248
232
  if sys.platform == "darwin":
249
233
  return f"macOS {platform.mac_ver()[0]}".strip()
250
- source = _text("/etc/os-release") or ""
251
- fields = dict(line.split("=", 1) for line in source.splitlines() if "=" in line)
252
- return fields.get("PRETTY_NAME", "").strip('"')
234
+ kv = dict(s.split("=", 1) for s in (_text("/etc/os-release") or "").splitlines() if "=" in s)
235
+ return kv.get("PRETTY_NAME", "").strip('"')
253
236
 
254
237
 
255
238
  def _cpu_model() -> str:
@@ -265,66 +248,57 @@ def _cpu_model() -> str:
265
248
 
266
249
  with winreg.OpenKey(
267
250
  winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0"
268
- ) as key:
269
- value, _ = winreg.QueryValueEx(key, "ProcessorNameString")
270
- return str(value).strip()
251
+ ) as k:
252
+ return str(winreg.QueryValueEx(k, "ProcessorNameString")[0]).strip()
271
253
  except (ImportError, OSError):
272
254
  pass
273
255
  return platform.processor()
274
256
 
275
257
 
276
258
  def ram_from_meminfo(text: str) -> tuple[int, int] | None:
277
- """(total, available) from /proc/meminfo text, or None. MemAvailable includes reclaimable
278
- page cache; kernels without it fall back to MemFree. Zero is a real value."""
259
+ """(total, available) from /proc/meminfo text, or None (falls back to MemFree)."""
279
260
  fields = {}
280
261
  for line in text.splitlines():
281
262
  name, sep, value = line.partition(":")
282
- if not sep or name not in ("MemTotal", "MemAvailable", "MemFree"):
283
- continue
284
- parts = value.split()
285
- if len(parts) != 2 or parts[1] != "kB":
286
- continue
287
- try:
288
- fields[name] = int(parts[0]) * 1024
289
- except ValueError:
290
- return None
263
+ parts = value.split() if sep and name in ("MemTotal", "MemAvailable", "MemFree") else []
264
+ if len(parts) == 2 and parts[1] == "kB":
265
+ try:
266
+ fields[name] = int(parts[0]) * 1024
267
+ except ValueError:
268
+ return None
291
269
  total = fields.get("MemTotal")
292
- available = fields["MemAvailable"] if "MemAvailable" in fields else fields.get("MemFree")
293
- if total is None or total <= 0 or available is None or not 0 <= available <= total:
294
- return None
295
- return total, available
270
+ avail = fields["MemAvailable"] if "MemAvailable" in fields else fields.get("MemFree")
271
+ return (total, avail) if total and avail is not None and 0 <= avail <= total else None
296
272
 
297
273
 
298
274
  def ram() -> tuple[int, int]:
299
275
  if sys.platform == "win32":
300
- # MEMORYSTATUSEX: two DWORDs (length/load), then seven DWORDLONGs; 64 bytes, aligned.
301
- memory = (ctypes.c_uint64 * 8)(64)
302
- kernel = ctypes.WinDLL("kernel32", use_last_error=True)
303
- if not kernel.GlobalMemoryStatusEx(ctypes.byref(memory)):
276
+ mem = (ctypes.c_uint64 * 8)(64) # MEMORYSTATUSEX: 64B header + 7 DWORDLONGs
277
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True) # type: ignore[attr-defined]
278
+ if not k32.GlobalMemoryStatusEx(ctypes.byref(mem)):
304
279
  raise OSError("GlobalMemoryStatusEx failed")
305
- return int(memory[1]), int(memory[2]) # ullTotalPhys, ullAvailPhys
280
+ return int(mem[1]), int(mem[2]) # ullTotalPhys, ullAvailPhys
306
281
  if sys.platform.startswith("linux"):
307
282
  parsed = ram_from_meminfo(_text("/proc/meminfo") or "")
308
283
  if parsed:
309
284
  return parsed
310
285
  if sys.platform == "darwin":
311
- total_rc, total_out, _ = _run(["/usr/sbin/sysctl", "-n", "hw.memsize"])
312
- vm_rc, out, _ = _run(["/usr/bin/vm_stat"])
313
- if total_rc != 0 or vm_rc != 0:
286
+ rc1, total_out, _ = _run(["/usr/sbin/sysctl", "-n", "hw.memsize"])
287
+ rc2, out, _ = _run(["/usr/bin/vm_stat"])
288
+ if rc1 or rc2:
314
289
  raise OSError("RAM measurement unavailable")
315
290
  return metal_probe.available_memory(total_out, out)
316
291
  try:
317
- page = os.sysconf("SC_PAGE_SIZE")
318
- return os.sysconf("SC_PHYS_PAGES") * page, os.sysconf("SC_AVPHYS_PAGES") * page
292
+ pg = os.sysconf("SC_PAGE_SIZE")
293
+ return os.sysconf("SC_PHYS_PAGES") * pg, os.sysconf("SC_AVPHYS_PAGES") * pg
319
294
  except (ValueError, OSError, AttributeError):
320
295
  return 0, 0
321
296
 
322
297
 
323
298
  def _nvidia_smi() -> str | None:
324
- found = shutil.which("nvidia-smi")
325
- if found is None and os.path.exists("/usr/lib/wsl/lib/nvidia-smi"):
326
- found = "/usr/lib/wsl/lib/nvidia-smi"
327
- return found
299
+ return shutil.which("nvidia-smi") or (
300
+ "/usr/lib/wsl/lib/nvidia-smi" if os.path.exists("/usr/lib/wsl/lib/nvidia-smi") else None
301
+ )
328
302
 
329
303
 
330
304
  def parse_gpu_csv(text: str) -> list[GPU]:
@@ -349,8 +323,8 @@ def parse_gpu_csv(text: str) -> list[GPU]:
349
323
  "total_bytes": int(total) << 20,
350
324
  "free_bytes": int(free) << 20,
351
325
  "used_bytes": int(used) << 20,
352
- "util_percent": int(util) if util.isdigit() else None,
353
326
  "driver_version": driver,
327
+ "util_percent": int(util) if util.isdigit() else None,
354
328
  }
355
329
  except ValueError:
356
330
  continue
@@ -364,31 +338,22 @@ def _nvidia(errors: list[dict[str, str]]) -> tuple[dict[str, str] | None, list[G
364
338
  exe = _nvidia_smi()
365
339
  if exe is None:
366
340
  return None, []
367
- rc, out, err = _run(
368
- [
369
- exe,
370
- "--query-gpu=index,uuid,name,pci.bus_id,pci.device_id,memory.total,"
371
- "memory.free,memory.used,utilization.gpu,driver_version,"
372
- "pcie.link.gen.max,pcie.link.width.current",
373
- "--format=csv,noheader,nounits",
374
- ]
341
+ fields = (
342
+ "index,uuid,name,pci.bus_id,pci.device_id,memory.total,memory.free,"
343
+ "memory.used,utilization.gpu,driver_version,pcie.link.gen.max,pcie.link.width.current"
375
344
  )
345
+ rc, out, err = _run([exe, f"--query-gpu={fields}", "--format=csv,noheader,nounits"])
376
346
  if rc != 0:
377
347
  errors.append({"source": "nvidia-smi", "error": (err or out).strip()[:300]})
378
348
  return None, []
379
349
  gpus = parse_gpu_csv(out)
380
- header = _run([exe])[1]
381
- m = re.search(r"CUDA Version:\s*([\d.]+)", header)
382
- info = {
383
- "driver_version": gpus[0]["driver_version"] if gpus else "",
384
- "cuda_version": m.group(1) if m else "",
385
- }
386
- return info, gpus
350
+ m = re.search(r"CUDA Version:\s*([\d.]+)", _run([exe])[1])
351
+ drv = gpus[0]["driver_version"] if gpus else ""
352
+ return {"driver_version": drv, "cuda_version": m.group(1) if m else ""}, gpus
387
353
 
388
354
 
389
355
  def _cuda_pool() -> CudaPool | None:
390
- """Allocator pool and INTEGRATED attribute of CUDA device 0 via the driver library, or None.
391
- Ported from Hermes: this is how unified-memory NVIDIA parts are told apart from discrete."""
356
+ """Allocator pool and INTEGRATED attribute of CUDA device 0 via driver library, or None."""
392
357
  for name in ("libcuda.so.1", "libcuda.so", "nvcuda.dll"):
393
358
  try:
394
359
  cuda = ctypes.CDLL(name)
@@ -398,27 +363,23 @@ def _cuda_pool() -> CudaPool | None:
398
363
  else:
399
364
  return None
400
365
  try:
401
- if cuda.cuInit(0) != 0:
402
- return None
403
- dev = ctypes.c_int()
404
- if cuda.cuDeviceGet(ctypes.byref(dev), 0) != 0:
405
- return None
406
- total = ctypes.c_size_t()
366
+ dev, total, attr, byref = ctypes.c_int(), ctypes.c_size_t(), ctypes.c_int(), ctypes.byref
407
367
  getter = getattr(cuda, "cuDeviceTotalMem_v2", None) or cuda.cuDeviceTotalMem
408
- if getter(ctypes.byref(total), dev) != 0 or total.value <= 0:
368
+ if (
369
+ cuda.cuInit(0)
370
+ or cuda.cuDeviceGet(byref(dev), 0)
371
+ or getter(byref(total), dev)
372
+ or total.value <= 0
373
+ ):
409
374
  return None
410
- integrated = None
411
- attr = ctypes.c_int()
412
- if cuda.cuDeviceGetAttribute(ctypes.byref(attr), _CU_DEVICE_ATTRIBUTE_INTEGRATED, dev) == 0:
413
- integrated = bool(attr.value)
414
- return {"total_bytes": total.value, "integrated": integrated}
375
+ ok_attr = cuda.cuDeviceGetAttribute(byref(attr), _CU_DEVICE_ATTRIBUTE_INTEGRATED, dev) == 0
376
+ return {"total_bytes": total.value, "integrated": bool(attr.value) if ok_attr else None}
415
377
  except (OSError, AttributeError):
416
378
  return None
417
379
 
418
380
 
419
381
  def shared_libraries(names: Sequence[str] = HOST_LIBRARIES) -> dict[str, bool]:
420
- """Whether the dynamic loader finds each library on its default search path, which is all
421
- an engine without its own copy has."""
382
+ """Whether the dynamic loader finds each library on its default search path."""
422
383
  found = {}
423
384
  for name in names:
424
385
  try:
@@ -461,37 +422,26 @@ def _get_json(url: str, timeout: float = 3) -> tuple[int, object]:
461
422
 
462
423
 
463
424
  def probe_llama_server(port: int) -> Server | None:
464
- """Fingerprint a genuine llama-server via /props (Ollama and LM Studio answer /v1/models but
465
- not /props). Ported from Hermes detect.py."""
425
+ """Fingerprint llama-server via /props (Ollama and LM Studio answer /v1/models only)."""
466
426
  root = f"http://127.0.0.1:{port}"
467
427
  status, props = _get_json(root + "/props")
468
- if status == 401:
469
- # Hermes counts a 401 as a keyed llama-server; any other keyed service answers the same,
470
- # so the hit stays unverified until a key proves it.
471
- return {
472
- "port": port,
473
- "base_url": root + "/v1",
474
- "build_info": "",
475
- "model_path": "",
476
- "n_ctx": None,
477
- "router_mode": False,
478
- "auth_required": True,
479
- "verified": False,
480
- }
481
- if status != 200 or not isinstance(props, dict) or not props.get("build_info"):
428
+ pdict = props if isinstance(props, dict) else {}
429
+ ok = status == 200 and bool(pdict)
430
+ if status != 401 and (not ok or not pdict.get("build_info")):
482
431
  return None
483
- dgs = props.get("default_generation_settings")
484
- models_status, models = _get_json(root + "/models")
432
+ dgs = pdict.get("default_generation_settings")
433
+ m_st, models = _get_json(root + "/models") if ok else (0, None)
485
434
  n_ctx = dgs.get("n_ctx") if isinstance(dgs, dict) else None
435
+ router = ok and m_st == 200 and isinstance(models, dict) and "data" in models
486
436
  return {
487
437
  "port": port,
488
438
  "base_url": root + "/v1",
489
- "build_info": str(props.get("build_info")),
490
- "model_path": str(props.get("model_path", "")),
439
+ "build_info": str(pdict.get("build_info", "")) if ok else "",
440
+ "model_path": str(pdict.get("model_path", "")) if ok else "",
491
441
  "n_ctx": n_ctx if type(n_ctx) is int else None,
492
- "router_mode": models_status == 200 and isinstance(models, dict) and "data" in models,
493
- "auth_required": False,
494
- "verified": True,
442
+ "router_mode": router,
443
+ "auth_required": status == 401,
444
+ "verified": ok,
495
445
  }
496
446
 
497
447
 
@@ -504,30 +454,23 @@ def _flags(path: str, env: dict[str, str]) -> list[str]:
504
454
 
505
455
 
506
456
  def _engines(extra_paths: Sequence[str]) -> list[OptionalEngine]:
507
- candidates = []
508
- which = shutil.which("llama-server")
509
- if which:
510
- candidates.append(which)
457
+ paths = [p for p in [shutil.which("llama-server")] if p]
511
458
  for pattern in _ENGINE_GLOBS:
512
- candidates.extend(sorted(glob.glob(os.path.expanduser(pattern))))
513
- candidates.extend(extra_paths)
459
+ paths.extend(sorted(glob.glob(os.path.expanduser(pattern))))
514
460
  engines: list[OptionalEngine] = []
515
- for path in dict.fromkeys(os.path.realpath(p) for p in candidates):
461
+ for path in dict.fromkeys(os.path.realpath(p) for p in (*paths, *extra_paths)):
516
462
  if not os.access(path, os.X_OK):
517
463
  continue
518
- env = dict(os.environ, CUDA_VISIBLE_DEVICES="") # version only; do not wake every GPU
519
- directory = os.path.dirname(path)
520
- env["LD_LIBRARY_PATH"] = directory + os.pathsep + env.get("LD_LIBRARY_PATH", "")
464
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="") # version only; do not wake GPUs
465
+ env["LD_LIBRARY_PATH"] = os.path.dirname(path) + os.pathsep + env.get("LD_LIBRARY_PATH", "")
521
466
  rc, out, err = _run([path, "--version"], timeout=20, env=env)
522
467
  text = out + err
523
468
  build = version = commit = None
524
- semver = _SEMVER_RE.search(text)
525
- legacy = None if semver else _VERSION_RE.search(text)
526
- if semver:
527
- version, commit = semver.group(1), semver.group(3)
528
- build = "b" + semver.group(2) if int(semver.group(2)) > 1 else None
529
- elif legacy:
530
- build, commit = "b" + legacy.group(1), legacy.group(2)
469
+ if sv := _SEMVER_RE.search(text):
470
+ version, commit = sv.group(1), sv.group(3)
471
+ build = "b" + sv.group(2) if int(sv.group(2)) > 1 else None
472
+ elif lg := _VERSION_RE.search(text):
473
+ build, commit = "b" + lg.group(1), lg.group(2)
531
474
  engines.append(
532
475
  {
533
476
  "path": path,
@@ -558,8 +501,7 @@ def _at(root: str, path: str) -> str:
558
501
 
559
502
 
560
503
  def environment(root: str = "/") -> str:
561
- """bare, container or wsl. Unknown when PID 1's cgroup is unreadable and no marker file shows:
562
- a cgroup-v2 container with a private namespace looks like a bare host from there."""
504
+ """bare, container, wsl or unknown (cgroup-v2 private namespace looks bare)."""
563
505
  if any(os.path.exists(_at(root, p)) for p in ("/.dockerenv", "/run/.containerenv")):
564
506
  return "container"
565
507
  init = _text(_at(root, "/proc/1/cgroup"))
@@ -571,58 +513,49 @@ def environment(root: str = "/") -> str:
571
513
 
572
514
 
573
515
  def cgroup_memory(root: str = "/") -> CgroupMemory | None:
574
- """The memory ceiling of this process's cgroup: of it and its ancestors, the level with the
575
- least headroom (limit minus usage). None where there is no cgroup (macOS)."""
516
+ """Memory ceiling of this process's cgroup (tightest limit-usage headroom across ancestors)."""
576
517
  rows = [r.split(":", 2) for r in (_text(_at(root, "/proc/self/cgroup")) or "").splitlines()]
577
- for row in rows: # hybrid hosts keep the memory controller on v1
578
- if len(row) == 3 and "memory" in row[1].split(","):
579
- files = ("memory.limit_in_bytes", "memory.usage_in_bytes")
580
- return _tightest(_at(root, "/sys/fs/cgroup/memory"), row[2], files, 1)
581
- for row in rows:
582
- if len(row) == 3 and row[:2] == ["0", ""]:
583
- return _tightest(
584
- _at(root, "/sys/fs/cgroup"), row[2], ("memory.max", "memory.current"), 2
585
- )
586
- return None
587
-
588
-
589
- def _tightest(mount: str, path: str, files: tuple[str, str], version: int) -> CgroupMemory:
518
+ v1 = next((r[2] for r in rows if len(r) == 3 and "memory" in r[1].split(",")), None)
519
+ if v1 is not None:
520
+ spec = ("/sys/fs/cgroup/memory", v1, ("memory.limit_in_bytes", "memory.usage_in_bytes"), 1)
521
+ elif (v2 := next((r[2] for r in rows if len(r) == 3 and r[:2] == ["0", ""]), None)) is not None:
522
+ spec = ("/sys/fs/cgroup", v2, ("memory.max", "memory.current"), 2)
523
+ else:
524
+ return None
525
+ return _tightest(_at(root, spec[0]), spec[1], spec[2], spec[3])
526
+
527
+
528
+ def _tightest(mount: str, path: str, files: tuple[str, str], v: int) -> CgroupMemory:
590
529
  # Without a cgroup namespace the path is the host's, mounted as a container's root: walk up.
591
530
  parts = [p for p in path.strip().split("/") if p]
592
- levels = [os.path.join(mount, *parts[:n]) for n in range(len(parts), -1, -1)]
593
- levels = [d for d in levels if os.path.isdir(d)]
531
+ levels = [
532
+ d for n in range(len(parts), -1, -1) if os.path.isdir(d := os.path.join(mount, *parts[:n]))
533
+ ]
594
534
  readable = bool(levels)
595
- tightest: tuple[int | None, int | None, int | None] = (None, None, None)
535
+ best: tuple[int | None, int | None, int | None] = (None, None, None)
596
536
  for level in levels:
597
537
  try:
598
538
  limit = int(_read(os.path.join(level, files[0])).strip())
599
539
  except (FileNotFoundError, ValueError):
600
- continue # the root cgroup has no limit file; v2 writes "max" for no limit
540
+ continue # root cgroup omits limit; v2 uses "max"
601
541
  except OSError:
602
542
  readable = False
603
543
  continue
604
544
  usage = _text(os.path.join(level, files[1])) or ""
605
545
  used = int(usage) if usage.strip().isdigit() else None
606
- if limit < _UNLIMITED and (tightest[0] is None or limit - (used or 0) < tightest[0]):
607
- tightest = (limit - (used or 0), limit, used)
608
- _, limit_bytes, usage_bytes = tightest
609
- return {
610
- "version": version,
611
- "limit_bytes": limit_bytes,
612
- "usage_bytes": usage_bytes,
613
- "readable": readable,
614
- }
546
+ if limit < _UNLIMITED and (best[0] is None or limit - (used or 0) < best[0]):
547
+ best = (limit - (used or 0), limit, used)
548
+ return {"version": v, "limit_bytes": best[1], "usage_bytes": best[2], "readable": readable}
615
549
 
616
550
 
617
551
  def parse_field_csv(text: str) -> dict[int, str]:
618
- """{index: value} of an ``index,FIELD`` query; [N/A] and [Not Supported] cells are left out."""
552
+ """{index: value} of an ``index,FIELD`` query; [N/A] and [Not Supported] cells left out."""
619
553
  rows = csv.reader(text.strip().splitlines(), skipinitialspace=True)
620
554
  cells = {int(r[0]): r[1].strip() for r in rows if len(r) == 2 and r[0].strip().isdigit()}
621
555
  return {i: v for i, v in cells.items() if v and not v.startswith("[")}
622
556
 
623
557
 
624
558
  def _field(exe: str, name: str) -> dict[int, str]:
625
- # Its own query: a driver that does not know the field fails it without losing the cards.
626
559
  rc, out, _ = _run([exe, f"--query-gpu=index,{name}", "--format=csv,noheader,nounits"])
627
560
  return parse_field_csv(out) if rc == 0 else {}
628
561
 
@@ -635,7 +568,6 @@ def _mark_mig(exe: str, gpus: list[GPU]) -> None:
635
568
 
636
569
 
637
570
  def _mark_details(exe: str, gpus: list[GPU]) -> None:
638
- """Compute capability, reserved MiB and display state where the driver reports them."""
639
571
  cap, reserved, display = (_field(exe, f) for f in DETAIL_FIELDS)
640
572
  for gpu in gpus:
641
573
  i = gpu["index"]
@@ -691,11 +623,14 @@ def collect(
691
623
  errors.append({"source": "memory-probe", "error": "RAM measurement unavailable"})
692
624
  nvidia, gpus = _nvidia(errors)
693
625
  if gpus:
694
- _mark_mig(_nvidia_smi() or "nvidia-smi", gpus)
695
- _mark_details(_nvidia_smi() or "nvidia-smi", gpus)
696
- scanned = dict.fromkeys([*ports, *SERVICE_PORTS])
626
+ smi = _nvidia_smi() or "nvidia-smi"
627
+ _mark_mig(smi, gpus)
628
+ _mark_details(smi, gpus)
697
629
  with ThreadPoolExecutor(max_workers=16) as pool: # Windows refuses a closed port after ~2 s
698
- servers = [s for s in pool.map(probe_llama_server, scanned) if s]
630
+ servers = [
631
+ s for s in pool.map(probe_llama_server, dict.fromkeys([*ports, *SERVICE_PORTS])) if s
632
+ ]
633
+ is_linux = sys.platform.startswith("linux")
699
634
  facts: HostFacts = {
700
635
  "schema": SCHEMA,
701
636
  "collected_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
@@ -719,15 +654,15 @@ def collect(
719
654
  "gpu_vendor_class": _gpu_vendor_class(),
720
655
  "nvidia": nvidia,
721
656
  "gpus": gpus,
722
- "cuda_pool": _cuda_pool() if gpus or sys.platform.startswith("linux") else None,
657
+ "cuda_pool": _cuda_pool() if gpus or is_linux else None,
723
658
  "llama_servers": servers,
724
659
  "engines": _engines(engine_paths),
725
660
  "disk": _disk(models_dir),
726
661
  "service_manager": _service_manager(),
727
662
  "errors": errors,
728
- "environment": environment() if sys.platform.startswith("linux") else "bare",
663
+ "environment": environment() if is_linux else "bare",
729
664
  "cgroup_memory": cgroup_memory(),
730
- "shared_libraries": shared_libraries() if sys.platform.startswith("linux") else {},
665
+ "shared_libraries": shared_libraries() if is_linux else {},
731
666
  }
732
667
  if facts["platform"] == "darwin" and facts["arch"] == "arm64":
733
668
  facts["metal"] = metal_probe.metal_device()
@@ -736,8 +671,7 @@ def collect(
736
671
 
737
672
  def main(argv: list[str] | None = None) -> None:
738
673
  parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
739
- listed = ",".join(map(str, SERVICE_PORTS))
740
- parser.add_argument("--ports", default=listed, help="comma-separated loopback ports to read")
674
+ parser.add_argument("--ports", default=",".join(map(str, SERVICE_PORTS)), help="ports to read")
741
675
  parser.add_argument("--models-dir", default="~/.local/share/localmodels/models")
742
676
  parser.add_argument("--engine", action="append", default=[], help="extra llama-server path")
743
677
  args = parser.parse_args(argv)