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

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 (83) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +82 -72
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/budget.py +40 -14
  5. package/modules/localmodels/catalog.json +473 -36
  6. package/modules/localmodels/debug_mode.py +25 -0
  7. package/modules/localmodels/deploy.py +3 -0
  8. package/modules/localmodels/download-mirrors.json +47 -0
  9. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +13 -1
  10. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +79 -0
  11. package/modules/localmodels/engines.py +31 -6
  12. package/modules/localmodels/gateway.py +23 -6
  13. package/modules/localmodels/gateway_bifrost.py +6 -2
  14. package/modules/localmodels/harness.py +8 -2
  15. package/modules/localmodels/harness_gateway.py +78 -17
  16. package/modules/localmodels/harness_probe.py +5 -1
  17. package/modules/localmodels/hosts.py +52 -5
  18. package/modules/localmodels/library_floor.py +76 -0
  19. package/modules/localmodels/library_jobs.py +60 -7
  20. package/modules/localmodels/library_model.py +38 -2
  21. package/modules/localmodels/library_poly.py +272 -0
  22. package/modules/localmodels/library_pricing.py +251 -79
  23. package/modules/localmodels/library_serve.py +27 -4
  24. package/modules/localmodels/library_state.py +16 -0
  25. package/modules/localmodels/library_status.py +46 -18
  26. package/modules/localmodels/library_vram.py +123 -0
  27. package/modules/localmodels/llm_rank.py +42 -1
  28. package/modules/localmodels/magpie_windows.py +312 -0
  29. package/modules/localmodels/probe.py +39 -37
  30. package/modules/localmodels/process_identity.py +26 -33
  31. package/modules/localmodels/process_identity_darwin.py +189 -0
  32. package/modules/localmodels/process_identity_linux.py +62 -30
  33. package/modules/localmodels/recommend.py +3 -1
  34. package/modules/localmodels/remote_ops.py +11 -0
  35. package/modules/localmodels/remote_ops_download.py +30 -5
  36. package/modules/localmodels/remote_ops_service.py +15 -46
  37. package/modules/localmodels/reuse.py +13 -6
  38. package/modules/localmodels/runtime_io.py +32 -18
  39. package/modules/localmodels/service_probe.py +1 -1
  40. package/modules/localmodels/setup_inspection.py +97 -80
  41. package/modules/localmodels/setup_inspection_harness.py +147 -0
  42. package/modules/localmodels/setup_text.py +24 -0
  43. package/modules/localmodels/setup_upgrade.py +155 -0
  44. package/modules/localmodels/stack.py +3 -1
  45. package/modules/localmodels/stack_auto.py +6 -2
  46. package/modules/localmodels/stack_clients.py +1 -1
  47. package/modules/localmodels/stack_compose.py +5 -1
  48. package/modules/localmodels/stack_down.py +25 -16
  49. package/modules/localmodels/stack_hardware.py +17 -3
  50. package/modules/localmodels/stack_picks.py +28 -13
  51. package/modules/localmodels/stack_remove.py +3 -1
  52. package/modules/localmodels/stack_route.py +5 -1
  53. package/modules/localmodels/stack_suite.py +29 -8
  54. package/modules/localmodels/stack_view_access.py +238 -58
  55. package/modules/localmodels/stack_view_hub.py +12 -7
  56. package/modules/localmodels/stack_view_serve.py +13 -6
  57. package/modules/localmodels/strata-poly-serve-0.2.19-poly.1.txt +428 -0
  58. package/modules/localmodels/strata_poly_server.py +14 -2
  59. package/modules/localmodels/suite.py +19 -3
  60. package/modules/localmodels/tool_archive.py +4 -0
  61. package/modules/localmodels/transport.py +3 -1
  62. package/modules/localmodels/tui.py +4 -1
  63. package/modules/localmodels/tui_dialogs.py +42 -9
  64. package/modules/localmodels/tui_modals.py +63 -16
  65. package/modules/localmodels/tui_screen.py +80 -53
  66. package/modules/localmodels/tui_views.py +36 -6
  67. package/modules/localmodels/vision.py +4 -2
  68. package/modules/localmodels/web/index.html +996 -300
  69. package/modules/localmodels/web/sizecalc/app.js +616 -88
  70. package/modules/localmodels/web/sizecalc/page.html +239 -106
  71. package/modules/localmodels/web/view/fleet.js +25 -2
  72. package/modules/localmodels/web/view/nav.js +19 -3
  73. package/modules/localmodels/web/view/view.css +110 -22
  74. package/modules/localmodels/web/view/view.js +40 -22
  75. package/modules/localmodels/win_probe.py +204 -0
  76. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/METADATA +1 -1
  77. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/RECORD +79 -69
  78. package/package.json +1 -1
  79. package/tool.json +1 -1
  80. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/WHEEL +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/entry_points.txt +0 -0
  82. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/NOTICE +0 -0
  83. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.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
29
+ from localmodels import metal_probe, win_probe
30
30
  except ImportError:
31
31
  import metal_probe # type: ignore[import-not-found,no-redef]
32
+ import win_probe # type: ignore[import-not-found,no-redef]
32
33
 
33
34
 
34
35
  class GPUBase(TypedDict):
@@ -102,10 +103,7 @@ class CgroupMemory(TypedDict):
102
103
 
103
104
  class _ComputeSince20261024(TypedDict, total=False):
104
105
  in_suite: bool # verified current-user deployment in the suite; never just a cgroup label
105
- # A Mac process's resident file cache: its resident memory less its physical footprint
106
- # (mapped GGUF weights that are not wired). The RAM available already counts these pages
107
- # (metal_probe.available_memory), so a stop gives back only the rest. Absent: unknown.
108
- cached_bytes: int
106
+ cached_bytes: int # Mac process resident file cache (already counted as available RAM)
109
107
 
110
108
 
111
109
  class ComputeProcess(_ComputeSince20261024):
@@ -183,6 +181,7 @@ class HostFacts(RequiredHostFacts, total=False):
183
181
  memory_bandwidth: MemoryBandwidth # only after probe --measure-bandwidth
184
182
  shared_libraries: dict[str, bool] # HOST_LIBRARIES: can the loader find each one
185
183
  metal: dict[str, object] | None # metal_probe.py on Apple Silicon (2026-10-29; metal.Metal)
184
+ gpu_processes: list[win_probe.GpuAppMemory] # Windows WDDM per-app local VRAM (CIM)
186
185
 
187
186
 
188
187
  SCHEMA = "localmodels.host-facts/v1"
@@ -250,15 +249,8 @@ def _cpu_model() -> str:
250
249
  if sys.platform == "darwin":
251
250
  return _run(["/usr/sbin/sysctl", "-n", "machdep.cpu.brand_string"])[1].strip()
252
251
  if sys.platform == "win32":
253
- try:
254
- import winreg
255
-
256
- with winreg.OpenKey(
257
- winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0"
258
- ) as k:
259
- return str(winreg.QueryValueEx(k, "ProcessorNameString")[0]).strip()
260
- except (ImportError, OSError):
261
- pass
252
+ if model := win_probe.cpu_model():
253
+ return model
262
254
  return platform.processor()
263
255
 
264
256
 
@@ -280,11 +272,7 @@ def ram_from_meminfo(text: str) -> tuple[int, int] | None:
280
272
 
281
273
  def ram() -> tuple[int, int]:
282
274
  if sys.platform == "win32":
283
- mem = (ctypes.c_uint64 * 8)(64) # MEMORYSTATUSEX: 64B header + 7 DWORDLONGs
284
- k32 = ctypes.WinDLL("kernel32", use_last_error=True) # type: ignore[attr-defined]
285
- if not k32.GlobalMemoryStatusEx(ctypes.byref(mem)):
286
- raise OSError("GlobalMemoryStatusEx failed")
287
- return int(mem[1]), int(mem[2]) # ullTotalPhys, ullAvailPhys
275
+ return win_probe.ram()
288
276
  if sys.platform.startswith("linux"):
289
277
  parsed = ram_from_meminfo(_text("/proc/meminfo") or "")
290
278
  if parsed:
@@ -403,17 +391,24 @@ def _nvidia(errors: list[dict[str, str]]) -> tuple[dict[str, str] | None, list[G
403
391
  if rc != 0:
404
392
  errors.append({"source": "nvidia-smi", "error": (err or out).strip()[:300]})
405
393
  return None, []
406
- gpus = parse_gpu_csv(out)
407
- drv = "" if not gpus or gpus[0]["driver_version"].startswith("[") else gpus[0]["driver_version"]
408
- cuda_version = _cuda_driver_version()
409
- if not cuda_version or not drv:
394
+ gpus, text = parse_gpu_csv(out), out.strip()
395
+ if not gpus and text:
396
+ no_dev = "no devices were found" in text.lower()
397
+ msg = text[:300] if no_dev else "nvidia-smi reported unmeasured GPU memory"
398
+ errors.append({"source": "nvidia-smi", "error": msg})
399
+ if no_dev:
400
+ return None, []
401
+ raw_drv = gpus[0]["driver_version"] if gpus else ""
402
+ drv, cuda_version = "" if raw_drv.startswith("[") else raw_drv, _cuda_driver_version()
403
+ if not (cuda_version and drv):
410
404
  banner = _run([exe])[1]
411
405
  cuda_version = cuda_version or parse_cuda_version(banner)
412
406
  drv = drv or parse_driver_version(banner)
413
407
  for gpu in gpus:
414
408
  if not gpu["driver_version"] or gpu["driver_version"].startswith("["):
415
409
  gpu["driver_version"] = drv
416
- return {"driver_version": drv, "cuda_version": cuda_version}, gpus
410
+ meta = {"driver_version": drv, "cuda_version": cuda_version}
411
+ return (meta, gpus) if (gpus or drv or cuda_version) else (None, [])
417
412
 
418
413
 
419
414
  def _cuda_pool() -> CudaPool | None:
@@ -449,15 +444,22 @@ def shared_libraries(names: Sequence[str] = HOST_LIBRARIES) -> dict[str, bool]:
449
444
  return found
450
445
 
451
446
 
447
+ def _windows_gpu_vendor_class() -> str:
448
+ """Inspect Windows display adapter PCI vendor IDs via stdlib winreg."""
449
+ return win_probe.gpu_vendor_class(_GPU_PCI_VENDORS, _GPU_PRIORITY)
450
+
451
+
452
452
  def _gpu_vendor_class() -> str:
453
453
  exists = os.path.exists
454
454
  if sys.platform == "darwin":
455
455
  return "apple_silicon" if _arch() == "arm64" else "unknown"
456
456
  if sys.platform == "win32":
457
- return "nvidia" if _nvidia_smi() or exists(_win_system32("nvcuda.dll")) else "unknown"
458
- if exists("/proc/driver/nvidia/version") or exists("/usr/lib/wsl/lib/nvidia-smi"):
459
- return "nvidia"
460
- if exists("/usr/lib/wsl/lib/libcuda.so.1"):
457
+ if _nvidia_smi() or exists(_win_system32("nvcuda.dll")):
458
+ return "nvidia"
459
+ return _windows_gpu_vendor_class()
460
+ if exists("/proc/driver/nvidia/version") or any(
461
+ exists("/usr/lib/wsl/lib/" + f) for f in ("nvidia-smi", "libcuda.so.1")
462
+ ):
461
463
  return "nvidia"
462
464
  root = "/sys/class/drm"
463
465
  try:
@@ -466,9 +468,8 @@ def _gpu_vendor_class() -> str:
466
468
  return "unknown"
467
469
  found = set()
468
470
  for card in cards:
469
- vendor = (_text(os.path.join(root, card, "device", "vendor")) or "")[:16].strip().lower()
470
- vendor = vendor[2:] if vendor.startswith("0x") else vendor
471
- found.add(_GPU_PCI_VENDORS.get(vendor))
471
+ v = (_text(os.path.join(root, card, "device", "vendor")) or "")[:16].strip().lower()
472
+ found.add(_GPU_PCI_VENDORS.get(v[2:] if v.startswith("0x") else v))
472
473
  return next((name for name in _GPU_PRIORITY if name in found), "none")
473
474
 
474
475
 
@@ -644,8 +645,7 @@ def _mark_details(exe: str, gpus: list[GPU]) -> None:
644
645
 
645
646
 
646
647
  def _disk(path: str) -> Disk:
647
- path = os.path.expanduser(path)
648
- probe = path
648
+ path = probe = os.path.expanduser(path)
649
649
  while probe and not os.path.exists(probe):
650
650
  probe = os.path.dirname(probe)
651
651
  try:
@@ -695,6 +695,7 @@ def collect(
695
695
  s for s in pool.map(probe_llama_server, dict.fromkeys([*ports, *SERVICE_PORTS])) if s
696
696
  ]
697
697
  is_linux = sys.platform.startswith("linux")
698
+ vendor = _gpu_vendor_class()
698
699
  facts: HostFacts = {
699
700
  "schema": SCHEMA,
700
701
  "collected_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
@@ -715,10 +716,10 @@ def collect(
715
716
  "available_bytes": ram_avail,
716
717
  **(metal_probe.memory_status() if sys.platform == "darwin" else {}),
717
718
  },
718
- "gpu_vendor_class": _gpu_vendor_class(),
719
+ "gpu_vendor_class": vendor,
719
720
  "nvidia": nvidia,
720
721
  "gpus": gpus,
721
- "cuda_pool": _cuda_pool() if gpus or is_linux else None,
722
+ "cuda_pool": _cuda_pool() if gpus or is_linux or vendor == "nvidia" else None,
722
723
  "llama_servers": servers,
723
724
  "engines": _engines(engine_paths),
724
725
  "disk": _disk(models_dir),
@@ -730,6 +731,8 @@ def collect(
730
731
  }
731
732
  if facts["platform"] == "darwin" and facts["arch"] == "arm64":
732
733
  facts["metal"] = metal_probe.metal_device()
734
+ if facts["platform"] == "win32" and gpus and (gpu_procs := win_probe.gpu_process_memory()):
735
+ facts["gpu_processes"] = gpu_procs
733
736
  return facts
734
737
 
735
738
 
@@ -740,8 +743,7 @@ def main(argv: list[str] | None = None) -> None:
740
743
  parser.add_argument("--engine", action="append", default=[], help="extra llama-server path")
741
744
  args = parser.parse_args(argv)
742
745
  ports = tuple(int(p) for p in args.ports.split(",") if p.strip())
743
- json.dump(collect(ports, args.models_dir, args.engine), sys.stdout, indent=1, sort_keys=True)
744
- sys.stdout.write("\n")
746
+ print(json.dumps(collect(ports, args.models_dir, args.engine), indent=1, sort_keys=True))
745
747
 
746
748
 
747
749
  if __name__ == "__main__":
@@ -1,8 +1,9 @@
1
- """Owned process identity receipts and Linux command proof; stdlib-only, Python 3.8+.
1
+ """Owned process identity receipts and command proof; stdlib-only, Python 3.8+.
2
2
 
3
3
  Receipts bind PID, UID, PGID and start time against PID reuse without storing secrets. On
4
- Windows, receipts use kernel32/advapi32 creation times and SID tokens (uid 0 for this user, -1
5
- otherwise; pgid=pid), and stopping kills the tree via ``taskkill``.
4
+ Linux, receipts use ``/proc/<pid>/stat`` boot ticks; on macOS, ``libSystem`` ``sysctl``
5
+ microsecond start times; on Windows, kernel32/advapi32 creation times and SID tokens (uid 0
6
+ for this user, -1 otherwise; pgid=pid), and stopping kills the tree via ``taskkill``.
6
7
  """
7
8
 
8
9
  from __future__ import annotations
@@ -18,8 +19,9 @@ from pathlib import Path
18
19
  from typing import Any, TypedDict
19
20
 
20
21
  try:
21
- from localmodels import process_identity_linux
22
+ from localmodels import process_identity_darwin, process_identity_linux
22
23
  except ImportError: # run as a bare file from this directory
24
+ import process_identity_darwin # type: ignore[import-not-found,no-redef]
23
25
  import process_identity_linux # type: ignore[import-not-found,no-redef]
24
26
 
25
27
 
@@ -490,9 +492,15 @@ _IDENTITY_FIELDS = {"pid": int, "uid": int, "pgid": int, "started": str}
490
492
 
491
493
 
492
494
  def _same_start(current: str, saved: str) -> bool:
493
- return current == saved or (
494
- sys.platform.startswith("linux") and process_identity_linux.same_start(current, saved)
495
- )
495
+ if current == saved:
496
+ return True
497
+ if sys.platform.startswith("linux"):
498
+ epoch = process_identity_linux.started_epoch(current)
499
+ elif sys.platform == "darwin":
500
+ epoch = process_identity_darwin.started_epoch(current)
501
+ else:
502
+ return False
503
+ return process_identity_linux.matches_legacy_lstart(epoch, saved)
496
504
 
497
505
 
498
506
  def _valid_identity(saved: dict[str, Any]) -> bool:
@@ -520,31 +528,13 @@ def inspect(pid: int) -> Identity | None:
520
528
  return _windows_inspect(pid)
521
529
  if sys.platform.startswith("linux"):
522
530
  found = process_identity_linux.inspect(pid)
523
- if found is None:
524
- return None
525
- return {"pid": pid, "uid": found[0], "pgid": found[1], "started": found[2]}
526
- # LC_ALL=C keeps lstart in 5 English tokens (zh_CN outputs 4).
527
- result = subprocess.run(
528
- ["/bin/ps", "-p", str(pid), "-o", "uid=,pgid=,lstart=,stat="],
529
- capture_output=True,
530
- text=True,
531
- timeout=5,
532
- check=False,
533
- env={**os.environ, "LC_ALL": "C"},
534
- )
535
- fields = result.stdout.split()
536
- if result.returncode == 1 and not fields and not result.stderr.strip():
537
- return None
538
- if result.returncode or len(fields) != 8:
539
- raise OSError("process identity unavailable")
540
- if fields[-1].startswith("Z"):
531
+ elif sys.platform == "darwin":
532
+ found = process_identity_darwin.inspect(pid)
533
+ else:
534
+ found = process_identity_linux.posix_ps_inspect(pid)
535
+ if found is None:
541
536
  return None
542
- return {
543
- "pid": pid,
544
- "uid": int(fields[0]),
545
- "pgid": int(fields[1]),
546
- "started": " ".join(fields[2:7]),
547
- }
537
+ return {"pid": pid, "uid": found[0], "pgid": found[1], "started": found[2]}
548
538
 
549
539
 
550
540
  def _private(path: Path) -> str:
@@ -706,9 +696,12 @@ def listener_owned(port: int, pid: int | None) -> bool:
706
696
 
707
697
 
708
698
  def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
709
- """Read-only Linux argv proof (plus shebang); on Windows checks owned executable image path."""
710
- if _windows():
699
+ """Read-only argv proof (plus shebang); on Windows checks owned executable image path."""
700
+ if root == "/" and _windows():
711
701
  return _windows_command_matches(pid, expected)
702
+ if root == "/" and sys.platform == "darwin":
703
+ info = process_identity_darwin.command_info(pid)
704
+ return info is not None and process_identity_linux.argv_matches(info[0], info[1], expected)
712
705
  return process_identity_linux.command_matches(pid, expected, root)
713
706
 
714
707
 
@@ -0,0 +1,189 @@
1
+ """macOS sysctl process identity, process-group listing, and argv proof; stdlib-only, Python 3.8+.
2
+
3
+ Reads process metadata directly from ``libSystem.B.dylib`` ``sysctl`` (``KERN_PROC_PID``,
4
+ ``KERN_PROC_PGRP``, ``KERN_PROCARGS2``) instead of executing ``/bin/ps`` (a setuid restricted
5
+ binary that raises ``PermissionError`` in restricted macOS environments).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ctypes
11
+ import errno
12
+ import os
13
+ import struct
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ _CTL_KERN = 1
18
+ _KERN_PROC = 14
19
+ _KERN_PROC_PID = 1
20
+ _KERN_PROC_PGRP = 2
21
+ _KERN_PROCARGS2 = 49
22
+ _SZOMB = 5
23
+
24
+ # 64-bit macOS (arm64 and x86_64) struct kinfo_proc ABI layout (verified against MacOSX SDK).
25
+ _KINFO_PROC_SIZE = 648
26
+ _OFF_START_TVSEC = 0 # int64 kp_proc.p_starttime.tv_sec
27
+ _OFF_START_TVUSEC = 8 # int32 kp_proc.p_starttime.tv_usec
28
+ _OFF_P_STAT = 36 # uint8 kp_proc.p_stat
29
+ _OFF_P_PID = 40 # int32 kp_proc.p_pid
30
+ _OFF_CR_UID = 420 # uint32 kp_eproc.e_ucred.cr_uid (effective UID)
31
+ _OFF_E_PGID = 564 # int32 kp_eproc.e_pgid
32
+
33
+ _LIB: list[Any] = []
34
+
35
+
36
+ def _sysctl_fn() -> Any:
37
+ if _LIB:
38
+ return _LIB[0]
39
+ lib = ctypes.CDLL("/usr/lib/libSystem.B.dylib", use_errno=True)
40
+ fn = lib.sysctl
41
+ fn.argtypes = (
42
+ ctypes.POINTER(ctypes.c_int),
43
+ ctypes.c_uint,
44
+ ctypes.c_void_p,
45
+ ctypes.POINTER(ctypes.c_size_t),
46
+ ctypes.c_void_p,
47
+ ctypes.c_size_t,
48
+ )
49
+ fn.restype = ctypes.c_int
50
+ _LIB.append(fn)
51
+ return fn
52
+
53
+
54
+ def _sysctl(mib: tuple[int, ...], *, extra_bytes: int = 0) -> bytes:
55
+ """Query a Darwin sysctl MIB, retrying if the buffer grows between sizing and reading."""
56
+ fn = _sysctl_fn()
57
+ mib_arr = (ctypes.c_int * len(mib))(*mib)
58
+ for attempt in range(3):
59
+ size = ctypes.c_size_t(0)
60
+ ctypes.set_errno(0)
61
+ if fn(mib_arr, len(mib), None, ctypes.byref(size), None, 0) != 0:
62
+ err = ctypes.get_errno()
63
+ raise OSError(err, os.strerror(err) if err else "sysctl size failed")
64
+ if size.value == 0:
65
+ return b""
66
+ alloc = size.value + extra_bytes * (attempt + 1)
67
+ out_size = ctypes.c_size_t(alloc)
68
+ buf = ctypes.create_string_buffer(alloc)
69
+ ctypes.set_errno(0)
70
+ if fn(mib_arr, len(mib), buf, ctypes.byref(out_size), None, 0) == 0:
71
+ return buf.raw[: out_size.value]
72
+ err = ctypes.get_errno()
73
+ if err != errno.ENOMEM or attempt == 2:
74
+ raise OSError(err, os.strerror(err) if err else "sysctl read failed")
75
+ raise OSError("sysctl read failed")
76
+
77
+
78
+ def _parse_kinfo(raw: bytes) -> list[tuple[int, int, int, int, str]]:
79
+ """Decode ``struct kinfo_proc`` array into ``(pid, euid, pgid, p_stat, started)`` tuples."""
80
+ if not raw:
81
+ return []
82
+ if len(raw) % _KINFO_PROC_SIZE != 0:
83
+ raise OSError("process identity unavailable")
84
+ rows: list[tuple[int, int, int, int, str]] = []
85
+ for offset in range(0, len(raw), _KINFO_PROC_SIZE):
86
+ tv_sec, tv_usec = struct.unpack_from("<qi", raw, offset + _OFF_START_TVSEC)
87
+ if tv_sec < 0 or not 0 <= tv_usec < 1_000_000:
88
+ raise OSError("process identity unavailable")
89
+ p_stat = raw[offset + _OFF_P_STAT]
90
+ (p_pid,) = struct.unpack_from("<i", raw, offset + _OFF_P_PID)
91
+ (cr_uid,) = struct.unpack_from("<I", raw, offset + _OFF_CR_UID)
92
+ (e_pgid,) = struct.unpack_from("<i", raw, offset + _OFF_E_PGID)
93
+ rows.append((p_pid, cr_uid, e_pgid, p_stat, f"{tv_sec}.{tv_usec:06d}"))
94
+ return rows
95
+
96
+
97
+ def _kinfo_rows(kind: int, arg: int) -> list[tuple[int, int, int, int, str]]:
98
+ extra = _KINFO_PROC_SIZE * 8 if kind == _KERN_PROC_PGRP else 0
99
+ try:
100
+ raw = _sysctl((_CTL_KERN, _KERN_PROC, kind, arg), extra_bytes=extra)
101
+ except OSError:
102
+ raise OSError("process identity unavailable") from None
103
+ return _parse_kinfo(raw)
104
+
105
+
106
+ def inspect(pid: int) -> tuple[int, int, str] | None:
107
+ """Return ``(euid, pgid, start_sec.usec)`` via ``KERN_PROC_PID``, or None if gone/zombie."""
108
+ rows = _kinfo_rows(_KERN_PROC_PID, pid)
109
+ if not rows:
110
+ return None
111
+ p_pid, uid, pgid, p_stat, started = rows[0]
112
+ if p_pid != pid or p_stat == _SZOMB:
113
+ return None
114
+ return uid, pgid, started
115
+
116
+
117
+ def process_state(pid: int) -> str | None:
118
+ """Return ``'Z'`` for a zombie, ``'S'`` for a live process, or None when gone."""
119
+ rows = _kinfo_rows(_KERN_PROC_PID, pid)
120
+ if not rows:
121
+ return None
122
+ p_pid, _, _, p_stat, _ = rows[0]
123
+ if p_pid != pid:
124
+ return None
125
+ return "Z" if p_stat == _SZOMB else "S"
126
+
127
+
128
+ def group_members(pgid: int) -> dict[int, str]:
129
+ """Return live ``{pid: started}`` in process group ``pgid``; raise if another user owns one."""
130
+ members: dict[int, str] = {}
131
+ own_uid = os.getuid()
132
+ for member_pid, uid, member_pgid, p_stat, started in _kinfo_rows(_KERN_PROC_PGRP, pgid):
133
+ if member_pgid != pgid or p_stat == _SZOMB:
134
+ continue
135
+ if uid != own_uid:
136
+ raise RuntimeError("the service process group has another owner; config left unchanged")
137
+ members[member_pid] = started
138
+ return members
139
+
140
+
141
+ def started_epoch(started: str) -> float | None:
142
+ """Unix timestamp of a macOS ``<sec>.<usec>`` start receipt, or None if not in that form."""
143
+ sec_text, sep, usec_text = started.partition(".")
144
+ if not sep or not sec_text.isdigit() or not usec_text.isdigit() or len(usec_text) != 6:
145
+ return None
146
+ usec = int(usec_text)
147
+ if usec >= 1_000_000:
148
+ return None
149
+ return int(sec_text) + usec / 1_000_000.0
150
+
151
+
152
+ def _parse_procargs2(raw: bytes) -> tuple[str, list[str]] | None:
153
+ """Decode ``KERN_PROCARGS2`` payload into ``(exec_path, argv)``, stopping before envp."""
154
+ if len(raw) < 5:
155
+ return None
156
+ (argc,) = struct.unpack_from("<i", raw, 0)
157
+ if argc <= 0 or argc > 65536:
158
+ return None
159
+ nul = raw.find(b"\x00", 4)
160
+ if nul < 0:
161
+ return None
162
+ exec_path = raw[4:nul].decode("utf-8", "surrogateescape")
163
+ pos = nul + 1
164
+ while pos < len(raw) and raw[pos] == 0:
165
+ pos += 1
166
+ argv: list[str] = []
167
+ for _ in range(argc):
168
+ end = raw.find(b"\x00", pos)
169
+ if end < 0:
170
+ return None
171
+ argv.append(raw[pos:end].decode("utf-8", "surrogateescape"))
172
+ pos = end + 1
173
+ return exec_path, argv
174
+
175
+
176
+ def command_info(pid: int) -> tuple[list[str], Path] | None:
177
+ """Read-only macOS argv and executable path for an owned process, without retaining envp."""
178
+ try:
179
+ found = inspect(pid)
180
+ if found is None or found[0] != os.getuid():
181
+ return None
182
+ raw = _sysctl((_CTL_KERN, _KERN_PROCARGS2, pid))
183
+ except OSError:
184
+ return None
185
+ parsed = _parse_procargs2(raw)
186
+ if parsed is None:
187
+ return None
188
+ exec_path, argv = parsed
189
+ return argv, Path(exec_path)
@@ -1,15 +1,17 @@
1
- """Linux /proc process identity, legacy lstart compatibility, and argv proof; stdlib-only, Python 3.8+."""
1
+ """Linux /proc process identity, shared POSIX legacy lstart/argv matching; stdlib-only, Python 3.8+."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
5
  import os
6
6
  import shlex
7
7
  import shutil
8
+ import subprocess
8
9
  import time
9
10
  from pathlib import Path
10
11
 
11
- # Receipts written before Linux switched from ``ps -o lstart=`` to /proc/<pid>/stat boot ticks
12
- # hold wall-clock seconds derived from /proc/stat btime, which can drift by ~1-2 s under NTP.
12
+ # Receipts written before Linux switched to /proc boot ticks and macOS switched to sysctl
13
+ # microsecond timestamps hold C-locale ``ps -o lstart=`` wall-clock seconds, which can differ
14
+ # by a few seconds due to rounding or NTP btime jitter.
13
15
  _LEGACY_LSTART_TOLERANCE_S = 5.0
14
16
  _ENGLISH_DAYS = frozenset(("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))
15
17
  _ENGLISH_MONTHS = {
@@ -68,6 +70,20 @@ def _boot_time(root: str = "/") -> int | None:
68
70
  return None
69
71
 
70
72
 
73
+ def started_epoch(started: str, root: str = "/") -> float | None:
74
+ """Unix timestamp of a ``/proc/<pid>/stat`` boot-tick receipt, or None if unreadable."""
75
+ if not started.isdigit():
76
+ return None
77
+ try:
78
+ hz = os.sysconf("SC_CLK_TCK")
79
+ except (OSError, ValueError):
80
+ return None
81
+ btime = _boot_time(root)
82
+ if btime is None or hz <= 0:
83
+ return None
84
+ return btime + int(started) / hz
85
+
86
+
71
87
  def _parse_legacy_lstart(value: str) -> float | None:
72
88
  """Parse C-locale ``ps -o lstart=`` (``Wed Nov 18 06:16:50 2026``) without relying on LC_TIME."""
73
89
  parts = value.split()
@@ -88,35 +104,21 @@ def _parse_legacy_lstart(value: str) -> float | None:
88
104
  return None
89
105
 
90
106
 
91
- def same_start(current_started: str, saved_started: str, root: str = "/") -> bool:
92
- """Match exact boot ticks, or a pre-upgrade ``ps -o lstart=`` receipt within NTP btime jitter."""
93
- if current_started == saved_started:
94
- return True
95
- if not current_started.isdigit():
107
+ def matches_legacy_lstart(actual_epoch: float | None, saved_started: str) -> bool:
108
+ """Match a live process's epoch timestamp against a pre-upgrade C-locale ``lstart`` receipt."""
109
+ if actual_epoch is None:
96
110
  return False
97
111
  saved_epoch = _parse_legacy_lstart(saved_started)
98
- if saved_epoch is None:
99
- return False
100
- try:
101
- hz = os.sysconf("SC_CLK_TCK")
102
- except (OSError, ValueError):
103
- return False
104
- btime = _boot_time(root)
105
- if btime is None or hz <= 0:
106
- return False
107
- actual_epoch = btime + int(current_started) / hz
108
- return abs(actual_epoch - saved_epoch) <= _LEGACY_LSTART_TOLERANCE_S
112
+ return saved_epoch is not None and abs(actual_epoch - saved_epoch) <= _LEGACY_LSTART_TOLERANCE_S
109
113
 
110
114
 
111
- def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
112
- """Read-only Linux ``/proc/<pid>/cmdline`` argv proof (including ``#!`` scripts)."""
115
+ def argv_matches(actual: list[str], exe: Path, expected: list[str], root: str = "/") -> bool:
116
+ """Verify exact argv match or single-interpreter ``#!`` script match against ``exe``."""
117
+ if not expected:
118
+ return False
119
+ if actual == expected:
120
+ return True
113
121
  try:
114
- process = Path(root) / "proc" / str(pid)
115
- if process.stat().st_uid != os.getuid():
116
- return False
117
- actual = process.joinpath("cmdline").read_bytes().decode().rstrip("\0").split("\0")
118
- if actual == expected:
119
- return True
120
122
  target = expected[0] if root == "/" else Path(root) / expected[0].lstrip("/")
121
123
  with open(target, "rb") as executable:
122
124
  header = executable.readline(512).decode()
@@ -128,8 +130,38 @@ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
128
130
  if len(interp) != 1 or actual[1:] != expected:
129
131
  return False
130
132
  resolved = shutil.which(interp[0])
131
- return (
132
- resolved is not None and process.joinpath("exe").resolve() == Path(resolved).resolve()
133
- )
133
+ return resolved is not None and exe.resolve() == Path(resolved).resolve()
134
134
  except (OSError, ValueError, UnicodeError, IndexError):
135
135
  return False
136
+
137
+
138
+ def posix_ps_inspect(pid: int) -> tuple[int, int, str] | None:
139
+ """Generic POSIX ``/bin/ps`` fallback (neither Linux nor macOS); LC_ALL=C fixes lstart."""
140
+ result = subprocess.run(
141
+ ["/bin/ps", "-p", str(pid), "-o", "uid=,pgid=,lstart=,stat="],
142
+ capture_output=True,
143
+ text=True,
144
+ timeout=5,
145
+ check=False,
146
+ env={**os.environ, "LC_ALL": "C"},
147
+ )
148
+ fields = result.stdout.split()
149
+ if result.returncode == 1 and not fields and not result.stderr.strip():
150
+ return None
151
+ if result.returncode or len(fields) != 8:
152
+ raise OSError("process identity unavailable")
153
+ if fields[-1].startswith("Z"):
154
+ return None
155
+ return int(fields[0]), int(fields[1]), " ".join(fields[2:7])
156
+
157
+
158
+ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
159
+ """Read-only Linux ``/proc/<pid>/cmdline`` argv proof (including ``#!`` scripts)."""
160
+ try:
161
+ process = Path(root) / "proc" / str(pid)
162
+ if process.stat().st_uid != os.getuid():
163
+ return False
164
+ actual = process.joinpath("cmdline").read_bytes().decode().rstrip("\0").split("\0")
165
+ return argv_matches(actual, process.joinpath("exe"), expected, root)
166
+ except (OSError, ValueError, UnicodeError):
167
+ return False
@@ -179,7 +179,9 @@ def recommendation(
179
179
  candidates = [
180
180
  (p, budget)
181
181
  for p in host
182
- if not p.conflicts and (budget := agent_budget(p, facts)) is not None
182
+ if not p.conflicts
183
+ and not p.budget.uma
184
+ and (budget := agent_budget(p, facts)) is not None
183
185
  ]
184
186
  candidates.sort(key=lambda pair: -pair[1].usable_vram_bytes)
185
187
  fitting = []
@@ -406,9 +406,11 @@ def fetch(
406
406
  return None
407
407
  free = shutil.disk_usage(os.path.dirname(dest)).free
408
408
  part = dest + ".part"
409
+ had_part = os.path.exists(part)
409
410
  have = remote_ops_download.kept_bytes(part, size)
410
411
  if have > size:
411
412
  remote_ops_download.discard(part)
413
+ had_part = False
412
414
  have = 0
413
415
  if size - have > free:
414
416
  raise RuntimeError(f"low disk space: {label} needs {size - have} more bytes, {free} free")
@@ -417,9 +419,12 @@ def fetch(
417
419
  error: Exception | None = None
418
420
  failed: list[Source] = []
419
421
  for source, ranged in remote_ops_download.ordered(sources, size, label, region, failed):
422
+ probed_bad = any(f["url"] == source["url"] for f in failed)
420
423
  try:
421
424
  if source.get("member"):
422
425
  remote_ops_download.npm_transfer(source, part, size, label)
426
+ elif probed_bad:
427
+ remote_ops_download.transfer(source, part, size, label, ranged, attempts=1)
423
428
  else:
424
429
  remote_ops_download.transfer(source, part, size, label, ranged)
425
430
  except Exception as exc: # noqa: BLE001 - the next source is tried, the last re-raised
@@ -445,6 +450,8 @@ def fetch(
445
450
  extra = {"region_fallback": switch} if switch else {}
446
451
  emit("log", message=f"downloaded and verified {label} from {source['source']}", **extra)
447
452
  return switch
453
+ if not had_part and remote_ops_download.kept_bytes(part, size) == 0:
454
+ remote_ops_download.discard(part)
448
455
  raise error or RuntimeError(f"{label} has no download source")
449
456
 
450
457
 
@@ -511,6 +518,10 @@ def unpack(archive: str, directory: str, keep: tuple[str, ...] = ()) -> None:
511
518
  if member.islnk() and strip:
512
519
  member.linkname = target.lstrip("./").split("/", 1)[-1]
513
520
  member.name = name
521
+ if member.isdir():
522
+ member.mode |= 0o700
523
+ elif member.isfile():
524
+ member.mode |= 0o200
514
525
  tar.extract(member, directory)
515
526
 
516
527