@simplexai/localmodels-linux-x64 0.1.0-dev.55 → 0.1.0-dev.57

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 (62) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +61 -55
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/bifrost_admin.py +337 -0
  5. package/modules/localmodels/bifrost_checks.py +23 -10
  6. package/modules/localmodels/bifrost_config.py +13 -5
  7. package/modules/localmodels/bifrost_models.py +2 -1
  8. package/modules/localmodels/catalog.json +12 -9
  9. package/modules/localmodels/engines.py +24 -1
  10. package/modules/localmodels/gateway_accept.py +4 -3
  11. package/modules/localmodels/gateway_bifrost.py +2 -1
  12. package/modules/localmodels/gateway_cli.py +4 -3
  13. package/modules/localmodels/gateway_server.py +3 -1
  14. package/modules/localmodels/harness.py +2 -2
  15. package/modules/localmodels/hf_repo.py +27 -4
  16. package/modules/localmodels/library_floor.py +3 -1
  17. package/modules/localmodels/library_gateway.py +26 -4
  18. package/modules/localmodels/library_jobs.py +44 -6
  19. package/modules/localmodels/library_kept.py +117 -0
  20. package/modules/localmodels/library_model.py +1 -0
  21. package/modules/localmodels/library_order.py +234 -0
  22. package/modules/localmodels/library_poly.py +20 -16
  23. package/modules/localmodels/library_pricing.py +8 -1
  24. package/modules/localmodels/library_serve.py +9 -3
  25. package/modules/localmodels/library_state.py +12 -2
  26. package/modules/localmodels/library_status.py +2 -0
  27. package/modules/localmodels/llm_rank.py +11 -8
  28. package/modules/localmodels/mirrors.py +464 -0
  29. package/modules/localmodels/recommend.py +2 -2
  30. package/modules/localmodels/records.py +1 -0
  31. package/modules/localmodels/region.py +457 -42
  32. package/modules/localmodels/remote_ops.py +130 -33
  33. package/modules/localmodels/remote_ops_download.py +233 -418
  34. package/modules/localmodels/remote_ops_mirrors.py +290 -0
  35. package/modules/localmodels/remote_ops_ranges.py +447 -0
  36. package/modules/localmodels/runtime-lock.json +19 -19
  37. package/modules/localmodels/runtime_auth.py +2 -1
  38. package/modules/localmodels/runtime_cli.py +1 -1
  39. package/modules/localmodels/runtime_install.py +5 -2
  40. package/modules/localmodels/runtime_io.py +5 -6
  41. package/modules/localmodels/runtime_pi.py +2 -1
  42. package/modules/localmodels/runtime_windows_acl.py +39 -0
  43. package/modules/localmodels/setup_inspection.py +4 -0
  44. package/modules/localmodels/source_byok_probe.py +2 -1
  45. package/modules/localmodels/stack.py +13 -3
  46. package/modules/localmodels/stack_auto.py +38 -5
  47. package/modules/localmodels/stack_cli.py +1 -0
  48. package/modules/localmodels/stack_compose.py +2 -1
  49. package/modules/localmodels/stack_events.py +15 -0
  50. package/modules/localmodels/stack_plan.py +5 -1
  51. package/modules/localmodels/stack_progress.py +30 -5
  52. package/modules/localmodels/stack_run.py +117 -0
  53. package/modules/localmodels/stack_try.py +4 -1
  54. package/modules/localmodels/transport.py +2 -0
  55. package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/METADATA +1 -1
  56. package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/RECORD +58 -52
  57. package/package.json +1 -1
  58. package/tool.json +1 -1
  59. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/WHEEL +0 -0
  60. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/entry_points.txt +0 -0
  61. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/licenses/NOTICE +0 -0
  62. /package/modules/{simplex_localmodels-0.1.0.dev55.dist-info → simplex_localmodels-0.1.0.dev57.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -6,6 +6,7 @@ from __future__ import annotations
6
6
 
7
7
  import base64
8
8
  import contextlib
9
+ import http.client
9
10
  import json
10
11
  import os
11
12
  import tempfile
@@ -67,7 +68,7 @@ def logged_calls(addr: str, provider: str, objects: str | None = None) -> int |
67
68
  query["objects"] = objects
68
69
  try:
69
70
  found = _admin_get(addr, "/api/logs?" + urllib.parse.urlencode(query))
70
- except (urllib.error.URLError, OSError, ValueError):
71
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError):
71
72
  return None
72
73
  page = found.get("pagination")
73
74
  total = page.get("total_count") if isinstance(page, dict) else None
@@ -84,13 +85,25 @@ def logged_after(addr: str, provider: str, before: int | None) -> int | None:
84
85
  return after
85
86
 
86
87
 
88
+ def _rule_name(row: dict[str, Any]) -> Any:
89
+ rule_id = row.get("routing_rule_id")
90
+ if rule_id in (COMPLEX_RULE, AGENT_RULE):
91
+ return rule_id
92
+ rule_name = row.get("routing_rule_name")
93
+ if rule_name in (COMPLEX_RULE, AGENT_RULE):
94
+ return rule_name
95
+ return rule_id or rule_name
96
+
97
+
87
98
  def _routed_log(addr: str, provider: str | None, since: str) -> dict[str, Any] | None:
88
99
  for _ in range(10):
89
- with contextlib.suppress(urllib.error.URLError, OSError, ValueError):
100
+ with contextlib.suppress(
101
+ urllib.error.URLError, OSError, http.client.HTTPException, ValueError
102
+ ):
90
103
  for row in logs(
91
104
  addr, objects="chat_completion", **({"providers": provider} if provider else {})
92
105
  ):
93
- if str(row.get("timestamp", "")) >= since and row.get("routing_rule_id") in (
106
+ if str(row.get("timestamp", "")) >= since and _rule_name(row) in (
94
107
  COMPLEX_RULE,
95
108
  AGENT_RULE,
96
109
  ):
@@ -147,7 +160,7 @@ def tier_routes(gw: harness.GatewayPlan, timeout: float) -> list[Check]:
147
160
  and row.get("status") == "success"
148
161
  and row.get("complexity_mechanism") == "decision"
149
162
  and targets.get(str(row.get("complexity_tier")))
150
- == (row.get("provider"), row.get("model"), row.get("routing_rule_id"))
163
+ == (row.get("provider"), row.get("model"), _rule_name(row))
151
164
  ),
152
165
  None,
153
166
  )
@@ -166,7 +179,7 @@ def tier_routes(gw: harness.GatewayPlan, timeout: float) -> list[Check]:
166
179
  ),
167
180
  }
168
181
  )
169
- except (urllib.error.URLError, OSError, ValueError) as exc:
182
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
170
183
  checks.append(
171
184
  {
172
185
  "check": f"gateway {label} tier target",
@@ -202,7 +215,7 @@ def direct_targets(gw: harness.GatewayPlan, timeout: float) -> list[Check]:
202
215
  )
203
216
  ok = TOUCH_EXPECT in gateway_requests.text(answer).lower()
204
217
  detail = f"{endpoint['model']} {'answered' if ok else 'failed its readiness question'}"
205
- except (OSError, ValueError) as exc:
218
+ except (OSError, http.client.HTTPException, ValueError) as exc:
206
219
  ok, detail = False, f"{type(exc).__name__}: direct LLM readiness unavailable"
207
220
  checks.append({"check": f"LLM {role} readiness", "ok": ok, "detail": detail})
208
221
  return checks
@@ -241,7 +254,7 @@ def accept(
241
254
  with opener().open(f"http://{addr}/v1/models", timeout=60) as r:
242
255
  listed = json.loads(r.read() or b"{}").get("data") or []
243
256
  rows = {str(m.get("id")): m for m in listed if isinstance(m, dict)}
244
- except (urllib.error.URLError, OSError, ValueError) as exc:
257
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
245
258
  rows = {}
246
259
  check("bifrost /v1/models", False, f"{type(exc).__name__}: {exc}")
247
260
  ids = set(rows)
@@ -284,7 +297,7 @@ def accept(
284
297
  )
285
298
  answer = gateway_requests.text(resp)
286
299
  check(f"gateway {AGENT_MODEL}", TOUCH_EXPECT in answer.lower(), answer.strip()[:200])
287
- except (urllib.error.URLError, OSError, ValueError) as exc:
300
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
288
301
  check(f"gateway {AGENT_MODEL}", False, f"{type(exc).__name__}: {exc}")
289
302
  row = _routed_log(addr, None if gw.get("llm_fast") else gw["llm_provider"], since)
290
303
  check(
@@ -312,7 +325,7 @@ def accept(
312
325
  name,
313
326
  *gateway_requests.aux_answer(addr, ep, f"{pid}/{ep['model']}", timeout),
314
327
  )
315
- except (urllib.error.URLError, OSError, ValueError) as exc:
328
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
316
329
  check(name, False, f"{type(exc).__name__}: {exc}")
317
330
  continue
318
331
  after = logged_after(addr, pid, before)
@@ -491,7 +504,7 @@ def usage(doc: hosts.Owned) -> Finding | None:
491
504
  record["addr"],
492
505
  "/api/logs?" + urllib.parse.urlencode({"start_time": start, "limit": "1"}),
493
506
  )
494
- except (urllib.error.URLError, OSError, ValueError):
507
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError):
495
508
  return finding("gateway.usage", "warn", "cannot read the Bifrost request log")
496
509
  page = found.get("pagination")
497
510
  total = page.get("total_count", 0) if isinstance(page, dict) else 0
@@ -196,10 +196,18 @@ def _text(value: Any) -> str:
196
196
  return json.dumps(value, ensure_ascii=False, indent=1) + "\n"
197
197
 
198
198
 
199
- def write_config(app: Path, config: dict[str, Any], sheets: dict[str, Any] | None = None) -> bool:
200
- """Write config.json (0600), and the datasheets it names when given, where any differs; the
201
- derived config store goes with them, so providers or windows a new config leaves out cannot
202
- linger in it, and Bifrost loads the datasheets into the empty store before it answers."""
199
+ def write_config(
200
+ app: Path,
201
+ config: dict[str, Any],
202
+ sheets: dict[str, Any] | None = None,
203
+ *,
204
+ drop_store: bool = True,
205
+ ) -> bool:
206
+ """Write config.json (0600), and the datasheets it names when given, where any differs.
207
+ When ``drop_store`` is True (cold-restart path), the derived config store goes with them so
208
+ providers or windows a new config leaves out cannot linger in it and Bifrost loads the
209
+ datasheets into the empty store before it answers. Live Admin API hot-reloads pass
210
+ ``drop_store=False`` so the running instance keeps its open SQLite store."""
203
211
  files = (sheets or {}) | {"config.json": config}
204
212
  changed = False
205
213
  for name, value in files.items():
@@ -216,7 +224,7 @@ def write_config(app: Path, config: dict[str, Any], sheets: dict[str, Any] | Non
216
224
  f.write(text)
217
225
  os.replace(tmp, path)
218
226
  changed = True
219
- if changed:
227
+ if changed and drop_store:
220
228
  for name in STORE:
221
229
  (app / name).unlink(missing_ok=True)
222
230
  return changed
@@ -11,6 +11,7 @@ A name the listing lacks is an error: the gateway does not serve it.
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
+ import http.client
14
15
  import json
15
16
  import urllib.error
16
17
  from typing import Any, Literal, TypedDict
@@ -117,7 +118,7 @@ def listed(addr: str, timeout: float = 20) -> list[str]:
117
118
  try:
118
119
  with opener().open(f"http://{addr}/v1/models", timeout=timeout) as r:
119
120
  value = json.loads(r.read() or b"{}")
120
- except (urllib.error.URLError, OSError, ValueError) as exc:
121
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
121
122
  raise HarnessError(
122
123
  f"Bifrost at {addr} does not list its models ({type(exc).__name__}); is it running?"
123
124
  " `stack status` shows it, `stack up` starts it"
@@ -440,13 +440,13 @@
440
440
  "quant": "GSQ-RCO-IQ2_XS",
441
441
  "files": [
442
442
  {
443
- "path": "Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf",
443
+ "path": "IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf",
444
444
  "size_bytes": 39225954592,
445
445
  "revision": "ed59f92082b1e93c0e96d60a8b11aab089b52f09",
446
446
  "sha256": "92cee27ae5bbadcd732416a0f7a7f0acc092399dbbe8f5a5efa707c2ec0a49d7"
447
447
  },
448
448
  {
449
- "path": "Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf",
449
+ "path": "IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf",
450
450
  "size_bytes": 28800138432,
451
451
  "revision": "ed59f92082b1e93c0e96d60a8b11aab089b52f09",
452
452
  "sha256": "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"
@@ -466,6 +466,7 @@
466
466
  "architecture": "qwen4exp",
467
467
  "mtp_draft_depth": 3,
468
468
  "mmproj": {
469
+ "repo": "unsloth/Qwen3.8-Flash-Next-GGUF",
469
470
  "path": "mmproj-BF16.gguf",
470
471
  "size_bytes": 907542944,
471
472
  "local": "mmproj-Qwen3.8-Flash-Next-BF16.gguf",
@@ -530,13 +531,13 @@
530
531
  "quant": "GSQ-RCO-IQ3_S",
531
532
  "files": [
532
533
  {
533
- "path": "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf",
534
+ "path": "IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf",
534
535
  "size_bytes": 54817524224,
535
536
  "revision": "ed59f92082b1e93c0e96d60a8b11aab089b52f09",
536
537
  "sha256": "4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"
537
538
  },
538
539
  {
539
- "path": "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf",
540
+ "path": "IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf",
540
541
  "size_bytes": 28800138432,
541
542
  "revision": "ed59f92082b1e93c0e96d60a8b11aab089b52f09",
542
543
  "sha256": "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"
@@ -556,6 +557,7 @@
556
557
  "architecture": "qwen4exp",
557
558
  "mtp_draft_depth": 3,
558
559
  "mmproj": {
560
+ "repo": "unsloth/Qwen3.8-Flash-Next-GGUF",
559
561
  "path": "mmproj-BF16.gguf",
560
562
  "size_bytes": 907542944,
561
563
  "local": "mmproj-Qwen3.8-Flash-Next-BF16.gguf",
@@ -1559,7 +1561,7 @@
1559
1561
  {
1560
1562
  "id": "ornith-1.5-9b",
1561
1563
  "display_name": "Ornith 1.5 9B",
1562
- "description": "Ornith 1.5 9B (2026-08, continued training on the Qwen3.5-9B architecture) at Q4_K_M for 24 GB unified-memory Macs",
1564
+ "description": "Compact 9B model with vision and strong coding and agent capability for 8–16 GB GPUs and Apple Silicon Macs.",
1563
1565
  "repo": "ornith-ai/Ornith-1.5-9B-GGUF",
1564
1566
  "license": "MIT",
1565
1567
  "license_url": "https://huggingface.co/ornith-ai/Ornith-1.5-9B-GGUF/blob/abdd624b12ebf020b767fff532ff44fe552b28c3/README.md",
@@ -1567,6 +1569,7 @@
1567
1569
  "publisher": "Ornith AI",
1568
1570
  "parameters": "9B",
1569
1571
  "status": "candidate",
1572
+ "library": true,
1570
1573
  "tasks": [
1571
1574
  "llm",
1572
1575
  "vision"
@@ -3105,18 +3108,18 @@
3105
3108
  "memory_estimate_bytes": 36507222016,
3106
3109
  "files": [
3107
3110
  {
3108
- "path": "Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf",
3111
+ "path": "IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf",
3109
3112
  "local_name": "Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf",
3110
3113
  "size_bytes": 39225954592,
3111
3114
  "sha256": "92cee27ae5bbadcd732416a0f7a7f0acc092399dbbe8f5a5efa707c2ec0a49d7",
3112
- "url": "{hf}/{repo}/resolve/{revision}/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf"
3115
+ "url": "{hf}/{repo}/resolve/{revision}/IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf"
3113
3116
  },
3114
3117
  {
3115
- "path": "Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf",
3118
+ "path": "IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf",
3116
3119
  "local_name": "Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf",
3117
3120
  "size_bytes": 28800138432,
3118
3121
  "sha256": "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113",
3119
- "url": "{hf}/{repo}/resolve/{revision}/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf"
3122
+ "url": "{hf}/{repo}/resolve/{revision}/IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf"
3120
3123
  },
3121
3124
  {
3122
3125
  "path": "packs/iq2_xs/conversions.json",
@@ -47,6 +47,24 @@ class EngineUnavailableError(PlanError):
47
47
  self.missing_libraries = missing_libraries
48
48
 
49
49
 
50
+ # Minimum NVIDIA display driver branch supporting each CUDA minor version
51
+ # (NVIDIA CUDA Compatibility Table). Unmapped versions return "" rather than
52
+ # guessing a driver branch.
53
+ _MIN_DRIVER_BY_CUDA: dict[tuple[int, int], str] = {
54
+ (12, 4): "550",
55
+ (12, 6): "560",
56
+ (12, 8): "570",
57
+ (12, 9): "575",
58
+ (13, 0): "580",
59
+ (13, 1): "580",
60
+ }
61
+
62
+
63
+ def min_driver_for_cuda(required_cuda: str) -> str:
64
+ """Minimum NVIDIA display driver branch supporting ``required_cuda``, or empty."""
65
+ return _MIN_DRIVER_BY_CUDA.get(_cuda_tuple(required_cuda), "")
66
+
67
+
50
68
  class CudaDriverError(PlanError):
51
69
  """The host's NVIDIA driver supports too old a CUDA version, or none could be detected."""
52
70
 
@@ -57,11 +75,13 @@ class CudaDriverError(PlanError):
57
75
  required_cuda: str,
58
76
  detected_cuda: str = "",
59
77
  driver_version: str = "",
78
+ required_driver: str = "",
60
79
  ) -> None:
61
80
  super().__init__(message)
62
81
  self.required_cuda = required_cuda
63
82
  self.detected_cuda = detected_cuda
64
83
  self.driver_version = driver_version
84
+ self.required_driver = required_driver or min_driver_for_cuda(required_cuda)
65
85
 
66
86
 
67
87
  def _version(text: str | None) -> tuple[int, ...]:
@@ -161,7 +181,9 @@ def select_engine_build(
161
181
  )
162
182
  if not builds:
163
183
  if backend == "cuda" and platform_builds:
164
- oldest = min((b["min_cuda"] for b in platform_builds), key=_cuda_tuple)
184
+ oldest_build = min(platform_builds, key=lambda b: _cuda_tuple(b["min_cuda"]))
185
+ oldest = oldest_build["min_cuda"]
186
+ required_driver = oldest_build.get("min_driver") or min_driver_for_cuda(oldest)
165
187
  driver_version = ((facts.get("nvidia") or {}).get("driver_version") or "").strip()
166
188
  if driver == (0, 0):
167
189
  detail = f" (could not detect the driver's CUDA version; requires CUDA >= {oldest})"
@@ -178,6 +200,7 @@ def select_engine_build(
178
200
  required_cuda=oldest,
179
201
  detected_cuda=detected,
180
202
  driver_version=driver_version,
203
+ required_driver=required_driver,
181
204
  )
182
205
  raise PlanError(
183
206
  f"no {lock['tag']} prebuilt engine for {platform}/{facts.get('arch')}/{backend}"
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import csv
6
+ import http.client
6
7
  import io
7
8
  import subprocess
8
9
  import tempfile
@@ -45,7 +46,7 @@ def check_decision(
45
46
  key,
46
47
  timeout,
47
48
  )
48
- except (urllib.error.URLError, OSError, ValueError) as exc:
49
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
49
50
  return {"check": name, "ok": False, "detail": f"{type(exc).__name__}: {exc}"}
50
51
  answers = resp.get("answers")
51
52
  answer = answers.get("outage") if isinstance(answers, dict) else None
@@ -154,7 +155,7 @@ def accept(
154
155
  )
155
156
  answer = text(resp)
156
157
  check(f"gateway group/{gw['group']}", TOUCH_EXPECT in answer.lower(), answer.strip()[:200])
157
- except (urllib.error.URLError, OSError, ValueError) as exc:
158
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
158
159
  check(f"gateway group/{gw['group']}", False, f"{type(exc).__name__}: {exc}")
159
160
  if routed:
160
161
  after = after_fn(plan, decider, "routing", before)
@@ -170,7 +171,7 @@ def accept(
170
171
  try:
171
172
  harness_gateway.require_target(plan)
172
173
  check(name, *aux_answer(gw["addr"], ep, f"{pid}/{ep['model']}", timeout))
173
- except (urllib.error.URLError, OSError, ValueError) as exc:
174
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
174
175
  check(name, False, f"{type(exc).__name__}: {exc}")
175
176
  continue
176
177
  after = after_fn(plan, pid, None, before)
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import contextlib
6
+ import http.client
6
7
  import os
7
8
  import secrets
8
9
  import shutil
@@ -328,7 +329,7 @@ def healthy(addr: str, timeout: float = 5) -> bool:
328
329
  try:
329
330
  with opener().open(f"http://{addr}/health", timeout=timeout) as r:
330
331
  return bool(r.status == 200)
331
- except (urllib.error.URLError, OSError, ValueError):
332
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError):
332
333
  return False
333
334
 
334
335
 
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import argparse
6
6
  import errno
7
7
  import hashlib
8
+ import http.client
8
9
  import json
9
10
  import os
10
11
  import secrets
@@ -228,7 +229,7 @@ def status(root: Path) -> dict[str, Any]:
228
229
  authenticated=live.get("authenticated") is True,
229
230
  models=live.get("models", []),
230
231
  )
231
- except (OSError, ValueError, urllib.error.URLError):
232
+ except (OSError, ValueError, urllib.error.URLError, http.client.HTTPException):
232
233
  pass
233
234
  return result
234
235
 
@@ -251,14 +252,14 @@ def _stop(root: Path) -> dict[str, Any]:
251
252
  while True:
252
253
  try:
253
254
  live = _request(root, state, "status")
254
- except (OSError, ValueError, urllib.error.URLError):
255
+ except (OSError, ValueError, urllib.error.URLError, http.client.HTTPException):
255
256
  live = None
256
257
  if live is not None:
257
258
  if live.get("instance") != state["instance"]:
258
259
  raise ValueError("Gateway ownership mismatch")
259
260
  try:
260
261
  _request(root, state, "stop", method="POST")
261
- except (OSError, ValueError, urllib.error.URLError):
262
+ except (OSError, ValueError, urllib.error.URLError, http.client.HTTPException):
262
263
  pass # The server may have closed between its status and stop requests.
263
264
  if worker_idle(root):
264
265
  if state.get("kind") == "bifrost":
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import argparse
6
6
  import hmac
7
+ import http.client
7
8
  import http.server
8
9
  import json
9
10
  import os
@@ -293,7 +294,7 @@ def ingress_handler(
293
294
  if self.path == "/_localmodels/status" and self.command == "GET":
294
295
  try:
295
296
  models = model_ids(state["upstreamPort"])
296
- except (OSError, ValueError, urllib.error.URLError):
297
+ except (OSError, ValueError, urllib.error.URLError, http.client.HTTPException):
297
298
  models = []
298
299
  ready = False
299
300
  else:
@@ -327,6 +328,7 @@ def ingress_handler(
327
328
  _, current["authenticated"] = configure(root, state)
328
329
  except (
329
330
  OSError,
331
+ http.client.HTTPException,
330
332
  ValueError,
331
333
  TypeError,
332
334
  AttributeError,
@@ -51,7 +51,7 @@ from localmodels.npm_transport import ToolBuild as ToolBuild
51
51
  from localmodels.npm_transport import fetch_bifrost
52
52
  from localmodels.remote_ops import Archive, fetch
53
53
  from localmodels.remote_ops_download import npm_copies
54
- from localmodels.runtime_io import Event, error_cause
54
+ from localmodels.runtime_io import Event, error_cause, rename_with_retry
55
55
  from localmodels.stack_events import CombinedEvents as _CombinedEvents
56
56
  from localmodels.stack_events import ToolEvents
57
57
  from localmodels.tool_archive import (
@@ -606,7 +606,7 @@ def _install_tree(tools_dir: Path, name: str, unpack: Callable[[Path], None], ma
606
606
  (staging / ".complete").write_text(marker + "\n", encoding="utf-8")
607
607
  if final.exists():
608
608
  shutil.rmtree(final)
609
- staging.rename(final)
609
+ rename_with_retry(staging, final)
610
610
  finally:
611
611
  if staging.exists():
612
612
  shutil.rmtree(staging)
@@ -15,6 +15,7 @@ Because the Hub is queried, ``--offline`` plans refuse repo specs and keep takin
15
15
  from __future__ import annotations
16
16
 
17
17
  import difflib
18
+ import http.client
18
19
  import io
19
20
  import json
20
21
  import re
@@ -193,6 +194,26 @@ def close_ids(name: str, ids: Sequence[str]) -> list[str]:
193
194
  return [i for score, i in scored[:3] if score >= max(0.6, best - 0.1)]
194
195
 
195
196
 
197
+ def _hub_call(repo: str, call: Callable[[], object]) -> object:
198
+ try:
199
+ return call()
200
+ except http.client.HTTPException as exc:
201
+ raise PlanError(
202
+ f"Hub HTTP error reading {repo} ({type(exc).__name__})",
203
+ cause_code="HUB_UNREACHABLE",
204
+ ) from exc
205
+
206
+
207
+ def _hub_header(repo: str, url: str, read_range: FetchBytes) -> GGUFHeader:
208
+ try:
209
+ return _repo_header(url, read_range)
210
+ except http.client.HTTPException as exc:
211
+ raise PlanError(
212
+ f"Hub HTTP error reading {repo} ({type(exc).__name__})",
213
+ cause_code="HUB_UNREACHABLE",
214
+ ) from exc
215
+
216
+
196
217
  def entry_for(
197
218
  spec: str,
198
219
  entries: tuple[cat.CatalogEntry, ...],
@@ -234,7 +255,7 @@ def entry_for(
234
255
  f"/revision/{urllib.parse.quote(revision)}" if revision else ""
235
256
  )
236
257
  try:
237
- doc = decode(hf_get(first), ModelInfo)
258
+ doc = decode(_hub_call(repo, lambda: hf_get(first)), ModelInfo)
238
259
  except urllib.error.HTTPError:
239
260
  raise
240
261
  except OSError as exc:
@@ -244,7 +265,7 @@ def entry_for(
244
265
  commit = doc.get("sha")
245
266
  if not commit:
246
267
  raise PlanError(f"{repo} does not resolve on the Hub")
247
- raw_tree = hf_get(f"{api}/api/models/{repo}/tree/{commit}")
268
+ raw_tree = _hub_call(repo, lambda: hf_get(f"{api}/api/models/{repo}/tree/{commit}"))
248
269
  if not isinstance(raw_tree, list):
249
270
  raise PlanError("Hub tree must be an array")
250
271
  tree = [
@@ -256,8 +277,10 @@ def entry_for(
256
277
  if not groups:
257
278
  raise PlanError(f"{repo} has no .gguf model file")
258
279
  stem, files = _pick(groups, quant, repo)
259
- header = _repo_header(
260
- f"{api}/{repo}/resolve/{commit}/{urllib.parse.quote(files[0]['path'])}", read_range
280
+ header = _hub_header(
281
+ repo,
282
+ f"{api}/{repo}/resolve/{commit}/{urllib.parse.quote(files[0]['path'])}",
283
+ read_range,
261
284
  )
262
285
  card = doc.get("cardData") or {}
263
286
  license_name, license_link = _license(card)
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from localmodels import budget, context_policy, library_pricing, metal, suite, vision
5
+ from localmodels import budget, context_policy, library_kept, library_pricing, metal, suite, vision
6
6
  from localmodels.estimator import agent_footprint_bytes, eager
7
7
  from localmodels.library_pricing import Model
8
8
  from localmodels.probe import HostFacts
@@ -22,6 +22,8 @@ def floor_metadata(
22
22
  unified memory, and avoids mixing host RAM shortfalls (``memory_kind == "ram"``) into VRAM
23
23
  floor bytes.
24
24
  """
25
+ if library_kept.retired(model.entry): # no recipe left to price; only what was on disk
26
+ return shortfall_bytes, 0, False, sum(f.size_bytes for f in model.variant.files)
25
27
  if model.entry.runtime == "strata-poly":
26
28
  recipe = suite.recipe(model.entry.id)
27
29
  window = int(recipe.get("context") or model.entry.n_ctx_train)
@@ -23,6 +23,7 @@ from pathlib import Path
23
23
  from typing import Any
24
24
 
25
25
  from localmodels import (
26
+ bifrost_admin,
26
27
  bifrost_config,
27
28
  bifrost_datasheet,
28
29
  bifrost_models,
@@ -163,12 +164,33 @@ def read_sheet(app: Path) -> dict[str, Any]:
163
164
 
164
165
 
165
166
  def apply_config(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict[str, Any]) -> None:
166
- """Write the config and datasheet; restart the instance when they changed. A gateway left
167
- with no provider at all (no library model, and nothing of the stack such as its LLM,
168
- decision model or foundation services) serves nobody: it is stopped instead, its record
169
- and config kept, and the next load starts it again."""
167
+ """Apply updated config and datasheet to the gateway.
168
+
169
+ When the owned Bifrost is already running and only hot-reloadable state changed (providers,
170
+ routing rules, removing the complexity analyzer, or model context windows), push the delta
171
+ through Bifrost's Admin API and persist ``config.json``/datasheets without dropping
172
+ ``config.db`` or restarting the process — keeping active streams on other models alive.
173
+ Any Admin API error or non-hot-reloadable change falls back to the cold-restart path. A
174
+ gateway left with no provider at all (no library model, and nothing of the stack such as
175
+ its LLM, decision model or foundation services) serves nobody: it is stopped instead, its
176
+ record and config kept, and the next load starts it again."""
170
177
  app = Path(record["app_dir"])
171
178
  params = {bifrost_datasheet.DATASHEET: sheet, bifrost_datasheet.PARAMETERS: {}}
179
+ if config.get("providers") and bifrost_config.differs(app, config, params):
180
+ before = gateway_bifrost.read_config(app)
181
+ before_sheet = read_sheet(app)
182
+ if gateway_bifrost._healthy_owned(record) and bifrost_admin.can_hot_reload(before, config):
183
+ try:
184
+ bifrost_admin.sync_live(
185
+ record,
186
+ before,
187
+ config,
188
+ params,
189
+ sheet_changed=(sheet != before_sheet),
190
+ )
191
+ return
192
+ except bifrost_admin.AdminError:
193
+ pass # fall back to cold restart so config.json and config.db converge cleanly
172
194
  if (
173
195
  STOP_BEFORE_CONFIG_CHANGE
174
196
  and record["how"] != "unit"
@@ -179,8 +179,9 @@ def _download_telemetry(phase: str, event: dict[str, object]) -> tuple[str | Non
179
179
 
180
180
 
181
181
  class _Counter:
182
- """Bytes of the whole model: the files already verified (or partially downloaded on disk)
183
- count as done; each progress event moves its file's counter for the phase it reports."""
182
+ """Bytes of the whole model (plus engine archives whenever the engine step downloads them):
183
+ the files already verified (or partially downloaded on disk) count as done; each progress
184
+ event moves its file's counter for the phase it reports."""
184
185
 
185
186
  def __init__(self, model: str, plan: Plan, handle: JobHandle) -> None:
186
187
  self.model, self.handle = model, handle
@@ -198,20 +199,55 @@ class _Counter:
198
199
  )
199
200
  for f in plan["files"]
200
201
  }
202
+ self.engine_sizes: dict[str, int] = {}
203
+ self.engine_done: dict[str, int] = {}
204
+ self._include_engine = False
205
+ engine_spec = plan.get("engine")
206
+ if isinstance(engine_spec, dict) and engine_spec.get("source") == "release":
207
+ engine_dir = os.path.expanduser(str(engine_spec.get("dir") or ""))
208
+ archive_cache = os.path.join(os.path.dirname(engine_dir), ".archives")
209
+ for asset in engine_spec.get("assets") or ():
210
+ name = str(asset["name"])
211
+ size = int(asset["size_bytes"])
212
+ self.engine_sizes[name] = size
213
+ archive = os.path.join(archive_cache, name)
214
+ if os.path.isfile(archive) and os.path.getsize(archive) == size:
215
+ self.engine_done[name] = size
216
+ else:
217
+ self.engine_done[name] = min(
218
+ size, remote_ops_download.kept_bytes(archive + ".part", size)
219
+ )
201
220
 
202
221
  @property
203
222
  def total(self) -> int:
204
- return sum(self.sizes.values())
223
+ base = sum(self.sizes.values())
224
+ return base + sum(self.engine_sizes.values()) if self._include_engine else base
225
+
226
+ def finish_engine(self) -> None:
227
+ """Mark engine assets complete once the engine step succeeds, keeping progress monotonic."""
228
+ if not self._include_engine:
229
+ return
230
+ for name, size in self.engine_sizes.items():
231
+ self.engine_done[name] = size
205
232
 
206
233
  def __call__(self, event: dict[str, object]) -> None:
207
234
  label = str(event.get("file") or "")
208
- if event.get("event") != "progress" or label not in self.sizes:
235
+ if event.get("event") != "progress":
236
+ return
237
+ if label in self.sizes:
238
+ target_done, target_sizes = self.done, self.sizes
239
+ elif label in self.engine_sizes:
240
+ self._include_engine = True
241
+ target_done, target_sizes = self.engine_done, self.engine_sizes
242
+ else:
209
243
  return
210
244
  phase: Phase = "verify" if event.get("phase") == "verify" else "download"
211
245
  done = event.get("done")
212
246
  speed = event.get("bytes_per_s")
213
- self.done[label] = int(done) if isinstance(done, int) else 0
247
+ target_done[label] = min(target_sizes[label], int(done) if isinstance(done, int) else 0)
214
248
  finished = sum(min(n, self.sizes[k]) for k, n in self.done.items())
249
+ if self._include_engine:
250
+ finished += sum(min(n, self.engine_sizes[k]) for k, n in self.engine_done.items())
215
251
  rate = int(speed) if isinstance(speed, int) and phase == "download" else 0
216
252
  source, connections = _download_telemetry(phase, event)
217
253
  self.handle.update(
@@ -273,13 +309,15 @@ def fetch(
273
309
  steps = ("engine", *steps)
274
310
  mine: Plan = {**plan, "files": _with_reuse(files) if files else files}
275
311
  for step in steps:
276
- on_event = counter if step == "download" else None
312
+ on_event = counter if step in ("engine", "download") else None
277
313
  outcome, result = run.run_action(
278
314
  step, deploy_steps.step_params(mine, step, ""), on_event=on_event or (lambda _e: None)
279
315
  )
280
316
  if result.returncode != 0 or outcome.get("event") != "result":
281
317
  message = str(outcome.get("message") or result.stderr.strip()[-500:] or "failed")
282
318
  raise LibraryError(_code(message), message, failed=True)
319
+ if step == "engine":
320
+ counter.finish_engine()
283
321
  if engine and (reqs := plan["launch"].get("frontend_requirements")):
284
322
  try:
285
323
  frontend.install(str(plan["launch"]["frontend_base_dir"]), str(reqs))