@simplexai/localmodels-linux-x64 0.1.0-dev.44 → 0.1.0-dev.47

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 (86) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +81 -83
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +0 -1
  5. package/modules/localmodels/bifrost_checks.py +3 -127
  6. package/modules/localmodels/bifrost_clients.py +1 -1
  7. package/modules/localmodels/bifrost_config.py +2 -2
  8. package/modules/localmodels/bifrost_pi.py +1 -1
  9. package/modules/localmodels/budget.py +16 -1
  10. package/modules/localmodels/catalog.json +165 -50
  11. package/modules/localmodels/catalog.py +20 -5
  12. package/modules/localmodels/catalog_recipes.py +9 -1
  13. package/modules/localmodels/context_policy.py +32 -9
  14. package/modules/localmodels/deploy.py +20 -14
  15. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +98 -0
  16. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +41 -1
  17. package/modules/localmodels/engines.py +28 -2
  18. package/modules/localmodels/estimator.py +12 -3
  19. package/modules/localmodels/gateway.py +50 -15
  20. package/modules/localmodels/gateway_accept.py +8 -5
  21. package/modules/localmodels/gateway_bifrost.py +108 -34
  22. package/modules/localmodels/gateway_cli.py +5 -2
  23. package/modules/localmodels/gateway_requests.py +9 -2
  24. package/modules/localmodels/gguf.py +6 -2
  25. package/modules/localmodels/harness.py +38 -11
  26. package/modules/localmodels/harness_gateway.py +1 -1
  27. package/modules/localmodels/harness_probe.py +60 -13
  28. package/modules/localmodels/hosts.py +7 -20
  29. package/modules/localmodels/library_gateway.py +12 -9
  30. package/modules/localmodels/library_pricing.py +7 -9
  31. package/modules/localmodels/library_state.py +6 -4
  32. package/modules/localmodels/npm_transport.py +62 -54
  33. package/modules/localmodels/probe.py +38 -11
  34. package/modules/localmodels/process_identity.py +47 -33
  35. package/modules/localmodels/process_identity_linux.py +135 -0
  36. package/modules/localmodels/process_windows.py +150 -1
  37. package/modules/localmodels/recommend.py +1 -1
  38. package/modules/localmodels/recommend_cli.py +2 -2
  39. package/modules/localmodels/remote_ops.py +14 -6
  40. package/modules/localmodels/remote_ops_download.py +1 -1
  41. package/modules/localmodels/remote_ops_verify.py +0 -33
  42. package/modules/localmodels/runtime_install.py +2 -1
  43. package/modules/localmodels/runtime_io.py +149 -34
  44. package/modules/localmodels/runtime_windows_acl.py +100 -0
  45. package/modules/localmodels/service_probe.py +26 -20
  46. package/modules/localmodels/setup_inspection.py +132 -36
  47. package/modules/localmodels/setup_text.py +14 -0
  48. package/modules/localmodels/source_byok.py +6 -3
  49. package/modules/localmodels/source_cli.py +8 -1
  50. package/modules/localmodels/stack.py +1 -5
  51. package/modules/localmodels/stack_args.py +6 -8
  52. package/modules/localmodels/stack_binding.py +61 -3
  53. package/modules/localmodels/stack_compose.py +3 -8
  54. package/modules/localmodels/stack_events.py +2 -1
  55. package/modules/localmodels/stack_lifecycle.py +7 -4
  56. package/modules/localmodels/stack_plan.py +1 -4
  57. package/modules/localmodels/stack_ports.py +0 -1
  58. package/modules/localmodels/stack_run.py +15 -30
  59. package/modules/localmodels/stack_suite.py +23 -46
  60. package/modules/localmodels/stack_summary.py +0 -1
  61. package/modules/localmodels/stack_try.py +3 -92
  62. package/modules/localmodels/stack_up.py +7 -3
  63. package/modules/localmodels/stack_update.py +5 -5
  64. package/modules/localmodels/stack_view_apply.py +1 -1
  65. package/modules/localmodels/stack_view_llm.py +1 -1
  66. package/modules/localmodels/stack_view_sandbox.py +3 -3
  67. package/modules/localmodels/stack_view_text.py +0 -1
  68. package/modules/localmodels/stack_view_words.py +0 -1
  69. package/modules/localmodels/stack_warm.py +18 -7
  70. package/modules/localmodels/strata_poly_server.py +4 -2
  71. package/modules/localmodels/suite.py +4 -7
  72. package/modules/localmodels/transport.py +7 -1
  73. package/modules/localmodels/tui_dialogs.py +0 -1
  74. package/modules/localmodels/web/view/view.css +0 -3
  75. package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/METADATA +1 -1
  76. package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/RECORD +78 -80
  77. package/package.json +1 -1
  78. package/tool.json +1 -1
  79. package/modules/localmodels/bifrost_search.py +0 -66
  80. package/modules/localmodels/gateway_search.py +0 -223
  81. package/modules/localmodels/search-ddgs-9.16.1.txt +0 -222
  82. package/modules/localmodels/search_server.py +0 -474
  83. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/WHEEL +0 -0
  84. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/entry_points.txt +0 -0
  85. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/licenses/NOTICE +0 -0
  86. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -415,38 +415,6 @@ def _verify_tts(root: str, p: remote_ops.VerifyParams) -> None:
415
415
  )
416
416
 
417
417
 
418
- SEARCH_ATTEMPTS = 3 # free engines throttle by exit IP: aws-l4 answered 2 of 3 queries 8 s apart
419
- SEARCH_RETRY_S = 5.0
420
-
421
-
422
- def _verify_search(root: str, p: remote_ops.VerifyParams) -> None:
423
- """A real web search answers with at least one result page; the engine named is the one that
424
- answered (DuckDuckGo unless it is rate limited). Only "no engine answered" is asked again, a
425
- few times and spaced out; any other failure is final."""
426
- started = time.monotonic()
427
- query = urllib.parse.urlencode({"q": remote_ops.SEARCH_QUERY, "format": "json"})
428
- for attempt in range(1, SEARCH_ATTEMPTS + 1):
429
- try:
430
- resp = remote_ops._http(f"{root}/search?{query}", p["api_key"], timeout=120)
431
- break
432
- except urllib.error.HTTPError as exc:
433
- if exc.code != 502 or json.loads(exc.read(1024)) != {
434
- "error": "SEARCH_PROVIDER_UNAVAILABLE"
435
- }:
436
- raise
437
- if attempt == SEARCH_ATTEMPTS:
438
- raise RuntimeError("SEARCH_PROVIDER_UNAVAILABLE") from None
439
- time.sleep(SEARCH_RETRY_S)
440
- results = resp.get("results")
441
- if not isinstance(results, list) or not all(isinstance(r, dict) for r in results):
442
- raise ValueError("invalid search results")
443
- urls = [str(r.get("url") or "") for r in results]
444
- found = [u for u in urls if u.startswith(("http://", "https://"))]
445
- engine = str(results[0].get("engine") or "") if results else ""
446
- answer = f"{len(found)} results via {engine or '?'}"
447
- _report(bool(found), answer, started, "the search returned no results page")
448
-
449
-
450
418
  CONTRACTS = {
451
419
  "systemone": _verify_decision,
452
420
  "health": lambda root, p: remote_ops.emit(
@@ -456,5 +424,4 @@ CONTRACTS = {
456
424
  "rerank": _verify_rerank,
457
425
  "stt": _verify_stt,
458
426
  "tts": _verify_tts,
459
- "search": _verify_search,
460
427
  }
@@ -84,7 +84,8 @@ def _fetch_modules(
84
84
  nonlocal shown
85
85
  with lock:
86
86
  if update.get("kind") != "progress":
87
- if update.get("state") != "reused":
87
+ # ~120 modules download at once: per-module connects and reuse are noise
88
+ if update.get("state") not in ("reused", "connecting"):
88
89
  event(update)
89
90
  return
90
91
  count = int(update["completed"])
@@ -19,12 +19,13 @@ import urllib.error
19
19
  import urllib.parse
20
20
  import urllib.request
21
21
  import zipfile
22
+ from collections import deque
22
23
  from collections.abc import Callable
23
24
  from pathlib import Path
24
25
  from typing import Any, cast
25
26
 
26
27
  # remote_ops before remote_ops_download: the bundle's entry module loads its siblings
27
- from localmodels import region, remote_ops, remote_ops_download, runtime_windows_acl
28
+ from localmodels import npm_transport, region, remote_ops, remote_ops_download, runtime_windows_acl
28
29
 
29
30
  Event = Callable[[dict[str, Any]], None]
30
31
 
@@ -222,6 +223,13 @@ def _extract_archive(archive: Path, target: Path) -> None:
222
223
 
223
224
 
224
225
  DOWNLOAD_ATTEMPTS = 5
226
+ # One timeout covers the connection, the response headers and each read: a retry resumes the
227
+ # kept bytes, so a stalled connection is cheap to replace and needs no separate read timeout.
228
+ DOWNLOAD_TIMEOUT_S = 15
229
+ # A host that delivers less than SLOW_BYTES_PER_S over a whole SLOW_WINDOW_S window is left for
230
+ # another host serving the same file, when one is still worth trying (see ``download``).
231
+ SLOW_BYTES_PER_S = 512 * 1024
232
+ SLOW_WINDOW_S = 15
225
233
  _RETRY_HTTP = frozenset({408, 425, 429, 500, 502, 503, 504})
226
234
 
227
235
 
@@ -229,13 +237,16 @@ class RuntimeDownloadError(ValueError):
229
237
  """A pinned artifact could not be downloaded. The message names only the host, the file,
230
238
  a fixed reason and the bytes kept: no URL query, header or response body."""
231
239
 
232
- def __init__(self, url: str, reason: str, kept: int, *, retryable: bool) -> None:
240
+ def __init__(
241
+ self, url: str, reason: str, kept: int, *, retryable: bool, slow: bool = False
242
+ ) -> None:
233
243
  parts = urllib.parse.urlsplit(url)
234
244
  self.host = parts.hostname or "the download host"
235
245
  self.file = parts.path.rsplit("/", 1)[-1] or "artifact"
236
246
  self.reason = reason
237
247
  self.kept = kept
238
248
  self.retryable = retryable
249
+ self.slow = slow # the host was left for being too slow, not for failing
239
250
  message = f"Download of {self.file} from {self.host} failed: {reason}."
240
251
  if kept:
241
252
  message += f" {kept} bytes are kept; a retry resumes from there."
@@ -248,16 +259,19 @@ class RuntimeDownloadError(ValueError):
248
259
 
249
260
 
250
261
  class _TransferError(Exception):
251
- def __init__(self, reason: str, *, retryable: bool = True) -> None:
262
+ def __init__(self, reason: str, *, retryable: bool = True, slow: bool = False) -> None:
252
263
  super().__init__(reason)
253
264
  self.reason = reason
254
265
  self.retryable = retryable
266
+ self.slow = slow
255
267
 
256
268
 
257
269
  def _network_reason(exc: BaseException) -> tuple[str, bool]:
258
270
  """A fixed description of a network failure, and whether trying again can help."""
259
271
  if isinstance(exc, urllib.error.HTTPError):
260
272
  return f"HTTP {exc.code}", exc.code in _RETRY_HTTP
273
+ if isinstance(exc, npm_transport.UnsafeRedirect):
274
+ return "the server redirected to a URL without HTTPS or with credentials", False
261
275
  if isinstance(exc, urllib.error.URLError) and isinstance(exc.reason, BaseException):
262
276
  exc = exc.reason
263
277
  if isinstance(exc, ssl.SSLCertVerificationError):
@@ -304,14 +318,25 @@ class Rate:
304
318
  return found
305
319
 
306
320
 
307
- def _transfer(url: str, part: Path, limit: int, event: Event, *, retry_missing: bool) -> None:
308
- """One request for the rest of ``part``; network failures raise _TransferError."""
321
+ def _transfer(
322
+ url: str,
323
+ part: Path,
324
+ limit: int,
325
+ event: Event,
326
+ *,
327
+ retry_missing: bool,
328
+ slow_abort: bool = False,
329
+ clock: Callable[[], float] = time.monotonic,
330
+ ) -> None:
331
+ """One request for the rest of ``part``; network failures raise _TransferError. With
332
+ ``slow_abort``, a whole SLOW_WINDOW_S below SLOW_BYTES_PER_S raises one marked ``slow``."""
309
333
  have = part.stat().st_size
310
334
  request = urllib.request.Request(url, headers={"User-Agent": "localmodels-runtime"})
311
335
  if have:
312
336
  request.add_header("Range", f"bytes={have}-")
313
337
  try:
314
- source = urllib.request.urlopen(request, timeout=30)
338
+ # Redirects stay on HTTPS without credentials, as for every npm download of this tool.
339
+ source = npm_transport.https_opener().open(request, timeout=DOWNLOAD_TIMEOUT_S)
315
340
  except urllib.error.HTTPError as exc:
316
341
  if exc.code == 404 and retry_missing:
317
342
  raise _TransferError("HTTP 404") from None
@@ -331,6 +356,7 @@ def _transfer(url: str, part: Path, limit: int, event: Event, *, retry_missing:
331
356
  length = source.headers.get("Content-Length")
332
357
  total = completed + int(length) if length and length.isdigit() else None
333
358
  rate = Rate(completed)
359
+ window, window_bytes = clock(), 0
334
360
  with part.open("ab" if resumed else "wb") as output:
335
361
  while True:
336
362
  try:
@@ -344,6 +370,17 @@ def _transfer(url: str, part: Path, limit: int, event: Event, *, retry_missing:
344
370
  output.truncate(0)
345
371
  raise ValueError("Runtime artifact exceeds size limit")
346
372
  output.write(chunk)
373
+ window_bytes += len(chunk)
374
+ elapsed = clock() - window
375
+ # The rest arriving within one window at the floor is not worth another host
376
+ # (it also keeps a finished file from being left on its last read).
377
+ near_done = (
378
+ total is not None and total - completed <= SLOW_BYTES_PER_S * SLOW_WINDOW_S
379
+ )
380
+ if slow_abort and elapsed >= SLOW_WINDOW_S and not near_done:
381
+ if window_bytes < SLOW_BYTES_PER_S * elapsed:
382
+ raise _TransferError("the download is too slow", slow=True)
383
+ window, window_bytes = window + elapsed, 0
347
384
  event(
348
385
  {
349
386
  "kind": "progress",
@@ -375,6 +412,11 @@ def download_urls(url: str) -> list[str]:
375
412
  return region.prefer(region.current_region(), [u for u in every if u not in cn], cn)
376
413
 
377
414
 
415
+ def _host(url: str) -> str:
416
+ """The host name of ``url`` alone: events never carry a path, query or credentials."""
417
+ return urllib.parse.urlsplit(url).hostname or ""
418
+
419
+
378
420
  def download(
379
421
  artifact: dict[str, Any],
380
422
  destination: Path,
@@ -383,16 +425,25 @@ def download(
383
425
  attempts: int = DOWNLOAD_ATTEMPTS,
384
426
  pause: Callable[[float], None] = time.sleep,
385
427
  retry_missing: bool = False,
428
+ clock: Callable[[], float] = time.monotonic,
386
429
  ) -> None:
387
430
  """Fetch a pinned artifact into ``destination``, which must not exist. Network failures are
388
431
  retried with backoff and each retry resumes ``destination.part``; a part left by an earlier
389
- call is resumed too. Only content matching the pinned digest is published. When every
390
- retry against one host fails, the next host serving the same file (``download_urls``) is
391
- tried, and a success on the other region's side switches the region."""
392
- urls = download_urls(artifact["url"])
432
+ call is resumed too, also from another host, since the bytes are pinned by digest. Only
433
+ content matching the pinned digest is published.
434
+
435
+ The hosts serving the same file (``download_urls``) are tried in turn. A host that fails
436
+ every retry is dropped. A host slower than SLOW_BYTES_PER_S is left once for the next host
437
+ and queued again last, never to be left for slowness again; only a host followed by one not
438
+ yet left for slowness may be left, so a uniformly slow network switches once and the last
439
+ host always finishes. A success on the other region's side after a failure on the preferred
440
+ side switches the region."""
441
+ urls = deque(download_urls(artifact["url"]))
393
442
  preferred = remote_ops_download.side(urls[0])
394
443
  failed_preferred = False
395
- for index, url in enumerate(urls):
444
+ slow: set[str] = set() # hosts already left once for slowness
445
+ while urls:
446
+ url = urls.popleft()
396
447
  try:
397
448
  _download_from(
398
449
  url,
@@ -402,11 +453,30 @@ def download(
402
453
  attempts=attempts,
403
454
  pause=pause,
404
455
  retry_missing=retry_missing,
456
+ slow_abort=url not in slow and any(u not in slow for u in urls),
457
+ clock=clock,
405
458
  )
406
- except RuntimeDownloadError:
407
- if index + 1 == len(urls):
459
+ except RuntimeDownloadError as exc:
460
+ if exc.slow:
461
+ slow.add(url)
462
+ urls.append(url)
463
+ else:
464
+ # Only a failure moves the region: the region also picks model hubs, so a slow
465
+ # npm mirror must not send a cn user's model downloads to huggingface.co.
466
+ failed_preferred = failed_preferred or remote_ops_download.side(url) == preferred
467
+ if not urls:
408
468
  raise
409
- failed_preferred = failed_preferred or remote_ops_download.side(url) == preferred
469
+ event(
470
+ {
471
+ "kind": "stage",
472
+ "stage": "download",
473
+ "state": "switching",
474
+ "from": _host(url),
475
+ "to": _host(urls[0]),
476
+ "reason": "slow" if exc.slow else exc.reason,
477
+ "completed": exc.kept,
478
+ }
479
+ )
410
480
  continue
411
481
  used = remote_ops_download.side(url)
412
482
  if failed_preferred and used and used != preferred:
@@ -423,6 +493,8 @@ def _download_from(
423
493
  attempts: int,
424
494
  pause: Callable[[float], None],
425
495
  retry_missing: bool,
496
+ slow_abort: bool = False,
497
+ clock: Callable[[], float] = time.monotonic,
426
498
  ) -> None:
427
499
  part = destination.with_name(destination.name + ".part")
428
500
  if destination.exists() or destination.is_symlink():
@@ -435,39 +507,82 @@ def _download_from(
435
507
  flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
436
508
  os.close(os.open(part, flags, 0o600))
437
509
  private_permissions(part, created=True)
438
- attempt = 0
510
+ # Bytes kept by an earlier call: they may be another version's when the pin changed.
511
+ resumed = part.stat().st_size > 0
512
+ if resumed and _matches(part, artifact):
513
+ _publish(part, destination)
514
+ return
439
515
  while True:
440
- attempt += 1
441
- try:
442
- _transfer(url, part, artifact["maxBytes"], event, retry_missing=retry_missing)
443
- break
444
- except _TransferError as exc:
445
- kept = part.stat().st_size
446
- if not exc.retryable or attempt >= attempts:
447
- raise RuntimeDownloadError(url, exc.reason, kept, retryable=exc.retryable) from None
448
- wait = min(30, 2**attempt)
516
+ attempt = 0
517
+ while True:
518
+ attempt += 1
449
519
  event(
450
520
  {
451
521
  "kind": "stage",
452
522
  "stage": "download",
453
- "state": "retrying",
523
+ "state": "connecting",
524
+ "host": _host(url),
454
525
  "attempt": attempt,
455
526
  "attempts": attempts,
456
- "reason": exc.reason,
457
- "completed": kept,
458
- "waitSeconds": wait,
459
527
  }
460
528
  )
461
- pause(wait)
462
- digest = hashlib.new(artifact["algorithm"])
463
- with part.open("rb") as stream:
464
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
465
- digest.update(chunk)
466
- if digest.hexdigest() != artifact["digest"]:
529
+ try:
530
+ _transfer(
531
+ url,
532
+ part,
533
+ artifact["maxBytes"],
534
+ event,
535
+ retry_missing=retry_missing,
536
+ slow_abort=slow_abort,
537
+ clock=clock,
538
+ )
539
+ break
540
+ except _TransferError as exc:
541
+ kept = part.stat().st_size
542
+ if exc.slow: # not retried here: the caller moves to another host
543
+ raise RuntimeDownloadError(
544
+ url, exc.reason, kept, retryable=True, slow=True
545
+ ) from None
546
+ if not exc.retryable or attempt >= attempts:
547
+ raise RuntimeDownloadError(
548
+ url, exc.reason, kept, retryable=exc.retryable
549
+ ) from None
550
+ wait = min(30, 2**attempt)
551
+ event(
552
+ {
553
+ "kind": "stage",
554
+ "stage": "download",
555
+ "state": "retrying",
556
+ "attempt": attempt,
557
+ "attempts": attempts,
558
+ "reason": exc.reason,
559
+ "completed": kept,
560
+ "waitSeconds": wait,
561
+ }
562
+ )
563
+ pause(wait)
564
+ if _matches(part, artifact):
565
+ break
566
+ if resumed: # restart once from zero on this host rather than blame it
567
+ part.write_bytes(b"")
568
+ resumed = False
569
+ continue
467
570
  part.unlink()
468
571
  raise RuntimeDownloadError(
469
572
  url, "the content does not match the pinned digest", 0, retryable=True
470
573
  )
574
+ _publish(part, destination)
575
+
576
+
577
+ def _matches(part: Path, artifact: dict[str, Any]) -> bool:
578
+ digest = hashlib.new(artifact["algorithm"])
579
+ with part.open("rb") as stream:
580
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
581
+ digest.update(chunk)
582
+ return bool(digest.hexdigest() == artifact["digest"])
583
+
584
+
585
+ def _publish(part: Path, destination: Path) -> None:
471
586
  part.rename(destination)
472
587
  private_permissions(destination)
473
588
 
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import functools
6
+ import os
6
7
  from pathlib import Path
7
8
  from typing import Any
8
9
 
@@ -28,6 +29,9 @@ def api() -> tuple[Any, Any]:
28
29
  "GetSecurityDescriptorDacl": [pointer, int_ptr, out, int_ptr],
29
30
  "GetSecurityDescriptorControl": [pointer, ushort_ptr, uint_ptr],
30
31
  "GetAce": [pointer, integer, out],
32
+ "GetSecurityInfo": [pointer, integer, integer, out, out, out, out, out],
33
+ "CreateWellKnownSid": [integer, pointer, pointer, uint_ptr],
34
+ "CheckTokenMembership": [pointer, pointer, int_ptr],
31
35
  }
32
36
  for name, arguments in signatures.items():
33
37
  function = getattr(advapi, name)
@@ -70,6 +74,102 @@ def identity() -> tuple[Any, Any, Any, Any, str]:
70
74
  kernel.CloseHandle(token)
71
75
 
72
76
 
77
+ @functools.lru_cache(maxsize=1)
78
+ def is_administrator() -> bool:
79
+ """Whether this process's user is in BUILTIN\\Administrators, enabled in its token or in the
80
+ UAC-linked elevated token: the same administrator who installed elevated, now resuming from a
81
+ normal (filtered) desktop session."""
82
+ import ctypes
83
+
84
+ advapi, kernel = api()
85
+ administrators = ctypes.create_string_buffer(68) # SECURITY_MAX_SID_SIZE
86
+ size = ctypes.c_uint(ctypes.sizeof(administrators))
87
+ # WinBuiltinAdministratorsSid (26)
88
+ if not advapi.CreateWellKnownSid(26, None, administrators, ctypes.byref(size)):
89
+ raise ValueError("Cannot construct the Administrators SID")
90
+
91
+ def member(token: Any) -> bool:
92
+ found = ctypes.c_int()
93
+ if not advapi.CheckTokenMembership(token, administrators, ctypes.byref(found)):
94
+ raise ValueError("Cannot check Administrators membership")
95
+ return bool(found.value)
96
+
97
+ if member(None):
98
+ return True
99
+ token = ctypes.c_void_p()
100
+ if not advapi.OpenProcessToken(kernel.GetCurrentProcess(), 0x8, ctypes.byref(token)):
101
+ raise ValueError("Cannot query the process token")
102
+ try:
103
+ elevation, returned = ctypes.c_uint(), ctypes.c_uint()
104
+ # TokenElevationType (18): TokenElevationTypeLimited (3) is the filtered half of a UAC pair.
105
+ if not advapi.GetTokenInformation(
106
+ token, 18, ctypes.byref(elevation), ctypes.sizeof(elevation), ctypes.byref(returned)
107
+ ):
108
+ raise ValueError("Cannot query the token elevation type")
109
+ if elevation.value != 3:
110
+ return False
111
+ linked = ctypes.c_void_p()
112
+ # TokenLinkedToken (19)
113
+ if not advapi.GetTokenInformation(
114
+ token, 19, ctypes.byref(linked), ctypes.sizeof(linked), ctypes.byref(returned)
115
+ ):
116
+ raise ValueError("Cannot query the linked elevated token")
117
+ try:
118
+ return member(linked)
119
+ finally:
120
+ kernel.CloseHandle(linked)
121
+ finally:
122
+ kernel.CloseHandle(token)
123
+
124
+
125
+ def open_unfollowed(path: Path) -> int:
126
+ """A read-only descriptor for ``path`` itself, never a link or junction's target, so its
127
+ attributes, owner and bytes all come from one object. Others may still replace or delete the
128
+ path meanwhile. FileNotFoundError when it is missing."""
129
+ import importlib
130
+
131
+ winapi: Any = importlib.import_module("_winapi")
132
+ msvcrt: Any = importlib.import_module("msvcrt")
133
+ # FILE_SHARE_READ | FILE_SHARE_DELETE; FILE_FLAG_OPEN_REPARSE_POINT. The handle is not
134
+ # inheritable (no security attributes).
135
+ handle = winapi.CreateFile(
136
+ str(path), winapi.GENERIC_READ, 0x1 | 0x4, winapi.NULL, winapi.OPEN_EXISTING, 0x00200000, 0
137
+ )
138
+ try:
139
+ return int(msvcrt.open_osfhandle(handle, os.O_RDONLY))
140
+ except OSError:
141
+ winapi.CloseHandle(handle)
142
+ raise
143
+
144
+
145
+ def descriptor_owner_sid(fd: int) -> str:
146
+ """The owner of the file open on ``fd``, as a string SID."""
147
+ import ctypes
148
+ import importlib
149
+
150
+ msvcrt: Any = importlib.import_module("msvcrt")
151
+ advapi, kernel = api()
152
+ owner, descriptor = ctypes.c_void_p(), ctypes.c_void_p()
153
+ try:
154
+ # SE_FILE_OBJECT (1), OWNER_SECURITY_INFORMATION (1)
155
+ error = advapi.GetSecurityInfo(
156
+ msvcrt.get_osfhandle(fd),
157
+ 1,
158
+ 0x1,
159
+ ctypes.byref(owner),
160
+ None,
161
+ None,
162
+ None,
163
+ ctypes.byref(descriptor),
164
+ )
165
+ if error:
166
+ raise OSError(error, "cannot read the file's owner")
167
+ return sid_text(advapi, kernel, owner)
168
+ finally:
169
+ if descriptor.value:
170
+ kernel.LocalFree(descriptor)
171
+
172
+
73
173
  def private_permissions(path: Path, created: bool) -> None:
74
174
  """Query owner/DACL only; protect a newly created DACL without changing owner/group/SACL."""
75
175
  import ctypes
@@ -19,6 +19,7 @@ from __future__ import annotations
19
19
  import argparse
20
20
  import csv
21
21
  import json
22
+ import ntpath
22
23
  import os
23
24
  import re
24
25
  import shlex
@@ -35,9 +36,10 @@ from concurrent.futures import ThreadPoolExecutor
35
36
  from pathlib import Path
36
37
 
37
38
  try:
38
- from localmodels import process_identity, remote_ops_launchd
39
+ from localmodels import process_identity, process_windows, remote_ops_launchd
39
40
  except ImportError:
40
41
  import process_identity # type: ignore[import-not-found,no-redef]
42
+ import process_windows # type: ignore[import-not-found,no-redef]
41
43
  import remote_ops_launchd # type: ignore[import-not-found,no-redef]
42
44
 
43
45
  _TIMEOUT_S = 10
@@ -64,9 +66,21 @@ def _run(argv: list[str], timeout: float = _TIMEOUT_S) -> tuple[int | None, str,
64
66
 
65
67
  def _nvidia_smi() -> str | None:
66
68
  found = shutil.which("nvidia-smi")
67
- if found is None and os.path.exists("/usr/lib/wsl/lib/nvidia-smi"):
68
- found = "/usr/lib/wsl/lib/nvidia-smi"
69
- return found
69
+ if found:
70
+ return found
71
+ if sys.platform == "win32":
72
+ system_root = os.environ.get("SystemRoot") or r"C:\Windows"
73
+ program_files = os.environ.get("ProgramFiles") or r"C:\Program Files"
74
+ for candidate in (
75
+ ntpath.join(system_root, "System32", "nvidia-smi.exe"),
76
+ ntpath.join(program_files, "NVIDIA Corporation", "NVSMI", "nvidia-smi.exe"),
77
+ ):
78
+ if os.path.exists(candidate):
79
+ return candidate
80
+ return None
81
+ if os.path.exists("/usr/lib/wsl/lib/nvidia-smi"):
82
+ return "/usr/lib/wsl/lib/nvidia-smi"
83
+ return None
70
84
 
71
85
 
72
86
  def _read(path: str) -> str:
@@ -136,6 +150,10 @@ def _linux_identity(pid: int, root: str) -> tuple[int, int, int, int, str] | Non
136
150
 
137
151
  def in_suite(pid: int, root: str = "/") -> bool:
138
152
  """Only a verified owned deployment may reclaim capacity from its suite membership."""
153
+ if sys.platform == "win32":
154
+ # Windows has no systemd slice; every verified deployment this tool owns belongs to
155
+ # the stack, as on macOS (parse_darwin_ps).
156
+ return process_owned(pid, root) is True
139
157
  identity = _linux_identity(pid, root)
140
158
  cgroup = _text(_at(root, f"/proc/{pid}") + "/cgroup")
141
159
  return (
@@ -221,25 +239,13 @@ def _linux_deployment(pid: int, root: str, argv: list[str], cgroup: str) -> str
221
239
  return None
222
240
 
223
241
 
224
- WINDOWS_DEPLOYMENTS = "~/.local/share/localmodels/deployments" # deploy.DEFAULT_BASE_DIR's
242
+ WINDOWS_DEPLOYMENTS = process_windows.WINDOWS_DEPLOYMENTS
225
243
 
226
244
 
227
245
  def _windows_owned(pid: int, deployments: str = WINDOWS_DEPLOYMENTS) -> bool | None:
228
- """Windows: a live receipt of one of this user's nohup deployments names the process."""
229
- try:
230
- found = process_identity.inspect(pid)
231
- except PermissionError:
232
- return False # protected or elevated process of another token: never this user's
233
- except OSError:
234
- return None
235
- if found is None:
236
- return None
237
- if found["uid"] != 0:
238
- return False
239
- for receipt in Path(os.path.expanduser(deployments)).glob("*/server.pid"):
240
- if process_identity.status(receipt) == ("active", pid):
241
- return True
242
- return False
246
+ """Windows: a live receipt of one of this user's nohup deployments names the process or
247
+ a verified same-user ancestor (e.g. ``strata_poly_server.py`` -> ``strata-poly.exe``)."""
248
+ return process_windows.windows_owned(pid, deployments)
243
249
 
244
250
 
245
251
  def process_owned(pid: int, root: str = "/") -> bool | None: