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

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 (81) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +76 -79
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +0 -1
  5. package/modules/localmodels/auth_proxy.py +285 -82
  6. package/modules/localmodels/bifrost_checks.py +3 -127
  7. package/modules/localmodels/bifrost_clients.py +1 -1
  8. package/modules/localmodels/bifrost_config.py +2 -2
  9. package/modules/localmodels/bifrost_models.py +9 -2
  10. package/modules/localmodels/bifrost_pi.py +1 -1
  11. package/modules/localmodels/bifrost_provider.py +42 -7
  12. package/modules/localmodels/budget.py +16 -1
  13. package/modules/localmodels/catalog.json +15 -50
  14. package/modules/localmodels/catalog_recipes.py +1 -1
  15. package/modules/localmodels/debug_mode.py +2 -18
  16. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +41 -1
  17. package/modules/localmodels/engines.py +19 -6
  18. package/modules/localmodels/gateway.py +50 -15
  19. package/modules/localmodels/gateway_accept.py +8 -5
  20. package/modules/localmodels/gateway_bifrost.py +23 -13
  21. package/modules/localmodels/gateway_cli.py +5 -2
  22. package/modules/localmodels/gateway_requests.py +9 -2
  23. package/modules/localmodels/harness.py +41 -12
  24. package/modules/localmodels/harness_gateway.py +1 -1
  25. package/modules/localmodels/hosts.py +7 -20
  26. package/modules/localmodels/library_convert.py +491 -57
  27. package/modules/localmodels/library_gateway.py +27 -16
  28. package/modules/localmodels/library_pricing.py +155 -31
  29. package/modules/localmodels/library_status.py +29 -4
  30. package/modules/localmodels/npm_transport.py +62 -54
  31. package/modules/localmodels/probe.py +42 -9
  32. package/modules/localmodels/recommend.py +1 -1
  33. package/modules/localmodels/recommend_cli.py +2 -2
  34. package/modules/localmodels/remote_ops.py +14 -6
  35. package/modules/localmodels/remote_ops_download.py +1 -1
  36. package/modules/localmodels/remote_ops_verify.py +0 -33
  37. package/modules/localmodels/runtime_args.py +2 -1
  38. package/modules/localmodels/runtime_auth.py +75 -25
  39. package/modules/localmodels/runtime_cli.py +9 -9
  40. package/modules/localmodels/runtime_install.py +57 -23
  41. package/modules/localmodels/runtime_io.py +224 -243
  42. package/modules/localmodels/runtime_process.py +15 -7
  43. package/modules/localmodels/runtime_windows_acl.py +196 -0
  44. package/modules/localmodels/source_byok.py +122 -33
  45. package/modules/localmodels/source_byok_probe.py +57 -141
  46. package/modules/localmodels/source_cli.py +19 -18
  47. package/modules/localmodels/stack.py +13 -6
  48. package/modules/localmodels/stack_args.py +6 -8
  49. package/modules/localmodels/stack_binding.py +3 -3
  50. package/modules/localmodels/stack_client_settings.py +8 -1
  51. package/modules/localmodels/stack_compose.py +4 -8
  52. package/modules/localmodels/stack_events.py +2 -1
  53. package/modules/localmodels/stack_plan.py +1 -4
  54. package/modules/localmodels/stack_ports.py +0 -1
  55. package/modules/localmodels/stack_route.py +1 -5
  56. package/modules/localmodels/stack_run.py +15 -30
  57. package/modules/localmodels/stack_suite.py +23 -46
  58. package/modules/localmodels/stack_summary.py +0 -1
  59. package/modules/localmodels/stack_try.py +3 -92
  60. package/modules/localmodels/stack_up.py +27 -4
  61. package/modules/localmodels/stack_update.py +5 -5
  62. package/modules/localmodels/stack_view_apply.py +1 -1
  63. package/modules/localmodels/stack_view_sandbox.py +0 -2
  64. package/modules/localmodels/stack_view_text.py +0 -1
  65. package/modules/localmodels/stack_view_words.py +0 -1
  66. package/modules/localmodels/suite.py +4 -7
  67. package/modules/localmodels/tui_dialogs.py +0 -1
  68. package/modules/localmodels/vision.py +2 -1
  69. package/modules/localmodels/web/view/view.css +1 -4
  70. package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/METADATA +1 -1
  71. package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/RECORD +73 -76
  72. package/package.json +1 -1
  73. package/tool.json +1 -1
  74. package/modules/localmodels/bifrost_search.py +0 -66
  75. package/modules/localmodels/gateway_search.py +0 -223
  76. package/modules/localmodels/search-ddgs-9.16.1.txt +0 -222
  77. package/modules/localmodels/search_server.py +0 -474
  78. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/WHEEL +0 -0
  79. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/entry_points.txt +0 -0
  80. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/NOTICE +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -2,10 +2,12 @@
2
2
 
3
3
  Every figure comes from ``deploy.build_plan`` in the stack's agent posture (the estimator and
4
4
  context policy ``stack plan`` uses): a model's memory is its plan's ``vram_bytes`` (on a Mac its
5
- ``unified_bytes``), its window the plan's. Fit is judged on capacity (every card empty), so it
6
- does not move as other models load; whether a model can load *now* is the same planner on the
7
- free memory less what loading models have reserved. The catalog shown is the chat models
8
- ``validated`` for this platform; a model already on disk stays listed.
5
+ ``unified_bytes``), its window the plan's. Fit is judged on loadable capacity (loaded library
6
+ models unloaded, keeping macOS's idle baseline and observed desktop/WDDM GPU overhead), so it does
7
+ not move as models load and never admits a model whose plan exceeds its pool; whether a model can
8
+ load *now* is the same planner on the free memory less what loading models have reserved. The
9
+ catalog shown is the chat models ``validated`` for this platform; a model already on disk stays
10
+ listed.
9
11
  """
10
12
 
11
13
  from __future__ import annotations
@@ -14,22 +16,37 @@ import copy
14
16
  import functools
15
17
  import os
16
18
  import shutil
17
- from collections.abc import Iterable
19
+ from collections.abc import Iterable, Mapping
18
20
  from dataclasses import dataclass
19
21
  from pathlib import Path
20
22
  from typing import Any
21
23
 
22
- from localmodels import budget, deploy, hosts, llm_rank, metal, plan_envelope, stack_hardware
24
+ from localmodels import (
25
+ budget,
26
+ context_policy,
27
+ deploy,
28
+ hosts,
29
+ llm_rank,
30
+ metal,
31
+ plan_envelope,
32
+ stack_hardware,
33
+ vision,
34
+ )
23
35
  from localmodels import catalog as cat
24
36
  from localmodels.context_policy import AgentPosture
25
- from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES, METAL_VRAM_RESERVE_BYTES
37
+ from localmodels.estimator import (
38
+ AGENT_VRAM_RESERVE_BYTES,
39
+ METAL_VRAM_RESERVE_BYTES,
40
+ PhysicsRefusal,
41
+ )
26
42
  from localmodels.library_model import LibraryError, Reason, display_name, split_id
27
- from localmodels.probe import HostFacts
43
+ from localmodels.probe import GPU, HostFacts
28
44
  from localmodels.records import Plan
29
45
  from localmodels.stack_plan import platform_error
30
46
 
31
47
  POOL_RAM_FRACTION = 0.8 # a "system" pool's budget: RAM x 0.8 (contract v2)
32
48
  UNIFIED_RESERVE_BYTES = metal.HOST_KEEP_BYTES + METAL_VRAM_RESERVE_BYTES
49
+ DESKTOP_VRAM_BASELINE_CAP_BYTES = budget.DESKTOP_VRAM_BASELINE_CAP_BYTES
33
50
 
34
51
 
35
52
  @functools.cache
@@ -187,12 +204,61 @@ def pool_of(plan: Plan) -> str:
187
204
  return "system"
188
205
 
189
206
 
190
- def capacity(facts: HostFacts) -> HostFacts:
191
- """``facts`` with every card and the RAM empty: what fit is judged on."""
207
+ def _owned_gpu_bytes(facts: HostFacts, gpu: GPU, reclaimable: Mapping[str, int] | None) -> int:
208
+ pool = f"gpu:{gpu['index']}"
209
+ from_records = max(0, int((reclaimable or {}).get(pool, 0)))
210
+ services = facts.get("services")
211
+ procs = (services.get("compute_processes") if services else None) or []
212
+ from_procs = sum(
213
+ int(p.get("used_bytes") or 0)
214
+ for p in procs
215
+ if p["gpu_uuid"] == gpu["uuid"] and p.get("owned") is True
216
+ )
217
+ return max(from_records, from_procs)
218
+
219
+
220
+ def _foreign_gpu_bytes(facts: HostFacts, gpu: GPU) -> int:
221
+ services = facts.get("services")
222
+ procs = (services.get("compute_processes") if services else None) or []
223
+ return sum(
224
+ int(p.get("used_bytes") or 0)
225
+ for p in procs
226
+ if p["gpu_uuid"] == gpu["uuid"] and budget.foreign_work(p, facts)
227
+ )
228
+
229
+
230
+ def _gpu_capacity_free(facts: HostFacts, gpu: GPU, reclaimable: Mapping[str, int] | None) -> int:
231
+ """Loadable VRAM on ``gpu`` once owned models and transient foreign work clear, keeping
232
+ observed desktop/WDDM baseline occupancy on Windows and display-active GPUs."""
233
+ total = gpu["total_bytes"]
234
+ if facts.get("platform") != "win32" and not gpu.get("display_active"):
235
+ return total
236
+ taken = max(gpu["used_bytes"], max(0, total - gpu["free_bytes"]))
237
+ desktop_used = max(
238
+ 0, taken - _owned_gpu_bytes(facts, gpu, reclaimable) - _foreign_gpu_bytes(facts, gpu)
239
+ )
240
+ baseline = min(desktop_used, DESKTOP_VRAM_BASELINE_CAP_BYTES)
241
+ return min(total, max(gpu["free_bytes"], total - baseline))
242
+
243
+
244
+ def capacity(facts: HostFacts, *, reclaimable: Mapping[str, int] | None = None) -> HostFacts:
245
+ """``facts`` at loadable capacity once loaded library models are unloaded: keeps macOS's
246
+ idle baseline (``metal.in_use``) on Apple Silicon and observed desktop/WDDM baseline VRAM
247
+ on Windows and display-active GPUs instead of pretending zero OS/desktop overhead."""
192
248
  seen = copy.deepcopy(facts)
193
249
  for gpu in seen.get("gpus") or []:
194
- gpu["free_bytes"], gpu["used_bytes"] = gpu["total_bytes"], 0
195
- seen["ram"]["available_bytes"] = seen["ram"]["total_bytes"]
250
+ free = _gpu_capacity_free(facts, gpu, reclaimable)
251
+ gpu["free_bytes"], gpu["used_bytes"] = free, max(0, gpu["total_bytes"] - free)
252
+ ram = seen["ram"]
253
+ if metal.supported(seen):
254
+ total = ram["total_bytes"]
255
+ idle = max(0, total - metal.in_use(total))
256
+ ram["available_bytes"] = min(total, max(ram["available_bytes"], idle))
257
+ if ram.get("pressure_level") is not None:
258
+ ram["pressure_level"] = 1
259
+ ram.pop("pressure_kept_bytes", None)
260
+ else:
261
+ ram["available_bytes"] = ram["total_bytes"]
196
262
  seen["llama_servers"] = []
197
263
  seen["disk"] = {**seen["disk"], "free_bytes": None}
198
264
  if services := seen.get("services"):
@@ -246,7 +312,7 @@ def price(
246
312
  if problem := metal.problem(facts):
247
313
  raise LiveMemoryUnavailable(problem)
248
314
  facts, _ = metal.pressured(facts)
249
- return deploy.build_plan(
315
+ plan = deploy.build_plan(
250
316
  hosts.LOCAL_ID,
251
317
  facts,
252
318
  deploy.PlanOptions(
@@ -262,6 +328,20 @@ def price(
262
328
  entries=catalog,
263
329
  resolver=deploy.catalog_pins,
264
330
  )
331
+ total = pool_total(facts, pool)
332
+ used = memory_bytes(plan)
333
+ if used > total:
334
+ refused = PhysicsRefusal(
335
+ needed_bytes=used,
336
+ available_bytes=total,
337
+ message=f"{model.id} needs {used} bytes, exceeding pool {pool} total {total} bytes",
338
+ )
339
+ raise deploy.AgentMemoryError(
340
+ refused.message,
341
+ refused,
342
+ "unified memory" if pool == "unified" else "GPU memory",
343
+ )
344
+ return plan
265
345
 
266
346
 
267
347
  def memory_bytes(plan: Plan) -> int:
@@ -284,7 +364,28 @@ class Priced:
284
364
  load_free_bytes: int = 0 # pool-aligned free memory on the planned pool
285
365
 
286
366
 
287
- def live_fit(
367
+ def _min_pool_need(model: Model, pool: str, exc: deploy.AgentMemoryError) -> int:
368
+ """Exact pool-aligned free bytes required at the agent floor when ``available_bytes`` clamped
369
+ to zero inside ``agent_budget`` or ``vision.priced``."""
370
+ if gpu_index(pool) is not None:
371
+ return exc.needed_bytes + AGENT_VRAM_RESERVE_BYTES
372
+ if pool == "unified":
373
+ profile = model.entry.profile(model.variant)
374
+ mac_posture = context_policy.posture_for(posture(), "metal")
375
+ host_side = context_policy.cache_floor_bytes(
376
+ mac_posture, profile
377
+ ) + context_policy.metal_host_bytes(profile, mac_posture)
378
+ vision_extra = (
379
+ vision.llama_device_bytes(model.entry.mmproj, "gpu")
380
+ if model.entry.mmproj is not None
381
+ and vision.llama_reader_enabled(model.entry.mmproj, mac_posture.vision)
382
+ else 0
383
+ )
384
+ return exc.needed_bytes + vision_extra + host_side
385
+ return exc.needed_bytes
386
+
387
+
388
+ def _live_plan(
288
389
  facts: HostFacts,
289
390
  model: Model,
290
391
  pool: str,
@@ -293,24 +394,43 @@ def live_fit(
293
394
  reserved: dict[str, int],
294
395
  *,
295
396
  fallback_need: int = 0,
296
- ) -> tuple[bool, int, int]:
297
- """Check whether ``model`` fits ``pool`` in live memory right now.
298
-
299
- Returns ``(fits_now, load_need_bytes, load_free_bytes)`` aligned with ``pool_free`` so row
300
- and dialog figures match the pool summary while preserving the exact live deficit.
301
- """
397
+ ) -> tuple[Plan | None, int, int]:
302
398
  now = live(facts, reserved)
303
399
  if pool not in pools(now):
304
- return False, max(fallback_need, 1), 0
400
+ return None, max(fallback_need, 1), 0
305
401
  free = pool_free(now, pool)
306
402
  try:
307
- price(now, model, pool, base_dir, catalog, require_live=True)
403
+ plan = price(now, model, pool, base_dir, catalog, require_live=True)
308
404
  except deploy.AgentMemoryError as exc:
309
405
  deficit = max(1, exc.needed_bytes - exc.available_bytes)
310
- return False, free + deficit, free
406
+ need = free + deficit
407
+ if exc.available_bytes == 0:
408
+ need = max(need, _min_pool_need(model, pool, exc))
409
+ return None, need, free
311
410
  except plan_envelope.PlanError:
312
- return False, max(fallback_need, free + 1), free
313
- return True, 0, free
411
+ return None, max(fallback_need, free + 1), free
412
+ return plan, 0, free
413
+
414
+
415
+ def live_fit(
416
+ facts: HostFacts,
417
+ model: Model,
418
+ pool: str,
419
+ base_dir: str,
420
+ catalog: tuple[cat.CatalogEntry, ...],
421
+ reserved: dict[str, int],
422
+ *,
423
+ fallback_need: int = 0,
424
+ ) -> tuple[bool, int, int]:
425
+ """Check whether ``model`` fits ``pool`` in live memory right now.
426
+
427
+ Returns ``(fits_now, load_need_bytes, load_free_bytes)`` aligned with ``pool_free`` so row
428
+ and dialog figures match the pool summary while preserving the exact live deficit.
429
+ """
430
+ plan, load_need, load_free = _live_plan(
431
+ facts, model, pool, base_dir, catalog, reserved, fallback_need=fallback_need
432
+ )
433
+ return plan is not None, load_need, load_free
314
434
 
315
435
 
316
436
  def judge(
@@ -319,10 +439,14 @@ def judge(
319
439
  base_dir: str,
320
440
  catalog: tuple[cat.CatalogEntry, ...],
321
441
  reserved: dict[str, int],
442
+ *,
443
+ reclaimable: Mapping[str, int] | None = None,
322
444
  ) -> Priced:
323
- """Fit on capacity; the planned pool is the card with the most free memory that fits now,
324
- else (nothing has room now) the freest card that fits at all, else the unified pool."""
325
- cap, now = capacity(facts), live(facts, reserved)
445
+ """Fit on loadable capacity; the planned pool is the card with the most free memory that
446
+ fits now, else (nothing has room now) the freest card that fits at all, else the unified pool.
447
+ When the model fits live now, its live plan is returned so displayed context and memory match
448
+ what ``library load`` will actually allocate."""
449
+ cap, now = capacity(facts, reclaimable=reclaimable), live(facts, reserved)
326
450
  order = sorted(pools(facts), key=lambda p: -pool_free(now, p))
327
451
  fallback: Priced | None = None
328
452
  shortfall: tuple[int, int] | None = None
@@ -339,11 +463,11 @@ def judge(
339
463
  except plan_envelope.PlanError:
340
464
  continue
341
465
  fit = "unified" if pool == "unified" else "gpu"
342
- fits, load_need, load_free = live_fit(
466
+ live_plan, load_need, load_free = _live_plan(
343
467
  facts, model, pool, base_dir, catalog, reserved, fallback_need=memory_bytes(plan)
344
468
  )
345
- if fits:
346
- return Priced(fit, pool, plan, True, load_free_bytes=load_free)
469
+ if live_plan is not None:
470
+ return Priced(fit, pool, live_plan, True, load_free_bytes=load_free)
347
471
  if fallback is None:
348
472
  fallback = Priced(
349
473
  fit, pool, plan, False, load_need_bytes=load_need, load_free_bytes=load_free
@@ -31,6 +31,7 @@ from localmodels.library_model import (
31
31
  DownloadSource,
32
32
  Holder,
33
33
  Host,
34
+ LibraryError,
34
35
  Load,
35
36
  LoadStep,
36
37
  MemoryPressure,
@@ -80,6 +81,7 @@ class Library:
80
81
  jobs: dict[str, tuple[Job, bool]]
81
82
  catalog: tuple[cat.CatalogEntry, ...]
82
83
  priced: dict[str, Priced] = field(default_factory=dict)
84
+ _health: dict[str, bool] = field(default_factory=dict, repr=False)
83
85
 
84
86
  @classmethod
85
87
  def read(cls, facts: HostFacts, base_dir: str) -> Library:
@@ -92,7 +94,9 @@ class Library:
92
94
  )
93
95
 
94
96
  def healthy(self, base_url: str) -> bool:
95
- return answering(base_url)
97
+ if base_url not in self._health:
98
+ self._health[base_url] = answering(base_url)
99
+ return self._health[base_url]
96
100
 
97
101
  def reserved(self) -> dict[str, int]:
98
102
  """Memory loading models hold before the probe can see it, per pool."""
@@ -102,6 +106,18 @@ class Library:
102
106
  found[job["pool"]] = found.get(job["pool"], 0) + job["memory_bytes"]
103
107
  return found
104
108
 
109
+ def reclaimable(self) -> dict[str, int]:
110
+ """Memory loaded library models hold in ``facts`` now, freed if unloaded, per pool."""
111
+ found: dict[str, int] = {}
112
+ for record in self.records.values():
113
+ if record["state"] != "loaded":
114
+ continue
115
+ if not self.healthy(str(record["plan"]["endpoint"]["base_url"])):
116
+ continue
117
+ pool = record["pool"]
118
+ found[pool] = found.get(pool, 0) + library_pricing.memory_bytes(record["plan"])
119
+ return found
120
+
105
121
  def models(self) -> list[Model]:
106
122
  rows = library_pricing.shown(self.facts, self.catalog)
107
123
  known = {m.id for m in rows}
@@ -109,14 +125,19 @@ class Library:
109
125
  if model_id not in known:
110
126
  try:
111
127
  rows.append(library_pricing.find(model_id, self.catalog))
112
- except ValueError:
128
+ except (ValueError, LibraryError):
113
129
  continue
114
130
  return rows
115
131
 
116
132
  def judge(self, model: Model) -> Priced:
117
133
  if model.id not in self.priced:
118
134
  self.priced[model.id] = library_pricing.judge(
119
- self.facts, model, self.base_dir, self.catalog, self.reserved()
135
+ self.facts,
136
+ model,
137
+ self.base_dir,
138
+ self.catalog,
139
+ self.reserved(),
140
+ reclaimable=self.reclaimable(),
120
141
  )
121
142
  return self.priced[model.id]
122
143
 
@@ -156,7 +177,11 @@ def _plan_of(lib: Library, model: Model, record: Record | None, priced: Priced)
156
177
  if job is not None and alive and job["pool"] != priced.pool:
157
178
  try:
158
179
  return library_pricing.price(
159
- library_pricing.capacity(lib.facts), model, job["pool"], lib.base_dir, lib.catalog
180
+ library_pricing.capacity(lib.facts, reclaimable=lib.reclaimable()),
181
+ model,
182
+ job["pool"],
183
+ lib.base_dir,
184
+ lib.catalog,
160
185
  )
161
186
  except plan_envelope.PlanError:
162
187
  return priced.plan
@@ -6,13 +6,14 @@ import hashlib
6
6
  import http.client
7
7
  import os
8
8
  import queue
9
+ import re
9
10
  import sys
10
11
  import tarfile
11
12
  import threading
12
13
  import time
13
14
  import urllib.error
14
15
  import urllib.request
15
- from collections.abc import Mapping
16
+ from collections.abc import Callable, Mapping
16
17
  from pathlib import Path
17
18
  from typing import Any, TypedDict
18
19
  from urllib.parse import urljoin, urlsplit
@@ -31,12 +32,16 @@ def archive_size_cap(binary_size: int) -> int:
31
32
  return min(binary_size + NPM_OVERHEAD_BYTES, MAX_ARCHIVE_BYTES)
32
33
 
33
34
 
35
+ class UnsafeRedirect(urllib.error.URLError):
36
+ """A URL or redirect target without HTTPS, or with credentials, that is never contacted."""
37
+
38
+
34
39
  def _check_url(url: str, *, redirect: bool = False) -> str:
35
40
  try:
36
41
  parts = urlsplit(url)
37
42
  _ = parts.port
38
43
  except ValueError as error:
39
- raise urllib.error.URLError("invalid npm URL") from error
44
+ raise UnsafeRedirect("invalid npm URL") from error
40
45
  local_fixture = (
41
46
  not redirect
42
47
  and parts.scheme == "http"
@@ -49,19 +54,19 @@ def _check_url(url: str, *, redirect: bool = False) -> str:
49
54
  or parts.username is not None
50
55
  or parts.password is not None
51
56
  ):
52
- raise urllib.error.URLError("npm URL must use HTTPS without credentials")
57
+ raise UnsafeRedirect("npm URL must use HTTPS without credentials")
53
58
  return url
54
59
 
55
60
 
56
61
  def _redirect_target(url: str, location: str, hops: int) -> str:
57
62
  if hops >= 5:
58
- raise urllib.error.URLError("npm redirect limit exceeded")
63
+ raise UnsafeRedirect("npm redirect limit exceeded")
59
64
  if not location:
60
- raise urllib.error.URLError("npm redirect is missing its target")
65
+ raise UnsafeRedirect("npm redirect is missing its target")
61
66
  try:
62
67
  target = urljoin(url, location)
63
68
  except ValueError as error:
64
- raise urllib.error.URLError("invalid npm redirect URL") from error
69
+ raise UnsafeRedirect("invalid npm redirect URL") from error
65
70
  return _check_url(target, redirect=True)
66
71
 
67
72
 
@@ -207,47 +212,6 @@ def race(name: str, version: str, env: Mapping[str, str]) -> str | None:
207
212
  return None
208
213
 
209
214
 
210
- def download_package(pin: Mapping[str, Any], destination: Path, binary_size: int) -> str:
211
- """Only transport failures retry another region (and switch the process's region to it).
212
- A size or digest mismatch is fatal."""
213
- from localmodels import region as regions # region probes through this module
214
-
215
- cap = archive_size_cap(binary_size)
216
- if pin.get("bytes"):
217
- if not 0 < pin["bytes"] <= cap:
218
- raise ValueError("npm archive size pin exceeds limit")
219
- cap = pin["bytes"]
220
- region = regions.current_region()
221
- for attempt in range(2):
222
- url = package_url(pin["package"], pin["version"], region, os.environ)
223
- try:
224
- digest = hashlib.sha256()
225
- size = 0
226
- with https_opener().open(_check_url(url), timeout=300) as response:
227
- with destination.open("wb") as output:
228
- while chunk := response.read(65536):
229
- size += len(chunk)
230
- if size > cap:
231
- raise ValueError("npm archive size exceeds limit")
232
- digest.update(chunk)
233
- output.write(chunk)
234
- except (ConnectionError, TimeoutError, urllib.error.URLError, http.client.HTTPException):
235
- destination.unlink(missing_ok=True)
236
- if attempt:
237
- raise
238
- region = "cn" if region == "global" else "global"
239
- continue
240
- if (pin.get("bytes") and size != pin["bytes"]) or (
241
- pin.get("sha256") and digest.hexdigest() != pin["sha256"]
242
- ):
243
- destination.unlink(missing_ok=True)
244
- raise ValueError("npm archive SHA256 or size mismatch")
245
- if attempt:
246
- regions.fallback_to(region)
247
- return region
248
- raise AssertionError("unreachable npm failover")
249
-
250
-
251
215
  def extract_bifrost(archive: Path, destination: Path, digest: str, size: int) -> None:
252
216
  with tarfile.open(archive) as source:
253
217
  binaries = []
@@ -277,10 +241,54 @@ def extract_bifrost(archive: Path, destination: Path, digest: str, size: int) ->
277
241
  destination.chmod(0o755)
278
242
 
279
243
 
280
- def install_bifrost(build: Mapping[str, Any], destination: Path) -> None:
281
- archive = destination.with_suffix(".tgz")
282
- try:
283
- download_package(build["npm"], archive, build["size_bytes"])
284
- extract_bifrost(archive, destination, build["sha256"], build["size_bytes"])
285
- finally:
286
- archive.unlink(missing_ok=True)
244
+ def _archive_pin(build: Mapping[str, Any]) -> tuple[str, int]:
245
+ """The npm tarball's SHA256 and size, which every Bifrost build of the tool lock carries."""
246
+ pin = build["npm"]
247
+ digest, size = pin.get("sha256"), pin.get("bytes")
248
+ if (
249
+ not isinstance(digest, str)
250
+ or not re.fullmatch("[0-9a-f]{64}", digest)
251
+ or type(size) is not int
252
+ or not 0 < size <= archive_size_cap(build["size_bytes"])
253
+ ):
254
+ raise ValueError(
255
+ "Bifrost npm archive pin is missing or invalid (the tool lock needs npm sha256 and"
256
+ " bytes)"
257
+ )
258
+ return digest, size
259
+
260
+
261
+ def _sha256(path: Path) -> str:
262
+ digest = hashlib.sha256()
263
+ with path.open("rb") as stream:
264
+ for chunk in iter(lambda: stream.read(1 << 20), b""):
265
+ digest.update(chunk)
266
+ return digest.hexdigest()
267
+
268
+
269
+ def fetch_bifrost(
270
+ build: Mapping[str, Any],
271
+ destination: Path,
272
+ archive: Path,
273
+ event: Callable[[dict[str, Any]], None],
274
+ ) -> None:
275
+ """Put the pinned Bifrost binary of ``build`` at ``destination``. The npm tarball downloads
276
+ to ``archive``, which must outlive this call: an interrupted download keeps
277
+ ``archive.part`` for the next call to resume (``runtime_io.download``, which also moves
278
+ between the npm registry and its mirror), and a complete tarball left by a crash before
279
+ extraction is reused when it matches the pin. The tarball is deleted once extracted."""
280
+ from localmodels import runtime_io # runtime_io reaches the region through this module
281
+
282
+ digest, size = _archive_pin(build)
283
+ if archive.exists() or archive.is_symlink():
284
+ if archive.is_file() and not archive.is_symlink() and _sha256(archive) == digest:
285
+ event({"kind": "stage", "stage": "download", "state": "reused"})
286
+ else:
287
+ archive.unlink()
288
+ if not archive.exists():
289
+ pin = build["npm"]
290
+ url = _check_url(package_url(pin["package"], pin["version"], "global", os.environ))
291
+ artifact = {"url": url, "algorithm": "sha256", "digest": digest, "maxBytes": size}
292
+ runtime_io.download(artifact, archive, event)
293
+ extract_bifrost(archive, destination, build["sha256"], build["size_bytes"])
294
+ archive.unlink()
@@ -202,6 +202,7 @@ _VERSION_RE = re.compile(r"version:\s*(\d+)\s*\(([0-9a-f]+)\)")
202
202
  _SEMVER_RE = re.compile(r"version:\s*([\w.\-]+)\s*\(build\s*(\d+),\s*commit\s*([0-9a-f]+)\)")
203
203
  SERVICE_PORTS = (8080, 9931, 18100, 18321, 18331, 18351, 18352, 18370)
204
204
  _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)
205
206
  HOST_LIBRARIES = ("libgomp.so.1",)
206
207
  DETAIL_FIELDS = ("compute_cap", "memory.reserved", "display_active") # nvidia-smi names
207
208
  _UNLIMITED = 1 << 60 # cgroup v1 reports "no limit" as a page-aligned LONG_MAX
@@ -338,6 +339,43 @@ def parse_gpu_csv(text: str) -> list[GPU]:
338
339
  return gpus
339
340
 
340
341
 
342
+ def parse_cuda_version(text: str) -> str:
343
+ """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 ""
346
+
347
+
348
+ def _load_cuda_driver() -> ctypes.CDLL | None:
349
+ names: tuple[str, ...] = (
350
+ ("nvcuda.dll",)
351
+ if sys.platform == "win32"
352
+ else ("libcuda.so.1", "libcuda.so", "/usr/lib/wsl/lib/libcuda.so.1")
353
+ if sys.platform.startswith("linux")
354
+ else ()
355
+ )
356
+ for name in names:
357
+ try:
358
+ return ctypes.CDLL(name)
359
+ except OSError:
360
+ continue
361
+ return None
362
+
363
+
364
+ def _cuda_driver_version() -> str:
365
+ """Driver-supported CUDA version via ``cuDriverGetVersion()`` (e.g. 13050 -> '13.5')."""
366
+ cuda = _load_cuda_driver()
367
+ if cuda is None:
368
+ return ""
369
+ try:
370
+ version = ctypes.c_int()
371
+ if cuda.cuDriverGetVersion(ctypes.byref(version)) != 0 or version.value < 1000:
372
+ return ""
373
+ major, rem = divmod(version.value, 1000)
374
+ return f"{major}.{rem // 10}"
375
+ except (OSError, AttributeError):
376
+ return ""
377
+
378
+
341
379
  def _nvidia(errors: list[dict[str, str]]) -> tuple[dict[str, str] | None, list[GPU]]:
342
380
  exe = _nvidia_smi()
343
381
  if exe is None:
@@ -351,20 +389,15 @@ def _nvidia(errors: list[dict[str, str]]) -> tuple[dict[str, str] | None, list[G
351
389
  errors.append({"source": "nvidia-smi", "error": (err or out).strip()[:300]})
352
390
  return None, []
353
391
  gpus = parse_gpu_csv(out)
354
- m = re.search(r"CUDA Version:\s*([\d.]+)", _run([exe])[1])
392
+ cuda_version = _cuda_driver_version() or parse_cuda_version(_run([exe])[1])
355
393
  drv = gpus[0]["driver_version"] if gpus else ""
356
- return {"driver_version": drv, "cuda_version": m.group(1) if m else ""}, gpus
394
+ return {"driver_version": drv, "cuda_version": cuda_version}, gpus
357
395
 
358
396
 
359
397
  def _cuda_pool() -> CudaPool | None:
360
398
  """Allocator pool and INTEGRATED attribute of CUDA device 0 via driver library, or None."""
361
- for name in ("libcuda.so.1", "libcuda.so", "nvcuda.dll"):
362
- try:
363
- cuda = ctypes.CDLL(name)
364
- break
365
- except OSError:
366
- continue
367
- else:
399
+ cuda = _load_cuda_driver()
400
+ if cuda is None:
368
401
  return None
369
402
  try:
370
403
  dev, total, attr, byref = ctypes.c_int(), ctypes.c_size_t(), ctypes.c_int(), ctypes.byref
@@ -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]: