@simplexai/localmodels-linux-x64 0.1.0-dev.54 → 0.1.0-dev.56

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 (44) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +43 -38
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/bifrost_admin.py +336 -0
  5. package/modules/localmodels/bifrost_checks.py +12 -2
  6. package/modules/localmodels/bifrost_config.py +13 -5
  7. package/modules/localmodels/catalog.json +2 -1
  8. package/modules/localmodels/debug_mode.py +6 -3
  9. package/modules/localmodels/engines.py +24 -1
  10. package/modules/localmodels/library_floor.py +3 -1
  11. package/modules/localmodels/library_gateway.py +26 -4
  12. package/modules/localmodels/library_jobs.py +44 -6
  13. package/modules/localmodels/library_kept.py +117 -0
  14. package/modules/localmodels/library_model.py +1 -0
  15. package/modules/localmodels/library_order.py +234 -0
  16. package/modules/localmodels/library_poly.py +20 -16
  17. package/modules/localmodels/library_pricing.py +8 -1
  18. package/modules/localmodels/library_serve.py +9 -3
  19. package/modules/localmodels/library_state.py +12 -2
  20. package/modules/localmodels/library_status.py +2 -0
  21. package/modules/localmodels/llm_rank.py +11 -8
  22. package/modules/localmodels/mirrors.py +464 -0
  23. package/modules/localmodels/recommend.py +2 -2
  24. package/modules/localmodels/records.py +1 -0
  25. package/modules/localmodels/region.py +457 -42
  26. package/modules/localmodels/remote_ops.py +130 -33
  27. package/modules/localmodels/remote_ops_download.py +313 -273
  28. package/modules/localmodels/remote_ops_mirrors.py +290 -0
  29. package/modules/localmodels/runtime-lock.json +19 -19
  30. package/modules/localmodels/runtime_io.py +2 -4
  31. package/modules/localmodels/runtime_releases.py +6 -0
  32. package/modules/localmodels/setup_inspection.py +4 -0
  33. package/modules/localmodels/stack_auto.py +38 -5
  34. package/modules/localmodels/stack_compose.py +2 -1
  35. package/modules/localmodels/stack_try.py +4 -1
  36. package/modules/localmodels/transport.py +1 -0
  37. package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/METADATA +1 -1
  38. package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/RECORD +40 -35
  39. package/package.json +1 -1
  40. package/tool.json +1 -1
  41. /package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/WHEEL +0 -0
  42. /package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/entry_points.txt +0 -0
  43. /package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/licenses/NOTICE +0 -0
  44. /package/modules/{simplex_localmodels-0.1.0.dev54.dist-info → simplex_localmodels-0.1.0.dev56.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -27,6 +27,7 @@ from localmodels import (
27
27
  deploy,
28
28
  engines,
29
29
  hosts,
30
+ library_kept,
30
31
  library_poly,
31
32
  library_vram,
32
33
  llm_rank,
@@ -106,7 +107,9 @@ def shown(facts: HostFacts, catalog: Iterable[cat.CatalogEntry]) -> list[Model]:
106
107
 
107
108
 
108
109
  def find(model_id: str, catalog: Iterable[cat.CatalogEntry]) -> Model:
109
- """The catalog row a library id names (``id:QUANT``; a bare id is its last variant)."""
110
+ """The catalog row a library id names (``id:QUANT``; a bare id is its last variant), else
111
+ the model a library record on disk holds under that id (library_kept)."""
112
+ catalog = tuple(catalog)
110
113
  catalog_id, quant = split_id(model_id)
111
114
  for entry in catalog:
112
115
  if entry.id == catalog_id and is_chat(entry):
@@ -116,6 +119,8 @@ def find(model_id: str, catalog: Iterable[cat.CatalogEntry]) -> Model:
116
119
  return Model(entry, variant)
117
120
  if poly := library_poly.find_entry(model_id):
118
121
  return Model(*poly)
122
+ if kept := library_kept.find_entry(model_id, catalog):
123
+ return Model(*kept)
119
124
  raise LibraryError("MODEL_UNKNOWN", f"the catalog has no chat model {model_id}")
120
125
 
121
126
 
@@ -353,6 +358,8 @@ def price(
353
358
  placement = pools(facts).get(pool)
354
359
  if placement is None:
355
360
  raise plan_envelope.PlanError(f"this computer has no pool {pool}")
361
+ if library_kept.retired(model.entry):
362
+ raise plan_envelope.PlanError(f"this version no longer ships {model.id}")
356
363
  if model.entry.runtime == "strata-poly":
357
364
  return library_poly.price(
358
365
  facts, model.entry.id, pool, base_dir, port, posture(), require_live=require_live
@@ -26,6 +26,7 @@ from localmodels import (
26
26
  hosts,
27
27
  library_gateway,
28
28
  library_jobs,
29
+ library_kept,
29
30
  library_pricing,
30
31
  library_state,
31
32
  library_status,
@@ -348,9 +349,9 @@ def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts
348
349
 
349
350
 
350
351
  def _row(model: Model, base_dir: str) -> Row:
351
- return library_status.model_row(
352
- library_status.Library.read(library_jobs.probe(), base_dir), model.id
353
- )
352
+ """The model's row now; by the model resolved before the command, as a removed model kept
353
+ only by its record (library_kept) no longer resolves by its id."""
354
+ return library_status.row(library_status.Library.read(library_jobs.probe(), base_dir), model)
354
355
 
355
356
 
356
357
  def load(model_id: str, base_dir: str, unload: list[str]) -> Row:
@@ -375,6 +376,11 @@ def load(model_id: str, base_dir: str, unload: list[str]) -> Row:
375
376
  url = str(record["plan"]["endpoint"]["base_url"])
376
377
  if record["state"] == "loaded" and library_status.answering(url):
377
378
  return library_status.model_row(library_status.Library.read(facts, base_dir), model.id)
379
+ if library_kept.retired(model.entry):
380
+ raise LibraryError(
381
+ "INVALID_STATE",
382
+ f"this version no longer ships {model.id}; remove it and download a current model",
383
+ )
378
384
  for other in others:
379
385
  library_state.refuse_busy(other, "unload")
380
386
  found = library_state.load(other)
@@ -269,7 +269,12 @@ class JobHandle:
269
269
  ) -> None:
270
270
  import time
271
271
 
272
- prev = (self.job.get("phase"), self.job.get("load_step"), self.job.get("source"))
272
+ prev = (
273
+ self.job.get("phase"),
274
+ self.job.get("load_step"),
275
+ self.job.get("source"),
276
+ self.job.get("total"),
277
+ )
273
278
  self.job["phase"], self.job["done"], self.job["total"] = phase, done, total
274
279
  self.job["bytes_per_second"] = bytes_per_second
275
280
  if phase == "download":
@@ -288,7 +293,12 @@ class JobHandle:
288
293
  self.job["load_step"] = load_step
289
294
  else:
290
295
  self.job.pop("load_step", None)
291
- changed = (self.job.get("phase"), self.job.get("load_step"), self.job.get("source")) != prev
296
+ changed = (
297
+ self.job.get("phase"),
298
+ self.job.get("load_step"),
299
+ self.job.get("source"),
300
+ self.job.get("total"),
301
+ ) != prev
292
302
  now = time.monotonic()
293
303
  if changed or now - self._written >= JOB_WRITE_EVERY_S or done >= total:
294
304
  self._written = now
@@ -17,6 +17,7 @@ from localmodels import (
17
17
  hosts,
18
18
  library_floor,
19
19
  library_gateway,
20
+ library_order,
20
21
  library_pricing,
21
22
  library_state,
22
23
  library_vram,
@@ -574,6 +575,7 @@ def build(lib: Library) -> Status:
574
575
  chosen = library_pricing.recommend(now, candidates, lib.base_dir)
575
576
  for r in rows:
576
577
  r["recommended"] = r["id"] == chosen
578
+ rows = library_order.order_rows(lib.facts, models, rows)
577
579
  status_doc: Status = {
578
580
  "schema": STATUS_SCHEMA,
579
581
  "tool_version": __version__,
@@ -90,13 +90,16 @@ PRODUCT_DEFAULTS = {
90
90
  # every 16 GB Mac, stays on the ladder rather than a lower-scored model such as Qwen3.6-35B-A3B.
91
91
  MAC_DEFAULT_YIELD_SCORE = 50
92
92
 
93
- # The Mac small-memory ladder (roadmap decisions 57 and 61, user-selected; replaces decision
93
+ # The Mac small-memory ladder (roadmap decisions 57, 61 and 68, user-selected; replaces decision
94
94
  # 39's LFM3-1.7B): on every Apple Silicon Mac of MAC_LADDER_MIN_BYTES or more, while no validated
95
- # model scoring MAC_DEFAULT_YIELD_SCORE or more fits, Spark-X2.6-4B Q4_K_M is the sole rung and
96
- # minimum automatic floor (1.7B is below the 4B floor, so Macs with less free memory refuse
97
- # rather than dropping to 1.7B). The rung is a candidate outside SimplexAI ranking: its catalog
98
- # score is unranked (0) and never competes with installed scores.
99
- MAC_LADDER = ("spark-x2.6-4b-q4km",)
95
+ # model scoring MAC_DEFAULT_YIELD_SCORE or more fits, --llm auto tries Ornith 1.5 9B Q4_K_M first
96
+ # (fits 16 GB idle Macs and busy 24 GB+ Macs from ~12.5 GiB available), then falls back to
97
+ # Spark-X2.6-4B Q4_K_M as the minimum automatic floor (1.7B is retired, so Macs with less free
98
+ # memory refuse). Under --prefer fastest, Spark-X2.6-4B Q4_K_M is tried ahead of Ornith 1.5 9B.
99
+ # Ladder rungs are candidates outside SimplexAI ranking: their catalog score never competes with
100
+ # installed scores.
101
+ MAC_LADDER = ("ornith-1.5-9b", "spark-x2.6-4b-q4km")
102
+ MAC_LADDER_FASTEST = ("spark-x2.6-4b-q4km", "ornith-1.5-9b")
100
103
  MAC_LADDER_MIN_BYTES = 16 * metal.GIB
101
104
  # Validated darwin entries the ladder replaces in automatic selection (decision 57): Ling-3.0-tiny
102
105
  # (25) was the 32 GB+ fallback. Explicit --llm still installs it.
@@ -120,10 +123,10 @@ class MacLadder:
120
123
 
121
124
 
122
125
  def mac_ladder(facts: HostFacts) -> MacLadder | None:
123
- """This Mac's ladder (decisions 57 and 61), or None off Apple Silicon and below 16 GB."""
126
+ """This Mac's ladder (decisions 57, 61 and 68), or None off Apple Silicon and below 16 GB."""
124
127
  if not metal.supported(facts) or facts["ram"]["total_bytes"] < MAC_LADDER_MIN_BYTES:
125
128
  return None
126
- return MacLadder(MAC_LADDER, MAC_LADDER)
129
+ return MacLadder(MAC_LADDER, MAC_LADDER_FASTEST)
127
130
 
128
131
 
129
132
  def mac_rung(entry: CatalogEntry, facts: HostFacts) -> bool:
@@ -0,0 +1,464 @@
1
+ """Dynamic speed-based mirror catalog and concurrent bandwidth probing for all ecosystems.
2
+
3
+ Covers Python (PyPI), JavaScript/Node (npm registry & Node.js distributions), AI model hubs
4
+ (Hugging Face / hf-mirror / ModelScope), Go (GOPROXY), Rust (rustup / crates dist), and
5
+ Homebrew. Probes are bounded in both bytes and wall-clock time, use HTTPS with safe redirects,
6
+ and never write raw proxy URLs or credentials to disk (only a SHA-256 fingerprint).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import datetime as dt
12
+ import hashlib
13
+ import http.client
14
+ import threading
15
+ import time
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+ from collections.abc import Callable, Mapping, Sequence
20
+ from dataclasses import dataclass
21
+ from typing import Literal, TypedDict
22
+
23
+ from localmodels import npm_transport
24
+
25
+ Side = Literal["global", "cn"]
26
+ EcosystemName = Literal["pypi", "npm", "node", "model_hub", "go", "rust", "homebrew"]
27
+
28
+ PROBE_TIMEOUT_S = 4.0
29
+ PROBE_MAX_BYTES = 128 << 10 # 128 KiB: enough to measure throughput, fast on slow links
30
+ PROBE_READ_BYTES = 32 << 10
31
+ PROXY_ENV_NAMES = frozenset({"http_proxy", "https_proxy", "all_proxy", "no_proxy"})
32
+ HOST_ALIASES: dict[str, str] = {"pypi.mirrors.ustc.edu.cn": "mirrors.ustc.edu.cn"}
33
+ VALID_METHODS = frozenset({"env", "probe", "fallback"})
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class MirrorCandidate:
38
+ """One candidate endpoint for a package/distribution ecosystem."""
39
+
40
+ name: str
41
+ side: Side
42
+ base_url: str
43
+ probe_url: str
44
+ probe_bytes: int = PROBE_MAX_BYTES
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class ProbeResult:
49
+ """Measured reachability and throughput for a single probe request."""
50
+
51
+ bytes_per_second: float
52
+ latency_ms: float
53
+ bytes_read: int
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class MeasuredCandidate:
58
+ """A reachable candidate paired with its measured throughput."""
59
+
60
+ candidate: MirrorCandidate
61
+ result: ProbeResult
62
+
63
+
64
+ class EcosystemRecord(TypedDict):
65
+ """Persisted per-ecosystem speed-selection record inside ``region.json``."""
66
+
67
+ region: Side
68
+ name: str
69
+ url: str
70
+ bytes_per_second: int
71
+ candidates: list[str]
72
+ measured_at: str
73
+ method: str
74
+
75
+
76
+ Prober = Callable[[str, int, float], ProbeResult | None]
77
+
78
+
79
+ ECOSYSTEMS: dict[EcosystemName, tuple[MirrorCandidate, ...]] = {
80
+ "pypi": (
81
+ MirrorCandidate(
82
+ name="pypi-official",
83
+ side="global",
84
+ base_url="https://pypi.org/simple/",
85
+ probe_url="https://pypi.org/simple/pip/",
86
+ ),
87
+ MirrorCandidate(
88
+ name="pypi-tsinghua",
89
+ side="cn",
90
+ base_url="https://pypi.tuna.tsinghua.edu.cn/simple/",
91
+ probe_url="https://pypi.tuna.tsinghua.edu.cn/simple/pip/",
92
+ ),
93
+ MirrorCandidate(
94
+ name="pypi-aliyun",
95
+ side="cn",
96
+ base_url="https://mirrors.aliyun.com/pypi/simple/",
97
+ probe_url="https://mirrors.aliyun.com/pypi/simple/pip/",
98
+ ),
99
+ MirrorCandidate(
100
+ name="pypi-ustc",
101
+ side="cn",
102
+ base_url="https://pypi.mirrors.ustc.edu.cn/simple/",
103
+ probe_url="https://pypi.mirrors.ustc.edu.cn/simple/pip/",
104
+ ),
105
+ MirrorCandidate(
106
+ name="pypi-tencent",
107
+ side="cn",
108
+ base_url="https://mirrors.cloud.tencent.com/pypi/simple/",
109
+ probe_url="https://mirrors.cloud.tencent.com/pypi/simple/pip/",
110
+ ),
111
+ ),
112
+ "npm": (
113
+ MirrorCandidate(
114
+ name="npm-official",
115
+ side="global",
116
+ base_url="https://registry.npmjs.org",
117
+ probe_url="https://registry.npmjs.org/pnpm/-/pnpm-11.7.0.tgz",
118
+ probe_bytes=65536,
119
+ ),
120
+ MirrorCandidate(
121
+ name="npm-npmmirror",
122
+ side="cn",
123
+ base_url="https://registry.npmmirror.com",
124
+ probe_url="https://registry.npmmirror.com/pnpm/-/pnpm-11.7.0.tgz",
125
+ probe_bytes=65536,
126
+ ),
127
+ ),
128
+ "node": (
129
+ MirrorCandidate(
130
+ name="node-official",
131
+ side="global",
132
+ base_url="https://nodejs.org/dist/",
133
+ probe_url="https://nodejs.org/dist/index.json",
134
+ ),
135
+ MirrorCandidate(
136
+ name="node-npmmirror",
137
+ side="cn",
138
+ base_url="https://cdn.npmmirror.com/binaries/node/",
139
+ probe_url="https://cdn.npmmirror.com/binaries/node/index.json",
140
+ ),
141
+ MirrorCandidate(
142
+ name="node-tsinghua",
143
+ side="cn",
144
+ base_url="https://mirrors.tuna.tsinghua.edu.cn/nodejs-release/",
145
+ probe_url="https://mirrors.tuna.tsinghua.edu.cn/nodejs-release/index.json",
146
+ ),
147
+ ),
148
+ "model_hub": (
149
+ MirrorCandidate(
150
+ name="huggingface",
151
+ side="global",
152
+ base_url="https://huggingface.co",
153
+ probe_url="https://huggingface.co/api/models/Qwen/Qwen2.5-0.5B",
154
+ probe_bytes=65536,
155
+ ),
156
+ MirrorCandidate(
157
+ name="hf-mirror",
158
+ side="cn",
159
+ base_url="https://hf-mirror.com",
160
+ probe_url="https://hf-mirror.com/api/models/Qwen/Qwen2.5-0.5B",
161
+ probe_bytes=65536,
162
+ ),
163
+ MirrorCandidate(
164
+ name="modelscope",
165
+ side="cn",
166
+ base_url="https://modelscope.cn",
167
+ probe_url="https://modelscope.cn/api/v1/models/Qwen/Qwen2.5-0.5B",
168
+ probe_bytes=65536,
169
+ ),
170
+ ),
171
+ "go": (
172
+ MirrorCandidate(
173
+ name="go-official",
174
+ side="global",
175
+ base_url="https://proxy.golang.org",
176
+ probe_url="https://proxy.golang.org/golang.org/x/text/@v/list",
177
+ probe_bytes=16384,
178
+ ),
179
+ MirrorCandidate(
180
+ name="goproxy-cn",
181
+ side="cn",
182
+ base_url="https://goproxy.cn",
183
+ probe_url="https://goproxy.cn/golang.org/x/text/@v/list",
184
+ probe_bytes=16384,
185
+ ),
186
+ MirrorCandidate(
187
+ name="goproxy-io",
188
+ side="cn",
189
+ base_url="https://goproxy.io",
190
+ probe_url="https://goproxy.io/golang.org/x/text/@v/list",
191
+ probe_bytes=16384,
192
+ ),
193
+ ),
194
+ "rust": (
195
+ MirrorCandidate(
196
+ name="rust-official",
197
+ side="global",
198
+ base_url="https://static.rust-lang.org",
199
+ probe_url="https://static.rust-lang.org/dist/channel-rust-stable.toml",
200
+ ),
201
+ MirrorCandidate(
202
+ name="rust-tsinghua",
203
+ side="cn",
204
+ base_url="https://mirrors.tuna.tsinghua.edu.cn/rustup",
205
+ probe_url="https://mirrors.tuna.tsinghua.edu.cn/rustup/dist/channel-rust-stable.toml",
206
+ ),
207
+ MirrorCandidate(
208
+ name="rust-ustc",
209
+ side="cn",
210
+ base_url="https://mirrors.ustc.edu.cn/rust-static",
211
+ probe_url="https://mirrors.ustc.edu.cn/rust-static/dist/channel-rust-stable.toml",
212
+ ),
213
+ ),
214
+ "homebrew": (
215
+ MirrorCandidate(
216
+ name="homebrew-official",
217
+ side="global",
218
+ base_url="https://formulae.brew.sh/api",
219
+ probe_url="https://formulae.brew.sh/api/formula.json",
220
+ ),
221
+ MirrorCandidate(
222
+ name="homebrew-tsinghua",
223
+ side="cn",
224
+ base_url="https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles/api",
225
+ probe_url="https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles/api/formula.json",
226
+ ),
227
+ MirrorCandidate(
228
+ name="homebrew-ustc",
229
+ side="cn",
230
+ base_url="https://mirrors.ustc.edu.cn/homebrew-bottles/api",
231
+ probe_url="https://mirrors.ustc.edu.cn/homebrew-bottles/api/formula.json",
232
+ ),
233
+ ),
234
+ }
235
+
236
+
237
+ _ALLOWED_BY_ECO: dict[EcosystemName, frozenset[str]] = {
238
+ eco: frozenset(item.base_url.rstrip("/") for item in items) for eco, items in ECOSYSTEMS.items()
239
+ }
240
+ _ALLOWED_ALL_URLS: frozenset[str] = frozenset().union(*_ALLOWED_BY_ECO.values())
241
+
242
+
243
+ def canonical_host(url_or_host: str) -> str:
244
+ """Normalize a mirror URL or hostname so sibling aliases (e.g. USTC PyPI) match."""
245
+ host = (
246
+ urllib.parse.urlsplit(url_or_host).hostname if "://" in url_or_host else url_or_host
247
+ ) or ""
248
+ low = host.lower()
249
+ return HOST_ALIASES.get(low, low)
250
+
251
+
252
+ def is_allowed_mirror_url(url: str, ecosystem: EcosystemName | None = None) -> bool:
253
+ """True only for clean, credential-free HTTPS URLs belonging to the built-in mirror catalog."""
254
+ if not isinstance(url, str) or not url or url != url.strip():
255
+ return False
256
+ if any(ch.isspace() for ch in url) or "," in url or "|" in url:
257
+ return False
258
+ parts = urllib.parse.urlsplit(url)
259
+ if (
260
+ parts.scheme != "https"
261
+ or not parts.hostname
262
+ or parts.username is not None
263
+ or parts.password is not None
264
+ or parts.query
265
+ or parts.fragment
266
+ ):
267
+ return False
268
+ normalized = url.rstrip("/")
269
+ allowed = _ALLOWED_BY_ECO[ecosystem] if ecosystem is not None else _ALLOWED_ALL_URLS
270
+ return normalized in allowed
271
+
272
+
273
+ def network_fingerprint(env: Mapping[str, str]) -> str:
274
+ """Short opaque hash of active proxy environment settings, or ``direct`` when none are set.
275
+
276
+ Never returns raw proxy URLs or credentials so it is safe to persist in ``region.json``.
277
+ """
278
+ items = [
279
+ f"{key.lower()}={value.strip()}"
280
+ for key, value in env.items()
281
+ if key.lower() in PROXY_ENV_NAMES and value.strip()
282
+ ]
283
+ if not items:
284
+ return "direct"
285
+ canonical = "\n".join(sorted(set(items))).encode("utf-8")
286
+ return "proxy:" + hashlib.sha256(canonical).hexdigest()[:16]
287
+
288
+
289
+ def is_loopback_http(url: str) -> bool:
290
+ parts = urllib.parse.urlsplit(url)
291
+ return parts.scheme == "http" and parts.hostname in ("127.0.0.1", "localhost", "::1")
292
+
293
+
294
+ def _safe_opener(url: str, *, allow_local_http: bool) -> urllib.request.OpenerDirector:
295
+ if allow_local_http and is_loopback_http(url):
296
+ return urllib.request.build_opener(urllib.request.ProxyHandler({}))
297
+ parts = urllib.parse.urlsplit(url)
298
+ if (
299
+ parts.scheme != "https"
300
+ or not parts.hostname
301
+ or parts.username is not None
302
+ or parts.password is not None
303
+ ):
304
+ raise npm_transport.UnsafeRedirect("mirror probe URL must use HTTPS without credentials")
305
+ return npm_transport.https_opener()
306
+
307
+
308
+ def probe_url(
309
+ url: str,
310
+ max_bytes: int = PROBE_MAX_BYTES,
311
+ timeout_s: float = PROBE_TIMEOUT_S,
312
+ *,
313
+ allow_local_http: bool = False,
314
+ ) -> ProbeResult | None:
315
+ """Fetch up to ``max_bytes`` from ``url`` within ``timeout_s`` and return measured speed."""
316
+ limit = max(1, max_bytes)
317
+ start = time.monotonic()
318
+ deadline = start + max(0.1, timeout_s)
319
+ request = urllib.request.Request(
320
+ url,
321
+ headers={
322
+ "User-Agent": "localmodels-mirror-probe",
323
+ "Range": f"bytes=0-{limit - 1}",
324
+ },
325
+ )
326
+ try:
327
+ opener = _safe_opener(url, allow_local_http=allow_local_http)
328
+ with opener.open(request, timeout=max(0.1, deadline - time.monotonic())) as response:
329
+ status = getattr(response, "status", 200)
330
+ if not 200 <= status < 300:
331
+ return None
332
+ first_byte_at = time.monotonic()
333
+ got = 0
334
+ read_fn = getattr(response, "read1", response.read)
335
+ while got < limit and time.monotonic() < deadline:
336
+ chunk = read_fn(min(PROBE_READ_BYTES, limit - got))
337
+ if not chunk:
338
+ break
339
+ got += len(chunk)
340
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError):
341
+ return None
342
+ if got <= 0:
343
+ return None
344
+ elapsed = max(1e-3, time.monotonic() - start)
345
+ latency_ms = max(0.0, (first_byte_at - start) * 1000.0)
346
+ return ProbeResult(
347
+ bytes_per_second=got / elapsed,
348
+ latency_ms=latency_ms,
349
+ bytes_read=got,
350
+ )
351
+
352
+
353
+ def probe_candidates(
354
+ candidates: Sequence[MirrorCandidate],
355
+ *,
356
+ timeout_s: float = PROBE_TIMEOUT_S,
357
+ prober: Prober | None = None,
358
+ ) -> list[MeasuredCandidate]:
359
+ """Concurrently probe ``candidates`` and return reachable ones sorted fastest-first."""
360
+ if not candidates:
361
+ return []
362
+ fn = probe_url if prober is None else prober
363
+ results: list[ProbeResult | None] = [None] * len(candidates)
364
+
365
+ def run_one(index: int, item: MirrorCandidate) -> None:
366
+ results[index] = fn(item.probe_url, item.probe_bytes, timeout_s)
367
+
368
+ if len(candidates) == 1:
369
+ run_one(0, candidates[0])
370
+ else:
371
+ threads = [
372
+ threading.Thread(target=run_one, args=(i, item), daemon=True)
373
+ for i, item in enumerate(candidates)
374
+ ]
375
+ for thread in threads:
376
+ thread.start()
377
+ deadline = time.monotonic() + max(0.2, timeout_s) + 0.5
378
+ for thread in threads:
379
+ thread.join(timeout=max(0.0, deadline - time.monotonic()))
380
+
381
+ ranked: list[tuple[float, int, MeasuredCandidate]] = []
382
+ for index, (item, result) in enumerate(zip(candidates, results, strict=False)):
383
+ if result is not None and result.bytes_per_second > 0:
384
+ ranked.append((-result.bytes_per_second, index, MeasuredCandidate(item, result)))
385
+ ranked.sort(key=lambda entry: (entry[0], entry[1]))
386
+ return [entry[2] for entry in ranked]
387
+
388
+
389
+ def probe_ecosystem(
390
+ ecosystem: EcosystemName,
391
+ *,
392
+ side_filter: Side | None = None,
393
+ timeout_s: float = PROBE_TIMEOUT_S,
394
+ prober: Prober | None = None,
395
+ method: str = "probe",
396
+ ) -> EcosystemRecord | None:
397
+ """Speed-probe candidates for ``ecosystem`` and return a persisted record for the winner."""
398
+ pool = ECOSYSTEMS[ecosystem]
399
+ if side_filter is not None:
400
+ pool = tuple(item for item in pool if item.side == side_filter)
401
+ measured = probe_candidates(pool, timeout_s=timeout_s, prober=prober)
402
+ if not measured:
403
+ return None
404
+ winner = measured[0]
405
+ return {
406
+ "region": winner.candidate.side,
407
+ "name": winner.candidate.name,
408
+ "url": winner.candidate.base_url,
409
+ "bytes_per_second": int(winner.result.bytes_per_second),
410
+ "candidates": [entry.candidate.base_url for entry in measured],
411
+ "measured_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
412
+ "method": method,
413
+ }
414
+
415
+
416
+ def default_cn_url(ecosystem: EcosystemName) -> str:
417
+ """First China mirror base URL for ``ecosystem`` when probes cannot reach any host."""
418
+ for candidate in ECOSYSTEMS[ecosystem]:
419
+ if candidate.side == "cn":
420
+ return candidate.base_url
421
+ return ECOSYSTEMS[ecosystem][0].base_url
422
+
423
+
424
+ def valid_ecosystem_record(
425
+ raw: object, ecosystem: EcosystemName | None = None
426
+ ) -> EcosystemRecord | None:
427
+ """Validate one persisted ecosystem entry loaded from ``region.json``."""
428
+ if not isinstance(raw, dict):
429
+ return None
430
+ reg = raw.get("region")
431
+ name = raw.get("name")
432
+ url = raw.get("url")
433
+ bps = raw.get("bytes_per_second")
434
+ cands = raw.get("candidates")
435
+ measured_at = raw.get("measured_at")
436
+ method = raw.get("method")
437
+ if (
438
+ reg not in ("global", "cn")
439
+ or not isinstance(name, str)
440
+ or not name
441
+ or not isinstance(url, str)
442
+ or not is_allowed_mirror_url(url, ecosystem)
443
+ or not isinstance(bps, int)
444
+ or isinstance(bps, bool)
445
+ or bps < 0
446
+ or not isinstance(cands, list)
447
+ or not all(
448
+ isinstance(item, str) and is_allowed_mirror_url(item, ecosystem) for item in cands
449
+ )
450
+ or not isinstance(measured_at, str)
451
+ or not measured_at
452
+ or not isinstance(method, str)
453
+ or method not in VALID_METHODS
454
+ ):
455
+ return None
456
+ return {
457
+ "region": reg,
458
+ "name": name,
459
+ "url": url,
460
+ "bytes_per_second": bps,
461
+ "candidates": list(cands),
462
+ "measured_at": measured_at,
463
+ "method": method,
464
+ }
@@ -78,8 +78,8 @@ _QUANT_REASONS = {
78
78
  RECOMMENDED_REASONS = {
79
79
  "windows-candidate-fallback": llm_rank.WINDOWS_FALLBACK_WARNING,
80
80
  "user-default": (
81
- "User-selected Mac small-memory ladder (Spark-X2.6, 64K shared by two slots); "
82
- "SimplexAI score and full acceptance pending."
81
+ "User-selected Mac small-memory ladder (Ornith 1.5 9B Q4_K_M, falling back to Spark-X2.6 "
82
+ "4B Q4_K_M); SimplexAI score and full acceptance pending."
83
83
  ),
84
84
  "product-default": "This machine's default model, chosen by its maker.",
85
85
  "best-quality-resident": (
@@ -47,6 +47,7 @@ class Build(TypedDict):
47
47
 
48
48
  class OptionalBuild(Build, total=False):
49
49
  min_cuda: str
50
+ min_driver: str
50
51
  min_glibc: str # highest GLIBC symbol version its binaries import
51
52
  variant: str # a rebuild of the tag: base OS and recipe revision, e.g. ubuntu22.04-r2
52
53
  provenance: str # URL of the rebuild's provenance JSON (image digest, flags, toolchain)