@simplexai/localmodels-darwin-arm64 0.1.0-dev.32.build.git9f03dd7a81cec1338df8eaf613ec9e3013365c9c → 0.1.0-dev.36

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 (143) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +141 -99
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/app.py +7 -2
  6. package/modules/localmodels/approval.py +4 -4
  7. package/modules/localmodels/bifrost_checks.py +121 -3
  8. package/modules/localmodels/bifrost_provider.py +53 -0
  9. package/modules/localmodels/bifrost_unit.py +32 -1
  10. package/modules/localmodels/budget.py +7 -1
  11. package/modules/localmodels/catalog.json +286 -12
  12. package/modules/localmodels/catalog.py +30 -29
  13. package/modules/localmodels/catalog_add.py +1 -0
  14. package/modules/localmodels/cli_parser.py +10 -2
  15. package/modules/localmodels/component.py +7 -1
  16. package/modules/localmodels/decode_calibration.json +6 -0
  17. package/modules/localmodels/decode_calibration.py +104 -0
  18. package/modules/localmodels/deploy.py +44 -7
  19. package/modules/localmodels/deploy_steps.py +10 -1
  20. package/modules/localmodels/engines-strata-0.1.49.2.json +31 -0
  21. package/modules/localmodels/engines-strata-0.1.59.1.json +31 -0
  22. package/modules/localmodels/engines.json +57 -1
  23. package/modules/localmodels/engines.py +6 -2
  24. package/modules/localmodels/estimator.py +21 -7
  25. package/modules/localmodels/frontend.py +4 -4
  26. package/modules/localmodels/gateway.py +14 -4
  27. package/modules/localmodels/gateway_app_bifrost.py +4 -3
  28. package/modules/localmodels/gateway_bifrost.py +70 -57
  29. package/modules/localmodels/gateway_probe.py +3 -4
  30. package/modules/localmodels/gguf.py +7 -0
  31. package/modules/localmodels/harness.py +24 -25
  32. package/modules/localmodels/harness_gateway.py +19 -10
  33. package/modules/localmodels/harness_probe.py +33 -6
  34. package/modules/localmodels/hosts.py +73 -9
  35. package/modules/localmodels/install.py +36 -6
  36. package/modules/localmodels/library_cli.py +179 -0
  37. package/modules/localmodels/library_convert.py +132 -0
  38. package/modules/localmodels/library_gateway.py +471 -0
  39. package/modules/localmodels/library_jobs.py +314 -0
  40. package/modules/localmodels/library_model.py +246 -0
  41. package/modules/localmodels/library_pricing.py +347 -0
  42. package/modules/localmodels/library_serve.py +348 -0
  43. package/modules/localmodels/library_state.py +373 -0
  44. package/modules/localmodels/library_status.py +349 -0
  45. package/modules/localmodels/llm_rank.py +77 -8
  46. package/modules/localmodels/memcalc.py +7 -30
  47. package/modules/localmodels/metal.py +26 -0
  48. package/modules/localmodels/metal_probe.py +11 -7
  49. package/modules/localmodels/plan_envelope.py +4 -1
  50. package/modules/localmodels/preparation.py +49 -0
  51. package/modules/localmodels/probe.py +8 -8
  52. package/modules/localmodels/process_identity.py +536 -9
  53. package/modules/localmodels/quant_formats.py +123 -0
  54. package/modules/localmodels/recommend.py +32 -3
  55. package/modules/localmodels/recommend_cli.py +8 -4
  56. package/modules/localmodels/records.py +1 -0
  57. package/modules/localmodels/remote_ops.py +104 -6
  58. package/modules/localmodels/remote_ops_download.py +17 -2
  59. package/modules/localmodels/remote_ops_prepare.py +425 -0
  60. package/modules/localmodels/remote_ops_remove.py +40 -7
  61. package/modules/localmodels/remote_ops_service.py +110 -8
  62. package/modules/localmodels/remote_ops_verify.py +15 -2
  63. package/modules/localmodels/runtime_auth.py +31 -1
  64. package/modules/localmodels/runtime_cli.py +3 -4
  65. package/modules/localmodels/runtime_io.py +50 -6
  66. package/modules/localmodels/service_autostart.py +45 -1
  67. package/modules/localmodels/service_control.py +13 -0
  68. package/modules/localmodels/service_deployment.py +12 -3
  69. package/modules/localmodels/service_jobs.py +33 -4
  70. package/modules/localmodels/service_probe.py +67 -13
  71. package/modules/localmodels/service_stop.py +152 -0
  72. package/modules/localmodels/service_worker.py +9 -1
  73. package/modules/localmodels/services_cli.py +50 -6
  74. package/modules/localmodels/setup_inspection.py +34 -25
  75. package/modules/localmodels/setup_text.py +118 -0
  76. package/modules/localmodels/sizecalc.py +625 -0
  77. package/modules/localmodels/sizecalc_cli.py +249 -0
  78. package/modules/localmodels/stack.py +69 -17
  79. package/modules/localmodels/stack_args.py +91 -19
  80. package/modules/localmodels/stack_auto.py +78 -0
  81. package/modules/localmodels/stack_binding.py +23 -35
  82. package/modules/localmodels/stack_card.py +195 -0
  83. package/modules/localmodels/stack_cleanup.py +379 -0
  84. package/modules/localmodels/stack_clients.py +4 -1
  85. package/modules/localmodels/stack_compose.py +173 -206
  86. package/modules/localmodels/stack_console.py +2 -0
  87. package/modules/localmodels/stack_decision.py +3 -2
  88. package/modules/localmodels/stack_down.py +189 -0
  89. package/modules/localmodels/stack_events.py +54 -0
  90. package/modules/localmodels/stack_hardware.py +30 -34
  91. package/modules/localmodels/stack_journal.py +29 -8
  92. package/modules/localmodels/stack_ledger.py +411 -0
  93. package/modules/localmodels/stack_lifecycle.py +162 -167
  94. package/modules/localmodels/stack_llm_ram.py +57 -5
  95. package/modules/localmodels/stack_memory.py +721 -0
  96. package/modules/localmodels/stack_picks.py +147 -0
  97. package/modules/localmodels/stack_plan.py +143 -25
  98. package/modules/localmodels/stack_ports.py +22 -0
  99. package/modules/localmodels/stack_preflight.py +699 -0
  100. package/modules/localmodels/stack_review.py +123 -5
  101. package/modules/localmodels/stack_rollback.py +2 -0
  102. package/modules/localmodels/stack_route.py +256 -0
  103. package/modules/localmodels/stack_run.py +11 -0
  104. package/modules/localmodels/stack_suite.py +107 -20
  105. package/modules/localmodels/stack_summary.py +65 -4
  106. package/modules/localmodels/stack_try.py +354 -0
  107. package/modules/localmodels/stack_try_client.py +194 -0
  108. package/modules/localmodels/stack_try_docs.py +139 -0
  109. package/modules/localmodels/stack_up.py +8 -1
  110. package/modules/localmodels/stack_update.py +29 -4
  111. package/modules/localmodels/stack_verify.py +3 -1
  112. package/modules/localmodels/stack_view.py +10 -11
  113. package/modules/localmodels/stack_view_apply.py +4 -2
  114. package/modules/localmodels/stack_view_events.py +2 -1
  115. package/modules/localmodels/stack_view_serve.py +3 -0
  116. package/modules/localmodels/stack_view_text.py +1 -1
  117. package/modules/localmodels/stack_view_words.py +4 -1
  118. package/modules/localmodels/stack_warm.py +574 -0
  119. package/modules/localmodels/stack_whatif.py +558 -0
  120. package/modules/localmodels/suite.py +48 -39
  121. package/modules/localmodels/tool_archive.py +40 -0
  122. package/modules/localmodels/tools.json +8 -0
  123. package/modules/localmodels/transport.py +1 -0
  124. package/modules/localmodels/vision.py +8 -1
  125. package/modules/localmodels/web/sizecalc/app.js +431 -0
  126. package/modules/localmodels/web/sizecalc/calc.js +269 -0
  127. package/modules/localmodels/web/sizecalc/page.html +362 -0
  128. package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
  129. package/modules/localmodels/web/view/i18n.js +1 -1
  130. package/modules/localmodels/web/view/logo-claude.svg +3 -0
  131. package/modules/localmodels/web/view/logo-codex.png +0 -0
  132. package/modules/localmodels/web/view/logo-pi.svg +6 -0
  133. package/modules/localmodels/web/view/view.css +4 -0
  134. package/modules/localmodels/web/view/view.js +15 -6
  135. package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/METADATA +1 -1
  136. package/modules/simplex_localmodels-0.1.0.dev36.dist-info/RECORD +242 -0
  137. package/package.json +1 -1
  138. package/tool.json +1 -1
  139. package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
  140. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/WHEEL +0 -0
  141. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/entry_points.txt +0 -0
  142. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/licenses/NOTICE +0 -0
  143. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -2,6 +2,12 @@
2
2
 
3
3
  A live PID alone cannot authorize a signal after PID reuse. Receipts bind the
4
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``.
5
11
  """
6
12
 
7
13
  from __future__ import annotations
@@ -12,9 +18,10 @@ import shlex
12
18
  import shutil
13
19
  import stat
14
20
  import subprocess
21
+ import sys
15
22
  import tempfile
16
23
  from pathlib import Path
17
- from typing import TypedDict
24
+ from typing import Any, TypedDict
18
25
 
19
26
 
20
27
  class Identity(TypedDict):
@@ -24,15 +31,472 @@ class Identity(TypedDict):
24
31
  started: str
25
32
 
26
33
 
34
+ def _windows() -> bool:
35
+ return sys.platform == "win32"
36
+
37
+
38
+ def current_uid() -> int:
39
+ """``os.getuid()``; 0 on Windows, where ``inspect`` reports this user's processes as 0."""
40
+ return 0 if _windows() else os.getuid()
41
+
42
+
43
+ # ── Windows ──
44
+
45
+ _STILL_ACTIVE = 259
46
+ _QUERY_LIMITED = 0x1000 # PROCESS_QUERY_LIMITED_INFORMATION
47
+
48
+
49
+ _API: list[tuple[Any, Any]] = []
50
+
51
+
52
+ def _api() -> tuple[Any, Any]:
53
+ """kernel32 and advapi32 with typed signatures: an untyped 64-bit HANDLE overflows."""
54
+ if _API:
55
+ return _API[0]
56
+ import ctypes
57
+ from ctypes import wintypes
58
+
59
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True) # type: ignore[attr-defined]
60
+ 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),
87
+ ):
88
+ function.argtypes, function.restype = args, result
89
+ _API.append((kernel, advapi))
90
+ return kernel, advapi
91
+
92
+
93
+ def _token_sid(handle: Any) -> str | None:
94
+ """The string SID of the user a process (``handle``) runs as."""
95
+ import ctypes
96
+ from ctypes import wintypes
97
+
98
+ kernel, advapi = _api()
99
+ token = wintypes.HANDLE()
100
+ if not advapi.OpenProcessToken(handle, 0x0008, ctypes.byref(token)): # TOKEN_QUERY
101
+ return None
102
+ try:
103
+ size = wintypes.DWORD()
104
+ advapi.GetTokenInformation(token, 1, None, 0, ctypes.byref(size)) # TokenUser
105
+ if not size.value:
106
+ return None
107
+ buffer = ctypes.create_string_buffer(size.value)
108
+ if not advapi.GetTokenInformation(token, 1, buffer, size, ctypes.byref(size)):
109
+ return None
110
+ sid = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_void_p))[0]
111
+ text = wintypes.LPWSTR()
112
+ if not advapi.ConvertSidToStringSidW(sid, ctypes.byref(text)):
113
+ return None
114
+ try:
115
+ return text.value
116
+ finally:
117
+ kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p))
118
+ finally:
119
+ kernel.CloseHandle(token)
120
+
121
+
122
+ def _own_sid() -> str | None:
123
+ kernel, _ = _api()
124
+ return _token_sid(kernel.GetCurrentProcess())
125
+
126
+
127
+ 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
132
+ from ctypes import wintypes
133
+
134
+ kernel, _ = _api()
135
+ handle = kernel.OpenProcess(_QUERY_LIMITED, False, pid)
136
+ if not handle:
137
+ error = ctypes.get_last_error() # type: ignore[attr-defined]
138
+ if error == 87: # ERROR_INVALID_PARAMETER: no such process
139
+ return None
140
+ raise OSError(f"cannot open process {pid} (Windows error {error})")
141
+ try:
142
+ code = wintypes.DWORD()
143
+ if not kernel.GetExitCodeProcess(handle, ctypes.byref(code)):
144
+ raise OSError("process exit code unavailable")
145
+ if code.value != _STILL_ACTIVE:
146
+ return None
147
+ times = [wintypes.FILETIME() for _ in range(4)]
148
+ if not kernel.GetProcessTimes(handle, *(ctypes.byref(t) for t in times)):
149
+ raise OSError("process start time unavailable")
150
+ created = (times[0].dwHighDateTime << 32) | times[0].dwLowDateTime
151
+ size = wintypes.DWORD(32768)
152
+ image = ctypes.create_unicode_buffer(size.value)
153
+ # System processes hide their image; they are never this user's anyway.
154
+ if not kernel.QueryFullProcessImageNameW(handle, 0, image, ctypes.byref(size)):
155
+ return str(created), "", None
156
+ return str(created), image.value, _token_sid(handle)
157
+ finally:
158
+ kernel.CloseHandle(handle)
159
+
160
+
161
+ def _windows_inspect(pid: int) -> Identity | None:
162
+ found = _windows_process(pid)
163
+ if found is None:
164
+ return None
165
+ started, _, sid = found
166
+ own = _own_sid()
167
+ uid = 0 if sid is not None and own is not None and sid == own else -1
168
+ return {"pid": pid, "uid": uid, "pgid": pid, "started": started}
169
+
170
+
171
+ def _parent_pids() -> dict[int, int]:
172
+ """Windows: {PID: parent PID} of every process (a Toolhelp snapshot)."""
173
+ import ctypes
174
+ from ctypes import wintypes
175
+
176
+ class Entry(ctypes.Structure):
177
+ _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),
183
+ ] # fmt: skip
184
+
185
+ kernel, _ = _api()
186
+ kernel.CreateToolhelp32Snapshot.argtypes = (wintypes.DWORD, wintypes.DWORD)
187
+ kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
188
+ for name in ("Process32FirstW", "Process32NextW"):
189
+ getattr(kernel, name).argtypes = (wintypes.HANDLE, ctypes.POINTER(Entry))
190
+ snapshot = kernel.CreateToolhelp32Snapshot(0x2, 0) # TH32CS_SNAPPROCESS
191
+ if snapshot in (None, wintypes.HANDLE(-1).value):
192
+ raise OSError("process snapshot unavailable")
193
+ found: dict[int, int] = {}
194
+ try:
195
+ entry = Entry()
196
+ entry.dwSize = ctypes.sizeof(Entry)
197
+ more = kernel.Process32FirstW(snapshot, ctypes.byref(entry))
198
+ while more:
199
+ found[entry.th32ProcessID] = entry.th32ParentProcessID
200
+ more = kernel.Process32NextW(snapshot, ctypes.byref(entry))
201
+ finally:
202
+ kernel.CloseHandle(snapshot)
203
+ return found
204
+
205
+
206
+ 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."""
213
+ if not _windows():
214
+ return False
215
+ path = Path(pid_file)
216
+ try:
217
+ saved = _recorded(path)
218
+ if saved is None or _windows_inspect(saved["pid"]) is not None:
219
+ 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
222
+ ]
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
+ if len(successors) != 1:
234
+ return False
235
+ save(path, successors[0])
236
+ return True
237
+ except (OSError, ValueError, RuntimeError):
238
+ return False
239
+
240
+
241
+ def image_path(pid: int) -> str | None:
242
+ """The executable a Windows process runs; None when it is gone or cannot be read."""
243
+ try:
244
+ found = _windows_process(pid)
245
+ except OSError:
246
+ return None
247
+ return found[1] or None if found else None
248
+
249
+
250
+ 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
254
+ import struct
255
+
256
+ iphlpapi = ctypes.WinDLL("iphlpapi") # type: ignore[attr-defined]
257
+ owners: set[int] = set()
258
+ for family, row_size, port_at, pid_at in ((2, 24, 8, 20), (23, 56, 20, 52)):
259
+ size = ctypes.c_ulong(0)
260
+ # TCP_TABLE_OWNER_PID_LISTENER = 3; first call sizes the buffer.
261
+ iphlpapi.GetExtendedTcpTable(None, ctypes.byref(size), False, family, 3, 0)
262
+ for _ in range(3):
263
+ buffer = ctypes.create_string_buffer(size.value or 4)
264
+ result = iphlpapi.GetExtendedTcpTable(buffer, ctypes.byref(size), False, family, 3, 0)
265
+ if result != 122: # ERROR_INSUFFICIENT_BUFFER: the table grew, size again
266
+ break
267
+ if result != 0:
268
+ return None
269
+ raw = buffer.raw
270
+ (count,) = struct.unpack_from("<I", raw, 0)
271
+ for index in range(count):
272
+ row = 4 + index * row_size
273
+ local_port = struct.unpack_from(">H", raw, row + port_at)[0]
274
+ if local_port == port:
275
+ owners.add(struct.unpack_from("<I", raw, row + pid_at)[0])
276
+ return owners
277
+
278
+
279
+ def _taskkill(pid: int, force: bool) -> bool:
280
+ """Ask Windows to end the tree under ``pid``; False when it says the request was not taken."""
281
+ root = os.environ.get("SystemRoot", r"C:\Windows")
282
+ argv = [os.path.join(root, "System32", "taskkill.exe"), "/PID", str(pid), "/T"]
283
+ argv += ["/F"] if force else []
284
+ return subprocess.run(argv, capture_output=True, timeout=30, check=False).returncode == 0
285
+
286
+
287
+ 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
+ import time
294
+
295
+ for force in (False, True):
296
+ if _windows_inspect(pid) != saved:
297
+ return True
298
+ if not _taskkill(pid, force) and not force:
299
+ continue
300
+ deadline = time.monotonic() + (min(grace, 2.0) if not force else 15.0)
301
+ while time.monotonic() < deadline:
302
+ if _windows_inspect(pid) != saved:
303
+ return True
304
+ time.sleep(0.2)
305
+ return _windows_inspect(pid) != saved
306
+
307
+
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).
318
+ _READ_MEMORY_INFO = _QUERY_LIMITED | 0x0010 # GetProcessMemoryInfo also wants PROCESS_VM_READ
319
+ _SET_INFORMATION = 0x0200 # PROCESS_SET_INFORMATION
320
+ _NORMAL_CLASS = 0x20 # NORMAL_PRIORITY_CLASS
321
+ _BACKGROUND_CLASSES = (0x40, 0x4000) # IDLE_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS
322
+ _MEMORY_PRIORITY = 0 # PROCESS_INFORMATION_CLASS: ProcessMemoryPriority
323
+ _MEMORY_NORMAL = 5 # MEMORY_PRIORITY_NORMAL; 1 is very low
324
+ _IO_PRIORITY = 33 # PROCESSINFOCLASS: ProcessIoPriority
325
+ _IO_NORMAL = 2 # IoPriorityNormal; 0 is very low
326
+
327
+
328
+ class Priority(TypedDict):
329
+ background: bool # the class, the memory priority or the I/O priority is below normal
330
+ memory_priority: int # 1 (very low) to 5 (normal)
331
+ resident_bytes: int # the working set now
332
+
333
+
334
+ 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
338
+ from ctypes import wintypes
339
+
340
+ try:
341
+ ntdll = ctypes.WinDLL("ntdll") # type: ignore[attr-defined]
342
+ query, change = ntdll.NtQueryInformationProcess, ntdll.NtSetInformationProcess
343
+ four = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.ULONG]
344
+ query.argtypes, change.argtypes = [*four, ctypes.c_void_p], four
345
+ seen = wintypes.ULONG(0 if value is None else value)
346
+ if value is not None:
347
+ change(handle, _IO_PRIORITY, ctypes.byref(seen), ctypes.sizeof(seen))
348
+ failed = query(handle, _IO_PRIORITY, ctypes.byref(seen), ctypes.sizeof(seen), None)
349
+ return None if failed else int(seen.value)
350
+ except (OSError, AttributeError):
351
+ return None
352
+
353
+
354
+ def _priority(kernel: Any, handle: Any) -> Priority:
355
+ import ctypes
356
+ from ctypes import wintypes
357
+
358
+ memory = wintypes.ULONG(0)
359
+ if not kernel.GetProcessInformation(
360
+ handle, _MEMORY_PRIORITY, ctypes.byref(memory), ctypes.sizeof(memory)
361
+ ):
362
+ 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.
365
+ counters = (ctypes.c_size_t * 9)()
366
+ ctypes.cast(counters, ctypes.POINTER(wintypes.DWORD))[0] = ctypes.sizeof(counters)
367
+ if not kernel.K32GetProcessMemoryInfo(handle, counters, ctypes.sizeof(counters)):
368
+ raise OSError("working set size unavailable")
369
+ io = _io_priority(handle)
370
+ 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),
374
+ "memory_priority": int(memory.value),
375
+ "resident_bytes": int(counters[2]),
376
+ }
377
+
378
+
379
+ def priority(pid: int) -> Priority | None:
380
+ """How Windows treats this process; None off Windows or when it has exited."""
381
+ if not _windows():
382
+ return None
383
+ kernel, _ = _api()
384
+ handle = kernel.OpenProcess(_READ_MEMORY_INFO, False, pid)
385
+ if not handle:
386
+ return None
387
+ try:
388
+ return _priority(kernel, handle)
389
+ finally:
390
+ kernel.CloseHandle(handle)
391
+
392
+
393
+ 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
398
+ from ctypes import wintypes
399
+
400
+ kernel, _ = _api()
401
+ handle = kernel.OpenProcess(_READ_MEMORY_INFO | _SET_INFORMATION, False, pid)
402
+ 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})")
405
+ try:
406
+ 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})")
411
+ if seen["memory_priority"] < _MEMORY_NORMAL:
412
+ normal = wintypes.ULONG(_MEMORY_NORMAL)
413
+ if not kernel.SetProcessInformation(
414
+ handle, _MEMORY_PRIORITY, ctypes.byref(normal), ctypes.sizeof(normal)
415
+ ):
416
+ error = ctypes.get_last_error() # type: ignore[attr-defined]
417
+ raise OSError(f"Windows refused the normal memory priority (error {error})")
418
+ io = _io_priority(handle)
419
+ if io is not None and io < _IO_NORMAL:
420
+ _io_priority(handle, _IO_NORMAL)
421
+ return _priority(kernel, handle)
422
+ finally:
423
+ kernel.CloseHandle(handle)
424
+
425
+
426
+ 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."""
430
+ if not _windows():
431
+ return 0
432
+ kernel, _ = _api()
433
+ handle = kernel.OpenProcess(_READ_MEMORY_INFO | 0x0100, False, pid) # and PROCESS_SET_QUOTA
434
+ if not handle:
435
+ return 0
436
+ try:
437
+ before = _priority(kernel, handle)["resident_bytes"]
438
+ if before <= above or not kernel.K32EmptyWorkingSet(handle):
439
+ return 0
440
+ return max(0, before - _priority(kernel, handle)["resident_bytes"])
441
+ except OSError:
442
+ return 0
443
+ finally:
444
+ kernel.CloseHandle(handle)
445
+
446
+
447
+ # CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW, plus CREATE_BREAKAWAY_FROM_JOB where the job
448
+ # allows it: an SSH session's job object would otherwise end the service with the session.
449
+ WINDOWS_FLAGS = 0x00000200 | 0x08000000
450
+ WINDOWS_BREAKAWAY = 0x01000000
451
+
452
+
453
+ 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``."""
457
+ if not _windows():
458
+ return subprocess.Popen(argv, start_new_session=True, **options)
459
+ try:
460
+ proc = subprocess.Popen(argv, creationflags=WINDOWS_FLAGS | WINDOWS_BREAKAWAY, **options)
461
+ except PermissionError: # the job does not allow breakaway
462
+ proc = subprocess.Popen(argv, creationflags=WINDOWS_FLAGS, **options)
463
+ try:
464
+ run_at_normal_priority(proc.pid)
465
+ except OSError: # it serves at the priority it inherited; stack warm reports and retries
466
+ pass
467
+ return proc
468
+
469
+
470
+ def kill_started(pid: int) -> None:
471
+ """End a process ``spawn_detached`` just started, with its group or tree."""
472
+ if _windows():
473
+ _taskkill(pid, True)
474
+ return
475
+ import signal
476
+
477
+ try:
478
+ os.killpg(pid, signal.SIGKILL)
479
+ except ProcessLookupError:
480
+ pass
481
+
482
+
483
+ # ── POSIX and shared ──
484
+
485
+
27
486
  def inspect(pid: int) -> Identity | None:
28
487
  if pid <= 1:
29
488
  return None
489
+ if _windows():
490
+ 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).
30
493
  result = subprocess.run(
31
494
  ["/bin/ps", "-p", str(pid), "-o", "uid=,pgid=,lstart=,stat="],
32
495
  capture_output=True,
33
496
  text=True,
34
497
  timeout=5,
35
498
  check=False,
499
+ env={**os.environ, "LC_ALL": "C"},
36
500
  )
37
501
  fields = result.stdout.split()
38
502
  if result.returncode == 1 and not fields and not result.stderr.strip():
@@ -51,7 +515,10 @@ def inspect(pid: int) -> Identity | None:
51
515
 
52
516
  def _private(path: Path) -> str:
53
517
  info = path.lstat()
54
- if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
518
+ if not stat.S_ISREG(info.st_mode):
519
+ raise ValueError("process receipt is not a private owned file")
520
+ # Windows has no POSIX owner or mode bits; the receipts live in the user's own profile.
521
+ if not _windows() and (info.st_uid != os.getuid() or info.st_mode & 0o077):
55
522
  raise ValueError("process receipt is not a private owned file")
56
523
  return path.read_text(encoding="utf-8")
57
524
 
@@ -69,7 +536,7 @@ def status(pid_file: str | Path) -> tuple[str, int | None]:
69
536
  if current is None:
70
537
  return "inactive", None
71
538
  saved = json.loads(_private(Path(str(path) + ".identity.json")))
72
- if current == saved and current["uid"] == os.getuid() and current["pgid"] == pid:
539
+ if current == saved and current["uid"] == current_uid() and current["pgid"] == pid:
73
540
  return "active", pid
74
541
  except (OSError, ValueError, subprocess.TimeoutExpired):
75
542
  pass
@@ -78,7 +545,7 @@ def status(pid_file: str | Path) -> tuple[str, int | None]:
78
545
 
79
546
  def save(pid_file: str | Path, pid: int) -> None:
80
547
  identity = inspect(pid)
81
- if identity is None or identity["uid"] != os.getuid() or identity["pgid"] != pid:
548
+ if identity is None or identity["uid"] != current_uid() or identity["pgid"] != pid:
82
549
  raise RuntimeError("cannot verify the new process group")
83
550
  path = Path(pid_file)
84
551
  with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as handle:
@@ -86,7 +553,8 @@ def save(pid_file: str | Path, pid: int) -> None:
86
553
  temporary = handle.name
87
554
  try:
88
555
  os.replace(temporary, str(path) + ".identity.json")
89
- fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
556
+ nofollow = getattr(os, "O_NOFOLLOW", 0) # Windows has none; the path is ours
557
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | nofollow, 0o600)
90
558
  with os.fdopen(fd, "w", encoding="utf-8") as handle:
91
559
  handle.write(str(pid))
92
560
  finally:
@@ -107,7 +575,7 @@ def _recorded(pid_file: Path) -> Identity | None:
107
575
  saved = json.loads(_private(Path(str(pid_file) + ".identity.json")))
108
576
  except FileNotFoundError:
109
577
  info = pid_file.lstat() # legacy: a bare PID file written before receipts existed
110
- if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid():
578
+ if not stat.S_ISREG(info.st_mode) or (not _windows() and info.st_uid != os.getuid()):
111
579
  raise ValueError("the PID file is not a regular file of this user") from None
112
580
  if inspect(int(pid_file.read_text(encoding="utf-8").strip())) is not None:
113
581
  raise ValueError(
@@ -122,7 +590,7 @@ def _recorded(pid_file: Path) -> Identity | None:
122
590
  or int(_private(pid_file).strip()) != saved["pid"]
123
591
  ):
124
592
  raise ValueError("malformed identity receipt")
125
- if saved["uid"] != os.getuid() or saved["pgid"] != saved["pid"]:
593
+ if saved["uid"] != current_uid() or saved["pgid"] != saved["pid"]:
126
594
  raise ValueError("the process in the receipt is not in its own process group of this user")
127
595
  return saved # type: ignore[return-value]
128
596
 
@@ -151,6 +619,13 @@ def stop(pid_file: str | Path, grace: float = 15.0) -> str:
151
619
  return "gone"
152
620
  if current != saved:
153
621
  raise ValueError("the process identity does not match the receipt")
622
+ if _windows():
623
+ if windows_stop_tree(saved["pid"], saved, grace):
624
+ _forget(path)
625
+ return "stopped"
626
+ raise RuntimeError(
627
+ f"did not stop {path}: process {saved['pid']} is still running after taskkill /F"
628
+ )
154
629
  for sig in (signal.SIGTERM, signal.SIGKILL):
155
630
  os.killpg(saved["pid"], sig)
156
631
  deadline = time.monotonic() + grace
@@ -161,6 +636,8 @@ def stop(pid_file: str | Path, grace: float = 15.0) -> str:
161
636
  time.sleep(0.1)
162
637
  except (OSError, ValueError, subprocess.TimeoutExpired) as exc:
163
638
  raise RuntimeError(f"did not stop {path}: {exc}") from None
639
+ except RuntimeError:
640
+ raise
164
641
  raise RuntimeError(
165
642
  f"did not stop {path}: process group {saved['pid']} is still running after SIGKILL"
166
643
  )
@@ -168,8 +645,10 @@ def stop(pid_file: str | Path, grace: float = 15.0) -> str:
168
645
 
169
646
  def require_owned(pid_file: str | Path) -> None:
170
647
  if status(pid_file)[0] == "unknown":
648
+ system = "Windows" if _windows() else "macOS"
171
649
  raise RuntimeError(
172
- "cannot verify who owns the macOS service process; keeping it, not starting, stopping or replacing"
650
+ f"cannot verify who owns the {system} service process; keeping it, not starting,"
651
+ " stopping or replacing"
173
652
  )
174
653
 
175
654
 
@@ -177,6 +656,11 @@ def listener_owned(port: int, pid: int | None) -> bool:
177
656
  """Do not send a deployment key to an unattributed loopback listener."""
178
657
  if pid is None:
179
658
  return False
659
+ if _windows():
660
+ try:
661
+ return listener_pids(port) == {pid}
662
+ except OSError:
663
+ return False
180
664
  try:
181
665
  result = subprocess.run(
182
666
  ["/usr/sbin/lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"],
@@ -196,7 +680,11 @@ def listener_owned(port: int, pid: int | None) -> bool:
196
680
 
197
681
 
198
682
  def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
199
- """Read-only Linux argv proof, including the kernel's single shebang interpreter."""
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."""
686
+ if _windows():
687
+ return _windows_command_matches(pid, expected)
200
688
  try:
201
689
  process = Path(root) / "proc" / str(pid)
202
690
  if process.stat().st_uid != os.getuid():
@@ -221,3 +709,42 @@ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
221
709
  )
222
710
  except (OSError, ValueError, UnicodeError, IndexError):
223
711
  return False
712
+
713
+
714
+ 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."""
719
+ path = Path(os.path.expanduser(python))
720
+ if path.name.lower() != "python.exe" or path.parent.name.lower() != "scripts":
721
+ return None
722
+ try:
723
+ config = (path.parent.parent / "pyvenv.cfg").read_text(encoding="utf-8")
724
+ except OSError:
725
+ return None
726
+ for line in config.splitlines():
727
+ key, _, value = line.partition("=")
728
+ if key.strip().lower() == "home" and value.strip():
729
+ base = Path(value.strip()) / "python.exe"
730
+ return str(base) if base.is_file() else None
731
+ return None
732
+
733
+
734
+ def _windows_command_matches(pid: int, expected: list[str]) -> bool:
735
+ try:
736
+ found = _windows_inspect(pid)
737
+ image = image_path(pid)
738
+ except OSError:
739
+ return False
740
+ if found is None or found["uid"] != 0 or image is None or not expected:
741
+ return False
742
+ want = os.path.expanduser(expected[0])
743
+ if not want.lower().endswith(".exe"):
744
+ want += ".exe"
745
+ wanted = [want, *filter(None, [venv_base(want)])]
746
+ try:
747
+ actual = os.path.normcase(os.path.realpath(image))
748
+ return any(actual == os.path.normcase(os.path.realpath(w)) for w in wanted)
749
+ except (OSError, ValueError):
750
+ return False