@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,17 +1,13 @@
1
- """Owned process identity receipts and Linux command proof; standard library, Python 3.8+.
1
+ """Owned process identity receipts and Linux command proof; stdlib-only, Python 3.8+.
2
2
 
3
- A live PID alone cannot authorize a signal after PID reuse. Receipts bind the
4
- PID, UID, process group and start time without retaining arguments or secrets.
5
-
6
- On Windows (no ``ps``, ``lsof`` or process groups) the same receipts come from the Win32 API
7
- through ctypes: the start time is the process creation time, ``uid`` is 0 for a process whose
8
- token belongs to the current user and -1 for anyone else's, and ``pgid`` is the PID itself,
9
- since every owned service is started as the root of its own process group. A stop ends the
10
- recorded process tree with ``taskkill``.
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``.
11
6
  """
12
7
 
13
8
  from __future__ import annotations
14
9
 
10
+ import ctypes
15
11
  import json
16
12
  import os
17
13
  import shlex
@@ -53,46 +49,37 @@ def _api() -> tuple[Any, Any]:
53
49
  """kernel32 and advapi32 with typed signatures: an untyped 64-bit HANDLE overflows."""
54
50
  if _API:
55
51
  return _API[0]
56
- import ctypes
57
52
  from ctypes import wintypes
58
53
 
59
54
  kernel = ctypes.WinDLL("kernel32", use_last_error=True) # type: ignore[attr-defined]
60
55
  advapi = ctypes.WinDLL("advapi32", use_last_error=True) # type: ignore[attr-defined]
61
- handle, dword, ptr = wintypes.HANDLE, wintypes.DWORD, ctypes.c_void_p
62
- for function, args, result in (
63
- (kernel.OpenProcess, (dword, wintypes.BOOL, dword), handle),
64
- (kernel.GetCurrentProcess, (), handle),
65
- (kernel.CloseHandle, (handle,), wintypes.BOOL),
66
- (kernel.LocalFree, (ptr,), ptr),
67
- (kernel.GetExitCodeProcess, (handle, ctypes.POINTER(dword)), wintypes.BOOL),
68
- (kernel.GetProcessTimes, (handle, *[ctypes.POINTER(wintypes.FILETIME)] * 4), wintypes.BOOL),
69
- (
70
- kernel.QueryFullProcessImageNameW,
71
- (handle, dword, wintypes.LPWSTR, ctypes.POINTER(dword)),
72
- wintypes.BOOL,
73
- ),
74
- (advapi.OpenProcessToken, (handle, dword, ctypes.POINTER(handle)), wintypes.BOOL),
75
- (
76
- advapi.GetTokenInformation,
77
- (handle, ctypes.c_int, ptr, dword, ctypes.POINTER(dword)),
78
- wintypes.BOOL,
79
- ),
80
- (advapi.ConvertSidToStringSidW, (ptr, ctypes.POINTER(wintypes.LPWSTR)), wintypes.BOOL),
81
- (kernel.K32GetProcessMemoryInfo, (handle, ptr, dword), wintypes.BOOL),
82
- (kernel.K32EmptyWorkingSet, (handle,), wintypes.BOOL),
83
- (kernel.GetPriorityClass, (handle,), dword),
84
- (kernel.SetPriorityClass, (handle, dword), wintypes.BOOL),
85
- (kernel.GetProcessInformation, (handle, ctypes.c_int, ptr, dword), wintypes.BOOL),
86
- (kernel.SetProcessInformation, (handle, ctypes.c_int, ptr, dword), wintypes.BOOL),
56
+ h, b, d, w, p = wintypes.HANDLE, wintypes.BOOL, wintypes.DWORD, wintypes.LPWSTR, ctypes.c_void_p
57
+ ptr = ctypes.POINTER
58
+ for fn, args, res in (
59
+ (kernel.OpenProcess, (d, b, d), h),
60
+ (kernel.GetCurrentProcess, (), h),
61
+ (kernel.CloseHandle, (h,), b),
62
+ (kernel.LocalFree, (p,), p),
63
+ (kernel.GetExitCodeProcess, (h, ptr(d)), b),
64
+ (kernel.GetProcessTimes, (h, *[ptr(wintypes.FILETIME)] * 4), b),
65
+ (kernel.QueryFullProcessImageNameW, (h, d, w, ptr(d)), b),
66
+ (advapi.OpenProcessToken, (h, d, ptr(h)), b),
67
+ (advapi.GetTokenInformation, (h, ctypes.c_int, p, d, ptr(d)), b),
68
+ (advapi.ConvertSidToStringSidW, (p, ptr(w)), b),
69
+ (kernel.K32GetProcessMemoryInfo, (h, p, d), b),
70
+ (kernel.K32EmptyWorkingSet, (h,), b),
71
+ (kernel.GetPriorityClass, (h,), d),
72
+ (kernel.SetPriorityClass, (h, d), b),
73
+ (kernel.GetProcessInformation, (h, ctypes.c_int, p, d), b),
74
+ (kernel.SetProcessInformation, (h, ctypes.c_int, p, d), b),
87
75
  ):
88
- function.argtypes, function.restype = args, result
76
+ fn.argtypes, fn.restype = args, res
89
77
  _API.append((kernel, advapi))
90
78
  return kernel, advapi
91
79
 
92
80
 
93
81
  def _token_sid(handle: Any) -> str | None:
94
82
  """The string SID of the user a process (``handle``) runs as."""
95
- import ctypes
96
83
  from ctypes import wintypes
97
84
 
98
85
  kernel, advapi = _api()
@@ -125,10 +112,7 @@ def _own_sid() -> str | None:
125
112
 
126
113
 
127
114
  def _windows_process(pid: int) -> tuple[str, str, str | None] | None:
128
- """(creation time, image path, owner SID) of a running process; None when it has exited
129
- or never existed. Raises OSError when the process exists but cannot be queried. The image
130
- is "" and the SID None for a protected process."""
131
- import ctypes
115
+ """(creation time, image path, owner SID) of PID, or None if exited (""/None if protected)."""
132
116
  from ctypes import wintypes
133
117
 
134
118
  kernel, _ = _api()
@@ -169,21 +153,20 @@ def _windows_inspect(pid: int) -> Identity | None:
169
153
 
170
154
 
171
155
  def _parent_pids() -> dict[int, int]:
172
- """Windows: {PID: parent PID} of every process (a Toolhelp snapshot)."""
173
- import ctypes
156
+ """Windows: {PID: parent PID} of every process (Toolhelp snapshot)."""
174
157
  from ctypes import wintypes
175
158
 
159
+ d, p = wintypes.DWORD, ctypes.c_void_p
160
+
176
161
  class Entry(ctypes.Structure):
177
162
  _fields_ = [
178
- ("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD),
179
- ("th32ProcessID", wintypes.DWORD), ("th32DefaultHeapID", ctypes.c_void_p),
180
- ("th32ModuleID", wintypes.DWORD), ("cntThreads", wintypes.DWORD),
181
- ("th32ParentProcessID", wintypes.DWORD), ("pcPriClassBase", ctypes.c_long),
182
- ("dwFlags", wintypes.DWORD), ("szExeFile", ctypes.c_wchar * 260),
163
+ ("dwSize", d), ("cntUsage", d), ("th32ProcessID", d), ("th32DefaultHeapID", p),
164
+ ("th32ModuleID", d), ("cntThreads", d), ("th32ParentProcessID", d),
165
+ ("pcPriClassBase", ctypes.c_long), ("dwFlags", d), ("szExeFile", ctypes.c_wchar * 260),
183
166
  ] # fmt: skip
184
167
 
185
168
  kernel, _ = _api()
186
- kernel.CreateToolhelp32Snapshot.argtypes = (wintypes.DWORD, wintypes.DWORD)
169
+ kernel.CreateToolhelp32Snapshot.argtypes = (d, d)
187
170
  kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
188
171
  for name in ("Process32FirstW", "Process32NextW"):
189
172
  getattr(kernel, name).argtypes = (wintypes.HANDLE, ctypes.POINTER(Entry))
@@ -192,8 +175,7 @@ def _parent_pids() -> dict[int, int]:
192
175
  raise OSError("process snapshot unavailable")
193
176
  found: dict[int, int] = {}
194
177
  try:
195
- entry = Entry()
196
- entry.dwSize = ctypes.sizeof(Entry)
178
+ entry = Entry(dwSize=ctypes.sizeof(Entry))
197
179
  more = kernel.Process32FirstW(snapshot, ctypes.byref(entry))
198
180
  while more:
199
181
  found[entry.th32ProcessID] = entry.th32ParentProcessID
@@ -204,12 +186,8 @@ def _parent_pids() -> dict[int, int]:
204
186
 
205
187
 
206
188
  def adopt_successor(pid_file: str | Path, program: str) -> bool:
207
- """Windows has no exec: a program that restarts into an updated copy of itself (``magpie
208
- serve`` after its binary is updated) continues as a new child process, and the receipt goes
209
- stale. Move the receipt to that child only when the chain is provable: the recorded process
210
- is gone and its PID names no newer process, and exactly one live process of this user runs
211
- ``program``, was created after the recorded one and has the recorded PID as its parent.
212
- True when the receipt now names it."""
189
+ """Move stale Windows receipt to a single verifiable child running ``program`` (restart
190
+ without exec, e.g. ``magpie serve``) when parent exited and exactly one newer user child matches."""
213
191
  if not _windows():
214
192
  return False
215
193
  path = Path(pid_file)
@@ -217,19 +195,16 @@ def adopt_successor(pid_file: str | Path, program: str) -> bool:
217
195
  saved = _recorded(path)
218
196
  if saved is None or _windows_inspect(saved["pid"]) is not None:
219
197
  return False # still running, or its PID was reused: nothing provable to adopt
220
- children = [
221
- pid for pid, parent in _parent_pids().items() if parent == saved["pid"] and pid > 0
198
+ successors = [
199
+ pid
200
+ for pid, parent in _parent_pids().items()
201
+ if parent == saved["pid"]
202
+ and pid > 0
203
+ and (found := _windows_inspect(pid)) is not None
204
+ and found["uid"] == 0
205
+ and int(found["started"]) > int(saved["started"])
206
+ and _windows_command_matches(pid, [program])
222
207
  ]
223
- successors = []
224
- for pid in children:
225
- found = _windows_inspect(pid)
226
- if (
227
- found is not None
228
- and found["uid"] == 0
229
- and int(found["started"]) > int(saved["started"])
230
- and _windows_command_matches(pid, [program])
231
- ):
232
- successors.append(pid)
233
208
  if len(successors) != 1:
234
209
  return False
235
210
  save(path, successors[0])
@@ -238,6 +213,27 @@ def adopt_successor(pid_file: str | Path, program: str) -> bool:
238
213
  return False
239
214
 
240
215
 
216
+ def alive(pid: int, foreign: bool = True) -> bool:
217
+ """Whether PID names a running process; ``foreign`` is the answer for another user's.
218
+ Never ``os.kill(pid, 0)`` on Windows: signal 0 is CTRL_C_EVENT there, sent to a console
219
+ process group instead of probing."""
220
+ if pid <= 0:
221
+ return False
222
+ if _windows():
223
+ try:
224
+ found = _windows_inspect(pid)
225
+ except OSError:
226
+ return foreign # it exists, but this user may not open it
227
+ return found is not None and (found["uid"] == 0 or foreign)
228
+ try:
229
+ os.kill(pid, 0)
230
+ except ProcessLookupError:
231
+ return False
232
+ except PermissionError:
233
+ return foreign
234
+ return True
235
+
236
+
241
237
  def image_path(pid: int) -> str | None:
242
238
  """The executable a Windows process runs; None when it is gone or cannot be read."""
243
239
  try:
@@ -248,9 +244,7 @@ def image_path(pid: int) -> str | None:
248
244
 
249
245
 
250
246
  def listener_pids(port: int) -> set[int] | None:
251
- """Windows: the processes listening on TCP ``port`` on any IPv4 or IPv6 address (the
252
- owner-PID TCP tables of iphlpapi); None when a table cannot be read."""
253
- import ctypes
247
+ """Windows: PIDs listening on TCP ``port`` (IPv4/IPv6 iphlpapi tables), or None on failure."""
254
248
  import struct
255
249
 
256
250
  iphlpapi = ctypes.WinDLL("iphlpapi") # type: ignore[attr-defined]
@@ -284,12 +278,19 @@ def _taskkill(pid: int, force: bool) -> bool:
284
278
  return subprocess.run(argv, capture_output=True, timeout=30, check=False).returncode == 0
285
279
 
286
280
 
281
+ def stop_children(pid: int) -> int:
282
+ """Windows: force-end the trees of ``pid``'s child processes (not ``pid`` itself); how many
283
+ children it found. A download ends the helper it runs this way when it is cancelled."""
284
+ if not _windows():
285
+ raise RuntimeError("stop_children is for Windows")
286
+ children = [child for child, parent in _parent_pids().items() if parent == pid and child > 0]
287
+ for child in children:
288
+ _taskkill(child, True)
289
+ return len(children)
290
+
291
+
287
292
  def windows_stop_tree(pid: int, saved: Identity, grace: float) -> bool:
288
- """End the receipt's process and its descendants: a polite ``taskkill /T``, then ``/F``.
289
- True once the recorded process is gone. The polite request is a window message. A service
290
- without a window is refused at once and forced at once; Magpie's serve takes the message
291
- and stays (watched for 16 s), so the wait is ``grace`` but at most 2 s. Waiting 15 s for
292
- each of three services cost an uninstall 50 s (home-win, 2026-11-12)."""
293
+ """Stop PID and descendants via polite ``taskkill /T`` (capped at 2 s) then ``/F``."""
293
294
  import time
294
295
 
295
296
  for force in (False, True):
@@ -305,16 +306,8 @@ def windows_stop_tree(pid: int, saved: Identity, grace: float) -> bool:
305
306
  return _windows_inspect(pid) != saved
306
307
 
307
308
 
308
- # ── Windows: a service runs at normal priority, whatever started it ──
309
- #
310
- # A process inherits three things from the one that starts it: its priority class, its memory
311
- # priority and its I/O priority. An install run from a scheduled task (Task Scheduler's default
312
- # priority is 7), or from any other background worker, therefore started the stack's services
313
- # as background work: BelowNormal, memory priority 2 of 5, low I/O priority. Windows takes the
314
- # memory of such a process while it idles, with 14 GB free: llama-server went from 180 MiB
315
- # resident to 32 MiB within minutes (RTX 4060 Ti, 2026-11-12). An enforced minimum working set
316
- # (SetProcessWorkingSetSizeEx, QUOTA_LIMITS_HARDWS_MIN_ENABLE, 512 MiB) did not stop that;
317
- # normal priority did: 153 MiB stayed resident through 20 idle minutes (more in stack_warm).
309
+ # Scheduled tasks start child services below normal (priority/memory/I/O), allowing Windows to
310
+ # trim idle resident pages aggressively; raising to normal prevents eviction (RTX 4060 Ti).
318
311
  _READ_MEMORY_INFO = _QUERY_LIMITED | 0x0010 # GetProcessMemoryInfo also wants PROCESS_VM_READ
319
312
  _SET_INFORMATION = 0x0200 # PROCESS_SET_INFORMATION
320
313
  _NORMAL_CLASS = 0x20 # NORMAL_PRIORITY_CLASS
@@ -332,9 +325,7 @@ class Priority(TypedDict):
332
325
 
333
326
 
334
327
  def _io_priority(handle: Any, value: int | None = None) -> int | None:
335
- """Read the I/O priority of a process, or set it to ``value`` first. kernel32 can only
336
- change the calling process, so this is ntdll; None when it does not answer."""
337
- import ctypes
328
+ """Read or set I/O priority via ntdll (kernel32 only changes the calling process)."""
338
329
  from ctypes import wintypes
339
330
 
340
331
  try:
@@ -352,7 +343,6 @@ def _io_priority(handle: Any, value: int | None = None) -> int | None:
352
343
 
353
344
 
354
345
  def _priority(kernel: Any, handle: Any) -> Priority:
355
- import ctypes
356
346
  from ctypes import wintypes
357
347
 
358
348
  memory = wintypes.ULONG(0)
@@ -360,17 +350,18 @@ def _priority(kernel: Any, handle: Any) -> Priority:
360
350
  handle, _MEMORY_PRIORITY, ctypes.byref(memory), ctypes.sizeof(memory)
361
351
  ):
362
352
  raise OSError("memory priority unavailable")
363
- # PROCESS_MEMORY_COUNTERS on 64-bit Windows (the only one the stack installs on): cb and
364
- # PageFaultCount (two DWORDs), then eight SIZE_T, of which the second is WorkingSetSize.
353
+ # PROCESS_MEMORY_COUNTERS on 64-bit Windows: cb+PageFaultCount (2 DWORDs), then SIZE_Ts ([2] is WorkingSetSize).
365
354
  counters = (ctypes.c_size_t * 9)()
366
355
  ctypes.cast(counters, ctypes.POINTER(wintypes.DWORD))[0] = ctypes.sizeof(counters)
367
356
  if not kernel.K32GetProcessMemoryInfo(handle, counters, ctypes.sizeof(counters)):
368
357
  raise OSError("working set size unavailable")
369
358
  io = _io_priority(handle)
370
359
  return {
371
- "background": kernel.GetPriorityClass(handle) in _BACKGROUND_CLASSES
372
- or memory.value < _MEMORY_NORMAL
373
- or (io is not None and io < _IO_NORMAL),
360
+ "background": (
361
+ kernel.GetPriorityClass(handle) in _BACKGROUND_CLASSES
362
+ or memory.value < _MEMORY_NORMAL
363
+ or (io is not None and io < _IO_NORMAL)
364
+ ),
374
365
  "memory_priority": int(memory.value),
375
366
  "resident_bytes": int(counters[2]),
376
367
  }
@@ -391,30 +382,28 @@ def priority(pid: int) -> Priority | None:
391
382
 
392
383
 
393
384
  def run_at_normal_priority(pid: int) -> Priority:
394
- """Raise this user's process to the normal priority class, memory priority and I/O priority
395
- where it is below them; nothing is lowered. Returns the state afterwards. Raises OSError
396
- when Windows refuses the class or the memory priority; the I/O priority is best effort."""
397
- import ctypes
385
+ """Raise class, memory and I/O priority to normal where lower; returns updated state."""
398
386
  from ctypes import wintypes
399
387
 
400
388
  kernel, _ = _api()
401
389
  handle = kernel.OpenProcess(_READ_MEMORY_INFO | _SET_INFORMATION, False, pid)
402
390
  if not handle:
403
- error = ctypes.get_last_error() # type: ignore[attr-defined]
404
- raise OSError(f"cannot open process {pid} to set its priority (Windows error {error})")
391
+ err = ctypes.get_last_error() # type: ignore[attr-defined]
392
+ raise OSError(f"cannot open process {pid} to set its priority (Windows error {err})")
405
393
  try:
406
394
  seen = _priority(kernel, handle)
407
- if kernel.GetPriorityClass(handle) in _BACKGROUND_CLASSES:
408
- if not kernel.SetPriorityClass(handle, _NORMAL_CLASS):
409
- error = ctypes.get_last_error() # type: ignore[attr-defined]
410
- raise OSError(f"Windows refused the normal priority class (error {error})")
395
+ if kernel.GetPriorityClass(handle) in _BACKGROUND_CLASSES and not kernel.SetPriorityClass(
396
+ handle, _NORMAL_CLASS
397
+ ):
398
+ err = ctypes.get_last_error() # type: ignore[attr-defined]
399
+ raise OSError(f"Windows refused the normal priority class (error {err})")
411
400
  if seen["memory_priority"] < _MEMORY_NORMAL:
412
401
  normal = wintypes.ULONG(_MEMORY_NORMAL)
413
402
  if not kernel.SetProcessInformation(
414
403
  handle, _MEMORY_PRIORITY, ctypes.byref(normal), ctypes.sizeof(normal)
415
404
  ):
416
- error = ctypes.get_last_error() # type: ignore[attr-defined]
417
- raise OSError(f"Windows refused the normal memory priority (error {error})")
405
+ err = ctypes.get_last_error() # type: ignore[attr-defined]
406
+ raise OSError(f"Windows refused the normal memory priority (error {err})")
418
407
  io = _io_priority(handle)
419
408
  if io is not None and io < _IO_NORMAL:
420
409
  _io_priority(handle, _IO_NORMAL)
@@ -424,9 +413,7 @@ def run_at_normal_priority(pid: int) -> Priority:
424
413
 
425
414
 
426
415
  def release_working_set(pid: int, above: int = 1 << 30) -> int:
427
- """Give back the resident pages of this user's process when it holds more than ``above``;
428
- what it uses again comes back as it is touched. Returns the bytes released: 0 off Windows,
429
- below the bar, or when Windows refuses."""
416
+ """Empty resident pages above ``above`` bytes on Windows; returns freed bytes."""
430
417
  if not _windows():
431
418
  return 0
432
419
  kernel, _ = _api()
@@ -451,9 +438,7 @@ WINDOWS_BREAKAWAY = 0x01000000
451
438
 
452
439
 
453
440
  def spawn_detached(argv: list[str], **options: Any) -> subprocess.Popen[bytes]:
454
- """Start a background service as the root of its own process group (POSIX session), with
455
- no console window on Windows and at normal priority there whatever priority this process
456
- has; the caller records it with ``save``."""
441
+ """Start a detached service in its own group/session (no console window, normal Windows priority)."""
457
442
  if not _windows():
458
443
  return subprocess.Popen(argv, start_new_session=True, **options)
459
444
  try:
@@ -488,8 +473,7 @@ def inspect(pid: int) -> Identity | None:
488
473
  return None
489
474
  if _windows():
490
475
  return _windows_inspect(pid)
491
- # LC_ALL=C: ps prints lstart in the session's locale, and zh_CN gives four words (weekday,
492
- # month/day, time, year) where the parse below expects five (the Mac mini, 2026-11-12).
476
+ # LC_ALL=C keeps lstart in 5 English tokens (zh_CN outputs 4).
493
477
  result = subprocess.run(
494
478
  ["/bin/ps", "-p", str(pid), "-o", "uid=,pgid=,lstart=,stat="],
495
479
  capture_output=True,
@@ -569,17 +553,16 @@ def _forget(pid_file: Path) -> None:
569
553
 
570
554
 
571
555
  def _recorded(pid_file: Path) -> Identity | None:
572
- """The receipt's identity; None for a legacy bare PID file whose process has ended.
573
- Raises ValueError when the receipt cannot prove anything (symlink, foreign, malformed)."""
556
+ """Receipt identity, or None for an exited legacy bare PID file; raises ValueError if untrusted."""
574
557
  try:
575
558
  saved = json.loads(_private(Path(str(pid_file) + ".identity.json")))
576
559
  except FileNotFoundError:
577
- info = pid_file.lstat() # legacy: a bare PID file written before receipts existed
560
+ info = pid_file.lstat() # legacy: bare PID file written before receipts existed
578
561
  if not stat.S_ISREG(info.st_mode) or (not _windows() and info.st_uid != os.getuid()):
579
562
  raise ValueError("the PID file is not a regular file of this user") from None
580
563
  if inspect(int(pid_file.read_text(encoding="utf-8").strip())) is not None:
581
564
  raise ValueError(
582
- "a legacy PID file has no identity receipt; cannot prove the process belongs to this tool"
565
+ "a legacy PID file has no identity receipt; cannot prove ownership"
583
566
  ) from None
584
567
  return None
585
568
  fields = {"pid": int, "uid": int, "pgid": int, "started": str}
@@ -596,15 +579,8 @@ def _recorded(pid_file: Path) -> Identity | None:
596
579
 
597
580
 
598
581
  def stop(pid_file: str | Path, grace: float = 15.0) -> str:
599
- """Stop the process group a receipt from `save` names, and say what happened.
600
-
601
- Signals go only to a live group whose UID, PGID and start time all match the receipt:
602
- SIGTERM, then SIGKILL after `grace` seconds. A recorded process that has ended, including
603
- one whose PID now names a newer process, needs no signal. Returns "none" (no receipt),
604
- "gone" or "stopped", and deletes the receipt. Raises RuntimeError without signalling when
605
- a legacy PID file names a running process, when the receipt is symlinked, foreign or
606
- malformed, or when `ps` fails; also when the group outlives SIGKILL. The receipt then
607
- stays for a retry."""
582
+ """Stop the receipt's process group (SIGTERM then SIGKILL after ``grace``) when UID/PGID/start match.
583
+ Returns 'none'|'gone'|'stopped'; leaves receipt and raises RuntimeError on verification/stop failure."""
608
584
  import signal
609
585
  import time
610
586
 
@@ -662,7 +638,7 @@ def listener_owned(port: int, pid: int | None) -> bool:
662
638
  except OSError:
663
639
  return False
664
640
  try:
665
- result = subprocess.run(
641
+ res = subprocess.run(
666
642
  ["/usr/sbin/lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"],
667
643
  capture_output=True,
668
644
  text=True,
@@ -672,17 +648,13 @@ def listener_owned(port: int, pid: int | None) -> bool:
672
648
  except (OSError, subprocess.TimeoutExpired):
673
649
  return False
674
650
  owners = {
675
- int(line[1:])
676
- for line in result.stdout.splitlines()
677
- if line.startswith("p") and line[1:].isdigit()
651
+ int(ln[1:]) for ln in res.stdout.splitlines() if ln.startswith("p") and ln[1:].isdigit()
678
652
  }
679
- return result.returncode == 0 and owners == {pid}
653
+ return res.returncode == 0 and owners == {pid}
680
654
 
681
655
 
682
656
  def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
683
- """Read-only Linux argv proof, including the kernel's single shebang interpreter. Windows
684
- cannot read another process's argv without its memory: the proof there is the executable
685
- image (``expected[0]``, ``.exe`` implied) of a process this user owns."""
657
+ """Read-only Linux argv proof (plus shebang); on Windows checks owned executable image path."""
686
658
  if _windows():
687
659
  return _windows_command_matches(pid, expected)
688
660
  try:
@@ -692,18 +664,17 @@ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
692
664
  actual = process.joinpath("cmdline").read_bytes().decode().rstrip("\0").split("\0")
693
665
  if actual == expected:
694
666
  return True
695
- with open(
696
- expected[0] if root == "/" else Path(root) / expected[0].lstrip("/"), "rb"
697
- ) as executable:
667
+ target = expected[0] if root == "/" else Path(root) / expected[0].lstrip("/")
668
+ with open(target, "rb") as executable:
698
669
  header = executable.readline(512).decode()
699
670
  if not header.startswith("#!"):
700
671
  return False
701
- interpreter = shlex.split(header[2:].strip())
702
- if interpreter[:1] == ["/usr/bin/env"]:
703
- interpreter = interpreter[1:]
704
- if len(interpreter) != 1 or actual[1:] != expected:
672
+ interp = shlex.split(header[2:].strip())
673
+ if interp[:1] == ["/usr/bin/env"]:
674
+ interp = interp[1:]
675
+ if len(interp) != 1 or actual[1:] != expected:
705
676
  return False
706
- resolved = shutil.which(interpreter[0])
677
+ resolved = shutil.which(interp[0])
707
678
  return (
708
679
  resolved is not None and process.joinpath("exe").resolve() == Path(resolved).resolve()
709
680
  )
@@ -712,10 +683,7 @@ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
712
683
 
713
684
 
714
685
  def venv_base(python: str) -> str | None:
715
- """Windows: the base interpreter behind a venv's ``Scripts/python.exe`` redirector (its
716
- pyvenv.cfg ``home``), which the redirector would start as a child; None for any other
717
- program. Services launch the base directly with ``__PYVENV_LAUNCHER__`` naming the venv's
718
- python, as the redirector does, so the recorded PID is the one that listens."""
686
+ """Windows: base ``python.exe`` from a venv's ``pyvenv.cfg`` ``home`` key, else None."""
719
687
  path = Path(os.path.expanduser(python))
720
688
  if path.name.lower() != "python.exe" or path.parent.name.lower() != "scripts":
721
689
  return None
@@ -733,15 +701,13 @@ def venv_base(python: str) -> str | None:
733
701
 
734
702
  def _windows_command_matches(pid: int, expected: list[str]) -> bool:
735
703
  try:
736
- found = _windows_inspect(pid)
737
- image = image_path(pid)
704
+ found, image = _windows_inspect(pid), image_path(pid)
738
705
  except OSError:
739
706
  return False
740
707
  if found is None or found["uid"] != 0 or image is None or not expected:
741
708
  return False
742
709
  want = os.path.expanduser(expected[0])
743
- if not want.lower().endswith(".exe"):
744
- want += ".exe"
710
+ want = want if want.lower().endswith(".exe") else want + ".exe"
745
711
  wanted = [want, *filter(None, [venv_base(want)])]
746
712
  try:
747
713
  actual = os.path.normcase(os.path.realpath(image))
@@ -0,0 +1,86 @@
1
+ """Windows process facts the controller upgrade needs beyond ``process_identity``: this
2
+ user's PIDs, a process's full command line, and ending exactly one process on the handle that
3
+ proved its creation time. stdlib only (ctypes); every function needs Windows.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import ctypes
9
+
10
+ from localmodels import process_identity
11
+
12
+
13
+ def own_pids() -> list[int]:
14
+ """Windows: the PIDs of this user's running processes (Toolhelp snapshot, SID compared)."""
15
+ own = []
16
+ for pid in sorted(process_identity._parent_pids()):
17
+ try:
18
+ found = process_identity.inspect(pid) if pid > 4 else None
19
+ except OSError:
20
+ continue # protected system processes are never this user's
21
+ if found is not None and found["uid"] == 0:
22
+ own.append(pid)
23
+ return own
24
+
25
+
26
+ def command_line(pid: int) -> str | None:
27
+ """Windows 8.1+: the full command line of PID (ntdll ProcessCommandLineInformation), or
28
+ None when it is gone or cannot be read."""
29
+ from ctypes import wintypes
30
+
31
+ class UnicodeString(ctypes.Structure):
32
+ _fields_ = [
33
+ ("Length", ctypes.c_ushort), ("MaximumLength", ctypes.c_ushort),
34
+ ("Buffer", ctypes.c_void_p),
35
+ ] # fmt: skip
36
+
37
+ kernel, _ = process_identity._api()
38
+ ntdll = ctypes.WinDLL("ntdll") # type: ignore[attr-defined]
39
+ query = ntdll.NtQueryInformationProcess
40
+ query.argtypes = (
41
+ wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.ULONG, ctypes.POINTER(wintypes.ULONG)
42
+ ) # fmt: skip
43
+ query.restype = ctypes.c_long
44
+ handle = kernel.OpenProcess(process_identity._QUERY_LIMITED, False, pid)
45
+ if not handle:
46
+ return None
47
+ try:
48
+ size = wintypes.ULONG(0)
49
+ query(handle, 60, None, 0, ctypes.byref(size)) # ProcessCommandLineInformation
50
+ if not size.value:
51
+ return None
52
+ buffer = ctypes.create_string_buffer(size.value)
53
+ if query(handle, 60, buffer, size, ctypes.byref(size)) != 0:
54
+ return None
55
+ text = UnicodeString.from_buffer(buffer)
56
+ return ctypes.wstring_at(text.Buffer, text.Length // 2) if text.Buffer else None
57
+ finally:
58
+ kernel.CloseHandle(handle)
59
+
60
+
61
+ def terminate(pid: int, started: str) -> bool:
62
+ """Windows: end exactly PID (not its tree) when its creation time is still ``started``,
63
+ checked on the same handle that terminates it, so a reused PID is never hit. False when
64
+ the process is another one now."""
65
+ from ctypes import wintypes
66
+
67
+ kernel, _ = process_identity._api()
68
+ kernel.TerminateProcess.argtypes = (wintypes.HANDLE, wintypes.UINT)
69
+ kernel.TerminateProcess.restype = wintypes.BOOL
70
+ handle = kernel.OpenProcess(
71
+ process_identity._QUERY_LIMITED | 0x0001, False, pid
72
+ ) # PROCESS_TERMINATE
73
+ if not handle:
74
+ return False
75
+ try:
76
+ times = [wintypes.FILETIME() for _ in range(4)]
77
+ if not kernel.GetProcessTimes(handle, *(ctypes.byref(t) for t in times)):
78
+ return False
79
+ created = (times[0].dwHighDateTime << 32) | times[0].dwLowDateTime
80
+ if str(created) != started:
81
+ return False
82
+ if not kernel.TerminateProcess(handle, 1):
83
+ raise OSError(f"cannot end process {pid} (Windows error {ctypes.get_last_error()})") # type: ignore[attr-defined]
84
+ return True
85
+ finally:
86
+ kernel.CloseHandle(handle)
@@ -77,7 +77,10 @@ _QUANT_REASONS = {
77
77
  }
78
78
  RECOMMENDED_REASONS = {
79
79
  "windows-candidate-fallback": llm_rank.WINDOWS_FALLBACK_WARNING,
80
- "user-default": "User-selected small-Mac default; SimplexAI score and full acceptance pending.",
80
+ "user-default": (
81
+ "User-selected Mac small-memory ladder (Spark-X2.6, 64K shared by two slots); "
82
+ "SimplexAI score and full acceptance pending."
83
+ ),
81
84
  "product-default": "This machine's default model, chosen by its maker.",
82
85
  "best-quality-resident": (
83
86
  "Candidates that pass the agent capacity gate are ranked by capability score first, "
@@ -171,7 +174,7 @@ def recommendation(
171
174
  placement.budget,
172
175
  live,
173
176
  backend=placement.backend,
174
- default_id=llm_rank.mac_default(facts),
177
+ ladder=ladder.smartest if (ladder := llm_rank.mac_ladder(facts)) else (),
175
178
  )
176
179
  if picked is not None:
177
180
  return picked[0], picked[1], placement
@@ -186,7 +189,7 @@ def recommendation(
186
189
  fitting = []
187
190
  for entry in (*live, fallback):
188
191
  for p, budget in candidates:
189
- if llm_rank.automatic_fit(entry, facts, budget, AGENT, {"search": True}):
192
+ if llm_rank.automatic_fit(entry, facts, budget, AGENT, {"search": False}):
190
193
  key = llm_rank.rank_key(entry, entry.variants[-1], budget)
191
194
  fitting.append((key, entry.id, p.gpu_indices[0]))
192
195
  break