@simplexai/localmodels-linux-x64 0.1.0-dev.49 → 0.1.0-dev.51

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 (67) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +65 -59
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/catalog.json +2395 -9
  5. package/modules/localmodels/deploy.py +29 -134
  6. package/modules/localmodels/download-mirrors.json +47 -0
  7. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +79 -0
  8. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +132 -0
  9. package/modules/localmodels/gateway.py +23 -6
  10. package/modules/localmodels/gateway_bifrost.py +6 -2
  11. package/modules/localmodels/harness.py +8 -2
  12. package/modules/localmodels/harness_gateway.py +78 -17
  13. package/modules/localmodels/harness_probe.py +43 -23
  14. package/modules/localmodels/hosts.py +52 -5
  15. package/modules/localmodels/library_floor.py +76 -0
  16. package/modules/localmodels/library_gateway.py +17 -1
  17. package/modules/localmodels/library_jobs.py +38 -6
  18. package/modules/localmodels/library_model.py +5 -0
  19. package/modules/localmodels/library_poly.py +273 -0
  20. package/modules/localmodels/library_pricing.py +24 -35
  21. package/modules/localmodels/library_serve.py +7 -0
  22. package/modules/localmodels/library_state.py +16 -0
  23. package/modules/localmodels/library_status.py +114 -29
  24. package/modules/localmodels/llm_rank.py +14 -0
  25. package/modules/localmodels/magpie_windows.py +312 -0
  26. package/modules/localmodels/plan_envelope.py +234 -3
  27. package/modules/localmodels/probe.py +1 -1
  28. package/modules/localmodels/process_identity.py +19 -9
  29. package/modules/localmodels/process_identity_darwin.py +155 -0
  30. package/modules/localmodels/remote_ops.py +11 -0
  31. package/modules/localmodels/remote_ops_download.py +30 -5
  32. package/modules/localmodels/remote_ops_service.py +11 -13
  33. package/modules/localmodels/reuse.py +13 -6
  34. package/modules/localmodels/runtime_cli.py +8 -8
  35. package/modules/localmodels/runtime_install.py +25 -1
  36. package/modules/localmodels/runtime_io.py +32 -18
  37. package/modules/localmodels/setup_inspection.py +83 -79
  38. package/modules/localmodels/setup_inspection_harness.py +147 -0
  39. package/modules/localmodels/setup_text.py +12 -0
  40. package/modules/localmodels/setup_upgrade.py +11 -1
  41. package/modules/localmodels/stack.py +3 -1
  42. package/modules/localmodels/stack_auto.py +6 -2
  43. package/modules/localmodels/stack_cli.py +39 -0
  44. package/modules/localmodels/stack_clients.py +1 -1
  45. package/modules/localmodels/stack_compose.py +12 -43
  46. package/modules/localmodels/stack_down.py +25 -16
  47. package/modules/localmodels/stack_hardware.py +12 -1
  48. package/modules/localmodels/stack_picks.py +28 -13
  49. package/modules/localmodels/stack_plan.py +55 -3
  50. package/modules/localmodels/stack_remove.py +3 -1
  51. package/modules/localmodels/stack_suite.py +80 -20
  52. package/modules/localmodels/strata-poly-serve-0.2.19-poly.1.txt +428 -0
  53. package/modules/localmodels/{strata-poly-serve-0.1.45-poly.9.txt → strata-poly-serve-0.2.20-poly.1.txt} +2 -2
  54. package/modules/localmodels/strata_poly_server.py +33 -2
  55. package/modules/localmodels/suite.py +45 -4
  56. package/modules/localmodels/tool_archive.py +4 -0
  57. package/modules/localmodels/vision.py +4 -2
  58. package/modules/localmodels/win_probe.py +24 -7
  59. package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/METADATA +1 -1
  60. package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/RECORD +62 -56
  61. package/package.json +1 -1
  62. package/tool.json +1 -1
  63. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +0 -75
  64. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/WHEEL +0 -0
  65. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/entry_points.txt +0 -0
  66. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/licenses/NOTICE +0 -0
  67. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -65,6 +65,20 @@ def strata_bar(llama_score: int, options: Mapping[str, object]) -> int:
65
65
  return llama_score + TIE_BAND
66
66
 
67
67
 
68
+ def strata_recipe_bar(
69
+ llama_score: int, options: Mapping[str, object], *, prefer_over_llama: bool = False
70
+ ) -> int:
71
+ """The installed score one Strata/PolyStrata recipe must reach to replace the llama.cpp pick:
72
+ a recipe marked ``prefer_over_llama`` (such as PolyStrata Inkling 2 Mini on CUDA 13+, which
73
+ offers higher-precision quants and faster decode/prefill on NVIDIA cards) wins ties against
74
+ llama.cpp under ``smartest``, while keeping ``--prefer fastest`` on llama.cpp when one fits."""
75
+ if options.get("prefer") == "fastest" and llama_score >= 0:
76
+ return 1 << 30
77
+ if prefer_over_llama:
78
+ return max(0, llama_score)
79
+ return llama_score + TIE_BAND
80
+
81
+
68
82
  PRODUCT_DEFAULTS = {
69
83
  ("win32", "cuda", "NVIDIA RTX Spark N1X"): "qwen3.8-27b",
70
84
  }
@@ -0,0 +1,312 @@
1
+ """Windows multi-hop successor adoption for private ``magpie serve`` instances.
2
+
3
+ Controller-side (Layer 4): ``process_windows`` stays self-contained Python 3.8 inside
4
+ ``BUNDLES["remote_ops"]`` so it cannot import ``runtime_io``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ctypes
10
+ import json
11
+ import os
12
+ import posixpath
13
+ import stat
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from localmodels import process_identity, process_windows, runtime_io
18
+
19
+
20
+ def _read_windows_argv0(text: str) -> tuple[str, int]:
21
+ """Read argv[0] per Windows CommandLineToArgvW (quotes toggle; backslashes are literal)."""
22
+ index, length, in_quotes = 0, len(text), False
23
+ buf: list[str] = []
24
+ while index < length:
25
+ ch = text[index]
26
+ if ch == '"':
27
+ in_quotes = not in_quotes
28
+ elif ch in " \t" and not in_quotes:
29
+ break
30
+ else:
31
+ buf.append(ch)
32
+ index += 1
33
+ return "".join(buf), index
34
+
35
+
36
+ def _read_windows_arg(text: str, index: int) -> tuple[str, int]:
37
+ """Read one non-argv[0] argument per Windows CommandLineToArgvW backslash/quote rules."""
38
+ length, in_quotes = len(text), False
39
+ buf: list[str] = []
40
+ while index < length:
41
+ ch = text[index]
42
+ if ch in " \t" and not in_quotes:
43
+ break
44
+ if ch == "\\":
45
+ slashes = 0
46
+ while index < length and text[index] == "\\":
47
+ slashes += 1
48
+ index += 1
49
+ if index < length and text[index] == '"':
50
+ buf.append("\\" * (slashes // 2))
51
+ if slashes % 2:
52
+ buf.append('"')
53
+ else:
54
+ in_quotes = not in_quotes
55
+ index += 1
56
+ else:
57
+ buf.append("\\" * slashes)
58
+ elif ch == '"':
59
+ if in_quotes and index + 1 < length and text[index + 1] == '"':
60
+ buf.append('"')
61
+ index += 2
62
+ else:
63
+ in_quotes = not in_quotes
64
+ index += 1
65
+ else:
66
+ buf.append(ch)
67
+ index += 1
68
+ return "".join(buf), index
69
+
70
+
71
+ def split_windows_cmdline(cmdline: str) -> list[str]:
72
+ """Parse a Windows command line into argv tokens following CommandLineToArgvW rules."""
73
+ text = cmdline.lstrip(" \t")
74
+ if not text:
75
+ return []
76
+ arg0, index = _read_windows_argv0(text)
77
+ args = [arg0]
78
+ length = len(text)
79
+ while index < length:
80
+ while index < length and text[index] in " \t":
81
+ index += 1
82
+ if index >= length:
83
+ break
84
+ arg, index = _read_windows_arg(text, index)
85
+ args.append(arg)
86
+ return args
87
+
88
+
89
+ def _is_magpie_serve_argv(argv: list[str]) -> bool:
90
+ """True only when ``serve`` is the actual Magpie subcommand (argv[1]), not a path segment."""
91
+ return len(argv) >= 2 and argv[1].lower() == "serve"
92
+
93
+
94
+ def _parse_windows_env_block(raw: bytes) -> dict[str, str]:
95
+ """Decode a Windows UTF-16LE double-NUL-terminated environment block (uppercased keys)."""
96
+ if len(raw) % 2:
97
+ raw = raw[:-1]
98
+ env: dict[str, str] = {}
99
+ for entry in raw.decode("utf-16-le", errors="replace").split("\x00"):
100
+ if not entry:
101
+ break
102
+ if "=" not in entry or entry.startswith("="):
103
+ continue
104
+ key, _, value = entry.partition("=")
105
+ env[key.upper()] = value
106
+ return env
107
+
108
+
109
+ def _read_remote_ptr(read_mem: Any, handle: Any, addr: int, ptr_size: int) -> int | None:
110
+ val = ctypes.c_size_t(0)
111
+ got = ctypes.c_size_t(0)
112
+ if not read_mem(handle, addr, ctypes.byref(val), ptr_size, ctypes.byref(got)):
113
+ return None
114
+ return int(val.value) if got.value == ptr_size else None
115
+
116
+
117
+ def process_environment(pid: int) -> dict[str, str] | None:
118
+ """Windows: read PID's PEB environment block via NtQueryInformationProcess + ReadProcessMemory.
119
+ Returns uppercased env mapping, or None when unavailable or off Windows."""
120
+ load: Any = getattr(ctypes, "WinDLL", None)
121
+ if load is None:
122
+ return None
123
+ from ctypes import wintypes
124
+
125
+ class BasicInfo(ctypes.Structure):
126
+ _fields_ = [
127
+ ("Reserved1", ctypes.c_void_p),
128
+ ("PebBaseAddress", ctypes.c_void_p),
129
+ ("Reserved2", ctypes.c_void_p * 2),
130
+ ("UniqueProcessId", ctypes.c_void_p),
131
+ ("Reserved3", ctypes.c_void_p),
132
+ ]
133
+
134
+ kernel, _ = process_identity._api()
135
+ ntdll = load("ntdll")
136
+ query = ntdll.NtQueryInformationProcess
137
+ query.argtypes = (
138
+ wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.ULONG, ctypes.POINTER(wintypes.ULONG)
139
+ ) # fmt: skip
140
+ query.restype = ctypes.c_long
141
+ read_mem = kernel.ReadProcessMemory
142
+ read_mem.argtypes = (
143
+ wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)
144
+ ) # fmt: skip
145
+ read_mem.restype = wintypes.BOOL
146
+ # PROCESS_QUERY_INFORMATION (0x0400) | PROCESS_VM_READ (0x0010)
147
+ handle = kernel.OpenProcess(0x0410, False, pid)
148
+ if not handle:
149
+ return None
150
+ try:
151
+ info = BasicInfo()
152
+ ret_len = wintypes.ULONG(0)
153
+ if query(handle, 0, ctypes.byref(info), ctypes.sizeof(info), ctypes.byref(ret_len)) != 0:
154
+ return None
155
+ if not info.PebBaseAddress:
156
+ return None
157
+ ptr_size = ctypes.sizeof(ctypes.c_size_t)
158
+ params_ptr = _read_remote_ptr(
159
+ read_mem, handle, int(info.PebBaseAddress) + (0x20 if ptr_size == 8 else 0x10), ptr_size
160
+ )
161
+ if not params_ptr:
162
+ return None
163
+ env_ptr = _read_remote_ptr(
164
+ read_mem, handle, params_ptr + (0x80 if ptr_size == 8 else 0x48), ptr_size
165
+ )
166
+ env_size = _read_remote_ptr(
167
+ read_mem, handle, params_ptr + (0x3F0 if ptr_size == 8 else 0x290), ptr_size
168
+ )
169
+ if not env_ptr or not env_size:
170
+ return None
171
+ to_read = min(env_size, 1 << 20)
172
+ buf = ctypes.create_string_buffer(to_read)
173
+ got = ctypes.c_size_t(0)
174
+ if not read_mem(handle, env_ptr, buf, to_read, ctypes.byref(got)) or got.value < 2:
175
+ return None
176
+ return _parse_windows_env_block(buf.raw[: got.value])
177
+ except OSError:
178
+ return None
179
+ finally:
180
+ kernel.CloseHandle(handle)
181
+
182
+
183
+ def _norm_path(value: str | Path) -> str:
184
+ text = str(value).strip()
185
+ if not text:
186
+ return ""
187
+ if os.name == "nt":
188
+ return os.path.normcase(os.path.realpath(text)).replace("\\", "/").rstrip("/")
189
+ slashed = text.replace("\\", "/")
190
+ if (len(slashed) >= 2 and slashed[1] == ":") or slashed.startswith("//"):
191
+ prefix = "//" if slashed.startswith("//") else ""
192
+ return (
193
+ (prefix + posixpath.normpath(slashed.lstrip("/") if prefix else slashed))
194
+ .rstrip("/")
195
+ .lower()
196
+ )
197
+ return os.path.realpath(slashed).rstrip("/").lower()
198
+
199
+
200
+ def _env_matches_gateway_home(env: dict[str, str], gateway_home: str | Path) -> bool:
201
+ """True only when the process environment positively targets this private ``gateway_home``."""
202
+ home_norm = _norm_path(gateway_home)
203
+ cfg_norm = _norm_path(Path(gateway_home) / ".config" / "magpie")
204
+ if not home_norm:
205
+ return False
206
+ upper = {k.upper(): v for k, v in env.items()}
207
+ if cfg := upper.get("MAGPIE_CONFIG_DIR", "").strip():
208
+ return _norm_path(cfg) == cfg_norm
209
+ userprofile = upper.get("USERPROFILE", "").strip()
210
+ if userprofile:
211
+ return _norm_path(userprofile) == home_norm
212
+ home = upper.get("HOME", "").strip()
213
+ return bool(home) and _norm_path(home) == home_norm
214
+
215
+
216
+ def _non_link_stat(path: Path) -> os.stat_result | None:
217
+ try:
218
+ info = path.lstat()
219
+ except OSError:
220
+ return None
221
+ if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400:
222
+ return None
223
+ return info
224
+
225
+
226
+ def _serving_lock_pid(gateway_home: str | Path) -> int | None:
227
+ """PID stored in private non-symlink ``gateway.serving.lock`` if readable; None otherwise."""
228
+ home = Path(gateway_home)
229
+ for parent in (home, home / ".config", home / ".config" / "magpie"):
230
+ pinfo = _non_link_stat(parent)
231
+ if pinfo is None or not stat.S_ISDIR(pinfo.st_mode):
232
+ return None
233
+ lock = home / ".config" / "magpie" / "gateway.serving.lock"
234
+ info = _non_link_stat(lock)
235
+ if info is None or not stat.S_ISREG(info.st_mode):
236
+ return None
237
+ try:
238
+ if os.name == "nt":
239
+ runtime_io.private_permissions(lock)
240
+ raw = lock.read_text(encoding="utf-8").strip()
241
+ except (OSError, ValueError):
242
+ return None
243
+ if raw.isdigit():
244
+ return int(raw)
245
+ try:
246
+ doc = json.loads(raw)
247
+ except ValueError:
248
+ return None
249
+ pid = doc.get("pid") if isinstance(doc, dict) else None
250
+ return pid if isinstance(pid, int) and not isinstance(pid, bool) and pid > 0 else None
251
+
252
+
253
+ def magpie_successor_pid(
254
+ saved: process_identity.Identity,
255
+ program: str,
256
+ port: int,
257
+ gateway_home: str | Path | None = None,
258
+ ) -> int | None:
259
+ """Windows: identify a single verified multi-hop successor of an owned ``magpie serve``
260
+ listening on the approved ``port`` (for example after periodic self-restarts broke the
261
+ 1-hop parent-PID chain). Fails closed: requires positive proof linking the listener to
262
+ ``gateway_home`` (private ``gateway.serving.lock`` PID match or matching PEB environment)."""
263
+ if gateway_home is None:
264
+ return None
265
+ listeners = process_identity.listener_pids(port)
266
+ if not listeners or len(listeners) != 1:
267
+ return None
268
+ cand = next(iter(listeners))
269
+ if cand <= 0:
270
+ return None
271
+ found = process_identity._windows_inspect(cand)
272
+ if found is None or found["uid"] != 0 or int(found["started"]) <= int(saved["started"]):
273
+ return None
274
+ if not process_identity._windows_command_matches(cand, [program]):
275
+ return None
276
+ cmdline = process_windows.command_line(cand)
277
+ if cmdline is not None and not _is_magpie_serve_argv(split_windows_cmdline(cmdline)):
278
+ return None
279
+ lock_pid = _serving_lock_pid(gateway_home)
280
+ if lock_pid is not None:
281
+ return cand if lock_pid == cand else None
282
+ if cmdline is None:
283
+ return None
284
+ proc_env = process_environment(cand)
285
+ if proc_env is None or not _env_matches_gateway_home(proc_env, gateway_home):
286
+ return None
287
+ return cand
288
+
289
+
290
+ def adopt_magpie_successor(
291
+ pid_file: str | Path,
292
+ program: str,
293
+ port: int | None = None,
294
+ gateway_home: str | Path | None = None,
295
+ ) -> bool:
296
+ """Adopt a restarted Windows ``magpie serve``: 1-hop child first, then multi-hop listener."""
297
+ if process_identity.adopt_successor(pid_file, program):
298
+ return True
299
+ if not process_identity._windows() or port is None:
300
+ return False
301
+ path = Path(pid_file)
302
+ try:
303
+ saved = process_identity._recorded(path)
304
+ if saved is None or process_identity._windows_inspect(saved["pid"]) is not None:
305
+ return False
306
+ cand = magpie_successor_pid(saved, program, port, gateway_home)
307
+ if cand is None:
308
+ return False
309
+ process_identity.save(path, cand)
310
+ return True
311
+ except (OSError, ValueError, RuntimeError):
312
+ return False
@@ -8,17 +8,34 @@ from __future__ import annotations
8
8
  import datetime as dt
9
9
  import functools
10
10
  import hashlib
11
+ import http.client
11
12
  import json
12
13
  import os
13
14
  import re
15
+ import sys
16
+ import time
17
+ import urllib.error
14
18
  import urllib.parse
15
- from collections.abc import Mapping
19
+ import urllib.request
20
+ from collections.abc import Callable, Mapping, Sequence
16
21
  from dataclasses import dataclass
17
22
  from pathlib import Path
23
+ from typing import TypedDict
18
24
 
25
+ from localmodels import catalog as cat
26
+ from localmodels import region
19
27
  from localmodels.budget import gib
28
+ from localmodels.contracts import decode
20
29
  from localmodels.probe import HostFacts
21
- from localmodels.records import Launch, ModelSpec, Plan, ReleaseEngine, ReusableFile, ServicePlan
30
+ from localmodels.records import (
31
+ Launch,
32
+ ModelSpec,
33
+ PinnedFile,
34
+ Plan,
35
+ ReleaseEngine,
36
+ ReusableFile,
37
+ ServicePlan,
38
+ )
22
39
  from localmodels.remote_ops import Source
23
40
 
24
41
  PLAN_SCHEMA = "localmodels.deployment-plan/v1"
@@ -27,6 +44,219 @@ PLAN_SCHEMA = "localmodels.deployment-plan/v1"
27
44
  class PlanError(ValueError):
28
45
  """The deployment cannot be planned as requested; the message says why."""
29
46
 
47
+ def __init__(self, message: str, *, cause_code: str | None = None) -> None:
48
+ super().__init__(message)
49
+ self.cause_code = cause_code
50
+
51
+
52
+ _COMMIT_SHA = re.compile(r"^[0-9a-f]{40}$")
53
+ _HF_GET_ATTEMPTS = 3
54
+ _HF_RETRY_DELAYS_S = (0.25, 0.75)
55
+
56
+
57
+ class HubUnreachableError(PlanError):
58
+ """The Hub API could not be reached over the network."""
59
+
60
+ def __init__(self, failures: Sequence[tuple[str, str]]) -> None:
61
+ self.failures = tuple(failures)
62
+ if len(self.failures) == 1:
63
+ host, reason = self.failures[0]
64
+ where = f"{host} to look up the model files ({reason})"
65
+ else:
66
+ where = (
67
+ " or ".join(f"{host} ({reason})" for host, reason in self.failures)
68
+ + " to look up the model files"
69
+ )
70
+ super().__init__(
71
+ f"cannot reach {where}; "
72
+ "name a reachable Hub with --hf-endpoint URL or HF_ENDPOINT (a mirror such as "
73
+ "https://hf-mirror.com), or plan from the catalog's pins with --offline",
74
+ cause_code="HUB_UNREACHABLE",
75
+ )
76
+
77
+
78
+ def _is_timeout(exc: BaseException) -> bool:
79
+ return isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError)
80
+
81
+
82
+ def hf_get(url: str) -> object:
83
+ """One Hub API document. Transient non-timeout disconnects retry briefly; timeouts fail over
84
+ immediately so a blackholed host does not stall."""
85
+ req = urllib.request.Request(url, headers={"User-Agent": "localmodels-plan"})
86
+ for attempt in range(_HF_GET_ATTEMPTS):
87
+ try:
88
+ with urllib.request.urlopen(req, timeout=20) as r:
89
+ return json.load(r)
90
+ except urllib.error.HTTPError:
91
+ raise # the Hub answered: a missing repo or revision is the caller's to report
92
+ except (OSError, http.client.HTTPException) as exc:
93
+ if _is_timeout(exc) or attempt + 1 >= _HF_GET_ATTEMPTS:
94
+ host = urllib.parse.urlsplit(url).netloc
95
+ raise HubUnreachableError([(host, str(getattr(exc, "reason", exc)))]) from exc
96
+ time.sleep(_HF_RETRY_DELAYS_S[attempt])
97
+ raise AssertionError("unreachable Hub retry loop")
98
+
99
+
100
+ def hub_get(
101
+ api: str,
102
+ path: str,
103
+ *,
104
+ mint: bool = False,
105
+ fetch: Callable[[str], object] = hf_get,
106
+ ) -> object:
107
+ """One Hub API document across region-ordered endpoints, preserving every failed host's reason."""
108
+ endpoints = [api.rstrip("/")] if mint else region.hub_endpoints(api)
109
+ failures: list[tuple[str, str]] = []
110
+ for index, endpoint in enumerate(endpoints):
111
+ try:
112
+ doc = fetch(endpoint + path)
113
+ except PlanError as exc:
114
+ if isinstance(exc, HubUnreachableError):
115
+ failures.extend(exc.failures)
116
+ else:
117
+ failures.append((urllib.parse.urlsplit(endpoint).netloc, str(exc)))
118
+ if index + 1 < len(endpoints):
119
+ continue
120
+ if mint and not region.explicit_hub(api):
121
+ what = path.split("/api/models/")[-1]
122
+ raise PlanError(
123
+ region.MINT_REFUSAL.format(what=what),
124
+ cause_code="HUB_UNREACHABLE",
125
+ ) from exc
126
+ if len(failures) > 1:
127
+ raise HubUnreachableError(failures) from exc
128
+ raise
129
+ if index:
130
+ region.fallback_to(region.side_of_endpoint(endpoint))
131
+ return doc
132
+ raise AssertionError("unreachable Hub loop")
133
+
134
+
135
+ class _Revision(TypedDict):
136
+ sha: str
137
+
138
+
139
+ class _LfsFile(TypedDict):
140
+ size: int
141
+ oid: str
142
+
143
+
144
+ class _TreeEntry(TypedDict):
145
+ path: str
146
+
147
+
148
+ class _OptionalTreeEntry(_TreeEntry, total=False):
149
+ lfs: _LfsFile
150
+
151
+
152
+ def _can_use_catalog_pin(asset: cat.AssetFile, api: str) -> bool:
153
+ return (
154
+ asset.sha256 is not None
155
+ and bool(_COMMIT_SHA.fullmatch(asset.revision))
156
+ and not region.explicit_hub(api)
157
+ )
158
+
159
+
160
+ def _pinned_from_catalog(repo: str, asset: cat.AssetFile) -> PinnedFile:
161
+ assert asset.sha256 is not None
162
+ return {
163
+ "repo": repo,
164
+ "path": asset.path,
165
+ "revision": asset.revision,
166
+ "size_bytes": asset.size_bytes,
167
+ "sha256": asset.sha256,
168
+ "local_name": asset.local_name,
169
+ }
170
+
171
+
172
+ def resolve_files(
173
+ assets: list[tuple[str, cat.AssetFile]],
174
+ api: str,
175
+ *,
176
+ fetch_hub: Callable[..., object] = hub_get,
177
+ ) -> list[PinnedFile]:
178
+ """Pin each asset via the Hub API, falling back to exact catalog pins when the default Hub is
179
+ unreachable over the network."""
180
+ revisions: dict[tuple[str, str, bool], str] = {}
181
+ trees: dict[tuple[str, str, str, bool], dict[str, _OptionalTreeEntry]] = {}
182
+ pinned: list[PinnedFile] = []
183
+ hub_offline = False
184
+ noticed_repos: set[str] = set()
185
+ for repo, asset in assets:
186
+ mint = asset.sha256 is None
187
+ fallback_ok = _can_use_catalog_pin(asset, api)
188
+ if hub_offline and fallback_ok:
189
+ pinned.append(_pinned_from_catalog(repo, asset))
190
+ continue
191
+ key = (repo, asset.revision, mint)
192
+ try:
193
+ if key not in revisions:
194
+ doc = decode(
195
+ fetch_hub(
196
+ api,
197
+ f"/api/models/{repo}/revision/{urllib.parse.quote(asset.revision)}",
198
+ mint=mint,
199
+ ),
200
+ _Revision,
201
+ )
202
+ revisions[key] = doc["sha"]
203
+ commit = revisions[key]
204
+ directory = asset.path.rsplit("/", 1)[0] if "/" in asset.path else ""
205
+ tkey = (repo, commit, directory, mint)
206
+ if tkey not in trees:
207
+ path = f"/api/models/{repo}/tree/{commit}" + (
208
+ f"/{urllib.parse.quote(directory)}" if directory else ""
209
+ )
210
+ entries = fetch_hub(api, path, mint=mint)
211
+ if not isinstance(entries, list):
212
+ raise PlanError("Hub tree must be an array")
213
+ parsed = [decode(e, _OptionalTreeEntry) for e in entries]
214
+ trees[tkey] = {e["path"]: e for e in parsed}
215
+ except HubUnreachableError:
216
+ if not fallback_ok:
217
+ raise
218
+ hub_offline = True
219
+ if repo not in noticed_repos:
220
+ noticed_repos.add(repo)
221
+ print(
222
+ f"localmodels: Hub unreachable; using catalog pins for {repo}",
223
+ file=sys.stderr,
224
+ )
225
+ pinned.append(_pinned_from_catalog(repo, asset))
226
+ continue
227
+ entry = trees[tkey].get(asset.path)
228
+ if entry is None or not entry.get("lfs"):
229
+ raise PlanError(f"{asset.path} not found in {repo}@{commit[:12]}")
230
+ if int(entry["lfs"]["size"]) != asset.size_bytes:
231
+ raise PlanError(
232
+ f"{asset.path} size {entry['lfs']['size']} != catalog size {asset.size_bytes}"
233
+ )
234
+ if asset.sha256 is not None and entry["lfs"]["oid"] != asset.sha256:
235
+ raise PlanError(f"{asset.path} on the Hub has a SHA256 the catalog does not pin")
236
+ pinned.append(
237
+ {
238
+ "repo": repo,
239
+ "path": asset.path,
240
+ "revision": commit,
241
+ "size_bytes": asset.size_bytes,
242
+ "sha256": entry["lfs"]["oid"],
243
+ "local_name": asset.local_name,
244
+ }
245
+ )
246
+ return pinned
247
+
248
+
249
+ def catalog_pins(assets: list[tuple[str, cat.AssetFile]], _api: str) -> list[PinnedFile]:
250
+ """Each asset at the commit and SHA256 the catalog pins, asking the Hub nothing."""
251
+ pinned: list[PinnedFile] = []
252
+ for repo, asset in assets:
253
+ if asset.sha256 is None:
254
+ raise PlanError(
255
+ f"catalog pins no commit and SHA256 for {repo}/{asset.path}; cannot plan it offline"
256
+ )
257
+ pinned.append(_pinned_from_catalog(repo, asset))
258
+ return pinned
259
+
30
260
 
31
261
  def deployment_name(model_id: str, port: int) -> str:
32
262
  return re.sub(r"[^a-z0-9.-]+", "-", f"{model_id}-{port}".lower())
@@ -154,7 +384,8 @@ def require_disk(facts: HostFacts, files: list[ReusableFile], *, local: bool = F
154
384
  if free is not None and total > free:
155
385
  raise PlanError(
156
386
  f"not enough disk space: needs {gib(total)}, {facts['disk']['path']} has only "
157
- f"{gib(free)} free"
387
+ f"{gib(free)} free",
388
+ cause_code="DISK_INSUFFICIENT",
158
389
  )
159
390
 
160
391
 
@@ -181,7 +181,7 @@ class HostFacts(RequiredHostFacts, total=False):
181
181
  memory_bandwidth: MemoryBandwidth # only after probe --measure-bandwidth
182
182
  shared_libraries: dict[str, bool] # HOST_LIBRARIES: can the loader find each one
183
183
  metal: dict[str, object] | None # metal_probe.py on Apple Silicon (2026-10-29; metal.Metal)
184
- gpu_processes: list[win_probe.GpuAppMemory] # Windows WDDM per-app dedicated VRAM (CIM)
184
+ gpu_processes: list[win_probe.GpuAppMemory] # Windows WDDM per-app local VRAM (CIM)
185
185
 
186
186
 
187
187
  SCHEMA = "localmodels.host-facts/v1"
@@ -264,13 +264,17 @@ def image_path(pid: int) -> str | None:
264
264
  return found[1] or None if found else None
265
265
 
266
266
 
267
- def listener_pids(port: int) -> set[int] | None:
268
- """Windows: PIDs listening on TCP ``port`` (IPv4/IPv6 iphlpapi tables), or None on failure."""
267
+ def listener_pids(port: int, *, host: str = "127.0.0.1") -> set[int] | None:
268
+ """Windows: PIDs listening on TCP ``port`` conflicting with ``host``, or None on failure."""
269
+ import ipaddress
269
270
  import struct
270
271
 
271
272
  iphlpapi = ctypes.WinDLL("iphlpapi") # type: ignore[attr-defined]
272
273
  owners: set[int] = set()
273
- for family, row_size, port_at, pid_at in ((2, 24, 8, 20), (23, 56, 20, 52)):
274
+ for family, row_size, addr_at, addr_len, port_at, pid_at in (
275
+ (2, 24, 4, 4, 8, 20),
276
+ (23, 56, 0, 16, 20, 52),
277
+ ):
274
278
  size = ctypes.c_ulong(0)
275
279
  # TCP_TABLE_OWNER_PID_LISTENER = 3; first call sizes the buffer.
276
280
  iphlpapi.GetExtendedTcpTable(None, ctypes.byref(size), False, family, 3, 0)
@@ -286,7 +290,15 @@ def listener_pids(port: int) -> set[int] | None:
286
290
  for index in range(count):
287
291
  row = 4 + index * row_size
288
292
  local_port = struct.unpack_from(">H", raw, row + port_at)[0]
289
- if local_port == port:
293
+ if local_port != port:
294
+ continue
295
+ addr_bytes = raw[row + addr_at : row + addr_at + addr_len]
296
+ bound = (
297
+ ipaddress.IPv4Address(addr_bytes)
298
+ if addr_len == 4
299
+ else ipaddress.IPv6Address(addr_bytes)
300
+ )
301
+ if process_identity_darwin.address_conflicts(bound, host):
290
302
  owners.add(struct.unpack_from("<I", raw, row + pid_at)[0])
291
303
  return owners
292
304
 
@@ -681,7 +693,7 @@ def listener_owned(port: int, pid: int | None) -> bool:
681
693
  return False
682
694
  try:
683
695
  res = subprocess.run(
684
- ["/usr/sbin/lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"],
696
+ ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpn"],
685
697
  capture_output=True,
686
698
  text=True,
687
699
  timeout=5,
@@ -689,10 +701,8 @@ def listener_owned(port: int, pid: int | None) -> bool:
689
701
  )
690
702
  except (OSError, subprocess.TimeoutExpired):
691
703
  return False
692
- owners = {
693
- int(ln[1:]) for ln in res.stdout.splitlines() if ln.startswith("p") and ln[1:].isdigit()
694
- }
695
- return res.returncode == 0 and owners == {pid}
704
+ parsed = process_identity_darwin.parse_lsof_listeners(res.stdout, port, "127.0.0.1")
705
+ return res.returncode == 0 and parsed is not None and parsed[0] == {pid}
696
706
 
697
707
 
698
708
  def command_matches(pid: int, expected: list[str], root: str = "/") -> bool: