@simplexai/localmodels-darwin-arm64 0.1.0-dev.44 → 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 (64) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +59 -63
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +0 -1
  5. package/modules/localmodels/bifrost_checks.py +3 -127
  6. package/modules/localmodels/bifrost_clients.py +1 -1
  7. package/modules/localmodels/bifrost_config.py +2 -2
  8. package/modules/localmodels/bifrost_pi.py +1 -1
  9. package/modules/localmodels/budget.py +16 -1
  10. package/modules/localmodels/catalog.json +15 -50
  11. package/modules/localmodels/catalog_recipes.py +1 -1
  12. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +41 -1
  13. package/modules/localmodels/gateway.py +50 -15
  14. package/modules/localmodels/gateway_accept.py +8 -5
  15. package/modules/localmodels/gateway_bifrost.py +13 -12
  16. package/modules/localmodels/gateway_cli.py +5 -2
  17. package/modules/localmodels/gateway_requests.py +9 -2
  18. package/modules/localmodels/harness.py +38 -11
  19. package/modules/localmodels/harness_gateway.py +1 -1
  20. package/modules/localmodels/hosts.py +7 -20
  21. package/modules/localmodels/library_gateway.py +12 -9
  22. package/modules/localmodels/library_pricing.py +1 -5
  23. package/modules/localmodels/npm_transport.py +62 -54
  24. package/modules/localmodels/recommend.py +1 -1
  25. package/modules/localmodels/recommend_cli.py +2 -2
  26. package/modules/localmodels/remote_ops.py +14 -6
  27. package/modules/localmodels/remote_ops_download.py +1 -1
  28. package/modules/localmodels/remote_ops_verify.py +0 -33
  29. package/modules/localmodels/runtime_install.py +2 -1
  30. package/modules/localmodels/runtime_io.py +149 -34
  31. package/modules/localmodels/source_byok.py +6 -3
  32. package/modules/localmodels/source_cli.py +8 -1
  33. package/modules/localmodels/stack.py +1 -5
  34. package/modules/localmodels/stack_args.py +6 -8
  35. package/modules/localmodels/stack_binding.py +3 -3
  36. package/modules/localmodels/stack_compose.py +3 -8
  37. package/modules/localmodels/stack_events.py +2 -1
  38. package/modules/localmodels/stack_plan.py +1 -4
  39. package/modules/localmodels/stack_ports.py +0 -1
  40. package/modules/localmodels/stack_run.py +15 -30
  41. package/modules/localmodels/stack_suite.py +23 -46
  42. package/modules/localmodels/stack_summary.py +0 -1
  43. package/modules/localmodels/stack_try.py +3 -92
  44. package/modules/localmodels/stack_up.py +7 -3
  45. package/modules/localmodels/stack_update.py +5 -5
  46. package/modules/localmodels/stack_view_apply.py +1 -1
  47. package/modules/localmodels/stack_view_sandbox.py +0 -2
  48. package/modules/localmodels/stack_view_text.py +0 -1
  49. package/modules/localmodels/stack_view_words.py +0 -1
  50. package/modules/localmodels/suite.py +4 -7
  51. package/modules/localmodels/tui_dialogs.py +0 -1
  52. package/modules/localmodels/web/view/view.css +0 -3
  53. package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/METADATA +1 -1
  54. package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/RECORD +56 -60
  55. package/package.json +1 -1
  56. package/tool.json +1 -1
  57. package/modules/localmodels/bifrost_search.py +0 -66
  58. package/modules/localmodels/gateway_search.py +0 -223
  59. package/modules/localmodels/search-ddgs-9.16.1.txt +0 -222
  60. package/modules/localmodels/search_server.py +0 -474
  61. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/WHEEL +0 -0
  62. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/entry_points.txt +0 -0
  63. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/NOTICE +0 -0
  64. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -33,6 +33,7 @@ from localmodels import (
33
33
  harness_probe,
34
34
  hosts,
35
35
  library_state,
36
+ runtime_io,
36
37
  vision,
37
38
  )
38
39
  from localmodels import catalog as cat
@@ -85,7 +86,7 @@ def _fail(detail: str) -> LibraryError:
85
86
  # ---------------------------------------------------------------------------- Bifrost
86
87
 
87
88
 
88
- def _install(facts: HostFacts) -> hosts.OwnedBifrost:
89
+ def _install(facts: HostFacts, event: runtime_io.Event = lambda _: None) -> hosts.OwnedBifrost:
89
90
  """This tool's Bifrost where none is recorded: the pinned binary, its record, an empty
90
91
  config with management authentication, then the instance itself."""
91
92
  addr = harness.bifrost_addr()
@@ -106,8 +107,9 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
106
107
  tools = Path(os.path.expanduser(tools_root))
107
108
  binary = next(a for a in actions if a["tool"] == "bifrost")
108
109
  if binary["action"] == "install":
109
- made = gateway_bifrost.install_binary(tools, binary, lambda _line: None)
110
- fetched = [str(tools / ".archives" / a["name"]) for a in binary["artifacts"]]
110
+ harness.own_downloads(tools, binary["artifacts"])
111
+ made = gateway_bifrost.install_binary(tools, binary, lambda _line: None, event)
112
+ fetched = [f for a in binary["artifacts"] for f in harness.archive_files(tools, a)]
111
113
 
112
114
  def own(doc: hosts.Owned) -> None:
113
115
  if made:
@@ -115,9 +117,7 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
115
117
  [*doc["tools"], {"path": made, "sha256": harness.digest(made)}],
116
118
  key=lambda t: t["path"],
117
119
  )
118
- doc["archives"] = sorted(
119
- set(doc["archives"]) | {p + s for p in fetched for s in ("", ".sha256")}
120
- )
120
+ doc["archives"] = sorted(set(doc["archives"]) | set(fetched))
121
121
 
122
122
  hosts.update_owned(own)
123
123
  gateway_bifrost.ensure(plan)
@@ -142,11 +142,14 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
142
142
  return record
143
143
 
144
144
 
145
- def ensure_instance(facts: HostFacts | None) -> hosts.OwnedBifrost | None:
146
- """Return this tool's Bifrost record, installing it first when ``facts`` are supplied."""
145
+ def ensure_instance(
146
+ facts: HostFacts | None, event: runtime_io.Event = lambda _: None
147
+ ) -> hosts.OwnedBifrost | None:
148
+ """Return this tool's Bifrost record, installing it first when ``facts`` are supplied;
149
+ ``event`` receives the binary's download events."""
147
150
  record = hosts.load_owned()["gateway"].get("bifrost")
148
151
  if record is None and facts is not None:
149
- record = _install(facts)
152
+ record = _install(facts, event)
150
153
  return record
151
154
 
152
155
 
@@ -46,11 +46,7 @@ from localmodels.stack_plan import platform_error
46
46
 
47
47
  POOL_RAM_FRACTION = 0.8 # a "system" pool's budget: RAM x 0.8 (contract v2)
48
48
  UNIFIED_RESERVE_BYTES = metal.HOST_KEEP_BYTES + METAL_VRAM_RESERVE_BYTES
49
- # Cap on observed non-model GPU VRAM kept back as a desktop/WDDM baseline on Windows and
50
- # display-active GPUs: keeps real desktop overhead (Windows 11 WDDM + DWM + Linger, ~2.2-2.5 GiB)
51
- # from pretending the card is empty, without letting a transient game or foreign server hide
52
- # models that fit once that program closes.
53
- DESKTOP_VRAM_BASELINE_CAP_BYTES = 3 * metal.GIB
49
+ DESKTOP_VRAM_BASELINE_CAP_BYTES = budget.DESKTOP_VRAM_BASELINE_CAP_BYTES
54
50
 
55
51
 
56
52
  @functools.cache
@@ -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()
@@ -185,7 +185,7 @@ def recommendation(
185
185
  fitting = []
186
186
  for entry in (*live, fallback):
187
187
  for p, budget in candidates:
188
- if llm_rank.automatic_fit(entry, facts, budget, AGENT, {"search": False}):
188
+ if llm_rank.automatic_fit(entry, facts, budget, AGENT, {}):
189
189
  key = llm_rank.rank_key(entry, entry.variants[-1], budget)
190
190
  fitting.append((key, entry.id, p.gpu_indices[0]))
191
191
  break
@@ -155,7 +155,7 @@ def _show_parts(
155
155
  " 理由 只选窗口至少 64K、满足引擎内存门槛的已验证 LLM;llama.cpp 权重和 KV 全驻留 GPU,"
156
156
  "Strata 允许专家驻留内存;能读图的默认开启图片输入"
157
157
  "(决策 31,--vision off 关闭),装机后 SimplexAI 分优先、"
158
- "预测解码速度其次(--prefer smartest);网页搜索默认不装(路线图决策 55,--search 安装);"
158
+ "预测解码速度其次(--prefer smartest);"
159
159
  "决策模型与 embedding/reranker/STT 是选装(--decision、--aux),按剩余资源装入,"
160
160
  "决策模型只放 GPU"
161
161
  )
@@ -178,7 +178,7 @@ def _show_parts(
178
178
  if all_models:
179
179
  print(
180
180
  f"可选组件:{command()} stack plan --decision auto --aux auto;"
181
- "决策模型与辅助模型默认不安装,网页搜索默认不装(--search 安装);"
181
+ "决策模型与辅助模型默认不安装;"
182
182
  "要多路并发用 --prefer concurrent;不会自动降低 LLM 门槛。"
183
183
  )
184
184
  for option in plan.get("decision_options", [])[:2]:
@@ -95,6 +95,9 @@ class _Archive(TypedDict):
95
95
 
96
96
  class Archive(_Archive, total=False):
97
97
  npm_copy: NpmCopy
98
+ # Only these paths of the archive are unpacked (prefixes, after its top folder is dropped):
99
+ # a source archive whose deepest paths would pass Windows' 260-character limit.
100
+ members: list[str]
98
101
 
99
102
 
100
103
  class ServiceParams(TypedDict): # all start, stop and status need; the base of the rest
@@ -206,7 +209,6 @@ RERANK_DOCS = [
206
209
  "The Pacific is the largest ocean on Earth.",
207
210
  ]
208
211
  RERANK_RELEVANT = 1
209
- SEARCH_QUERY = "Python programming language" # every engine finds pages for it
210
212
 
211
213
 
212
214
  def emit(event: str, **fields: object) -> None:
@@ -462,7 +464,7 @@ def _relative(name: str) -> str:
462
464
  return name
463
465
 
464
466
 
465
- def _unzip(archive: str, directory: str) -> None:
467
+ def _unzip(archive: str, directory: str, members: tuple[str, ...] = ()) -> None:
466
468
  """A Windows release zip: regular files only, each kept inside ``directory``."""
467
469
  with zipfile.ZipFile(archive) as bundle:
468
470
  names = [_relative(i.filename.replace("\\", "/")) for i in bundle.infolist()]
@@ -471,6 +473,8 @@ def _unzip(archive: str, directory: str) -> None:
471
473
  for info, name in zip(bundle.infolist(), names):
472
474
  if strip:
473
475
  name = name.split("/", 1)[1] if "/" in name else ""
476
+ if members and not name.startswith(members):
477
+ continue
474
478
  if not name or info.is_dir() or name.startswith("/") or ".." in name.split("/"):
475
479
  continue
476
480
  if ":" in name or (info.external_attr >> 16) & 0o170000 == 0o120000:
@@ -481,10 +485,12 @@ def _unzip(archive: str, directory: str) -> None:
481
485
  shutil.copyfileobj(source, dest)
482
486
 
483
487
 
484
- def unpack(archive: str, directory: str) -> None:
485
- """Extract into ``directory``, dropping the archive's single top folder when it has one."""
486
- if archive.endswith(".zip"):
487
- _unzip(archive, directory)
488
+ def unpack(archive: str, directory: str, keep: tuple[str, ...] = ()) -> None:
489
+ """Extract into ``directory``, dropping the archive's single top folder when it has one;
490
+ ``keep``: only the paths under these prefixes (Archive.members). A wheel is a zip
491
+ (PolyStrata's Windows build takes cuBLAS from NVIDIA's)."""
492
+ if archive.endswith((".zip", ".whl")):
493
+ _unzip(archive, directory, keep)
488
494
  return
489
495
  with tarfile.open(archive) as tar:
490
496
  members = tar.getmembers()
@@ -494,6 +500,8 @@ def unpack(archive: str, directory: str) -> None:
494
500
  name = member.name.lstrip("./")
495
501
  if strip:
496
502
  name = name.split("/", 1)[1] if "/" in name else ""
503
+ if keep and not name.startswith(keep):
504
+ continue
497
505
  if not name or name.startswith("/") or ".." in name.split("/"):
498
506
  continue
499
507
  if member.issym() or member.islnk():
@@ -56,7 +56,7 @@ def act_engine(p: remote_ops.EngineParams) -> None:
56
56
  npm_copies(a),
57
57
  p.get("region"),
58
58
  )
59
- remote_ops.unpack(archive, directory)
59
+ remote_ops.unpack(archive, directory, tuple(a.get("members") or ()))
60
60
  if not os.access(binary, os.X_OK):
61
61
  raise RuntimeError(f"the engine has no executable {os.path.relpath(binary, directory)}")
62
62
  remote_ops._write(done_marker, expected)
@@ -415,38 +415,6 @@ def _verify_tts(root: str, p: remote_ops.VerifyParams) -> None:
415
415
  )
416
416
 
417
417
 
418
- SEARCH_ATTEMPTS = 3 # free engines throttle by exit IP: aws-l4 answered 2 of 3 queries 8 s apart
419
- SEARCH_RETRY_S = 5.0
420
-
421
-
422
- def _verify_search(root: str, p: remote_ops.VerifyParams) -> None:
423
- """A real web search answers with at least one result page; the engine named is the one that
424
- answered (DuckDuckGo unless it is rate limited). Only "no engine answered" is asked again, a
425
- few times and spaced out; any other failure is final."""
426
- started = time.monotonic()
427
- query = urllib.parse.urlencode({"q": remote_ops.SEARCH_QUERY, "format": "json"})
428
- for attempt in range(1, SEARCH_ATTEMPTS + 1):
429
- try:
430
- resp = remote_ops._http(f"{root}/search?{query}", p["api_key"], timeout=120)
431
- break
432
- except urllib.error.HTTPError as exc:
433
- if exc.code != 502 or json.loads(exc.read(1024)) != {
434
- "error": "SEARCH_PROVIDER_UNAVAILABLE"
435
- }:
436
- raise
437
- if attempt == SEARCH_ATTEMPTS:
438
- raise RuntimeError("SEARCH_PROVIDER_UNAVAILABLE") from None
439
- time.sleep(SEARCH_RETRY_S)
440
- results = resp.get("results")
441
- if not isinstance(results, list) or not all(isinstance(r, dict) for r in results):
442
- raise ValueError("invalid search results")
443
- urls = [str(r.get("url") or "") for r in results]
444
- found = [u for u in urls if u.startswith(("http://", "https://"))]
445
- engine = str(results[0].get("engine") or "") if results else ""
446
- answer = f"{len(found)} results via {engine or '?'}"
447
- _report(bool(found), answer, started, "the search returned no results page")
448
-
449
-
450
418
  CONTRACTS = {
451
419
  "systemone": _verify_decision,
452
420
  "health": lambda root, p: remote_ops.emit(
@@ -456,5 +424,4 @@ CONTRACTS = {
456
424
  "rerank": _verify_rerank,
457
425
  "stt": _verify_stt,
458
426
  "tts": _verify_tts,
459
- "search": _verify_search,
460
427
  }
@@ -84,7 +84,8 @@ def _fetch_modules(
84
84
  nonlocal shown
85
85
  with lock:
86
86
  if update.get("kind") != "progress":
87
- if update.get("state") != "reused":
87
+ # ~120 modules download at once: per-module connects and reuse are noise
88
+ if update.get("state") not in ("reused", "connecting"):
88
89
  event(update)
89
90
  return
90
91
  count = int(update["completed"])