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

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 (55) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +54 -50
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/budget.py +40 -14
  5. package/modules/localmodels/catalog.json +57 -34
  6. package/modules/localmodels/debug_mode.py +25 -0
  7. package/modules/localmodels/deploy.py +3 -0
  8. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +13 -1
  9. package/modules/localmodels/engines.py +31 -6
  10. package/modules/localmodels/library_jobs.py +22 -1
  11. package/modules/localmodels/library_model.py +38 -2
  12. package/modules/localmodels/library_pricing.py +261 -78
  13. package/modules/localmodels/library_serve.py +20 -4
  14. package/modules/localmodels/library_status.py +19 -11
  15. package/modules/localmodels/library_vram.py +123 -0
  16. package/modules/localmodels/llm_rank.py +28 -1
  17. package/modules/localmodels/probe.py +39 -37
  18. package/modules/localmodels/process_identity.py +26 -33
  19. package/modules/localmodels/process_identity_darwin.py +189 -0
  20. package/modules/localmodels/process_identity_linux.py +62 -30
  21. package/modules/localmodels/recommend.py +3 -1
  22. package/modules/localmodels/remote_ops_service.py +15 -46
  23. package/modules/localmodels/service_probe.py +1 -1
  24. package/modules/localmodels/setup_inspection.py +14 -1
  25. package/modules/localmodels/setup_text.py +12 -0
  26. package/modules/localmodels/setup_upgrade.py +145 -0
  27. package/modules/localmodels/stack_compose.py +5 -1
  28. package/modules/localmodels/stack_hardware.py +5 -2
  29. package/modules/localmodels/stack_route.py +5 -1
  30. package/modules/localmodels/stack_suite.py +1 -1
  31. package/modules/localmodels/stack_view_access.py +238 -58
  32. package/modules/localmodels/stack_view_hub.py +12 -7
  33. package/modules/localmodels/stack_view_serve.py +13 -6
  34. package/modules/localmodels/transport.py +3 -1
  35. package/modules/localmodels/tui.py +4 -1
  36. package/modules/localmodels/tui_dialogs.py +42 -9
  37. package/modules/localmodels/tui_modals.py +63 -16
  38. package/modules/localmodels/tui_screen.py +80 -53
  39. package/modules/localmodels/tui_views.py +36 -6
  40. package/modules/localmodels/web/index.html +996 -300
  41. package/modules/localmodels/web/sizecalc/app.js +616 -88
  42. package/modules/localmodels/web/sizecalc/page.html +239 -106
  43. package/modules/localmodels/web/view/fleet.js +25 -2
  44. package/modules/localmodels/web/view/nav.js +19 -3
  45. package/modules/localmodels/web/view/view.css +110 -22
  46. package/modules/localmodels/web/view/view.js +40 -22
  47. package/modules/localmodels/win_probe.py +187 -0
  48. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/METADATA +1 -1
  49. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/RECORD +51 -47
  50. package/package.json +1 -1
  51. package/tool.json +1 -1
  52. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/WHEEL +0 -0
  53. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/entry_points.txt +0 -0
  54. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/licenses/NOTICE +0 -0
  55. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -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 = []
@@ -23,9 +23,15 @@ from pathlib import Path
23
23
  from typing import cast
24
24
 
25
25
  try:
26
- from localmodels import process_identity, remote_ops, remote_ops_launchd
26
+ from localmodels import (
27
+ process_identity,
28
+ process_identity_darwin,
29
+ remote_ops,
30
+ remote_ops_launchd,
31
+ )
27
32
  except ImportError: # run as a bare file from this directory
28
33
  import process_identity # type: ignore[import-not-found,no-redef]
34
+ import process_identity_darwin # type: ignore[import-not-found,no-redef]
29
35
  import remote_ops # type: ignore[import-not-found,no-redef]
30
36
  import remote_ops_launchd # type: ignore[import-not-found,no-redef]
31
37
 
@@ -133,21 +139,6 @@ def _previous_install(
133
139
  return {**p, "argv": cast("list[str]", argv), "env": cast("dict[str, str]", env), "port": port}
134
140
 
135
141
 
136
- def _ps(columns: str, pid: int | None = None) -> list[list[str]] | None:
137
- """macOS process rows from /bin/ps (no /proc there); None when ps cannot answer."""
138
- argv = ["/bin/ps", "-ww", "-o", columns] + (["-p", str(pid)] if pid else ["-A"])
139
- c_locale = {**os.environ, "LC_ALL": "C"} # lstart reads the same as a receipt's, whatever LANG
140
- try:
141
- done = subprocess.run(
142
- argv, capture_output=True, text=True, timeout=10, check=False, env=c_locale
143
- )
144
- except (OSError, subprocess.SubprocessError):
145
- return None
146
- if done.returncode not in (0, 1): # 1: no such process
147
- return None
148
- return [line.split(None, 4) for line in done.stdout.splitlines() if line.strip()]
149
-
150
-
151
142
  def _darwin_listener_pids(port: int) -> set[int] | None:
152
143
  """Processes listening on TCP ``port`` (lsof; its warnings about unrelated mounts aside)."""
153
144
  argv = ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"]
@@ -166,8 +157,10 @@ def _process_state(pid: int) -> str | None:
166
157
  if sys.platform == "win32":
167
158
  return "S" if process_identity.inspect(pid) is not None else None
168
159
  if sys.platform == "darwin":
169
- rows = _ps("stat=", pid)
170
- return rows[0][0][:1] if rows else None
160
+ try:
161
+ return process_identity_darwin.process_state(pid)
162
+ except OSError:
163
+ return None
171
164
  try:
172
165
  return Path("/proc", str(pid), "stat").read_text().rsplit(")", 1)[1].split()[0]
173
166
  except (FileNotFoundError, ProcessLookupError):
@@ -177,22 +170,6 @@ def _process_state(pid: int) -> str | None:
177
170
  def command_matches(pid: int, argv: list[str]) -> bool:
178
171
  """Prove the expected executable and arguments without retaining the process command."""
179
172
  expected = [remote_ops._home(arg) for arg in argv]
180
- if sys.platform == "win32":
181
- return process_identity.command_matches(pid, expected)
182
- if sys.platform == "darwin": # ps joins argv with spaces; the script execs the server
183
- rows = _ps("uid=,args=", pid)
184
- if not rows or len(rows[0]) < 2 or rows[0][0] != str(os.getuid()):
185
- return False
186
- actual = " ".join(rows[0][1:])
187
- if actual == " ".join(expected):
188
- return True
189
- try:
190
- with open(expected[0], "rb") as executable:
191
- header = executable.readline(512).decode()
192
- interpreter = shlex.split(header[2:].strip()) if header.startswith("#!") else []
193
- return len(interpreter) == 1 and actual == " ".join([interpreter[0], *expected])
194
- except (OSError, UnicodeError, ValueError, IndexError):
195
- return False
196
173
  return process_identity.command_matches(pid, expected)
197
174
 
198
175
 
@@ -206,18 +183,10 @@ def _group_members(pid: int) -> dict[int, str]:
206
183
  raise RuntimeError("the service process has another owner; config left unchanged")
207
184
  return {pid: found["started"]}
208
185
  if sys.platform == "darwin":
209
- rows = _ps("pid=,pgid=,uid=,stat=,lstart=")
210
- if rows is None:
211
- raise RuntimeError("cannot list processes; config left unchanged")
212
- for row in rows:
213
- if len(row) < 5 or row[1] != str(pid) or row[3].startswith("Z"):
214
- continue
215
- if row[2] != str(os.getuid()):
216
- raise RuntimeError(
217
- "the service process group has another owner; config left unchanged"
218
- )
219
- members[int(row[0])] = row[4].strip() # the start time, as /proc's starttime on Linux
220
- return members
186
+ try:
187
+ return process_identity_darwin.group_members(pid)
188
+ except OSError:
189
+ raise RuntimeError("cannot list processes; config left unchanged") from None
221
190
  for entry in Path("/proc").glob("[0-9]*"):
222
191
  try:
223
192
  fields = entry.joinpath("stat").read_text().rsplit(")", 1)[1].split()
@@ -509,7 +509,7 @@ def windows_graphics_pids(table: str) -> set[int]:
509
509
  """PIDs the plain ``nvidia-smi`` process table marks G or C+G. Under WDDM every desktop
510
510
  program (dwm, explorer, browsers) is a C+G client of the card and nvidia-smi lists it beside
511
511
  the compute processes without its memory; a model server is type C."""
512
- rows = re.findall(r"^\|\s+\d+\s+\S+\s+\S+\s+(\d+)\s+(C\+G|G)\s", table, re.M)
512
+ rows = re.findall(r"^\|\s+\d+(?:\s+\S+\s+\S+)?\s+(\d+)\s+(C\+G|G)\s", table, re.M)
513
513
  return {int(pid) for pid, _ in rows}
514
514
 
515
515
 
@@ -19,6 +19,7 @@ from localmodels import (
19
19
  probe,
20
20
  service_probe,
21
21
  setup_text,
22
+ setup_upgrade,
22
23
  stack,
23
24
  stack_binding,
24
25
  stack_hardware,
@@ -84,6 +85,7 @@ class _Basis(TypedDict, total=False):
84
85
  # With a plan (since 2026-11-13): the model, every GPU it uses and what it needs, with a
85
86
  # sentence in --lang, so an installer shows the recommendation without composing its own.
86
87
  summary: stack_review.PlanSummary
88
+ upgrade: setup_upgrade.StackUpgrade # when freeing desktop memory unlocks a stronger LLM
87
89
 
88
90
 
89
91
  class StackAvailability(_Basis):
@@ -268,6 +270,11 @@ def _stack(
268
270
  if reason["code"] == "plan-unavailable":
269
271
  if capacity := _capacity_availability(options, facts, lang):
270
272
  return capacity
273
+ else:
274
+ availability: StackAvailability = {"available": True, "reasons": [], "plan": plan}
275
+ if upgrade := setup_upgrade.upgrade_hint(options, facts, plan, lang, _capacity_facts):
276
+ availability["upgrade"] = upgrade
277
+ return availability
271
278
 
272
279
  return {"available": plan is not None, "reasons": [reason] if reason else [], "plan": plan}
273
280
 
@@ -435,11 +442,17 @@ def _classify(availability: StackAvailability, facts: HostFacts) -> None:
435
442
  def _nvidia_cards_unmeasured(facts: HostFacts) -> bool:
436
443
  """An NVIDIA driver is loaded but nvidia-smi listed no card: the cards are unknown, not absent,
437
444
  and planning would fall back to CPU and RAM. A unified-memory part has no nvidia-smi memory
438
- and is planned from its CUDA pool instead."""
445
+ and is planned from its CUDA pool instead. An explicit 'No devices were found' from nvidia-smi
446
+ (e.g. a hybrid laptop in iGPU-only mode with leftover driver files) confirms no active card."""
447
+ no_devices = any(
448
+ e.get("source") == "nvidia-smi" and "no devices were found" in e.get("error", "").lower()
449
+ for e in facts.get("errors") or []
450
+ )
439
451
  return (
440
452
  facts.get("gpu_vendor_class") == "nvidia"
441
453
  and not facts.get("gpus")
442
454
  and budget.unified_pool_bytes(facts) is None
455
+ and not no_devices
443
456
  )
444
457
 
445
458
 
@@ -53,6 +53,18 @@ MESSAGES: dict[str, tuple[str, str]] = {
53
53
  ),
54
54
  "free-gpu": ("GPU {index} 空闲显存 {free}", "GPU {index} has {free} free"),
55
55
  "free-ram": ("可用内存 {free}", "{free} of RAM is available"),
56
+ "upgrade-gpu-memory": (
57
+ "关闭部分占用 GPU {index} 显存的程序(当前空闲 {free},约需 {needed})并重新检查,"
58
+ "可升级安装更强的本地模型 {model};本工具不会停止任何进程。",
59
+ "Close programs using GPU {index} memory ({free} free; about {needed} needed) and "
60
+ "check again to install a stronger local model ({model}); this tool stops no process.",
61
+ ),
62
+ "upgrade-free-memory": (
63
+ "关闭其他占用内存的程序(当前可用 {free},约需 {needed})并重新检查,"
64
+ "可升级安装更强的本地模型 {model};本工具不会停止任何进程。",
65
+ "Close other programs using memory ({free} available; about {needed} needed) and "
66
+ "check again to install a stronger local model ({model}); this tool stops no process.",
67
+ ),
56
68
  "inference-app-running": (
57
69
  "这台电脑的硬件可以运行本地模型,但另一个推理程序正占用这台 Mac 的 GPU 与统一内存({apps})。"
58
70
  "本工具不会把它的内存算作可释放;请退出该程序后重新检查。",
@@ -0,0 +1,145 @@
1
+ """Optional upgrade hint for ``setup inspect`` when freeing desktop memory unlocks a stronger LLM."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import TypedDict
7
+
8
+ from localmodels import (
9
+ budget,
10
+ catalog,
11
+ catalog_recipes,
12
+ harness,
13
+ library_vram,
14
+ llm_rank,
15
+ stack,
16
+ stack_review,
17
+ win_probe,
18
+ )
19
+ from localmodels.contracts import decode
20
+ from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
21
+ from localmodels.plan_envelope import PlanError
22
+ from localmodels.probe import HostFacts
23
+ from localmodels.setup_text import Lang, text
24
+ from localmodels.stack_plan import StackError, StackOptions, StackPlan, deployments
25
+
26
+
27
+ class _ReasonFields(TypedDict, total=False):
28
+ gpuIndex: int
29
+ freeBytes: int
30
+ requiredBytes: int
31
+ detectedCudaVersion: str
32
+ requiredCudaVersion: str
33
+ driverVersion: str
34
+
35
+
36
+ class UpgradeReason(_ReasonFields):
37
+ code: str
38
+ message: str
39
+
40
+
41
+ class _UpgradeOptional(TypedDict, total=False):
42
+ gpuApps: list[win_probe.GpuAppMemory]
43
+
44
+
45
+ class StackUpgrade(_UpgradeOptional):
46
+ plan: StackPlan
47
+ summary: stack_review.PlanSummary
48
+ reasons: list[UpgradeReason]
49
+
50
+
51
+ def _llm_rank_tier(model_id: str, facts: HostFacts) -> tuple[int, int]:
52
+ """(tier, score) for comparing live vs idle-capacity picks: fallback/ladder rungs sit below
53
+ all primary validated models regardless of unranked editorial catalog anchors."""
54
+ if entry := catalog.find_entry(model_id):
55
+ if llm_rank.windows_fallback(entry, facts) or llm_rank.mac_rung(entry, facts):
56
+ return (0, 0)
57
+ return (1, entry.quality)
58
+ for comp in catalog_recipes.components():
59
+ if comp["id"] == model_id:
60
+ quality = comp.get("quality")
61
+ score = quality.get("score") if isinstance(quality, dict) else None
62
+ return (1, int(score) if isinstance(score, int) else 0)
63
+ return (0, 0)
64
+
65
+
66
+ def _vram_by_card(plan: StackPlan) -> dict[int, int]:
67
+ found: dict[int, int] = {}
68
+ for part in deployments(plan):
69
+ for gpu in decode(part["placement"].get("gpus") or [], list[stack_review.SelectedGPU]):
70
+ index = gpu["index"]
71
+ found[index] = found.get(index, 0) + int(str(part["launch"].get("vram_bytes") or 0))
72
+ return found
73
+
74
+
75
+ def upgrade_hint(
76
+ options: StackOptions,
77
+ facts: HostFacts,
78
+ live_plan: StackPlan,
79
+ lang: Lang,
80
+ capacity_facts: Callable[[HostFacts], HostFacts | None],
81
+ ) -> StackUpgrade | None:
82
+ """When freeing desktop memory toward the idle baseline unlocks a strictly stronger LLM,
83
+ return that idle plan, its summary, quantitative reasons, and any closeable GPU apps."""
84
+ roomy = capacity_facts(facts)
85
+ if roomy is None:
86
+ return None
87
+ try:
88
+ roomy_plan = stack.build(options, facts=roomy)
89
+ except (PlanError, StackError, harness.HarnessError):
90
+ return None
91
+ live_id = str(live_plan["llm"]["model"]["id"])
92
+ roomy_id = str(roomy_plan["llm"]["model"]["id"])
93
+ if live_id == roomy_id or _llm_rank_tier(roomy_id, facts) <= _llm_rank_tier(live_id, facts):
94
+ return None
95
+ summary = stack_review.summarize(roomy_plan, lang)
96
+ gib = budget.gib
97
+ reasons: list[UpgradeReason] = []
98
+ live_gpus = {g["index"]: g for g in facts.get("gpus") or []}
99
+ for index, vram in _vram_by_card(roomy_plan).items():
100
+ card = live_gpus.get(index)
101
+ required = vram + AGENT_VRAM_RESERVE_BYTES
102
+ if card is None or card["free_bytes"] >= required:
103
+ continue
104
+ reasons.append(
105
+ {
106
+ "code": "gpu-memory-required",
107
+ "message": text(
108
+ "upgrade-gpu-memory",
109
+ lang,
110
+ model=summary["llmName"],
111
+ index=index,
112
+ free=gib(card["free_bytes"]),
113
+ needed=gib(required),
114
+ ),
115
+ "gpuIndex": index,
116
+ "freeBytes": card["free_bytes"],
117
+ "requiredBytes": required,
118
+ }
119
+ )
120
+ ram_free = facts["ram"]["available_bytes"]
121
+ ram_required = summary["memoryBytes"]
122
+ if (not reasons or ram_free < ram_required) and ram_free < min(
123
+ ram_required, roomy["ram"]["available_bytes"]
124
+ ):
125
+ reasons.append(
126
+ {
127
+ "code": "free-memory-required",
128
+ "message": text(
129
+ "upgrade-free-memory",
130
+ lang,
131
+ model=summary["llmName"],
132
+ free=gib(ram_free),
133
+ needed=gib(ram_required),
134
+ ),
135
+ "freeBytes": ram_free,
136
+ "requiredBytes": ram_required,
137
+ }
138
+ )
139
+ if not reasons:
140
+ return None
141
+ hint: StackUpgrade = {"plan": roomy_plan, "summary": summary, "reasons": reasons}
142
+ if any(r["code"] == "gpu-memory-required" for r in reasons):
143
+ if apps := library_vram.closeable_gpu_apps(facts):
144
+ hint["gpuApps"] = apps
145
+ return hint
@@ -382,7 +382,11 @@ def _no_fit_reason(
382
382
  if mac or not gpus:
383
383
  return ""
384
384
  if not cards:
385
- eligible = [p for p in placements(facts) if not p.pooled and len(p.gpu_indices) == 1]
385
+ eligible = [
386
+ p
387
+ for p in placements(facts)
388
+ if not p.pooled and not p.budget.uma and len(p.gpu_indices) == 1
389
+ ]
386
390
  if not eligible:
387
391
  return ": no supported single-card GPU placement"
388
392
  if not all(p.conflicts for p in eligible):