@simplexai/localmodels-linux-x64 0.1.0-dev.35 → 0.1.0-dev.37

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 (126) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +124 -102
  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_config.py +188 -0
  7. package/modules/localmodels/budget.py +15 -2
  8. package/modules/localmodels/catalog.json +235 -2
  9. package/modules/localmodels/catalog.py +51 -320
  10. package/modules/localmodels/catalog_add.py +2 -8
  11. package/modules/localmodels/catalog_recipes.py +321 -0
  12. package/modules/localmodels/cli_parser.py +4 -1
  13. package/modules/localmodels/console.py +5 -4
  14. package/modules/localmodels/contracts.py +13 -3
  15. package/modules/localmodels/debug_cli.py +158 -0
  16. package/modules/localmodels/debug_mode.py +727 -0
  17. package/modules/localmodels/debug_stub_server.py +192 -0
  18. package/modules/localmodels/decode_calibration.json +1 -1
  19. package/modules/localmodels/decode_calibration.py +34 -17
  20. package/modules/localmodels/engines-strata-0.1.59.1.json +31 -0
  21. package/modules/localmodels/gateway.py +21 -155
  22. package/modules/localmodels/gateway_accept.py +201 -0
  23. package/modules/localmodels/gateway_bifrost.py +19 -184
  24. package/modules/localmodels/gateway_cli.py +11 -4
  25. package/modules/localmodels/gateway_foundations.py +2 -4
  26. package/modules/localmodels/gateway_probe.py +0 -1
  27. package/modules/localmodels/gateway_server.py +2 -3
  28. package/modules/localmodels/gpu_specs.py +12 -0
  29. package/modules/localmodels/guard.py +2 -7
  30. package/modules/localmodels/harness.py +16 -129
  31. package/modules/localmodels/harness_cleanup.py +135 -0
  32. package/modules/localmodels/harness_gateway.py +16 -14
  33. package/modules/localmodels/harness_probe.py +12 -4
  34. package/modules/localmodels/hosts.py +25 -2
  35. package/modules/localmodels/http_local.py +59 -0
  36. package/modules/localmodels/install.py +23 -8
  37. package/modules/localmodels/library_gateway.py +9 -9
  38. package/modules/localmodels/library_jobs.py +76 -27
  39. package/modules/localmodels/library_serve.py +12 -1
  40. package/modules/localmodels/library_state.py +6 -1
  41. package/modules/localmodels/llm_rank.py +155 -7
  42. package/modules/localmodels/metal_probe.py +11 -7
  43. package/modules/localmodels/probe.py +108 -174
  44. package/modules/localmodels/process_identity.py +109 -154
  45. package/modules/localmodels/process_windows.py +86 -0
  46. package/modules/localmodels/recommend.py +32 -3
  47. package/modules/localmodels/recommend_cli.py +14 -6
  48. package/modules/localmodels/remote_ops.py +65 -0
  49. package/modules/localmodels/remote_ops_download.py +2 -2
  50. package/modules/localmodels/remote_ops_prepare.py +19 -0
  51. package/modules/localmodels/remote_ops_service.py +14 -2
  52. package/modules/localmodels/runtime_args.py +10 -3
  53. package/modules/localmodels/runtime_auth.py +5 -9
  54. package/modules/localmodels/runtime_cli.py +128 -129
  55. package/modules/localmodels/runtime_discovery.py +84 -0
  56. package/modules/localmodels/runtime_install.py +101 -0
  57. package/modules/localmodels/runtime_releases.py +302 -0
  58. package/modules/localmodels/service_stop.py +8 -108
  59. package/modules/localmodels/service_upgrade.py +394 -63
  60. package/modules/localmodels/services_cli.py +24 -14
  61. package/modules/localmodels/setup_inspection.py +97 -9
  62. package/modules/localmodels/setup_text.py +7 -0
  63. package/modules/localmodels/sizecalc.py +0 -1
  64. package/modules/localmodels/stack.py +14 -221
  65. package/modules/localmodels/stack_arena.py +732 -0
  66. package/modules/localmodels/stack_args.py +15 -9
  67. package/modules/localmodels/stack_auto.py +384 -3
  68. package/modules/localmodels/stack_aux_gpu.py +4 -3
  69. package/modules/localmodels/stack_capacity.py +138 -0
  70. package/modules/localmodels/stack_cleanup.py +9 -4
  71. package/modules/localmodels/stack_cli.py +286 -0
  72. package/modules/localmodels/stack_compose.py +76 -32
  73. package/modules/localmodels/stack_console.py +9 -6
  74. package/modules/localmodels/stack_hardware.py +96 -270
  75. package/modules/localmodels/stack_hardware_text.py +263 -0
  76. package/modules/localmodels/stack_journal.py +3 -9
  77. package/modules/localmodels/stack_ledger.py +48 -18
  78. package/modules/localmodels/stack_lifecycle.py +33 -312
  79. package/modules/localmodels/stack_mcp.py +729 -0
  80. package/modules/localmodels/stack_memory.py +0 -2
  81. package/modules/localmodels/stack_picks.py +73 -18
  82. package/modules/localmodels/stack_plan.py +23 -5
  83. package/modules/localmodels/stack_preflight.py +11 -19
  84. package/modules/localmodels/stack_remove.py +373 -0
  85. package/modules/localmodels/stack_route.py +101 -17
  86. package/modules/localmodels/stack_suite.py +16 -10
  87. package/modules/localmodels/stack_summary.py +14 -0
  88. package/modules/localmodels/stack_try.py +238 -24
  89. package/modules/localmodels/stack_try_client.py +53 -15
  90. package/modules/localmodels/stack_try_docs.py +2 -2
  91. package/modules/localmodels/stack_view.py +24 -171
  92. package/modules/localmodels/stack_view_access.py +114 -1
  93. package/modules/localmodels/stack_view_agent.py +3 -13
  94. package/modules/localmodels/stack_view_hub.py +9 -10
  95. package/modules/localmodels/stack_view_llm.py +1 -1
  96. package/modules/localmodels/stack_view_sandbox.py +2 -2
  97. package/modules/localmodels/stack_view_schema.py +183 -0
  98. package/modules/localmodels/stack_view_serve.py +7 -1
  99. package/modules/localmodels/stack_view_service.py +1 -2
  100. package/modules/localmodels/stack_view_text.py +13 -9
  101. package/modules/localmodels/stack_warm.py +3 -0
  102. package/modules/localmodels/stack_warm_store.py +517 -0
  103. package/modules/localmodels/tui.py +28 -4
  104. package/modules/localmodels/tui_dialogs.py +136 -0
  105. package/modules/localmodels/tui_modals.py +279 -0
  106. package/modules/localmodels/tui_screen.py +113 -154
  107. package/modules/localmodels/tui_views.py +134 -203
  108. package/modules/localmodels/web/index.html +510 -101
  109. package/modules/localmodels/web/sizecalc/app.js +363 -10
  110. package/modules/localmodels/web/sizecalc/page.html +27 -3
  111. package/modules/localmodels/web/view/fleet.html +11 -2
  112. package/modules/localmodels/web/view/fleet.js +191 -17
  113. package/modules/localmodels/web/view/i18n.js +3 -2
  114. package/modules/localmodels/web/view/index.html +1 -1
  115. package/modules/localmodels/web/view/nav.js +22 -3
  116. package/modules/localmodels/web/view/view.css +63 -18
  117. package/modules/localmodels/web/view/view.js +169 -32
  118. package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/METADATA +1 -1
  119. package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/RECORD +120 -98
  120. package/package.json +1 -1
  121. package/tool.json +1 -1
  122. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  123. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/WHEEL +0 -0
  124. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/entry_points.txt +0 -0
  125. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/NOTICE +0 -0
  126. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.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]
@@ -285,11 +279,7 @@ def _taskkill(pid: int, force: bool) -> bool:
285
279
 
286
280
 
287
281
  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)."""
282
+ """Stop PID and descendants via polite ``taskkill /T`` (capped at 2 s) then ``/F``."""
293
283
  import time
294
284
 
295
285
  for force in (False, True):
@@ -305,16 +295,8 @@ def windows_stop_tree(pid: int, saved: Identity, grace: float) -> bool:
305
295
  return _windows_inspect(pid) != saved
306
296
 
307
297
 
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).
298
+ # Scheduled tasks start child services below normal (priority/memory/I/O), allowing Windows to
299
+ # trim idle resident pages aggressively; raising to normal prevents eviction (RTX 4060 Ti).
318
300
  _READ_MEMORY_INFO = _QUERY_LIMITED | 0x0010 # GetProcessMemoryInfo also wants PROCESS_VM_READ
319
301
  _SET_INFORMATION = 0x0200 # PROCESS_SET_INFORMATION
320
302
  _NORMAL_CLASS = 0x20 # NORMAL_PRIORITY_CLASS
@@ -332,9 +314,7 @@ class Priority(TypedDict):
332
314
 
333
315
 
334
316
  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
317
+ """Read or set I/O priority via ntdll (kernel32 only changes the calling process)."""
338
318
  from ctypes import wintypes
339
319
 
340
320
  try:
@@ -352,7 +332,6 @@ def _io_priority(handle: Any, value: int | None = None) -> int | None:
352
332
 
353
333
 
354
334
  def _priority(kernel: Any, handle: Any) -> Priority:
355
- import ctypes
356
335
  from ctypes import wintypes
357
336
 
358
337
  memory = wintypes.ULONG(0)
@@ -360,17 +339,18 @@ def _priority(kernel: Any, handle: Any) -> Priority:
360
339
  handle, _MEMORY_PRIORITY, ctypes.byref(memory), ctypes.sizeof(memory)
361
340
  ):
362
341
  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.
342
+ # PROCESS_MEMORY_COUNTERS on 64-bit Windows: cb+PageFaultCount (2 DWORDs), then SIZE_Ts ([2] is WorkingSetSize).
365
343
  counters = (ctypes.c_size_t * 9)()
366
344
  ctypes.cast(counters, ctypes.POINTER(wintypes.DWORD))[0] = ctypes.sizeof(counters)
367
345
  if not kernel.K32GetProcessMemoryInfo(handle, counters, ctypes.sizeof(counters)):
368
346
  raise OSError("working set size unavailable")
369
347
  io = _io_priority(handle)
370
348
  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),
349
+ "background": (
350
+ kernel.GetPriorityClass(handle) in _BACKGROUND_CLASSES
351
+ or memory.value < _MEMORY_NORMAL
352
+ or (io is not None and io < _IO_NORMAL)
353
+ ),
374
354
  "memory_priority": int(memory.value),
375
355
  "resident_bytes": int(counters[2]),
376
356
  }
@@ -391,30 +371,28 @@ def priority(pid: int) -> Priority | None:
391
371
 
392
372
 
393
373
  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
374
+ """Raise class, memory and I/O priority to normal where lower; returns updated state."""
398
375
  from ctypes import wintypes
399
376
 
400
377
  kernel, _ = _api()
401
378
  handle = kernel.OpenProcess(_READ_MEMORY_INFO | _SET_INFORMATION, False, pid)
402
379
  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})")
380
+ err = ctypes.get_last_error() # type: ignore[attr-defined]
381
+ raise OSError(f"cannot open process {pid} to set its priority (Windows error {err})")
405
382
  try:
406
383
  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})")
384
+ if kernel.GetPriorityClass(handle) in _BACKGROUND_CLASSES and not kernel.SetPriorityClass(
385
+ handle, _NORMAL_CLASS
386
+ ):
387
+ err = ctypes.get_last_error() # type: ignore[attr-defined]
388
+ raise OSError(f"Windows refused the normal priority class (error {err})")
411
389
  if seen["memory_priority"] < _MEMORY_NORMAL:
412
390
  normal = wintypes.ULONG(_MEMORY_NORMAL)
413
391
  if not kernel.SetProcessInformation(
414
392
  handle, _MEMORY_PRIORITY, ctypes.byref(normal), ctypes.sizeof(normal)
415
393
  ):
416
- error = ctypes.get_last_error() # type: ignore[attr-defined]
417
- raise OSError(f"Windows refused the normal memory priority (error {error})")
394
+ err = ctypes.get_last_error() # type: ignore[attr-defined]
395
+ raise OSError(f"Windows refused the normal memory priority (error {err})")
418
396
  io = _io_priority(handle)
419
397
  if io is not None and io < _IO_NORMAL:
420
398
  _io_priority(handle, _IO_NORMAL)
@@ -424,9 +402,7 @@ def run_at_normal_priority(pid: int) -> Priority:
424
402
 
425
403
 
426
404
  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."""
405
+ """Empty resident pages above ``above`` bytes on Windows; returns freed bytes."""
430
406
  if not _windows():
431
407
  return 0
432
408
  kernel, _ = _api()
@@ -451,9 +427,7 @@ WINDOWS_BREAKAWAY = 0x01000000
451
427
 
452
428
 
453
429
  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``."""
430
+ """Start a detached service in its own group/session (no console window, normal Windows priority)."""
457
431
  if not _windows():
458
432
  return subprocess.Popen(argv, start_new_session=True, **options)
459
433
  try:
@@ -488,8 +462,7 @@ def inspect(pid: int) -> Identity | None:
488
462
  return None
489
463
  if _windows():
490
464
  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).
465
+ # LC_ALL=C keeps lstart in 5 English tokens (zh_CN outputs 4).
493
466
  result = subprocess.run(
494
467
  ["/bin/ps", "-p", str(pid), "-o", "uid=,pgid=,lstart=,stat="],
495
468
  capture_output=True,
@@ -569,17 +542,16 @@ def _forget(pid_file: Path) -> None:
569
542
 
570
543
 
571
544
  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)."""
545
+ """Receipt identity, or None for an exited legacy bare PID file; raises ValueError if untrusted."""
574
546
  try:
575
547
  saved = json.loads(_private(Path(str(pid_file) + ".identity.json")))
576
548
  except FileNotFoundError:
577
- info = pid_file.lstat() # legacy: a bare PID file written before receipts existed
549
+ info = pid_file.lstat() # legacy: bare PID file written before receipts existed
578
550
  if not stat.S_ISREG(info.st_mode) or (not _windows() and info.st_uid != os.getuid()):
579
551
  raise ValueError("the PID file is not a regular file of this user") from None
580
552
  if inspect(int(pid_file.read_text(encoding="utf-8").strip())) is not None:
581
553
  raise ValueError(
582
- "a legacy PID file has no identity receipt; cannot prove the process belongs to this tool"
554
+ "a legacy PID file has no identity receipt; cannot prove ownership"
583
555
  ) from None
584
556
  return None
585
557
  fields = {"pid": int, "uid": int, "pgid": int, "started": str}
@@ -596,15 +568,8 @@ def _recorded(pid_file: Path) -> Identity | None:
596
568
 
597
569
 
598
570
  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."""
571
+ """Stop the receipt's process group (SIGTERM then SIGKILL after ``grace``) when UID/PGID/start match.
572
+ Returns 'none'|'gone'|'stopped'; leaves receipt and raises RuntimeError on verification/stop failure."""
608
573
  import signal
609
574
  import time
610
575
 
@@ -662,7 +627,7 @@ def listener_owned(port: int, pid: int | None) -> bool:
662
627
  except OSError:
663
628
  return False
664
629
  try:
665
- result = subprocess.run(
630
+ res = subprocess.run(
666
631
  ["/usr/sbin/lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"],
667
632
  capture_output=True,
668
633
  text=True,
@@ -672,17 +637,13 @@ def listener_owned(port: int, pid: int | None) -> bool:
672
637
  except (OSError, subprocess.TimeoutExpired):
673
638
  return False
674
639
  owners = {
675
- int(line[1:])
676
- for line in result.stdout.splitlines()
677
- if line.startswith("p") and line[1:].isdigit()
640
+ int(ln[1:]) for ln in res.stdout.splitlines() if ln.startswith("p") and ln[1:].isdigit()
678
641
  }
679
- return result.returncode == 0 and owners == {pid}
642
+ return res.returncode == 0 and owners == {pid}
680
643
 
681
644
 
682
645
  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."""
646
+ """Read-only Linux argv proof (plus shebang); on Windows checks owned executable image path."""
686
647
  if _windows():
687
648
  return _windows_command_matches(pid, expected)
688
649
  try:
@@ -692,18 +653,17 @@ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
692
653
  actual = process.joinpath("cmdline").read_bytes().decode().rstrip("\0").split("\0")
693
654
  if actual == expected:
694
655
  return True
695
- with open(
696
- expected[0] if root == "/" else Path(root) / expected[0].lstrip("/"), "rb"
697
- ) as executable:
656
+ target = expected[0] if root == "/" else Path(root) / expected[0].lstrip("/")
657
+ with open(target, "rb") as executable:
698
658
  header = executable.readline(512).decode()
699
659
  if not header.startswith("#!"):
700
660
  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:
661
+ interp = shlex.split(header[2:].strip())
662
+ if interp[:1] == ["/usr/bin/env"]:
663
+ interp = interp[1:]
664
+ if len(interp) != 1 or actual[1:] != expected:
705
665
  return False
706
- resolved = shutil.which(interpreter[0])
666
+ resolved = shutil.which(interp[0])
707
667
  return (
708
668
  resolved is not None and process.joinpath("exe").resolve() == Path(resolved).resolve()
709
669
  )
@@ -712,10 +672,7 @@ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
712
672
 
713
673
 
714
674
  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."""
675
+ """Windows: base ``python.exe`` from a venv's ``pyvenv.cfg`` ``home`` key, else None."""
719
676
  path = Path(os.path.expanduser(python))
720
677
  if path.name.lower() != "python.exe" or path.parent.name.lower() != "scripts":
721
678
  return None
@@ -733,15 +690,13 @@ def venv_base(python: str) -> str | None:
733
690
 
734
691
  def _windows_command_matches(pid: int, expected: list[str]) -> bool:
735
692
  try:
736
- found = _windows_inspect(pid)
737
- image = image_path(pid)
693
+ found, image = _windows_inspect(pid), image_path(pid)
738
694
  except OSError:
739
695
  return False
740
696
  if found is None or found["uid"] != 0 or image is None or not expected:
741
697
  return False
742
698
  want = os.path.expanduser(expected[0])
743
- if not want.lower().endswith(".exe"):
744
- want += ".exe"
699
+ want = want if want.lower().endswith(".exe") else want + ".exe"
745
700
  wanted = [want, *filter(None, [venv_base(want)])]
746
701
  try:
747
702
  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)
@@ -11,8 +11,8 @@ from typing import Literal, TypedDict
11
11
 
12
12
  from localmodels import catalog as cat
13
13
  from localmodels import llm_rank
14
- from localmodels.budget import Placement, gib, placements
15
- from localmodels.context_policy import window_k
14
+ from localmodels.budget import Placement, agent_budget, gib, placements
15
+ from localmodels.context_policy import AGENT, window_k
16
16
  from localmodels.estimator import PhysicsRefusal
17
17
  from localmodels.probe import HostFacts
18
18
 
@@ -76,6 +76,7 @@ _QUANT_REASONS = {
76
76
  ),
77
77
  }
78
78
  RECOMMENDED_REASONS = {
79
+ "windows-candidate-fallback": llm_rank.WINDOWS_FALLBACK_WARNING,
79
80
  "user-default": "User-selected small-Mac default; SimplexAI score and full acceptance pending.",
80
81
  "product-default": "This machine's default model, chosen by its maker.",
81
82
  "best-quality-resident": (
@@ -160,8 +161,12 @@ def recommendation(
160
161
  facts: HostFacts,
161
162
  ) -> tuple[cat.CatalogEntry, str, Placement] | None:
162
163
  """Pick an eligible LLM on one card, then a pooled split. Other entries stay inspectable."""
164
+ live = tuple(
165
+ e
166
+ for e in entries
167
+ if llm_rank.automatic_here(e, facts) and not llm_rank.windows_fallback(e, facts)
168
+ )
163
169
  for placement in _candidates(host):
164
- live = tuple(e for e in entries if llm_rank.automatic_here(e, facts))
165
170
  picked = llm_rank.recommended_entry(
166
171
  placement.budget,
167
172
  live,
@@ -170,6 +175,30 @@ def recommendation(
170
175
  )
171
176
  if picked is not None:
172
177
  return picked[0], picked[1], placement
178
+ fallback = next((e for e in entries if llm_rank.windows_fallback(e, facts)), None)
179
+ if fallback is not None:
180
+ candidates = [
181
+ (p, budget)
182
+ for p in host
183
+ if not p.conflicts and (budget := agent_budget(p, facts)) is not None
184
+ ]
185
+ candidates.sort(key=lambda pair: -pair[1].usable_vram_bytes)
186
+ fitting = []
187
+ for entry in (*live, fallback):
188
+ for p, budget in candidates:
189
+ if llm_rank.automatic_fit(entry, facts, budget, AGENT, {"search": False}):
190
+ key = llm_rank.rank_key(entry, entry.variants[-1], budget)
191
+ fitting.append((key, entry.id, p.gpu_indices[0]))
192
+ break
193
+ if not fitting:
194
+ return None
195
+ entry_id, index = llm_rank.choose(fitting, "smartest", fallback_ids={fallback.id})
196
+ if entry_id != fallback.id:
197
+ return None
198
+ fallback_placement = next((p for p in host if p.id == f"gpu:{index}"), None)
199
+ if fallback_placement is None:
200
+ return None
201
+ return fallback, "windows-candidate-fallback", fallback_placement
173
202
  return None
174
203
 
175
204