@simplexai/localmodels-darwin-arm64 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
@@ -11,6 +11,7 @@ import ctypes
11
11
  import datetime as dt
12
12
  import glob
13
13
  import json
14
+ import ntpath
14
15
  import os
15
16
  import platform
16
17
  import re
@@ -202,7 +203,8 @@ _VERSION_RE = re.compile(r"version:\s*(\d+)\s*\(([0-9a-f]+)\)")
202
203
  _SEMVER_RE = re.compile(r"version:\s*([\w.\-]+)\s*\(build\s*(\d+),\s*commit\s*([0-9a-f]+)\)")
203
204
  SERVICE_PORTS = (8080, 9931, 18100, 18321, 18331, 18351, 18352, 18370)
204
205
  _CONTAINER_CGROUP_RE = re.compile(r"docker|kubepods|containerd|libpod|lxc|crio")
205
- _CUDA_VERSION_RE = re.compile(r"CUDA(?:\s+UMD)?\s+Version\s*:\s*(\d+(?:\.\d+)*)", re.IGNORECASE)
206
+ _CUDA_RE = re.compile(r"\bCUDA(?:\s+(?:UMD|Driver|API))?\s+Version\s*:\s*(\d+(?:\.\d+)*)", re.I)
207
+ _DRIVER_RE = re.compile(r"\b(?:Driver|KMD)\s+Version\s*:\s*(\d+(?:\.\d+)*)", re.I)
206
208
  HOST_LIBRARIES = ("libgomp.so.1",)
207
209
  DETAIL_FIELDS = ("compute_cap", "memory.reserved", "display_active") # nvidia-smi names
208
210
  _UNLIMITED = 1 << 60 # cgroup v1 reports "no limit" as a page-aligned LONG_MAX
@@ -300,10 +302,19 @@ def ram() -> tuple[int, int]:
300
302
  return 0, 0
301
303
 
302
304
 
305
+ def _win_system32(name: str) -> str:
306
+ return ntpath.join(os.environ.get("SystemRoot") or r"C:\Windows", "System32", name)
307
+
308
+
303
309
  def _nvidia_smi() -> str | None:
304
- return shutil.which("nvidia-smi") or (
305
- "/usr/lib/wsl/lib/nvidia-smi" if os.path.exists("/usr/lib/wsl/lib/nvidia-smi") else None
306
- )
310
+ if found := shutil.which("nvidia-smi"):
311
+ return found
312
+ if sys.platform != "win32":
313
+ wsl = "/usr/lib/wsl/lib/nvidia-smi"
314
+ return wsl if os.path.exists(wsl) else None
315
+ pf = os.environ.get("ProgramFiles") or r"C:\Program Files"
316
+ nvsmi = ntpath.join(pf, "NVIDIA Corporation", "NVSMI", "nvidia-smi.exe")
317
+ return next((p for p in (_win_system32("nvidia-smi.exe"), nvsmi) if os.path.exists(p)), None)
307
318
 
308
319
 
309
320
  def parse_gpu_csv(text: str) -> list[GPU]:
@@ -341,13 +352,17 @@ def parse_gpu_csv(text: str) -> list[GPU]:
341
352
 
342
353
  def parse_cuda_version(text: str) -> str:
343
354
  """Driver-supported CUDA version from ``nvidia-smi`` banner or ``-q`` text, or empty."""
344
- match = _CUDA_VERSION_RE.search(text)
345
- return match.group(1) if match else ""
355
+ return m.group(1) if (m := _CUDA_RE.search(text)) else ""
356
+
357
+
358
+ def parse_driver_version(text: str) -> str:
359
+ """NVIDIA driver/KMD version from ``nvidia-smi`` banner or ``-q`` text, or empty."""
360
+ return m.group(1) if (m := _DRIVER_RE.search(text)) else ""
346
361
 
347
362
 
348
363
  def _load_cuda_driver() -> ctypes.CDLL | None:
349
364
  names: tuple[str, ...] = (
350
- ("nvcuda.dll",)
365
+ ("nvcuda.dll", _win_system32("nvcuda.dll"))
351
366
  if sys.platform == "win32"
352
367
  else ("libcuda.so.1", "libcuda.so", "/usr/lib/wsl/lib/libcuda.so.1")
353
368
  if sys.platform.startswith("linux")
@@ -389,8 +404,15 @@ def _nvidia(errors: list[dict[str, str]]) -> tuple[dict[str, str] | None, list[G
389
404
  errors.append({"source": "nvidia-smi", "error": (err or out).strip()[:300]})
390
405
  return None, []
391
406
  gpus = parse_gpu_csv(out)
392
- cuda_version = _cuda_driver_version() or parse_cuda_version(_run([exe])[1])
393
- drv = gpus[0]["driver_version"] if gpus else ""
407
+ drv = "" if not gpus or gpus[0]["driver_version"].startswith("[") else gpus[0]["driver_version"]
408
+ cuda_version = _cuda_driver_version()
409
+ if not cuda_version or not drv:
410
+ banner = _run([exe])[1]
411
+ cuda_version = cuda_version or parse_cuda_version(banner)
412
+ drv = drv or parse_driver_version(banner)
413
+ for gpu in gpus:
414
+ if not gpu["driver_version"] or gpu["driver_version"].startswith("["):
415
+ gpu["driver_version"] = drv
394
416
  return {"driver_version": drv, "cuda_version": cuda_version}, gpus
395
417
 
396
418
 
@@ -428,10 +450,15 @@ def shared_libraries(names: Sequence[str] = HOST_LIBRARIES) -> dict[str, bool]:
428
450
 
429
451
 
430
452
  def _gpu_vendor_class() -> str:
453
+ exists = os.path.exists
431
454
  if sys.platform == "darwin":
432
455
  return "apple_silicon" if _arch() == "arm64" else "unknown"
433
- if os.path.exists("/proc/driver/nvidia/version") or shutil.which("nvidia-smi.exe"):
434
- return "nvidia" # nvidia-smi.exe: Windows' driver installs it in System32
456
+ if sys.platform == "win32":
457
+ return "nvidia" if _nvidia_smi() or exists(_win_system32("nvcuda.dll")) else "unknown"
458
+ if exists("/proc/driver/nvidia/version") or exists("/usr/lib/wsl/lib/nvidia-smi"):
459
+ return "nvidia"
460
+ if exists("/usr/lib/wsl/lib/libcuda.so.1"):
461
+ return "nvidia"
435
462
  root = "/sys/class/drm"
436
463
  try:
437
464
  cards = [e for e in sorted(os.listdir(root)) if e.startswith("card") and "-" not in e][:16]
@@ -10,8 +10,6 @@ from __future__ import annotations
10
10
  import ctypes
11
11
  import json
12
12
  import os
13
- import shlex
14
- import shutil
15
13
  import stat
16
14
  import subprocess
17
15
  import sys
@@ -19,6 +17,11 @@ import tempfile
19
17
  from pathlib import Path
20
18
  from typing import Any, TypedDict
21
19
 
20
+ try:
21
+ from localmodels import process_identity_linux
22
+ except ImportError: # run as a bare file from this directory
23
+ import process_identity_linux # type: ignore[import-not-found,no-redef]
24
+
22
25
 
23
26
  class Identity(TypedDict):
24
27
  pid: int
@@ -483,12 +486,43 @@ def kill_started(pid: int) -> None:
483
486
 
484
487
  # ── POSIX and shared ──
485
488
 
489
+ _IDENTITY_FIELDS = {"pid": int, "uid": int, "pgid": int, "started": str}
490
+
491
+
492
+ def _same_start(current: str, saved: str) -> bool:
493
+ return current == saved or (
494
+ sys.platform.startswith("linux") and process_identity_linux.same_start(current, saved)
495
+ )
496
+
497
+
498
+ def _valid_identity(saved: dict[str, Any]) -> bool:
499
+ return set(saved) == set(_IDENTITY_FIELDS) and all(
500
+ type(saved[k]) is t for k, t in _IDENTITY_FIELDS.items()
501
+ )
502
+
503
+
504
+ def matches(current: Identity | None, saved: object) -> bool:
505
+ """Whether ``current`` proves the same process instance recorded in ``saved``."""
506
+ if current is None or not isinstance(saved, dict) or not _valid_identity(saved):
507
+ return False
508
+ return (
509
+ current["pid"] == saved["pid"]
510
+ and current["uid"] == saved["uid"]
511
+ and current["pgid"] == saved["pgid"]
512
+ and _same_start(current["started"], saved["started"])
513
+ )
514
+
486
515
 
487
516
  def inspect(pid: int) -> Identity | None:
488
517
  if pid <= 1:
489
518
  return None
490
519
  if _windows():
491
520
  return _windows_inspect(pid)
521
+ if sys.platform.startswith("linux"):
522
+ found = process_identity_linux.inspect(pid)
523
+ if found is None:
524
+ return None
525
+ return {"pid": pid, "uid": found[0], "pgid": found[1], "started": found[2]}
492
526
  # LC_ALL=C keeps lstart in 5 English tokens (zh_CN outputs 4).
493
527
  result = subprocess.run(
494
528
  ["/bin/ps", "-p", str(pid), "-o", "uid=,pgid=,lstart=,stat="],
@@ -536,7 +570,7 @@ def status(pid_file: str | Path) -> tuple[str, int | None]:
536
570
  if current is None:
537
571
  return "inactive", None
538
572
  saved = json.loads(_private(Path(str(path) + ".identity.json")))
539
- if current == saved and current["uid"] == current_uid() and current["pgid"] == pid:
573
+ if matches(current, saved) and current["uid"] == current_uid() and current["pgid"] == pid:
540
574
  return "active", pid
541
575
  except (OSError, ValueError, subprocess.TimeoutExpired):
542
576
  pass
@@ -581,11 +615,9 @@ def _recorded(pid_file: Path) -> Identity | None:
581
615
  "a legacy PID file has no identity receipt; cannot prove ownership"
582
616
  ) from None
583
617
  return None
584
- fields = {"pid": int, "uid": int, "pgid": int, "started": str}
585
618
  if (
586
619
  not isinstance(saved, dict)
587
- or set(saved) != set(fields)
588
- or not all(type(saved[k]) is t for k, t in fields.items())
620
+ or not _valid_identity(saved)
589
621
  or int(_private(pid_file).strip()) != saved["pid"]
590
622
  ):
591
623
  raise ValueError("malformed identity receipt")
@@ -606,13 +638,17 @@ def stop(pid_file: str | Path, grace: float = 15.0) -> str:
606
638
  try:
607
639
  saved = _recorded(path)
608
640
  current = None if saved is None else inspect(saved["pid"])
609
- if saved is None or current is None or current["started"] != saved["started"]:
641
+ if (
642
+ saved is None
643
+ or current is None
644
+ or not _same_start(current["started"], saved["started"])
645
+ ):
610
646
  _forget(path)
611
647
  return "gone"
612
- if current != saved:
648
+ if not matches(current, saved):
613
649
  raise ValueError("the process identity does not match the receipt")
614
650
  if _windows():
615
- if windows_stop_tree(saved["pid"], saved, grace):
651
+ if windows_stop_tree(saved["pid"], current, grace):
616
652
  _forget(path)
617
653
  return "stopped"
618
654
  raise RuntimeError(
@@ -622,7 +658,7 @@ def stop(pid_file: str | Path, grace: float = 15.0) -> str:
622
658
  os.killpg(saved["pid"], sig)
623
659
  deadline = time.monotonic() + grace
624
660
  while time.monotonic() < deadline:
625
- if inspect(saved["pid"]) != saved:
661
+ if inspect(saved["pid"]) != current:
626
662
  _forget(path)
627
663
  return "stopped"
628
664
  time.sleep(0.1)
@@ -673,29 +709,7 @@ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
673
709
  """Read-only Linux argv proof (plus shebang); on Windows checks owned executable image path."""
674
710
  if _windows():
675
711
  return _windows_command_matches(pid, expected)
676
- try:
677
- process = Path(root) / "proc" / str(pid)
678
- if process.stat().st_uid != os.getuid():
679
- return False
680
- actual = process.joinpath("cmdline").read_bytes().decode().rstrip("\0").split("\0")
681
- if actual == expected:
682
- return True
683
- target = expected[0] if root == "/" else Path(root) / expected[0].lstrip("/")
684
- with open(target, "rb") as executable:
685
- header = executable.readline(512).decode()
686
- if not header.startswith("#!"):
687
- return False
688
- interp = shlex.split(header[2:].strip())
689
- if interp[:1] == ["/usr/bin/env"]:
690
- interp = interp[1:]
691
- if len(interp) != 1 or actual[1:] != expected:
692
- return False
693
- resolved = shutil.which(interp[0])
694
- return (
695
- resolved is not None and process.joinpath("exe").resolve() == Path(resolved).resolve()
696
- )
697
- except (OSError, ValueError, UnicodeError, IndexError):
698
- return False
712
+ return process_identity_linux.command_matches(pid, expected, root)
699
713
 
700
714
 
701
715
  def venv_base(python: str) -> str | None:
@@ -0,0 +1,135 @@
1
+ """Linux /proc process identity, legacy lstart compatibility, and argv proof; stdlib-only, Python 3.8+."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shlex
7
+ import shutil
8
+ import time
9
+ from pathlib import Path
10
+
11
+ # Receipts written before Linux switched from ``ps -o lstart=`` to /proc/<pid>/stat boot ticks
12
+ # hold wall-clock seconds derived from /proc/stat btime, which can drift by ~1-2 s under NTP.
13
+ _LEGACY_LSTART_TOLERANCE_S = 5.0
14
+ _ENGLISH_DAYS = frozenset(("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))
15
+ _ENGLISH_MONTHS = {
16
+ "Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4, "May": 5, "Jun": 6,
17
+ "Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10, "Nov": 11, "Dec": 12,
18
+ } # fmt: skip
19
+
20
+
21
+ def _status_euid(status_text: str) -> int | None:
22
+ for line in status_text.splitlines():
23
+ if line.startswith("Uid:"):
24
+ parts = line.split()
25
+ if len(parts) == 5 and all(part.isdigit() for part in parts[1:]):
26
+ return int(parts[2])
27
+ return None
28
+ return None
29
+
30
+
31
+ def inspect(pid: int, root: str = "/") -> tuple[int, int, str] | None:
32
+ """Return ``(euid, pgid, starttime_ticks)`` from ``/proc/<pid>``, or None if gone/zombie."""
33
+ proc = Path(root) / "proc" / str(pid)
34
+ try:
35
+ stat_text = (proc / "stat").read_text(encoding="utf-8")
36
+ status_text = (proc / "status").read_text(encoding="utf-8")
37
+ except (FileNotFoundError, ProcessLookupError):
38
+ return None
39
+ except OSError:
40
+ raise OSError("process identity unavailable") from None
41
+ _, sep, after = stat_text.rpartition(")")
42
+ if not sep:
43
+ raise OSError("process identity unavailable")
44
+ fields = after.split()
45
+ if len(fields) <= 19 or not fields[19].isdigit():
46
+ raise OSError("process identity unavailable")
47
+ if fields[0] == "Z":
48
+ return None
49
+ uid = _status_euid(status_text)
50
+ if uid is None:
51
+ raise OSError("process identity unavailable")
52
+ try:
53
+ pgid = int(fields[2])
54
+ except ValueError:
55
+ raise OSError("process identity unavailable") from None
56
+ return uid, pgid, fields[19]
57
+
58
+
59
+ def _boot_time(root: str = "/") -> int | None:
60
+ try:
61
+ for line in (Path(root) / "proc" / "stat").read_text(encoding="ascii").splitlines():
62
+ if line.startswith("btime "):
63
+ parts = line.split()
64
+ if len(parts) == 2 and parts[1].isdigit():
65
+ return int(parts[1])
66
+ except OSError:
67
+ return None
68
+ return None
69
+
70
+
71
+ def _parse_legacy_lstart(value: str) -> float | None:
72
+ """Parse C-locale ``ps -o lstart=`` (``Wed Nov 18 06:16:50 2026``) without relying on LC_TIME."""
73
+ parts = value.split()
74
+ if len(parts) != 5 or parts[0] not in _ENGLISH_DAYS or parts[1] not in _ENGLISH_MONTHS:
75
+ return None
76
+ hms = parts[3].split(":")
77
+ if len(hms) != 3 or not (
78
+ parts[2].isdigit() and parts[4].isdigit() and all(p.isdigit() for p in hms)
79
+ ):
80
+ return None
81
+ try:
82
+ year, month, day = int(parts[4]), _ENGLISH_MONTHS[parts[1]], int(parts[2])
83
+ hour, minute, second = int(hms[0]), int(hms[1]), int(hms[2])
84
+ if not (1 <= day <= 31 and 0 <= hour <= 23 and 0 <= minute <= 59 and 0 <= second <= 60):
85
+ return None
86
+ return time.mktime((year, month, day, hour, minute, second, 0, 0, -1))
87
+ except (OverflowError, ValueError):
88
+ return None
89
+
90
+
91
+ def same_start(current_started: str, saved_started: str, root: str = "/") -> bool:
92
+ """Match exact boot ticks, or a pre-upgrade ``ps -o lstart=`` receipt within NTP btime jitter."""
93
+ if current_started == saved_started:
94
+ return True
95
+ if not current_started.isdigit():
96
+ return False
97
+ saved_epoch = _parse_legacy_lstart(saved_started)
98
+ if saved_epoch is None:
99
+ return False
100
+ try:
101
+ hz = os.sysconf("SC_CLK_TCK")
102
+ except (OSError, ValueError):
103
+ return False
104
+ btime = _boot_time(root)
105
+ if btime is None or hz <= 0:
106
+ return False
107
+ actual_epoch = btime + int(current_started) / hz
108
+ return abs(actual_epoch - saved_epoch) <= _LEGACY_LSTART_TOLERANCE_S
109
+
110
+
111
+ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
112
+ """Read-only Linux ``/proc/<pid>/cmdline`` argv proof (including ``#!`` scripts)."""
113
+ try:
114
+ process = Path(root) / "proc" / str(pid)
115
+ if process.stat().st_uid != os.getuid():
116
+ return False
117
+ actual = process.joinpath("cmdline").read_bytes().decode().rstrip("\0").split("\0")
118
+ if actual == expected:
119
+ return True
120
+ target = expected[0] if root == "/" else Path(root) / expected[0].lstrip("/")
121
+ with open(target, "rb") as executable:
122
+ header = executable.readline(512).decode()
123
+ if not header.startswith("#!"):
124
+ return False
125
+ interp = shlex.split(header[2:].strip())
126
+ if interp[:1] == ["/usr/bin/env"]:
127
+ interp = interp[1:]
128
+ if len(interp) != 1 or actual[1:] != expected:
129
+ return False
130
+ resolved = shutil.which(interp[0])
131
+ return (
132
+ resolved is not None and process.joinpath("exe").resolve() == Path(resolved).resolve()
133
+ )
134
+ except (OSError, ValueError, UnicodeError, IndexError):
135
+ return False
@@ -6,8 +6,16 @@ proved its creation time. stdlib only (ctypes); every function needs Windows.
6
6
  from __future__ import annotations
7
7
 
8
8
  import ctypes
9
+ import json
10
+ import os
11
+ from pathlib import Path
9
12
 
10
- from localmodels import process_identity
13
+ try:
14
+ from localmodels import process_identity
15
+ except ImportError: # run as a bare file beside service_probe
16
+ import process_identity # type: ignore[import-not-found,no-redef]
17
+
18
+ WINDOWS_DEPLOYMENTS = "~/.local/share/localmodels/deployments" # deploy.DEFAULT_BASE_DIR's
11
19
 
12
20
 
13
21
  def own_pids() -> list[int]:
@@ -84,3 +92,144 @@ def terminate(pid: int, started: str) -> bool:
84
92
  return True
85
93
  finally:
86
94
  kernel.CloseHandle(handle)
95
+
96
+
97
+ def windows_tree_pids(root_pid: int) -> list[int]:
98
+ """Windows: ``root_pid`` followed by its verified same-user descendant PIDs (BFS).
99
+ A launcher such as ``strata_poly_server.py`` is the recorded PID while its child
100
+ ``strata-poly.exe`` holds the GPU and memory. Creation timestamps reject recycled PIDs;
101
+ falls back to ``[root_pid]`` off Windows or when the snapshot is unavailable."""
102
+ if not process_identity._windows() or root_pid <= 0:
103
+ return [root_pid]
104
+ try:
105
+ root = process_identity.inspect(root_pid)
106
+ if root is None or root["uid"] != 0:
107
+ return [root_pid]
108
+ parents = process_identity._parent_pids()
109
+ except (OSError, AttributeError):
110
+ return [root_pid]
111
+ children_of: dict[int, list[int]] = {}
112
+ for child, parent in parents.items():
113
+ if child > 4 and parent > 0:
114
+ children_of.setdefault(parent, []).append(child)
115
+ tree: list[int] = [root_pid]
116
+ seen: set[int] = {root_pid}
117
+ queue: list[tuple[int, int]] = [(root_pid, int(root["started"]))]
118
+ while queue:
119
+ cur, cur_started = queue.pop(0)
120
+ for child in sorted(children_of.get(cur, ())):
121
+ if child in seen:
122
+ continue
123
+ seen.add(child)
124
+ try:
125
+ found = process_identity.inspect(child)
126
+ except (OSError, AttributeError):
127
+ continue
128
+ if found is None or found["uid"] != 0 or int(found["started"]) < cur_started:
129
+ continue
130
+ tree.append(child)
131
+ queue.append((child, int(found["started"])))
132
+ return tree
133
+
134
+
135
+ def _state_receipts() -> list[Path]:
136
+ """``server.pid`` paths named by local deployment records under ``LOCALMODELS_STATE``."""
137
+ state = os.path.expanduser(os.environ.get("LOCALMODELS_STATE", "~/.local/state/localmodels"))
138
+ records = Path(state) / "deployments" / "local"
139
+ found: list[Path] = []
140
+ try:
141
+ entries = list(records.glob("*.json"))[:256]
142
+ except OSError:
143
+ return found
144
+ for path in entries:
145
+ try:
146
+ if not path.is_file() or path.is_symlink():
147
+ continue
148
+ directory = json.loads(path.read_text(encoding="utf-8"))["plan"]["service"][
149
+ "deploy_dir"
150
+ ]
151
+ if isinstance(directory, str) and directory:
152
+ found.append(Path(os.path.expanduser(directory), "server.pid"))
153
+ except (OSError, ValueError, KeyError, TypeError):
154
+ continue
155
+ return found
156
+
157
+
158
+ def _receipt_roots(deployments: str) -> dict[int, str]:
159
+ """{PID: creation timestamp} of active, same-user Windows nohup deployment receipts."""
160
+ candidates: list[Path] = []
161
+ try:
162
+ candidates.extend(Path(os.path.expanduser(deployments)).glob("*/server.pid"))
163
+ except OSError:
164
+ pass
165
+ if deployments == WINDOWS_DEPLOYMENTS:
166
+ candidates.extend(_state_receipts())
167
+ active: dict[int, str] = {}
168
+ for receipt in dict.fromkeys(candidates):
169
+ state, active_pid = process_identity.status(receipt)
170
+ if state != "active" or active_pid is None:
171
+ continue
172
+ try:
173
+ info = process_identity.inspect(active_pid)
174
+ except OSError:
175
+ continue
176
+ if info is not None and info["uid"] == 0:
177
+ active[active_pid] = info["started"]
178
+ return active
179
+
180
+
181
+ def _ancestor_owned(
182
+ pid: int, original: process_identity.Identity, roots: dict[int, str]
183
+ ) -> bool | None:
184
+ """Walk Windows parent PIDs up to an active receipt, rejecting recycled PIDs and drift."""
185
+ try:
186
+ parents = process_identity._parent_pids()
187
+ except OSError:
188
+ return None
189
+ chain: list[tuple[int, process_identity.Identity]] = [(pid, original)]
190
+ cur, cur_id = pid, original
191
+ seen = {pid}
192
+ for _ in range(16):
193
+ parent = parents.get(cur)
194
+ if not parent or parent <= 4 or parent in seen:
195
+ return False
196
+ seen.add(parent)
197
+ try:
198
+ parent_id = process_identity.inspect(parent)
199
+ except PermissionError:
200
+ return False
201
+ except OSError:
202
+ return None
203
+ if parent_id is None or parent_id["uid"] != 0:
204
+ return False
205
+ if int(parent_id["started"]) > int(cur_id["started"]):
206
+ return False # parent PID was reused after cur started
207
+ chain.append((parent, parent_id))
208
+ if roots.get(parent) == parent_id["started"]:
209
+ try:
210
+ return all(process_identity.inspect(p) == saved for p, saved in chain)
211
+ except OSError:
212
+ return False
213
+ cur, cur_id = parent, parent_id
214
+ return False
215
+
216
+
217
+ def windows_owned(pid: int, deployments: str = WINDOWS_DEPLOYMENTS) -> bool | None:
218
+ """Windows: a live receipt of one of this user's nohup deployments names the process or
219
+ a verified same-user ancestor (e.g. ``strata_poly_server.py`` -> ``strata-poly.exe``)."""
220
+ try:
221
+ original = process_identity.inspect(pid)
222
+ except PermissionError:
223
+ return False # protected or elevated process of another token: never this user's
224
+ except OSError:
225
+ return None
226
+ if original is None:
227
+ return None
228
+ if original["uid"] != 0:
229
+ return False
230
+ roots = _receipt_roots(deployments)
231
+ if not roots:
232
+ return False
233
+ if roots.get(pid) == original["started"]:
234
+ return True
235
+ return _ancestor_owned(pid, original, roots)
@@ -185,7 +185,7 @@ def recommendation(
185
185
  fitting = []
186
186
  for entry in (*live, fallback):
187
187
  for p, budget in candidates:
188
- if llm_rank.automatic_fit(entry, facts, budget, AGENT, {"search": False}):
188
+ if llm_rank.automatic_fit(entry, facts, budget, AGENT, {}):
189
189
  key = llm_rank.rank_key(entry, entry.variants[-1], budget)
190
190
  fitting.append((key, entry.id, p.gpu_indices[0]))
191
191
  break
@@ -155,7 +155,7 @@ def _show_parts(
155
155
  " 理由 只选窗口至少 64K、满足引擎内存门槛的已验证 LLM;llama.cpp 权重和 KV 全驻留 GPU,"
156
156
  "Strata 允许专家驻留内存;能读图的默认开启图片输入"
157
157
  "(决策 31,--vision off 关闭),装机后 SimplexAI 分优先、"
158
- "预测解码速度其次(--prefer smartest);网页搜索默认不装(路线图决策 55,--search 安装);"
158
+ "预测解码速度其次(--prefer smartest);"
159
159
  "决策模型与 embedding/reranker/STT 是选装(--decision、--aux),按剩余资源装入,"
160
160
  "决策模型只放 GPU"
161
161
  )
@@ -178,7 +178,7 @@ def _show_parts(
178
178
  if all_models:
179
179
  print(
180
180
  f"可选组件:{command()} stack plan --decision auto --aux auto;"
181
- "决策模型与辅助模型默认不安装,网页搜索默认不装(--search 安装);"
181
+ "决策模型与辅助模型默认不安装;"
182
182
  "要多路并发用 --prefer concurrent;不会自动降低 LLM 门槛。"
183
183
  )
184
184
  for option in plan.get("decision_options", [])[:2]:
@@ -95,6 +95,9 @@ class _Archive(TypedDict):
95
95
 
96
96
  class Archive(_Archive, total=False):
97
97
  npm_copy: NpmCopy
98
+ # Only these paths of the archive are unpacked (prefixes, after its top folder is dropped):
99
+ # a source archive whose deepest paths would pass Windows' 260-character limit.
100
+ members: list[str]
98
101
 
99
102
 
100
103
  class ServiceParams(TypedDict): # all start, stop and status need; the base of the rest
@@ -206,7 +209,6 @@ RERANK_DOCS = [
206
209
  "The Pacific is the largest ocean on Earth.",
207
210
  ]
208
211
  RERANK_RELEVANT = 1
209
- SEARCH_QUERY = "Python programming language" # every engine finds pages for it
210
212
 
211
213
 
212
214
  def emit(event: str, **fields: object) -> None:
@@ -462,7 +464,7 @@ def _relative(name: str) -> str:
462
464
  return name
463
465
 
464
466
 
465
- def _unzip(archive: str, directory: str) -> None:
467
+ def _unzip(archive: str, directory: str, members: tuple[str, ...] = ()) -> None:
466
468
  """A Windows release zip: regular files only, each kept inside ``directory``."""
467
469
  with zipfile.ZipFile(archive) as bundle:
468
470
  names = [_relative(i.filename.replace("\\", "/")) for i in bundle.infolist()]
@@ -471,6 +473,8 @@ def _unzip(archive: str, directory: str) -> None:
471
473
  for info, name in zip(bundle.infolist(), names):
472
474
  if strip:
473
475
  name = name.split("/", 1)[1] if "/" in name else ""
476
+ if members and not name.startswith(members):
477
+ continue
474
478
  if not name or info.is_dir() or name.startswith("/") or ".." in name.split("/"):
475
479
  continue
476
480
  if ":" in name or (info.external_attr >> 16) & 0o170000 == 0o120000:
@@ -481,10 +485,12 @@ def _unzip(archive: str, directory: str) -> None:
481
485
  shutil.copyfileobj(source, dest)
482
486
 
483
487
 
484
- def unpack(archive: str, directory: str) -> None:
485
- """Extract into ``directory``, dropping the archive's single top folder when it has one."""
486
- if archive.endswith(".zip"):
487
- _unzip(archive, directory)
488
+ def unpack(archive: str, directory: str, keep: tuple[str, ...] = ()) -> None:
489
+ """Extract into ``directory``, dropping the archive's single top folder when it has one;
490
+ ``keep``: only the paths under these prefixes (Archive.members). A wheel is a zip
491
+ (PolyStrata's Windows build takes cuBLAS from NVIDIA's)."""
492
+ if archive.endswith((".zip", ".whl")):
493
+ _unzip(archive, directory, keep)
488
494
  return
489
495
  with tarfile.open(archive) as tar:
490
496
  members = tar.getmembers()
@@ -494,6 +500,8 @@ def unpack(archive: str, directory: str) -> None:
494
500
  name = member.name.lstrip("./")
495
501
  if strip:
496
502
  name = name.split("/", 1)[1] if "/" in name else ""
503
+ if keep and not name.startswith(keep):
504
+ continue
497
505
  if not name or name.startswith("/") or ".." in name.split("/"):
498
506
  continue
499
507
  if member.issym() or member.islnk():
@@ -56,7 +56,7 @@ def act_engine(p: remote_ops.EngineParams) -> None:
56
56
  npm_copies(a),
57
57
  p.get("region"),
58
58
  )
59
- remote_ops.unpack(archive, directory)
59
+ remote_ops.unpack(archive, directory, tuple(a.get("members") or ()))
60
60
  if not os.access(binary, os.X_OK):
61
61
  raise RuntimeError(f"the engine has no executable {os.path.relpath(binary, directory)}")
62
62
  remote_ops._write(done_marker, expected)