@simplexai/localmodels-darwin-arm64 0.1.0-dev.45 → 0.1.0-dev.48

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 (39) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +38 -36
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/catalog.json +150 -0
  5. package/modules/localmodels/catalog.py +20 -5
  6. package/modules/localmodels/catalog_recipes.py +8 -0
  7. package/modules/localmodels/context_policy.py +32 -9
  8. package/modules/localmodels/deploy.py +20 -14
  9. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +98 -0
  10. package/modules/localmodels/engines.py +28 -2
  11. package/modules/localmodels/estimator.py +12 -3
  12. package/modules/localmodels/gateway_bifrost.py +95 -22
  13. package/modules/localmodels/gguf.py +6 -2
  14. package/modules/localmodels/harness_probe.py +60 -13
  15. package/modules/localmodels/library_pricing.py +6 -4
  16. package/modules/localmodels/library_state.py +6 -4
  17. package/modules/localmodels/probe.py +38 -11
  18. package/modules/localmodels/process_identity.py +47 -33
  19. package/modules/localmodels/process_identity_linux.py +135 -0
  20. package/modules/localmodels/process_windows.py +150 -1
  21. package/modules/localmodels/runtime_windows_acl.py +100 -0
  22. package/modules/localmodels/service_probe.py +26 -20
  23. package/modules/localmodels/setup_inspection.py +132 -36
  24. package/modules/localmodels/setup_text.py +17 -3
  25. package/modules/localmodels/stack_binding.py +117 -12
  26. package/modules/localmodels/stack_lifecycle.py +7 -4
  27. package/modules/localmodels/stack_view_llm.py +1 -1
  28. package/modules/localmodels/stack_view_sandbox.py +3 -1
  29. package/modules/localmodels/stack_warm.py +18 -7
  30. package/modules/localmodels/strata_poly_server.py +4 -2
  31. package/modules/localmodels/transport.py +7 -1
  32. package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev48.dist-info}/METADATA +1 -1
  33. package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev48.dist-info}/RECORD +35 -33
  34. package/package.json +1 -1
  35. package/tool.json +1 -1
  36. /package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev48.dist-info}/WHEEL +0 -0
  37. /package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev48.dist-info}/entry_points.txt +0 -0
  38. /package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev48.dist-info}/licenses/NOTICE +0 -0
  39. /package/modules/{simplex_localmodels-0.1.0.dev45.dist-info → simplex_localmodels-0.1.0.dev48.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -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:
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import argparse
6
6
  import copy
7
7
  import json
8
+ import re
8
9
  import sys
9
10
  from pathlib import Path
10
11
  from typing import Any, Literal, TypedDict
@@ -24,6 +25,7 @@ from localmodels import (
24
25
  stack_review,
25
26
  )
26
27
  from localmodels.contracts import decode
28
+ from localmodels.engines import CudaDriverError
27
29
  from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
28
30
  from localmodels.plan_envelope import PlanError
29
31
  from localmodels.probe import HostFacts, Services
@@ -46,6 +48,10 @@ class _ReasonSince014(TypedDict, total=False):
46
48
  gpuIndex: int
47
49
  freeBytes: int
48
50
  requiredBytes: int
51
+ # On cuda-driver-update-required and cuda-driver-version-unknown: driver and CUDA versions.
52
+ detectedCudaVersion: str
53
+ requiredCudaVersion: str
54
+ driverVersion: str
49
55
 
50
56
 
51
57
  class Reason(_ReasonSince014):
@@ -94,10 +100,113 @@ class SetupReport(TypedDict):
94
100
  recommendation: str
95
101
 
96
102
 
103
+ _DRIVER_REASON_CODES = frozenset({"cuda-driver-update-required", "cuda-driver-version-unknown"})
104
+ _VERSION_RE = re.compile(r"^\d+(?:\.\d+){0,2}$")
105
+
106
+
97
107
  def _plan_reason(error: PlanError | StackError | harness.HarnessError) -> Reason:
98
108
  return {"code": "plan-unavailable", "message": str(error)}
99
109
 
100
110
 
111
+ def _cuda_driver_reason(error: CudaDriverError, lang: Lang) -> Reason:
112
+ detected = error.detected_cuda if _VERSION_RE.fullmatch(error.detected_cuda) else ""
113
+ required = error.required_cuda if _VERSION_RE.fullmatch(error.required_cuda) else ""
114
+ driver = error.driver_version if _VERSION_RE.fullmatch(error.driver_version) else ""
115
+ if detected:
116
+ reason: Reason = {
117
+ "code": "cuda-driver-update-required",
118
+ "message": text(
119
+ "cuda-driver-update-required",
120
+ lang,
121
+ detected=detected,
122
+ required=required or error.required_cuda,
123
+ ),
124
+ "detectedCudaVersion": detected,
125
+ }
126
+ else:
127
+ reason = {
128
+ "code": "cuda-driver-version-unknown",
129
+ "message": text(
130
+ "cuda-driver-version-unknown",
131
+ lang,
132
+ required=required or error.required_cuda,
133
+ ),
134
+ }
135
+ if required:
136
+ reason["requiredCudaVersion"] = required
137
+ if driver:
138
+ reason["driverVersion"] = driver
139
+ return reason
140
+
141
+
142
+ def _fits_with_required_cuda(options: StackOptions, facts: HostFacts, required_cuda: str) -> bool:
143
+ """Whether this computer's hardware fits a local stack once the NVIDIA driver supports
144
+ ``required_cuda`` (live or once other programs free memory)."""
145
+ upgraded = copy.deepcopy(facts)
146
+ upgraded["nvidia"] = {**(upgraded.get("nvidia") or {}), "cuda_version": required_cuda}
147
+ if _plans(options, upgraded):
148
+ return True
149
+ roomy = _capacity_facts(upgraded)
150
+ return roomy is not None and _plans(options, roomy)
151
+
152
+
153
+ def _driver_block(
154
+ error: PlanError | StackError | harness.HarnessError | None,
155
+ options: StackOptions,
156
+ facts: HostFacts,
157
+ lang: Lang,
158
+ ) -> StackAvailability | None:
159
+ if not isinstance(error, CudaDriverError):
160
+ return None
161
+ if not _fits_with_required_cuda(options, facts, error.required_cuda):
162
+ return None
163
+ return {
164
+ "available": False,
165
+ "reasons": [_cuda_driver_reason(error, lang)],
166
+ "plan": None,
167
+ }
168
+
169
+
170
+ def _capacity_availability(
171
+ options: StackOptions, facts: HostFacts, lang: Lang
172
+ ) -> StackAvailability | None:
173
+ roomy = _capacity_facts(facts)
174
+ if roomy is None:
175
+ return None
176
+ try:
177
+ plan = stack.build(options, facts=roomy)
178
+ except (PlanError, stack.StackError, harness.HarnessError) as roomy_exc:
179
+ if blocked := _driver_block(roomy_exc, options, roomy, lang):
180
+ return blocked
181
+ # The hardware itself is too small and the live refusal stands, unless only another
182
+ # inference app on a Mac's GPU stands in the way: that memory is not counted as freeable
183
+ # (roadmap decision 43), but the refusal names the app instead of blaming the hardware.
184
+ if alone := _fits_without_other_inference(options, roomy):
185
+ reason: Reason = {
186
+ "code": "plan-unavailable",
187
+ "message": text(
188
+ "inference-app-running",
189
+ lang,
190
+ apps="; ".join(metal.conflicts(facts)),
191
+ ),
192
+ }
193
+ return {
194
+ "available": False,
195
+ "reasons": [reason],
196
+ "plan": alone,
197
+ "basis": "capacity",
198
+ }
199
+ return None
200
+ # Roadmap decision 56: an install now prices the memory free now and would refuse, so the stack
201
+ # is not available; the plan shows what it needs.
202
+ return {
203
+ "available": False,
204
+ "reasons": _held_reasons(options, facts, roomy, plan, lang),
205
+ "plan": plan,
206
+ "basis": "capacity",
207
+ }
208
+
209
+
101
210
  def _stack(
102
211
  root: Path,
103
212
  facts: HostFacts,
@@ -132,6 +241,8 @@ def _stack(
132
241
  try:
133
242
  plan = stack.build(options, facts=facts)
134
243
  except (PlanError, stack.StackError, harness.HarnessError) as exc:
244
+ last_error: PlanError | StackError | harness.HarnessError | None = exc
245
+ last_options = options
135
246
  reason = _plan_reason(exc)
136
247
  # Consent decides by free VRAM whoever else uses a card (roadmap decision 60), so
137
248
  # only a Mac, whose sharing still needs every discovery section, skips the retry.
@@ -140,47 +251,23 @@ def _stack(
140
251
  and budget.holders(facts)
141
252
  and (not budget.unknown_services(facts) or not metal.supported(facts))
142
253
  ):
254
+ shared_options: StackOptions = {**options, "share_gpu": True}
143
255
  try:
144
- stack.build({**options, "share_gpu": True}, facts=facts)
256
+ stack.build(shared_options, facts=facts)
145
257
  except (PlanError, stack.StackError, harness.HarnessError) as shared_exc:
258
+ last_error, last_options = shared_exc, shared_options
146
259
  reason = _plan_reason(shared_exc)
147
260
  else:
261
+ last_error = None
148
262
  reason = {
149
263
  "code": "gpu-sharing-required",
150
264
  "message": text("gpu-sharing-required", lang),
151
265
  }
152
- if reason["code"] == "plan-unavailable" and (roomy := _capacity_facts(facts)):
153
- try:
154
- plan = stack.build(options, facts=roomy)
155
- except (PlanError, stack.StackError, harness.HarnessError):
156
- # The hardware itself is too small and the live refusal stands, unless only
157
- # another inference app on a Mac's GPU stands in the way: that memory is not
158
- # counted as freeable (roadmap decision 43), but the refusal names the app
159
- # instead of blaming the hardware.
160
- if alone := _fits_without_other_inference(options, roomy):
161
- reason = {
162
- "code": "plan-unavailable",
163
- "message": text(
164
- "inference-app-running",
165
- lang,
166
- apps="; ".join(metal.conflicts(facts)),
167
- ),
168
- }
169
- return {
170
- "available": False,
171
- "reasons": [reason],
172
- "plan": alone,
173
- "basis": "capacity",
174
- }
175
- else:
176
- # Roadmap decision 56: an install now prices the memory free now and would
177
- # refuse, so the stack is not available; the plan shows what it needs.
178
- return {
179
- "available": False,
180
- "reasons": _held_reasons(options, facts, roomy, plan, lang),
181
- "plan": plan,
182
- "basis": "capacity",
183
- }
266
+ if blocked := _driver_block(last_error, last_options, facts, lang):
267
+ return blocked
268
+ if reason["code"] == "plan-unavailable":
269
+ if capacity := _capacity_availability(options, facts, lang):
270
+ return capacity
184
271
 
185
272
  return {"available": plan is not None, "reasons": [reason] if reason else [], "plan": plan}
186
273
 
@@ -320,7 +407,11 @@ def _classify(availability: StackAvailability, facts: HostFacts) -> None:
320
407
  codes = {reason["code"] for reason in availability["reasons"]}
321
408
  if availability["available"]:
322
409
  availability["state"], availability["hardwareCapable"] = "ready", True
323
- elif availability.get("basis") == "capacity" or "gpu-sharing-required" in codes:
410
+ elif (
411
+ availability.get("basis") == "capacity"
412
+ or "gpu-sharing-required" in codes
413
+ or bool(codes & _DRIVER_REASON_CODES)
414
+ ):
324
415
  availability["state"], availability["hardwareCapable"] = "blocked-now", True
325
416
  else:
326
417
  availability["state"] = "unavailable"
@@ -433,8 +524,13 @@ INSPECT = (
433
524
  )
434
525
  INSPECT_REASONS = (
435
526
  "unsupported-platform · facts-unavailable · plan-unavailable · gpu-sharing-required\n"
436
- "(the last: a plan fits only beside other GPU work, its owner known or not; ask, then rerun "
437
- "with --share-gpu, which plans by the free VRAM)\n"
527
+ "cuda-driver-update-required · cuda-driver-version-unknown\n"
528
+ "(gpu-sharing-required: a plan fits only beside other GPU work, its owner known or not; ask, "
529
+ "then rerun with --share-gpu, which plans by the free VRAM)\n"
530
+ "cuda-driver-update-required / cuda-driver-version-unknown (stack.state is blocked-now, "
531
+ "hardwareCapable is true: the GPU can run local models, but the NVIDIA driver's CUDA version "
532
+ "is older than requiredCudaVersion or could not be read; detectedCudaVersion, "
533
+ "requiredCudaVersion and driverVersion carry the versions)\n"
438
534
  "gpu-memory-required (stack.state is blocked-now, stack.basis is capacity: other programs "
439
535
  "use the GPU memory the plan needs; close them and check again; gpuIndex, freeBytes and "
440
536
  "requiredBytes give the card and its free and needed VRAM)\n"
@@ -60,6 +60,20 @@ MESSAGES: dict[str, tuple[str, str]] = {
60
60
  "Mac's GPU and unified memory ({apps}). This tool does not count that memory as free; "
61
61
  "quit the app and check again.",
62
62
  ),
63
+ "cuda-driver-update-required": (
64
+ "这台电脑的显卡可以运行本地模型,但当前 NVIDIA 驱动支持的 CUDA 版本({detected})低于"
65
+ "本地模型引擎要求的最低版本(CUDA >= {required})。请更新 NVIDIA 驱动后重新检查。",
66
+ "This computer's GPU can run local models, but the installed NVIDIA driver supports "
67
+ "CUDA {detected}, older than the required CUDA {required} or newer. Update the NVIDIA "
68
+ "driver and check again.",
69
+ ),
70
+ "cuda-driver-version-unknown": (
71
+ "检测到 NVIDIA 显卡,但无法读取驱动支持的 CUDA 版本(需要 CUDA >= {required})。"
72
+ "请更新或重新安装 NVIDIA 驱动后重新检查。",
73
+ "An NVIDIA GPU was detected, but the driver's supported CUDA version could not be read "
74
+ "(requires CUDA {required} or newer). Update or reinstall the NVIDIA driver and check "
75
+ "again.",
76
+ ),
63
77
  "plan-invalid": (
64
78
  "批准计划不存在、无效或摘要不一致。",
65
79
  "The approved plan is missing or invalid, or its digest does not match.",
@@ -100,9 +114,9 @@ MESSAGES: dict[str, tuple[str, str]] = {
100
114
  "Run stack apply again to replace it.",
101
115
  ),
102
116
  "binding-unavailable": (
103
- "Pi 配置或本机状态无法安全读取,请恢复已有安装后重试。",
104
- "Pi's configuration or this computer's state cannot be read safely. Restore the "
105
- "existing install and try again.",
117
+ "无法安全验证 Pi 配置或本机状态,请检查本地模型安装,或先改用其他 AI 运行时。",
118
+ "Pi's configuration or this computer's state could not be verified safely. Check the "
119
+ "local model installation or choose another AI runtime.",
106
120
  ),
107
121
  # The plan summary: the model, where it runs and what it needs.
108
122
  "summary": (
@@ -5,6 +5,8 @@ from __future__ import annotations
5
5
  import hashlib
6
6
  import json
7
7
  import os
8
+ import stat
9
+ import sys
8
10
  from pathlib import Path
9
11
  from typing import TypedDict, cast
10
12
 
@@ -13,6 +15,8 @@ from localmodels import stack_lifecycle as lifecycle
13
15
  from localmodels.setup_text import Lang, text
14
16
  from localmodels.stack_plan import StackPlan, deployments
15
17
 
18
+ _REPARSE_POINT = 0x400 # FILE_ATTRIBUTE_REPARSE_POINT: a symbolic link, junction or mount point
19
+
16
20
 
17
21
  class Reason(TypedDict):
18
22
  code: str
@@ -37,7 +41,78 @@ class BindingReport(TypedDict):
37
41
  reasons: list[Reason]
38
42
 
39
43
 
44
+ def _windows() -> bool:
45
+ return os.name == "nt"
46
+
47
+
48
+ def _same_path(left: str | Path, right: str | Path) -> bool:
49
+ return os.path.normcase(os.path.normpath(os.path.expanduser(str(left)))) == os.path.normcase(
50
+ os.path.normpath(os.path.expanduser(str(right)))
51
+ )
52
+
53
+
54
+ def _same_real_path(left: str | Path, right: str | Path) -> bool:
55
+ return os.path.normcase(os.path.realpath(left)) == os.path.normcase(os.path.realpath(right))
56
+
57
+
58
+ def _with_path(env: dict[str, str], prefixes: list[str]) -> dict[str, str]:
59
+ merged = {key: value for key, value in env.items() if key.upper() != "PATH"}
60
+ merged["PATH"] = os.pathsep.join([*prefixes, os.environ.get("PATH", "")])
61
+ return merged
62
+
63
+
64
+ def _reparse_point(info: os.stat_result) -> bool:
65
+ return bool(getattr(info, "st_file_attributes", 0) & _REPARSE_POINT)
66
+
67
+
68
+ def _windows_profile_file(path: Path) -> bytes | None:
69
+ """``path``'s bytes when it is a regular file owned by this user, or by Administrators while
70
+ this user is an administrator (an elevated install creates files that group owns); None when
71
+ it is missing. Its type, owner and bytes come from one handle on the file itself, so a link,
72
+ a junction or a replacement mid-check cannot pass one test and supply the other."""
73
+ from localmodels import gateway_home, runtime_windows_acl
74
+
75
+ try:
76
+ fd = runtime_windows_acl.open_unfollowed(path)
77
+ except FileNotFoundError:
78
+ return None
79
+ with open(fd, "rb") as source:
80
+ info = os.fstat(fd)
81
+ if not stat.S_ISREG(info.st_mode) or _reparse_point(info):
82
+ raise ValueError("Pi configuration unavailable")
83
+ owner = runtime_windows_acl.descriptor_owner_sid(fd)
84
+ if owner != runtime_windows_acl.identity()[4] and not (
85
+ owner == gateway_home.ADMINISTRATORS_SID and runtime_windows_acl.is_administrator()
86
+ ):
87
+ raise ValueError("Pi configuration unavailable")
88
+ return source.read()
89
+
90
+
91
+ def _windows_profile_fingerprint(executable: Path, profile: Path) -> str:
92
+ """The POSIX fingerprint, same bytes in the same order, with ownership proved by owner SID:
93
+ Windows has no ``os.getuid``."""
94
+ if (
95
+ not executable.is_file()
96
+ or not os.access(executable, os.X_OK)
97
+ or profile.is_symlink()
98
+ or _reparse_point(profile.lstat())
99
+ ):
100
+ raise ValueError("Pi configuration unavailable")
101
+ digest = hashlib.sha256(executable.read_bytes())
102
+ for name in ("settings.json", "models.json", "auth.json"):
103
+ body = _windows_profile_file(profile / name)
104
+ if body is None:
105
+ if name == "auth.json":
106
+ continue
107
+ raise ValueError("Pi configuration unavailable")
108
+ digest.update(name.encode())
109
+ digest.update(body)
110
+ return digest.hexdigest()
111
+
112
+
40
113
  def _profile_fingerprint(executable: Path, profile: Path) -> str:
114
+ if _windows():
115
+ return _windows_profile_fingerprint(executable, profile)
41
116
  if not hasattr(os, "getuid"):
42
117
  raise ValueError("Pi profile ownership inspection is unavailable on this platform")
43
118
  uid = os.getuid()
@@ -139,7 +214,7 @@ def _deployments_ready(
139
214
  or entry["kind"] != service["kind"]
140
215
  # The manifest records the expanded directory (hosts.own_deployment); a plan on
141
216
  # the default base directory names it under "~".
142
- or entry["deploy_dir"] != os.path.expanduser(service["deploy_dir"])
217
+ or not _same_path(entry["deploy_dir"], service["deploy_dir"])
143
218
  or entry["port"] != service["port"]
144
219
  ):
145
220
  return False
@@ -156,7 +231,7 @@ def _bifrost_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") ->
156
231
  or record["addr"] != gateway["addr"]
157
232
  # an instance still on an earlier pinned binary is not the approved plan until apply
158
233
  # restarts it
159
- or record["binary"] != harness.tool_path(plan["harness"], "bifrost")
234
+ or not _same_path(record["binary"], harness.tool_path(plan["harness"], "bifrost"))
160
235
  or not owned["pi"]
161
236
  or owned["pi"]["model"] != gateway["pi_model"]
162
237
  ):
@@ -211,9 +286,9 @@ def _pi_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") -> PiBin
211
286
  fingerprint = _profile_fingerprint(executable, profile)
212
287
  magpie = harness.tool_path(plan["harness"], "magpie")
213
288
  env = {
214
- **harness.checked_gateway_environment(plan["harness"]),
215
- "PATH": os.pathsep.join(
216
- [str(executable.parent), str(Path(magpie).parent), os.environ.get("PATH", "")]
289
+ **_with_path(
290
+ harness.checked_gateway_environment(plan["harness"]),
291
+ [str(executable.parent), str(Path(magpie).parent)],
217
292
  ),
218
293
  "MAGPIE_ADDR": gateway["addr"],
219
294
  "PI_CODING_AGENT_DIR": str(profile),
@@ -229,8 +304,8 @@ def _pi_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") -> PiBin
229
304
  or state.get("gateway_other_user")
230
305
  or not state["pi"]
231
306
  or not state["magpie"]
232
- or os.path.realpath(state["magpie"]) != os.path.realpath(magpie)
233
- or os.path.realpath(state["pi"]) != os.path.realpath(executable)
307
+ or not _same_real_path(state["magpie"], magpie)
308
+ or not _same_real_path(state["pi"], executable)
234
309
  or state["pi_model"] != gateway["pi_model"]
235
310
  ):
236
311
  return _reason("gateway-unavailable", lang)
@@ -253,11 +328,14 @@ def _pi_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") -> PiBin
253
328
  def _stack_installed(plan: StackPlan, owned: hosts.Owned) -> bool:
254
329
  """The Node.js and pi the plan installed are still in the manifest: ``stack remove``
255
330
  deletes them and drops them from it. A tool the plan reused is no anchor."""
256
- paths = [Path(t["path"]) for t in owned["tools"]]
331
+ paths = [
332
+ Path(os.path.normcase(os.path.normpath(os.path.expanduser(t["path"]))))
333
+ for t in owned["tools"]
334
+ ]
257
335
  for tool in plan["harness"]["tools"]:
258
336
  if tool["action"] != "install" or tool["tool"] not in ("node", "pi"):
259
337
  continue
260
- wanted = Path(os.path.expanduser(tool["path"]))
338
+ wanted = Path(os.path.normcase(os.path.normpath(os.path.expanduser(tool["path"]))))
261
339
  if not any(wanted == path or path in wanted.parents for path in paths):
262
340
  return False
263
341
  return True
@@ -301,8 +379,10 @@ def _library_binding(
301
379
  return _reason("gateway-ownership", lang)
302
380
  magpie = harness.tool_path(plan["harness"], "magpie")
303
381
  env = {
304
- **harness.checked_gateway_environment(plan["harness"]),
305
- "PATH": os.pathsep.join([str(Path(magpie).parent), os.environ.get("PATH", "")]),
382
+ **_with_path(
383
+ harness.checked_gateway_environment(plan["harness"]),
384
+ [str(Path(magpie).parent)],
385
+ ),
306
386
  "MAGPIE_ADDR": gateway["addr"],
307
387
  }
308
388
  state = harness.inspect(
@@ -322,6 +402,23 @@ def _library_binding(
322
402
  }
323
403
 
324
404
 
405
+ def _diagnose_unavailable(exc: Exception) -> None:
406
+ """Emit one fixed-category stderr line without paths, secrets, or raw exception text."""
407
+ if isinstance(exc, harness.HarnessError):
408
+ cause = "harness-error"
409
+ elif isinstance(exc, FileNotFoundError):
410
+ cause = "profile-missing"
411
+ elif isinstance(exc, PermissionError):
412
+ cause = "profile-permission"
413
+ elif isinstance(exc, ValueError):
414
+ cause = "profile-invalid"
415
+ elif isinstance(exc, KeyError):
416
+ cause = "environment-missing"
417
+ else:
418
+ cause = type(exc).__name__.lower()
419
+ print(f"localmodels setup binding: unavailable cause={cause}", file=sys.stderr)
420
+
421
+
325
422
  def inspect_binding(path: Path, lang: Lang = "zh") -> BindingReport:
326
423
  report: BindingReport = {
327
424
  "schema": "localmodels.stack-binding/v1",
@@ -363,6 +460,14 @@ def inspect_binding(path: Path, lang: Lang = "zh") -> BindingReport:
363
460
  else:
364
461
  report["ready"] = True
365
462
  report["pi"] = binding
366
- except (OSError, ValueError, KeyError, StopIteration, AttributeError, harness.HarnessError):
463
+ except (
464
+ OSError,
465
+ ValueError,
466
+ KeyError,
467
+ StopIteration,
468
+ AttributeError,
469
+ harness.HarnessError,
470
+ ) as exc:
471
+ _diagnose_unavailable(exc)
367
472
  report["reasons"] = [_reason("binding-unavailable", lang)]
368
473
  return report
@@ -23,6 +23,7 @@ from localmodels import (
23
23
  hosts,
24
24
  http_local,
25
25
  process_identity,
26
+ process_windows,
26
27
  remote_ops_launchd,
27
28
  stack_cleanup,
28
29
  stack_remove,
@@ -127,13 +128,15 @@ def deployment_pids(plan: Plan) -> list[int]:
127
128
  """Current process identities of this exact deployment, including its unit children. A
128
129
  nohup or launchd deployment is its recorded process and the group that process leads: the
129
130
  server a launcher (slot_cache.py) starts is the one on the card's process list. Who holds
130
- the port is still asked of the recorded process alone (_not_serving). A Windows service is
131
- one process with no launcher: its recorded pid, with no look at other processes."""
131
+ the port is still asked of the recorded process alone (_not_serving). On Windows a launcher
132
+ (strata_poly_server.py) may also spawn a child engine (strata-poly.exe), so the recorded
133
+ process and its verified same-user descendants are returned."""
132
134
  state, pid = _service(plan)
133
135
  if state != "active" or pid is None:
134
136
  return []
135
- systemd = sys.platform.startswith("linux") and plan["service"]["kind"] == "systemd-user"
136
- if systemd or sys.platform == "win32":
137
+ if sys.platform == "win32":
138
+ return process_windows.windows_tree_pids(pid)
139
+ if sys.platform.startswith("linux") and plan["service"]["kind"] == "systemd-user":
137
140
  return _service_pids(plan, pid)
138
141
  return group_pids(pid)
139
142
 
@@ -40,6 +40,6 @@ def llm_parts(part: Plan, window: int | None = None) -> dict[str, int]:
40
40
  window or planned,
41
41
  slots=slots,
42
42
  kv_types=(str(kv_types[0]), str(kv_types[1])),
43
- ubatch=AGENT.ubatch,
43
+ ubatch=entry.agent_posture(AGENT).ubatch,
44
44
  mtp=_int(launch.get("mtp_draft_depth")) > 0,
45
45
  )
@@ -273,7 +273,9 @@ def sandbox(reading: Reading, ask: Ask) -> Sandbox:
273
273
  window = pick["window"] or posture.floor
274
274
  kv_name = pick["kv_types"] or _kv(posture.kv_types[-1])
275
275
  k, v = kv_name.split("/")
276
- parts = _parts(profile, window, slots, (k, v), posture.ubatch, pick["mtp"] > 0)
276
+ parts = _parts(
277
+ profile, window, slots, (k, v), entry.agent_posture(posture).ubatch, pick["mtp"] > 0
278
+ )
277
279
  if isinstance(decision, WindowDecision) and decision.vision_bytes:
278
280
  parts.append({"kind": "vision", "label": "Picture reader", "bytes": decision.vision_bytes})
279
281
  need = sum(p["bytes"] for p in parts)
@@ -49,6 +49,7 @@ from localmodels import (
49
49
  metal_probe,
50
50
  probe,
51
51
  process_identity,
52
+ process_windows,
52
53
  stack_up,
53
54
  stack_verify,
54
55
  stack_warm_store,
@@ -455,23 +456,33 @@ def pin_step(
455
456
  state, pid = process_identity.status(
456
457
  Path(os.path.expanduser(part["service"]["deploy_dir"]), "server.pid")
457
458
  )
458
- seen = probe(pid) if state == "active" and pid else None
459
- if pid is None or seen is None:
459
+ pids = process_windows.windows_tree_pids(pid) if state == "active" and pid else []
460
+ before = [(p, info) for p in pids if (info := probe(p)) is not None]
461
+ if pid is None or not before:
460
462
  step["detail"] = f"{part['name']} is not running; {command()} stack up starts it"
461
463
  return step
464
+ after: list[process_identity.Priority] = []
465
+ was_background: list[process_identity.Priority] = []
462
466
  try:
463
- now = normal(pid) if seen["background"] else seen
467
+ for p, info in before:
468
+ if info["background"]:
469
+ was_background.append(info)
470
+ after.append(normal(p))
471
+ else:
472
+ after.append(info)
464
473
  except OSError as exc:
465
474
  step["ok"] = False
466
475
  step["detail"] = f"{part['name']} is left running as background work: {exc}"
467
476
  return step
468
- step["ok"] = not now["background"]
477
+ step["ok"] = all(not info["background"] for info in after)
478
+ resident_mib = sum(info["resident_bytes"] for info in after) >> 20
479
+ worst = min(info["memory_priority"] for info in was_background) if was_background else 0
469
480
  step["detail"] = (
470
481
  f"{part['name']} runs at normal priority, so Windows leaves an idle server its memory "
471
- f"({now['resident_bytes'] >> 20} MiB resident now"
482
+ f"({resident_mib} MiB resident now"
472
483
  + (
473
- f"; it ran as background work before, memory priority {seen['memory_priority']} of 5)"
474
- if seen["background"]
484
+ f"; it ran as background work before, memory priority {worst} of 5)"
485
+ if was_background
475
486
  else ")"
476
487
  )
477
488
  )