@simplexai/localmodels-darwin-x64 0.1.0-dev.65 → 0.1.0-dev.66

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 (57) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +56 -55
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/auth_proxy.py +34 -2
  5. package/modules/localmodels/catalog.json +500 -16
  6. package/modules/localmodels/custom_hub.py +54 -6
  7. package/modules/localmodels/custom_probe.py +28 -0
  8. package/modules/localmodels/debug_stub_server.py +34 -1
  9. package/modules/localmodels/deploy.py +33 -349
  10. package/modules/localmodels/download-mirrors.json +43 -3
  11. package/modules/localmodels/draft_spec.py +1 -1
  12. package/modules/localmodels/engine_adapters/__init__.py +4 -2
  13. package/modules/localmodels/engine_adapters/auxiliary.py +4 -1
  14. package/modules/localmodels/engine_adapters/llama_cpp.py +539 -0
  15. package/modules/localmodels/engines-b11583.json +9 -5
  16. package/modules/localmodels/engines-b12757-mix-ef2df21.json +85 -1
  17. package/modules/localmodels/engines.json +9 -5
  18. package/modules/localmodels/harness_gateway.py +14 -3
  19. package/modules/localmodels/harness_probe.py +64 -3
  20. package/modules/localmodels/library_custom.py +9 -7
  21. package/modules/localmodels/library_elastic.py +5 -4
  22. package/modules/localmodels/library_jobs.py +138 -25
  23. package/modules/localmodels/library_model.py +22 -2
  24. package/modules/localmodels/library_order.py +1 -1
  25. package/modules/localmodels/library_serve.py +11 -4
  26. package/modules/localmodels/library_state.py +12 -0
  27. package/modules/localmodels/library_status.py +10 -0
  28. package/modules/localmodels/planning/budget.py +8 -3
  29. package/modules/localmodels/remote_ops_mirrors.py +55 -19
  30. package/modules/localmodels/service_deployment.py +3 -3
  31. package/modules/localmodels/setup_inspection.py +28 -1
  32. package/modules/localmodels/setup_inspection_harness.py +4 -1
  33. package/modules/localmodels/setup_text.py +6 -0
  34. package/modules/localmodels/slot_cache.py +1 -3
  35. package/modules/localmodels/speech_admission.py +16 -4
  36. package/modules/localmodels/speech_catalog.py +5 -1
  37. package/modules/localmodels/speech_cli.py +5 -5
  38. package/modules/localmodels/speech_jobs.py +101 -19
  39. package/modules/localmodels/speech_server.py +2 -0
  40. package/modules/localmodels/speech_worker_sensevoice.py +194 -6
  41. package/modules/localmodels/speech_workers.py +74 -6
  42. package/modules/localmodels/stack.py +13 -1
  43. package/modules/localmodels/stack_auto.py +6 -0
  44. package/modules/localmodels/stack_capacity.py +3 -3
  45. package/modules/localmodels/stack_cli.py +3 -0
  46. package/modules/localmodels/stack_compose.py +7 -3
  47. package/modules/localmodels/stack_ports.py +58 -27
  48. package/modules/localmodels/stack_suite.py +7 -1
  49. package/modules/localmodels/suite.py +1 -1
  50. package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/METADATA +1 -1
  51. package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/RECORD +53 -52
  52. package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/NOTICE +3 -0
  53. package/package.json +1 -1
  54. package/tool.json +1 -1
  55. /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/WHEEL +0 -0
  56. /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/entry_points.txt +0 -0
  57. /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -3,7 +3,7 @@
3
3
  "tag": "b11370",
4
4
  "commit": "bed0a856606ee4a24a164066f73d2379447033f5",
5
5
  "source": "https://github.com/ggml-org/llama.cpp/releases/tag/b11370",
6
- "note": "Release asset digests from the GitHub release API, read 2026-10-12. b11370 is the build Hermes' catalog constants were measured on. min_glibc is the highest GLIBC symbol version the build's binaries import (objdump -T, 2026-10-20); builds without it were not checked. The ubuntu22.04 variant (2026-10-23) is this repository's rebuild of the same commit for hosts whose glibc is older than upstream's 2.38: scripts/build_cuda_engine.py runs the release workflow's CMake flags in nvidia/cuda:12.8.2-devel-ubuntu22.04 pinned by digest; its provenance JSON records the image, flags and toolchain, and its archives live in the public generic package registry of simplexai/infra/llm-engine-builds. Every upstream Linux build links GCC's OpenMP runtime (libgomp.so.1, Debian package libgomp1; readelf NEEDED, 2026-10-23), which minimal images lack, so a plan on such a host stops instead of installing it. The ubuntu22.04-r2 rebuild (2026-10-23) carries its own libgomp.so.1 and replaces r1, which needed the system copy. The ubuntu22.04-r3 rebuild (2026-10-26) also compiles the q8_0-q4_0 FlashAttention K-V kernels (GGML_CUDA_FA_QUANTS), which the agent stack's K q8_0 / V q4_0 cache needs to decode at full speed (evidence/2026-10-25-vram-stack-probe-r3-lab12021); it replaces r2. Windows x64 builds (2026-11-11) are upstream's win-cuda-12.4/13.4 and win-cpu zips with their cudart companions, digests from the same release API; the CUDA zips hold llama-server.exe beside the ggml DLLs and the cudart zip adds the CUDA runtime DLLs to the same directory.",
6
+ "note": "Release asset digests from the GitHub release API, read 2026-10-12. b11370 is the build Hermes' catalog constants were measured on. min_glibc is the highest GLIBC symbol version the build's binaries import (objdump -T, 2026-10-20); builds without it were not checked. The ubuntu22.04 variant (2026-10-23) is this repository's rebuild of the same commit for hosts whose glibc is older than upstream's 2.38: scripts/build_cuda_engine.py runs the release workflow's CMake flags in nvidia/cuda:12.8.2-devel-ubuntu22.04 pinned by digest; its provenance JSON records the image, flags and toolchain, and its archives and provenance live on the project CloudFront CDN under cli/localmodels/engines/llama.cpp/b11370-cu12.8-ubuntu22.04-r3/. Every upstream Linux build links GCC's OpenMP runtime (libgomp.so.1, Debian package libgomp1; readelf NEEDED, 2026-10-23), which minimal images lack, so a plan on such a host stops instead of installing it. The ubuntu22.04-r2 rebuild (2026-10-23) carries its own libgomp.so.1 and replaces r1, which needed the system copy. The ubuntu22.04-r3 rebuild (2026-10-26) also compiles the q8_0-q4_0 FlashAttention K-V kernels (GGML_CUDA_FA_QUANTS), which the agent stack's K q8_0 / V q4_0 cache needs to decode at full speed (evidence/2026-10-25-vram-stack-probe-r3-lab12021); it replaces r2. Windows x64 builds (2026-11-11) are upstream's win-cuda-12.4/13.4 and win-cpu zips with their cudart companions, digests from the same release API; the CUDA zips hold llama-server.exe beside the ggml DLLs and the cudart zip adds the CUDA runtime DLLs to the same directory.",
7
7
  "builds": [
8
8
  {
9
9
  "platform": "linux",
@@ -40,17 +40,21 @@
40
40
  "min_cuda": "12.8",
41
41
  "min_glibc": "2.34",
42
42
  "variant": "ubuntu22.04-r3",
43
- "provenance": "http://192.168.10.117:6001/api/v4/projects/simplexai%2Finfra%2Fllm-engine-builds/packages/generic/llama.cpp-cuda/b11370-cu12.8-ubuntu22.04-r3/llama-b11370-bin-ubuntu22.04-r3-cuda-12.8-x64.provenance.json",
43
+ "provenance": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/engines/llama.cpp/b11370-cu12.8-ubuntu22.04-r3/llama-b11370-bin-ubuntu22.04-r3-cuda-12.8-x64.provenance.json",
44
44
  "assets": [
45
45
  {
46
46
  "name": "llama-b11370-bin-ubuntu22.04-r3-cuda-12.8-x64.tar.gz",
47
- "url": "http://192.168.10.117:6001/api/v4/projects/simplexai%2Finfra%2Fllm-engine-builds/packages/generic/llama.cpp-cuda/b11370-cu12.8-ubuntu22.04-r3/llama-b11370-bin-ubuntu22.04-r3-cuda-12.8-x64.tar.gz",
47
+ "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/engines/llama.cpp/b11370-cu12.8-ubuntu22.04-r3/llama-b11370-bin-ubuntu22.04-r3-cuda-12.8-x64.tar.gz",
48
48
  "sha256": "875cf9ee9e29afc60187312363ea721db51bb06138aef7c1ca63fc3d956b25b1",
49
- "size_bytes": 173034114
49
+ "size_bytes": 173034114,
50
+ "npm_copy": {
51
+ "package": "@simplexai/engine-llama-b11370-bin-ubuntu22.04-r3-cuda-12.8-x64",
52
+ "version": "0.0.0-sha256-875cf9ee9e29afc6"
53
+ }
50
54
  },
51
55
  {
52
56
  "name": "cudart-llama-b11370-bin-ubuntu22.04-r3-cuda-12.8-x64.tar.gz",
53
- "url": "http://192.168.10.117:6001/api/v4/projects/simplexai%2Finfra%2Fllm-engine-builds/packages/generic/llama.cpp-cuda/b11370-cu12.8-ubuntu22.04-r3/cudart-llama-b11370-bin-ubuntu22.04-r3-cuda-12.8-x64.tar.gz",
57
+ "url": "https://d2ikbbcl3j6jz9.cloudfront.net/cli/localmodels/engines/llama.cpp/b11370-cu12.8-ubuntu22.04-r3/cudart-llama-b11370-bin-ubuntu22.04-r3-cuda-12.8-x64.tar.gz",
54
58
  "sha256": "441680ed89b157f7e0bd7285771cc0d40fd61ab1110bf4c67a705dd9417ab624",
55
59
  "size_bytes": 593656099
56
60
  }
@@ -109,13 +109,19 @@ def select_address(
109
109
  ) -> str:
110
110
  """Resolve an automatic address before querying any gateway; fixed addresses never move."""
111
111
  candidates = [requested] if requested else [f"127.0.0.1:{p}" for p in range(3425, 3457)]
112
+ unknown = False
112
113
  for addr in candidates:
113
114
  try:
114
115
  busy = address_listening(addr, listening)
115
116
  except (OSError, RuntimeError) as exc:
116
- raise harness_core.HarnessError(
117
- "cannot confirm whether the Magpie gateway port is free"
118
- ) from exc
117
+ # An automatic address the probe cannot tell about is skipped like a busy one.
118
+ if requested:
119
+ raise harness_core.HarnessError(
120
+ "cannot confirm whether the Magpie gateway port is free; check again",
121
+ code="port-check-failed",
122
+ ) from exc
123
+ unknown = True
124
+ continue
119
125
  if not busy or owned(addr):
120
126
  return addr
121
127
  if requested:
@@ -124,6 +130,11 @@ def select_address(
124
130
  " that program is kept",
125
131
  code="gateway-port-in-use",
126
132
  )
133
+ if unknown:
134
+ raise harness_core.HarnessError(
135
+ "cannot confirm whether any Magpie default port 3425..3456 is free; check again",
136
+ code="port-check-failed",
137
+ )
127
138
  raise harness_core.HarnessError(
128
139
  "Magpie default ports 3425..3456 are all in use", code="gateway-port-in-use"
129
140
  )
@@ -2,12 +2,15 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import contextlib
6
+ import contextvars
5
7
  import errno
6
8
  import os
7
9
  import re
8
10
  import socket
9
11
  import subprocess
10
12
  import sys
13
+ from collections.abc import Iterator
11
14
  from pathlib import Path
12
15
 
13
16
  from localmodels import (
@@ -185,9 +188,53 @@ def _listdir(path: str) -> list[str]:
185
188
  return []
186
189
 
187
190
 
191
+ # A connect that times out met a listener whose accept backlog is full (or, on macOS, a bound
192
+ # socket that does not listen): the port is in use, not unknown.
193
+ _IN_USE_RESULTS = frozenset({errno.EAGAIN, errno.EWOULDBLOCK, errno.ETIMEDOUT})
194
+ _SNAPSHOT: contextvars.ContextVar[dict[int, bool | str] | None] = contextvars.ContextVar(
195
+ "loopback_snapshot", default=None
196
+ )
197
+
198
+
199
+ @contextlib.contextmanager
200
+ def loopback_snapshot() -> Iterator[None]:
201
+ """Within one plan each loopback port is probed once and every later question gets the same
202
+ answer, so a port chosen as free is not found taken a moment later by a slower probe (which
203
+ made ``--llm auto`` pass over a candidate). Nested uses share the outer snapshot."""
204
+ if _SNAPSHOT.get() is not None:
205
+ yield
206
+ return
207
+ token = _SNAPSHOT.set({})
208
+ try:
209
+ yield
210
+ finally:
211
+ _SNAPSHOT.reset(token)
212
+
213
+
188
214
  def loopback_listening(port: int) -> bool:
189
- """Only connection refusal proves that a loopback port has no TCP listener. Windows reads
190
- its listener table instead: a refused loopback connect retries there for about two seconds."""
215
+ """Only connection refusal proves that a loopback port has no TCP listener; a connect that
216
+ times out counts as in use. Raises OSError when neither can be told. Inside
217
+ ``loopback_snapshot`` the first answer for a port, or its error, is the answer for the plan."""
218
+ seen = _SNAPSHOT.get()
219
+ if seen is not None and port in seen:
220
+ known = seen[port]
221
+ if isinstance(known, str):
222
+ raise OSError(known)
223
+ return known
224
+ try:
225
+ answer = _probe_loopback(port)
226
+ except OSError as exc:
227
+ if seen is not None:
228
+ seen[port] = str(exc)
229
+ raise
230
+ if seen is not None:
231
+ seen[port] = answer
232
+ return answer
233
+
234
+
235
+ def _probe_loopback(port: int) -> bool:
236
+ """Windows reads its listener table instead: a refused loopback connect retries there for
237
+ about two seconds."""
191
238
  if sys.platform == "win32":
192
239
  if (pids := process_identity.listener_pids(port)) is None:
193
240
  raise OSError(f"cannot confirm whether port {port} is free")
@@ -195,13 +242,27 @@ def loopback_listening(port: int) -> bool:
195
242
  with socket.socket() as sock:
196
243
  sock.settimeout(1)
197
244
  result = sock.connect_ex(("127.0.0.1", port))
198
- if result == 0:
245
+ if result == 0 or result in _IN_USE_RESULTS:
199
246
  return True
200
247
  if result == errno.ECONNREFUSED:
201
248
  return False
202
249
  raise OSError(f"cannot confirm whether port {port} is free (connect result {result})")
203
250
 
204
251
 
252
+ def loopback_bindable(port: int) -> bool:
253
+ """Whether a server could bind ``127.0.0.1:port`` now, as http.server binds it (reusing
254
+ TIME_WAIT on POSIX). A port without a listener can still be held: where the ephemeral range
255
+ covers it, an outgoing connection's local port refuses bind() though connect() is refused."""
256
+ with socket.socket() as sock:
257
+ if os.name != "nt":
258
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
259
+ try:
260
+ sock.bind(("127.0.0.1", port))
261
+ except OSError:
262
+ return False
263
+ return True
264
+
265
+
205
266
  def bifrost_held(addr: str) -> str:
206
267
  """The refusal for a listener of this user's that the manifest does not own, naming it: a
207
268
  bifrost-http is most often another HOME's or state directory's localmodels gateway."""
@@ -45,7 +45,7 @@ from localmodels.planning import budget, memory_pools
45
45
  from localmodels.probe import HostFacts
46
46
  from localmodels.records import Plan, ReusableFile
47
47
 
48
- CUSTOM_ENGINE_TAG = "b12588-mix-c0c3de8"
48
+ CUSTOM_ENGINE_TAG = custom_probe.CUSTOM_ENGINE_TAG
49
49
  _SAFE_SEGMENT_RE = re.compile(r"[^a-z0-9._-]+")
50
50
  _REV_SAFE_RE = re.compile(r"[^a-zA-Z0-9._-]+")
51
51
 
@@ -251,17 +251,14 @@ def _select_pool_and_engine(
251
251
  adm = budget.admission_budget(facts, pool_id)
252
252
  total = memory_pools.pool_total(facts, pool_id)
253
253
  ceiling = adm.hard_ceiling_bytes if adm is not None and adm.hard_ceiling_bytes > 0 else total
254
- backend = "metal" if pool_id == "unified" and facts.get("platform") == "darwin" else "cuda"
255
- lock_path = engines.engine_lock_path(CUSTOM_ENGINE_TAG)
256
254
  try:
257
- build = engines.select_engine_build(facts, backend, lock_path)
255
+ engine_doc = custom_probe.custom_engine(facts, pool_id, base_dir)
258
256
  except engines.CudaDriverError as exc:
259
257
  raise LibraryError("DRIVER_UPDATE_REQUIRED", str(exc)) from None
260
258
  except engines.EngineUnavailableError as exc:
261
259
  raise LibraryError("RUNTIME_DEPENDENCY_MISSING", str(exc)) from None
262
260
  except plan_envelope.PlanError as exc:
263
261
  raise LibraryError("RUNTIME_DEPENDENCY_MISSING", str(exc)) from None
264
- engine_doc = cast(dict[str, object], engines.release_engine(build, base_dir))
265
262
  return pool_id, placement_id, ceiling, engine_doc
266
263
 
267
264
 
@@ -738,19 +735,21 @@ def download_custom(payload: Mapping[str, object], base_dir: str) -> Row:
738
735
  _cleanup_aborted(
739
736
  custom_model_id, job, handle, base_dir, preserve_dests=old_dests
740
737
  )
738
+ library_jobs.discard_engine_parts(engine_doc)
741
739
  raise LibraryError("CANCELLED", "the download was cancelled") from None
742
740
  except LibraryError as exc:
743
741
  safe_detail = custom_hub.redact_secrets(
744
742
  remote_ops.redact_text(exc.detail), extra_token=resolved_token
745
743
  )
744
+ was_cancelled = False
746
745
  with library_state.locked():
747
746
  if library_state.current(job):
748
747
  if library_state.cancelled(job):
749
748
  _cleanup_aborted(
750
749
  custom_model_id, job, handle, base_dir, preserve_dests=old_dests
751
750
  )
752
- raise LibraryError("CANCELLED", "the download was cancelled") from None
753
- if (
751
+ was_cancelled = True
752
+ elif (
754
753
  exc.code in library_jobs.KEEP_FAILED_DOWNLOAD_CODES
755
754
  and library_state.load(custom_model_id) is None
756
755
  ):
@@ -762,6 +761,9 @@ def download_custom(payload: Mapping[str, object], base_dir: str) -> Row:
762
761
  _cleanup_aborted(
763
762
  custom_model_id, job, handle, base_dir, preserve_dests=old_dests
764
763
  )
764
+ if was_cancelled:
765
+ library_jobs.discard_engine_parts(engine_doc)
766
+ raise LibraryError("CANCELLED", "the download was cancelled") from None
765
767
  raise LibraryError(exc.code, safe_detail, failed=exc.failed, **exc.fields) from None
766
768
  except Exception as exc:
767
769
  with library_state.locked():
@@ -27,6 +27,7 @@ from localmodels import (
27
27
  vision,
28
28
  )
29
29
  from localmodels.context_policy import AgentPosture
30
+ from localmodels.engine_adapters import llama_cpp
30
31
  from localmodels.estimator import (
31
32
  PhysicsRefusal,
32
33
  )
@@ -117,7 +118,7 @@ class ElasticRoomError(deploy.AgentMemoryError):
117
118
  def elastic_posture_ladder(
118
119
  base: AgentPosture,
119
120
  *,
120
- backend: str,
121
+ backend: budget.Backend,
121
122
  native_ctx: int = 0,
122
123
  max_agent_window: int = 0,
123
124
  ) -> tuple[PostureRung, ...]:
@@ -248,7 +249,7 @@ def minimum_memory_bytes(facts: HostFacts, model: Model, pool: str) -> int | Non
248
249
  return None
249
250
  if pool not in memory_pools.pools(facts):
250
251
  return None
251
- backend = "metal" if pool == "unified" and metal.supported(facts) else "cuda"
252
+ backend: budget.Backend = "metal" if pool == "unified" and metal.supported(facts) else "cuda"
252
253
  ladder = elastic_posture_ladder(
253
254
  library_pricing.posture(),
254
255
  backend=backend,
@@ -509,7 +510,7 @@ def _try_floor_admission(
509
510
 
510
511
 
511
512
  def _custom_ctx_ladder(
512
- base: AgentPosture, backend: str, ctx_tokens: int
513
+ base: AgentPosture, backend: budget.Backend, ctx_tokens: int
513
514
  ) -> tuple[PostureRung, ...]:
514
515
  requested = context_policy.posture_for(base, backend)
515
516
  pinned = replace(
@@ -530,7 +531,7 @@ def load_posture(model: Model, base_dir: str) -> AgentPosture:
530
531
  downloaded before the drafter shipped), the model is planned with the drafter off, exactly
531
532
  as when there is no headroom for it."""
532
533
  posture = library_pricing.posture()
533
- if model.entry.draft is None or deploy.drafter_in_place(model.entry, base_dir):
534
+ if model.entry.draft is None or llama_cpp.drafter_in_place(model.entry, base_dir):
534
535
  return posture
535
536
  return replace(posture, draft="off")
536
537
 
@@ -14,7 +14,7 @@ import os
14
14
  import signal
15
15
  import threading
16
16
  import time
17
- from collections.abc import Callable, Iterator
17
+ from collections.abc import Callable, Iterator, Mapping
18
18
  from contextlib import contextmanager
19
19
  from pathlib import Path
20
20
 
@@ -35,6 +35,7 @@ from localmodels import (
35
35
  process_identity,
36
36
  remote_ops,
37
37
  remote_ops_download,
38
+ remote_ops_mirrors,
38
39
  reuse,
39
40
  )
40
41
  from localmodels.deploy_steps import Action
@@ -208,6 +209,91 @@ def _download_telemetry(phase: str, event: dict[str, object]) -> tuple[str | Non
208
209
  return source, connections
209
210
 
210
211
 
212
+ def _release_engine(spec: object) -> Mapping[str, object] | None:
213
+ if isinstance(spec, Mapping) and spec.get("source") == "release" and spec.get("dir"):
214
+ return spec
215
+ return None
216
+
217
+
218
+ def _engine_archives(engine: Mapping[str, object]) -> list[tuple[str, int]]:
219
+ """``(archive path, size)`` of each release asset in the engines root's ``.archives``."""
220
+ engine_dir = os.path.expanduser(str(engine["dir"]))
221
+ cache = os.path.join(os.path.dirname(engine_dir), ".archives")
222
+ assets = engine.get("assets")
223
+ return [
224
+ (os.path.join(cache, str(a["name"])), int(a["size_bytes"]))
225
+ for a in (assets if isinstance(assets, list) else ())
226
+ if isinstance(a, Mapping)
227
+ ]
228
+
229
+
230
+ def engine_pending(spec: object) -> bool:
231
+ """Whether the plan's engine step will fetch archives: a pinned release whose directory
232
+ lacks the ``.complete`` marker for these assets (remote_ops_download.act_engine)."""
233
+ engine = _release_engine(spec)
234
+ if engine is None:
235
+ return False
236
+ assets = engine.get("assets")
237
+ expected = ",".join(
238
+ str(a.get("sha256") or "")
239
+ for a in (assets if isinstance(assets, list) else ())
240
+ if isinstance(a, Mapping)
241
+ )
242
+ marker = Path(os.path.expanduser(str(engine["dir"]))) / ".complete"
243
+ try:
244
+ return marker.read_text(encoding="utf-8").strip() != expected
245
+ except (OSError, UnicodeError):
246
+ return True
247
+
248
+
249
+ def _archive_done(archive: str, size: int) -> int:
250
+ if os.path.isfile(archive) and os.path.getsize(archive) == size:
251
+ return size
252
+ try:
253
+ return min(size, remote_ops_download.kept_bytes(archive + ".part", size))
254
+ except OSError:
255
+ return 0
256
+
257
+
258
+ def engine_missing_bytes(spec: object) -> int:
259
+ """Engine archive bytes a download still has to fetch (0 when the engine is installed)."""
260
+ engine = _release_engine(spec)
261
+ if engine is None or not engine_pending(engine):
262
+ return 0
263
+ return sum(size - _archive_done(path, size) for path, size in _engine_archives(engine))
264
+
265
+
266
+ ENGINE_LOCK_WAIT_S = 3.0 # how long a cancel waits for its own engine step to let go
267
+
268
+
269
+ def discard_engine_parts(spec: object) -> int:
270
+ """A cancelled download's partial engine archives (``.archives/*.part``): deleted unless
271
+ another download is fetching the engine now (it holds the engines-root lock). Returns the
272
+ bytes deleted."""
273
+ engine = _release_engine(spec)
274
+ if engine is None:
275
+ return 0
276
+ freed = 0
277
+ with remote_ops_mirrors.try_engine_lock(
278
+ os.path.expanduser(str(engine["dir"])), ENGINE_LOCK_WAIT_S
279
+ ) as held:
280
+ if not held:
281
+ return 0
282
+ for archive, size in _engine_archives(engine):
283
+ part = archive + ".part"
284
+ if not os.path.exists(part):
285
+ continue
286
+ try:
287
+ freed += min(size, remote_ops_download.kept_bytes(part, size))
288
+ except OSError:
289
+ pass
290
+ try:
291
+ remote_ops_download.discard(part)
292
+ except OSError:
293
+ pass
294
+ return freed
295
+
296
+
211
297
  class _Counter:
212
298
  """Bytes of the whole model (plus engine archives whenever the engine step downloads them):
213
299
  the files already verified (or partially downloaded on disk) count as done; each progress
@@ -220,6 +306,7 @@ class _Counter:
220
306
  handle: JobHandle,
221
307
  *,
222
308
  shard_count: int | None = None,
309
+ engine: bool = True,
223
310
  ) -> None:
224
311
  self.model, self.handle = model, handle
225
312
  self.shard_count = shard_count if shard_count and shard_count >= 1 else None
@@ -242,28 +329,36 @@ class _Counter:
242
329
  }
243
330
  self.engine_sizes: dict[str, int] = {}
244
331
  self.engine_done: dict[str, int] = {}
245
- self._include_engine = False
246
- engine_spec = plan.get("engine")
247
- if isinstance(engine_spec, dict) and engine_spec.get("source") == "release":
248
- engine_dir = os.path.expanduser(str(engine_spec.get("dir") or ""))
249
- archive_cache = os.path.join(os.path.dirname(engine_dir), ".archives")
250
- for asset in engine_spec.get("assets") or ():
251
- name = str(asset["name"])
252
- size = int(asset["size_bytes"])
253
- self.engine_sizes[name] = size
254
- archive = os.path.join(archive_cache, name)
255
- if os.path.isfile(archive) and os.path.getsize(archive) == size:
256
- self.engine_done[name] = size
257
- else:
258
- self.engine_done[name] = min(
259
- size, remote_ops_download.kept_bytes(archive + ".part", size)
260
- )
332
+ # Counted from the first line when the engine step will fetch archives, so the total
333
+ # does not jump once its first progress event arrives.
334
+ self._include_engine = engine and engine_pending(plan.get("engine"))
335
+ release = _release_engine(plan.get("engine")) if engine else None
336
+ for archive, size in _engine_archives(release) if release is not None else ():
337
+ name = os.path.basename(archive)
338
+ self.engine_sizes[name] = size
339
+ self.engine_done[name] = _archive_done(archive, size)
261
340
 
262
341
  @property
263
342
  def total(self) -> int:
264
343
  base = sum(self.sizes.values())
265
344
  return base + sum(self.engine_sizes.values()) if self._include_engine else base
266
345
 
346
+ @property
347
+ def finished(self) -> int:
348
+ done = sum(min(n, self.sizes[k]) for k, n in self.done.items())
349
+ return done + (self.engine_finished or 0)
350
+
351
+ @property
352
+ def engine_finished(self) -> int | None:
353
+ """Engine archive bytes done, inside ``finished``; None when no engine is fetched."""
354
+ if not self._include_engine:
355
+ return None
356
+ return sum(min(n, self.engine_sizes[k]) for k, n in self.engine_done.items())
357
+
358
+ @property
359
+ def engine_total(self) -> int | None:
360
+ return sum(self.engine_sizes.values()) if self._include_engine else None
361
+
267
362
  def finish_engine(self) -> None:
268
363
  """Mark engine assets complete once the engine step succeeds, keeping progress monotonic."""
269
364
  if not self._include_engine:
@@ -286,9 +381,7 @@ class _Counter:
286
381
  done = event.get("done")
287
382
  speed = event.get("bytes_per_s")
288
383
  target_done[label] = min(target_sizes[label], int(done) if isinstance(done, int) else 0)
289
- finished = sum(min(n, self.sizes[k]) for k, n in self.done.items())
290
- if self._include_engine:
291
- finished += sum(min(n, self.engine_sizes[k]) for k, n in self.engine_done.items())
384
+ finished = self.finished
292
385
  rate = int(speed) if isinstance(speed, int) and phase == "download" else 0
293
386
  source, connections = _download_telemetry(phase, event)
294
387
  shard_index: int | None = None
@@ -305,6 +398,8 @@ class _Counter:
305
398
  connections=connections,
306
399
  shard_index=shard_index,
307
400
  shard_count=shard_count,
401
+ engine_done=self.engine_finished,
402
+ engine_total=self.engine_total,
308
403
  )
309
404
  progress(
310
405
  self.model,
@@ -316,6 +411,8 @@ class _Counter:
316
411
  connections=connections,
317
412
  shard_index=shard_index,
318
413
  shard_count=shard_count,
414
+ engine_done=self.engine_finished,
415
+ engine_total=self.engine_total,
319
416
  )
320
417
 
321
418
 
@@ -356,8 +453,8 @@ def fetch(
356
453
  ) -> None:
357
454
  """The plan's engine (when it is a pinned release) and weights, as stack apply fetches them;
358
455
  ``only`` limits the weights to the files this job claims. Progress counts the whole model."""
359
- counter = _Counter(model, plan, handle, shard_count=shard_count)
360
- initial_done = sum(counter.done.values())
456
+ counter = _Counter(model, plan, handle, shard_count=shard_count, engine=engine)
457
+ initial_done = counter.finished
361
458
  init_shard_idx = 1 if counter.shard_count is not None else None
362
459
  handle.update(
363
460
  "download",
@@ -365,6 +462,8 @@ def fetch(
365
462
  counter.total,
366
463
  shard_index=init_shard_idx,
367
464
  shard_count=counter.shard_count,
465
+ engine_done=counter.engine_finished,
466
+ engine_total=counter.engine_total,
368
467
  )
369
468
  progress(
370
469
  model,
@@ -373,6 +472,8 @@ def fetch(
373
472
  counter.total,
374
473
  shard_index=init_shard_idx,
375
474
  shard_count=counter.shard_count,
475
+ engine_done=counter.engine_finished,
476
+ engine_total=counter.engine_total,
376
477
  )
377
478
  files = [f for f in plan["files"] if only is None or os.path.expanduser(f["dest"]) in only]
378
479
  steps: tuple[Action, ...] = ("download",) if files else ()
@@ -396,7 +497,14 @@ def fetch(
396
497
  frontend.install(str(plan["launch"]["frontend_base_dir"]), str(reqs))
397
498
  except frontend.FrontendError as exc:
398
499
  raise LibraryError("DOWNLOAD_FAILED", str(exc), failed=True) from None
399
- progress(model, "verify", counter.total, counter.total)
500
+ progress(
501
+ model,
502
+ "verify",
503
+ counter.total,
504
+ counter.total,
505
+ engine_done=counter.engine_total,
506
+ engine_total=counter.engine_total,
507
+ )
400
508
 
401
509
 
402
510
  WAIT_S = 2.0 # how often a download looks at a file another download is fetching
@@ -567,18 +675,23 @@ def download(
567
675
  with library_state.locked():
568
676
  if library_state.load(model.id) is None:
569
677
  _give_up(model.id, job, handle)
678
+ discard_engine_parts(plan.get("engine"))
570
679
  raise LibraryError("CANCELLED", "the download was cancelled") from None
571
680
  except LibraryError as exc:
681
+ was_cancelled = False
572
682
  with library_state.locked():
573
683
  if library_state.load(model.id) is None and library_state.current(job):
574
684
  if library_state.cancelled(job):
575
685
  _give_up(model.id, job, handle)
576
- raise LibraryError("CANCELLED", "the download was cancelled") from None
577
- if exc.code in KEEP_FAILED_DOWNLOAD_CODES:
686
+ was_cancelled = True
687
+ elif exc.code in KEEP_FAILED_DOWNLOAD_CODES:
578
688
  library_state.fail_job(handle.job, {"code": exc.code, "detail": exc.detail})
579
689
  claims.clear()
580
690
  else:
581
691
  _give_up(model.id, job, handle)
692
+ if was_cancelled:
693
+ discard_engine_parts(plan.get("engine"))
694
+ raise LibraryError("CANCELLED", "the download was cancelled") from None
582
695
  raise
583
696
  except Exception:
584
697
  with library_state.locked():
@@ -38,6 +38,9 @@ CustomRepoFormat = Literal["gguf", "mlx", "safetensors", "unknown"]
38
38
  MemoryEstimateBasis = Literal["gguf_header", "rough_1.2x_plus_0.8gb"]
39
39
  MemoryStatus = Literal["comfortable", "tight", "exceeds"]
40
40
  CustomIncompatibleReason = Literal["raw_safetensors", "mlx_unsupported", "no_runnable_files"]
41
+ # Why a probe came back "gated": access really is gated, or (Hugging Face 401 on metadata) the
42
+ # repo is private or does not exist; the Hub answers both alike.
43
+ CustomGatedReason = Literal["gated", "not_found_or_private"]
41
44
 
42
45
  # Extend only together with the contract (contracts/linger-installer/library-v2.schema.json).
43
46
  ERROR_CODES = (
@@ -266,6 +269,8 @@ class Download(_Download, total=False):
266
269
  connections: int
267
270
  shard_index: int
268
271
  shard_count: int
272
+ engine_done_bytes: int # engine archive bytes inside done_bytes (first install only)
273
+ engine_total_bytes: int
269
274
 
270
275
 
271
276
  class Load(TypedDict):
@@ -485,7 +490,7 @@ class CustomGgufMeta(TypedDict):
485
490
  has_chat_template: bool
486
491
 
487
492
 
488
- class CustomProbeHost(TypedDict):
493
+ class _CustomProbeHost(TypedDict):
489
494
  platform: str
490
495
  arch: str
491
496
  supported_formats: list[str]
@@ -496,6 +501,12 @@ class CustomProbeHost(TypedDict):
496
501
  pool_hard_ceiling_bytes: int
497
502
 
498
503
 
504
+ class CustomProbeHost(_CustomProbeHost, total=False):
505
+ # llama.cpp engine archive bytes the first custom download also fetches (0 once installed;
506
+ # absent when no engine build fits this host). Not part of any quant's size or disk check.
507
+ engine_download_bytes: int
508
+
509
+
499
510
  class CustomMmprojCandidate(TypedDict):
500
511
  path: str
501
512
  size_bytes: int
@@ -558,6 +569,7 @@ class CustomProbeGatedDoc(TypedDict):
558
569
  outcome: Literal["gated"]
559
570
  hub_http_status: Literal[401, 403]
560
571
  token_provided: bool
572
+ access_reason: CustomGatedReason
561
573
  repo: CustomProbeGatedRepo
562
574
 
563
575
 
@@ -624,8 +636,12 @@ def progress(
624
636
  load_step: str | None = None,
625
637
  shard_index: int | None = None,
626
638
  shard_count: int | None = None,
639
+ engine_done: int | None = None,
640
+ engine_total: int | None = None,
627
641
  ) -> None:
628
- """One JSONL progress line; counters are clamped to 0 <= done <= total."""
642
+ """One JSONL progress line; counters are clamped to 0 <= done <= total. ``engine_done`` /
643
+ ``engine_total``: the engine archive bytes inside done/total, sent while a download also
644
+ fetches the inference engine."""
629
645
  total = max(0, int(total))
630
646
  doc: dict[str, object] = {
631
647
  "schema": EVENT_SCHEMA,
@@ -646,6 +662,10 @@ def progress(
646
662
  doc["shard_index"] = shard_index
647
663
  if isinstance(shard_count, int) and not isinstance(shard_count, bool) and shard_count >= 1:
648
664
  doc["shard_count"] = shard_count
665
+ if phase in ("download", "verify") and engine_total is not None and engine_total > 0:
666
+ engine_cap = min(int(engine_total), total)
667
+ doc["engine_total"] = engine_cap
668
+ doc["engine_done"] = min(max(0, int(engine_done or 0)), engine_cap)
649
669
  _line(doc)
650
670
 
651
671
 
@@ -61,7 +61,7 @@ def _mac_suitability_key(
61
61
  -row_doc["context_tokens"],
62
62
  -variant.size_bytes,
63
63
  )
64
- elif entry.quality >= llm_rank.MAC_DEFAULT_YIELD_SCORE:
64
+ elif entry.status == "validated" and entry.quality >= llm_rank.MAC_DEFAULT_YIELD_SCORE:
65
65
  tier = 0
66
66
  rank_tuple = (
67
67
  -entry.quality,
@@ -26,6 +26,7 @@ from localmodels import (
26
26
  engines,
27
27
  frontend,
28
28
  harness,
29
+ harness_probe,
29
30
  hosts,
30
31
  library_convert,
31
32
  library_elastic,
@@ -281,6 +282,14 @@ def _room(
281
282
  ) from None
282
283
 
283
284
 
285
+ def _port_busy(port: int) -> bool:
286
+ """A listener holds ``port``, or bind() refuses it (an outgoing connection's local port where
287
+ the ephemeral range covers the service ports): the server's wrapper could not serve it."""
288
+ # Bind first: connect() to a bound, non-listening port is refused on Linux but answers EAGAIN
289
+ # on macOS, which loopback_listening reports as "cannot confirm".
290
+ return not harness_probe.loopback_bindable(port) or stack_ports.loopback_listening(port)
291
+
292
+
284
293
  def _port(facts: HostFacts) -> int:
285
294
  """Under ``locked()``: a free port that no recorded server and no live load holds; the
286
295
  caller reserves it in its load job before releasing the lock."""
@@ -293,10 +302,8 @@ def _port(facts: HostFacts) -> int:
293
302
  if alive and job.get("port")
294
303
  ]
295
304
  try:
296
- return stack_ports.default_port(
297
- facts, stack_ports.AUTO_PORTS, stack_ports.loopback_listening, reserved=taken
298
- )
299
- except (plan_envelope.PlanError, OSError) as exc:
305
+ return stack_ports.default_port(facts, stack_ports.AUTO_PORTS, _port_busy, reserved=taken)
306
+ except (plan_envelope.PlanError, stack_ports.PortProbeError, OSError) as exc:
300
307
  raise LibraryError("ENGINE_START_FAILED", str(exc)) from None
301
308
 
302
309