@simplexai/localmodels-linux-x64 0.1.0-dev.35 → 0.1.0-dev.37

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 (126) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +124 -102
  3. package/kit.py +1 -0
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +9 -3
  6. package/modules/localmodels/bifrost_config.py +188 -0
  7. package/modules/localmodels/budget.py +15 -2
  8. package/modules/localmodels/catalog.json +235 -2
  9. package/modules/localmodels/catalog.py +51 -320
  10. package/modules/localmodels/catalog_add.py +2 -8
  11. package/modules/localmodels/catalog_recipes.py +321 -0
  12. package/modules/localmodels/cli_parser.py +4 -1
  13. package/modules/localmodels/console.py +5 -4
  14. package/modules/localmodels/contracts.py +13 -3
  15. package/modules/localmodels/debug_cli.py +158 -0
  16. package/modules/localmodels/debug_mode.py +727 -0
  17. package/modules/localmodels/debug_stub_server.py +192 -0
  18. package/modules/localmodels/decode_calibration.json +1 -1
  19. package/modules/localmodels/decode_calibration.py +34 -17
  20. package/modules/localmodels/engines-strata-0.1.59.1.json +31 -0
  21. package/modules/localmodels/gateway.py +21 -155
  22. package/modules/localmodels/gateway_accept.py +201 -0
  23. package/modules/localmodels/gateway_bifrost.py +19 -184
  24. package/modules/localmodels/gateway_cli.py +11 -4
  25. package/modules/localmodels/gateway_foundations.py +2 -4
  26. package/modules/localmodels/gateway_probe.py +0 -1
  27. package/modules/localmodels/gateway_server.py +2 -3
  28. package/modules/localmodels/gpu_specs.py +12 -0
  29. package/modules/localmodels/guard.py +2 -7
  30. package/modules/localmodels/harness.py +16 -129
  31. package/modules/localmodels/harness_cleanup.py +135 -0
  32. package/modules/localmodels/harness_gateway.py +16 -14
  33. package/modules/localmodels/harness_probe.py +12 -4
  34. package/modules/localmodels/hosts.py +25 -2
  35. package/modules/localmodels/http_local.py +59 -0
  36. package/modules/localmodels/install.py +23 -8
  37. package/modules/localmodels/library_gateway.py +9 -9
  38. package/modules/localmodels/library_jobs.py +76 -27
  39. package/modules/localmodels/library_serve.py +12 -1
  40. package/modules/localmodels/library_state.py +6 -1
  41. package/modules/localmodels/llm_rank.py +155 -7
  42. package/modules/localmodels/metal_probe.py +11 -7
  43. package/modules/localmodels/probe.py +108 -174
  44. package/modules/localmodels/process_identity.py +109 -154
  45. package/modules/localmodels/process_windows.py +86 -0
  46. package/modules/localmodels/recommend.py +32 -3
  47. package/modules/localmodels/recommend_cli.py +14 -6
  48. package/modules/localmodels/remote_ops.py +65 -0
  49. package/modules/localmodels/remote_ops_download.py +2 -2
  50. package/modules/localmodels/remote_ops_prepare.py +19 -0
  51. package/modules/localmodels/remote_ops_service.py +14 -2
  52. package/modules/localmodels/runtime_args.py +10 -3
  53. package/modules/localmodels/runtime_auth.py +5 -9
  54. package/modules/localmodels/runtime_cli.py +128 -129
  55. package/modules/localmodels/runtime_discovery.py +84 -0
  56. package/modules/localmodels/runtime_install.py +101 -0
  57. package/modules/localmodels/runtime_releases.py +302 -0
  58. package/modules/localmodels/service_stop.py +8 -108
  59. package/modules/localmodels/service_upgrade.py +394 -63
  60. package/modules/localmodels/services_cli.py +24 -14
  61. package/modules/localmodels/setup_inspection.py +97 -9
  62. package/modules/localmodels/setup_text.py +7 -0
  63. package/modules/localmodels/sizecalc.py +0 -1
  64. package/modules/localmodels/stack.py +14 -221
  65. package/modules/localmodels/stack_arena.py +732 -0
  66. package/modules/localmodels/stack_args.py +15 -9
  67. package/modules/localmodels/stack_auto.py +384 -3
  68. package/modules/localmodels/stack_aux_gpu.py +4 -3
  69. package/modules/localmodels/stack_capacity.py +138 -0
  70. package/modules/localmodels/stack_cleanup.py +9 -4
  71. package/modules/localmodels/stack_cli.py +286 -0
  72. package/modules/localmodels/stack_compose.py +76 -32
  73. package/modules/localmodels/stack_console.py +9 -6
  74. package/modules/localmodels/stack_hardware.py +96 -270
  75. package/modules/localmodels/stack_hardware_text.py +263 -0
  76. package/modules/localmodels/stack_journal.py +3 -9
  77. package/modules/localmodels/stack_ledger.py +48 -18
  78. package/modules/localmodels/stack_lifecycle.py +33 -312
  79. package/modules/localmodels/stack_mcp.py +729 -0
  80. package/modules/localmodels/stack_memory.py +0 -2
  81. package/modules/localmodels/stack_picks.py +73 -18
  82. package/modules/localmodels/stack_plan.py +23 -5
  83. package/modules/localmodels/stack_preflight.py +11 -19
  84. package/modules/localmodels/stack_remove.py +373 -0
  85. package/modules/localmodels/stack_route.py +101 -17
  86. package/modules/localmodels/stack_suite.py +16 -10
  87. package/modules/localmodels/stack_summary.py +14 -0
  88. package/modules/localmodels/stack_try.py +238 -24
  89. package/modules/localmodels/stack_try_client.py +53 -15
  90. package/modules/localmodels/stack_try_docs.py +2 -2
  91. package/modules/localmodels/stack_view.py +24 -171
  92. package/modules/localmodels/stack_view_access.py +114 -1
  93. package/modules/localmodels/stack_view_agent.py +3 -13
  94. package/modules/localmodels/stack_view_hub.py +9 -10
  95. package/modules/localmodels/stack_view_llm.py +1 -1
  96. package/modules/localmodels/stack_view_sandbox.py +2 -2
  97. package/modules/localmodels/stack_view_schema.py +183 -0
  98. package/modules/localmodels/stack_view_serve.py +7 -1
  99. package/modules/localmodels/stack_view_service.py +1 -2
  100. package/modules/localmodels/stack_view_text.py +13 -9
  101. package/modules/localmodels/stack_warm.py +3 -0
  102. package/modules/localmodels/stack_warm_store.py +517 -0
  103. package/modules/localmodels/tui.py +28 -4
  104. package/modules/localmodels/tui_dialogs.py +136 -0
  105. package/modules/localmodels/tui_modals.py +279 -0
  106. package/modules/localmodels/tui_screen.py +113 -154
  107. package/modules/localmodels/tui_views.py +134 -203
  108. package/modules/localmodels/web/index.html +510 -101
  109. package/modules/localmodels/web/sizecalc/app.js +363 -10
  110. package/modules/localmodels/web/sizecalc/page.html +27 -3
  111. package/modules/localmodels/web/view/fleet.html +11 -2
  112. package/modules/localmodels/web/view/fleet.js +191 -17
  113. package/modules/localmodels/web/view/i18n.js +3 -2
  114. package/modules/localmodels/web/view/index.html +1 -1
  115. package/modules/localmodels/web/view/nav.js +22 -3
  116. package/modules/localmodels/web/view/view.css +63 -18
  117. package/modules/localmodels/web/view/view.js +169 -32
  118. package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/METADATA +1 -1
  119. package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/RECORD +120 -98
  120. package/package.json +1 -1
  121. package/tool.json +1 -1
  122. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  123. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/WHEEL +0 -0
  124. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/entry_points.txt +0 -0
  125. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/NOTICE +0 -0
  126. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,201 @@
1
+ """Acceptance and Magpie usage-log checks for the stack gateway."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import io
7
+ import subprocess
8
+ import tempfile
9
+ import time
10
+ import urllib.error
11
+ import uuid
12
+ from collections.abc import Callable
13
+ from typing import Any
14
+
15
+ from localmodels import gateway_clients, harness, harness_gateway
16
+ from localmodels.contracts import decode
17
+ from localmodels.gateway_requests import PI_ACCEPT_FLAGS, AuxEndpoint, aux_answer, post, text
18
+ from localmodels.gateway_search import SEARCH, Check, search_checks, search_url
19
+ from localmodels.harness import HarnessPlan, ToolPlan
20
+ from localmodels.remote_ops import DECISION_QUESTION, DECISION_STATE, TOUCH_EXPECT, TOUCH_PROMPT
21
+
22
+ PostFn = Callable[[str, dict[str, object], str, float], dict[str, Any]]
23
+ MagpieFn = Callable[..., subprocess.CompletedProcess[str]]
24
+
25
+
26
+ def check_decision(
27
+ url: str, model: str, key: str, timeout: float = 120, *, post_fn: PostFn = post
28
+ ) -> Check:
29
+ """The same readiness question remote_ops asks a decision model this tool deploys."""
30
+ name = f"decision {url}/systemone"
31
+ try:
32
+ resp = post_fn(
33
+ f"{url}/systemone",
34
+ {
35
+ "model": model,
36
+ "state": DECISION_STATE,
37
+ "questions": {"outage": DECISION_QUESTION},
38
+ },
39
+ key,
40
+ timeout,
41
+ )
42
+ except (urllib.error.URLError, OSError, ValueError) as exc:
43
+ return {"check": name, "ok": False, "detail": f"{type(exc).__name__}: {exc}"}
44
+ answers = resp.get("answers")
45
+ answer = answers.get("outage") if isinstance(answers, dict) else None
46
+ noul = answer.get("noul") if isinstance(answer, dict) else None
47
+ ok = isinstance(noul, int | float) and not isinstance(noul, bool) and 0.5 < noul <= 1
48
+ return {"check": name, "ok": ok, "detail": f"noul={noul}"}
49
+
50
+
51
+ def logged_calls(
52
+ plan: ToolPlan, provider: str, kind: str | None = None, *, magpie: MagpieFn
53
+ ) -> int | None:
54
+ """Successful calls to ``provider`` in Magpie's usage log, only those of ``kind`` if given
55
+ (``routing`` for classifier calls; an embedding or rerank call has none)."""
56
+ out = magpie(plan, "usage", "--csv", "--last", "6h", timeout=60)
57
+ if out.returncode != 0:
58
+ return None
59
+ rows = list(csv.DictReader(io.StringIO(out.stdout)))
60
+ if rows and "kind" not in rows[0]:
61
+ return None
62
+ return len(
63
+ [
64
+ r
65
+ for r in rows
66
+ if r.get("provider") == provider
67
+ and (kind is None or r.get("kind") == kind)
68
+ and r.get("status") == "200"
69
+ ]
70
+ )
71
+
72
+
73
+ def logged_after(
74
+ plan: ToolPlan,
75
+ provider: str,
76
+ kind: str | None,
77
+ before: int | None,
78
+ *,
79
+ calls_fn: Callable[[ToolPlan, str, str | None], int | None],
80
+ ) -> int | None:
81
+ after = before
82
+ for _ in range(10): # the usage log is written just after the reply
83
+ after = calls_fn(plan, provider, kind)
84
+ if before is None or after is None or after > before:
85
+ break
86
+ time.sleep(1)
87
+ return after
88
+
89
+
90
+ def accept(
91
+ plan: HarnessPlan,
92
+ decision_key: str | None,
93
+ aux: list[AuxEndpoint],
94
+ timeout: float = 600,
95
+ *,
96
+ aux_providers: dict[str, str],
97
+ is_bifrost: bool,
98
+ post_fn: PostFn = post,
99
+ magpie: MagpieFn,
100
+ run_tool: Callable[..., subprocess.CompletedProcess[str]],
101
+ tool_path: Callable[[ToolPlan, str], str],
102
+ calls_fn: Callable[[ToolPlan, str, str | None], int | None],
103
+ after_fn: Callable[[ToolPlan, str, str | None, int | None], int | None],
104
+ ) -> list[Check]:
105
+ """Each claim needs a request: provider tests through Magpie, one routed turn through the
106
+ gateway (the decision model must be consulted), one embedding, rerank or transcription request
107
+ per wired auxiliary (Magpie's usage log must gain its row), and one pi prompt with the stack's model.
108
+ A Bifrost plan is accepted by ``bifrost_checks.accept``."""
109
+ if is_bifrost:
110
+ from localmodels import bifrost_checks
111
+
112
+ return bifrost_checks.accept(plan, decision_key, aux, timeout)
113
+ gw = plan["gateway"]
114
+ checks: list[Check] = []
115
+
116
+ def check(name: str, ok: bool, detail: str) -> None:
117
+ checks.append({"check": name, "ok": ok, "detail": detail[-300:]})
118
+
119
+ def provider_test(pid: str, kind: str) -> None:
120
+ out = magpie(plan, "provider", "test", pid, timeout=timeout)
121
+ lines = [ln.strip() for ln in out.stdout.splitlines() if kind in ln]
122
+ check(
123
+ f"magpie provider test {pid}",
124
+ out.returncode == 0 and any("✓" in ln for ln in lines),
125
+ "; ".join(lines) or out.stderr.strip()[-200:],
126
+ )
127
+
128
+ provider_test(gw["llm_provider"], "chat")
129
+ if gw["decision"] is not None and decision_key is not None:
130
+ provider_test(gw["decision_provider"], "decide")
131
+ routed = gw["decision"] is not None and decision_key is not None
132
+ decider = gw["decision_provider"]
133
+ before = calls_fn(plan, decider, "routing") if routed else None
134
+ # Magpie remembers a classified message's intent; a fresh nonce per run reaches the classifier.
135
+ prompt = f"{TOUCH_PROMPT} (check {uuid.uuid4().hex[:8]})"
136
+ try:
137
+ harness_gateway.require_target(plan)
138
+ resp = post_fn(
139
+ f"http://{gw['addr']}/v1/chat/completions",
140
+ {
141
+ "model": f"group/{gw['group']}",
142
+ "messages": [{"role": "user", "content": prompt}],
143
+ "max_tokens": 512,
144
+ "temperature": 0,
145
+ },
146
+ "magpie",
147
+ timeout,
148
+ )
149
+ answer = text(resp)
150
+ check(f"gateway group/{gw['group']}", TOUCH_EXPECT in answer.lower(), answer.strip()[:200])
151
+ except (urllib.error.URLError, OSError, ValueError) as exc:
152
+ check(f"gateway group/{gw['group']}", False, f"{type(exc).__name__}: {exc}")
153
+ if routed:
154
+ after = after_fn(plan, decider, "routing", before)
155
+ check(
156
+ "gateway consulted decision model",
157
+ before is not None and after is not None and after > before,
158
+ f"Magpie routing calls to {decider}: {before} → {after}",
159
+ )
160
+ for ep in aux:
161
+ if ep["contract"] == SEARCH:
162
+ checks += search_checks(plan, search_url(ep), timeout)
163
+ continue
164
+ pid = aux_providers[ep["contract"]]
165
+ name = f"gateway {ep['contract']} {pid}/{ep['model']}"
166
+ before = calls_fn(plan, pid, None)
167
+ try:
168
+ harness_gateway.require_target(plan)
169
+ check(name, *aux_answer(gw["addr"], ep, f"{pid}/{ep['model']}", timeout))
170
+ except (urllib.error.URLError, OSError, ValueError) as exc:
171
+ check(name, False, f"{type(exc).__name__}: {exc}")
172
+ continue
173
+ after = after_fn(plan, pid, None, before)
174
+ check(
175
+ f"Magpie logged {ep['contract']}",
176
+ before is not None and after is not None and after > before,
177
+ f"Magpie calls to {pid}: {before} → {after}",
178
+ )
179
+ pi = tool_path(plan, "pi")
180
+ env = harness.checked_gateway_environment(plan)
181
+ loopback = "127.0.0.1,localhost"
182
+ env["NO_PROXY"] = env["no_proxy"] = ",".join(x for x in (env.get("NO_PROXY"), loopback) if x)
183
+ with tempfile.TemporaryDirectory(prefix="localmodels-pi-") as cwd:
184
+ out = run_tool([pi, *PI_ACCEPT_FLAGS, TOUCH_PROMPT], timeout=timeout, cwd=cwd, env=env)
185
+ check(
186
+ "pi -p via Magpie",
187
+ out.returncode == 0 and TOUCH_EXPECT in out.stdout.lower(),
188
+ (out.stdout.strip() or out.stderr.strip())[-200:],
189
+ )
190
+ checks += [
191
+ decode(result, Check)
192
+ for result in gateway_clients.accept(
193
+ plan,
194
+ TOUCH_PROMPT,
195
+ TOUCH_EXPECT,
196
+ timeout,
197
+ lambda: calls_fn(plan, gw["llm_provider"], None),
198
+ lambda b: after_fn(plan, gw["llm_provider"], None, b),
199
+ )
200
+ ]
201
+ return checks
@@ -3,11 +3,9 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import contextlib
6
- import json
7
6
  import os
8
7
  import secrets
9
8
  import shutil
10
- import signal
11
9
  import subprocess
12
10
  import time
13
11
  import urllib.error
@@ -19,7 +17,6 @@ from typing import Any
19
17
 
20
18
  from localmodels import (
21
19
  bifrost_datasheet,
22
- bifrost_provider,
23
20
  bifrost_search,
24
21
  bifrost_unit,
25
22
  gateway_keys,
@@ -27,15 +24,27 @@ from localmodels import (
27
24
  harness_gateway,
28
25
  harness_probe,
29
26
  hosts,
27
+ http_local,
30
28
  process_identity,
31
29
  remote_ops_service,
32
30
  )
31
+ from localmodels.bifrost_config import ADMIN_USER as ADMIN_USER
32
+ from localmodels.bifrost_config import AGENT_RULE as AGENT_RULE
33
+ from localmodels.bifrost_config import AUX_PROVIDERS as AUX_PROVIDERS
34
+ from localmodels.bifrost_config import COMPLEX_RULE as COMPLEX_RULE
35
+ from localmodels.bifrost_config import DECISION_TIMEOUT as DECISION_TIMEOUT
36
+ from localmodels.bifrost_config import FAST_PROVIDER as FAST_PROVIDER
37
+ from localmodels.bifrost_config import LOG_BATCH_INTERVAL as LOG_BATCH_INTERVAL
38
+ from localmodels.bifrost_config import STORE as STORE
39
+ from localmodels.bifrost_config import read_config as read_config
40
+ from localmodels.bifrost_config import render as render
41
+ from localmodels.bifrost_config import render_config as render_config
42
+ from localmodels.bifrost_config import write_config as write_config
33
43
  from localmodels.bifrost_provider import origin as origin
34
44
  from localmodels.bifrost_unit import unit, unit_file, unit_for
35
45
  from localmodels.gateway_requests import AuxEndpoint
36
46
  from localmodels.gateway_search import Check
37
47
  from localmodels.harness import (
38
- GatewayPlan,
39
48
  HarnessError,
40
49
  HarnessPlan,
41
50
  ToolAction,
@@ -44,6 +53,8 @@ from localmodels.harness import (
44
53
  ToolState,
45
54
  )
46
55
 
56
+ _write_config = write_config
57
+
47
58
  APP_DIR = "~/.local/share/localmodels/bifrost"
48
59
  # The routed model, named like Magpie's routing group: Codex, pi and Claude Code all send it, and
49
60
  # the LLM's key lists it and the routing rules match it. No Claude-specific name: Claude Code reads
@@ -51,31 +62,8 @@ APP_DIR = "~/.local/share/localmodels/bifrost"
51
62
  AGENT_MODEL = harness.GROUP
52
63
  PI_PROVIDER = "localmodels"
53
64
  PI_MODEL = f"{PI_PROVIDER}/{AGENT_MODEL}"
54
- ADMIN_USER = "localmodels"
55
65
  CALLER_KEY = gateway_keys.CALLER_KEY # clients send it; loopback inference checks no key
56
- LOG_BATCH_INTERVAL = "250ms" # logs_store.writer.batch_interval; Bifrost's default is 5s
57
- STORE = ("config.db", "config.db-wal", "config.db-shm") # derived from config.json and datasheets
58
- COMPLEX_RULE = "localmodels-agent-complex"
59
- AGENT_RULE = "localmodels-agent"
60
- FAST_PROVIDER = "localmodels-llm-fast"
61
- DECISION_TIMEOUT = "10s"
62
66
  HEALTH_TIMEOUT_S = 180.0
63
- # The auxiliaries Bifrost serves, by endpoint contract, under the provider ids Magpie used.
64
- AUX_PROVIDERS = {
65
- "embedding": "localmodels-embedding",
66
- "rerank": "localmodels-rerank",
67
- "stt": "localmodels-stt",
68
- }
69
- # The analyzer requires keyword lists even when the decision model classifies; they only decide
70
- # when it does not answer, so a few plain words suffice.
71
- _KEYWORDS = {
72
- "simple_keywords": ["hello", "thanks", "what is"],
73
- "medium_keywords": ["explain", "summarize", "write"],
74
- "complex_keywords": ["refactor", "debug", "design", "architecture"],
75
- }
76
-
77
-
78
- _AGENT_MATCH = f"model == '{AGENT_MODEL}'"
79
67
 
80
68
 
81
69
  def plan_tools(
@@ -192,7 +180,8 @@ def install_binary(tools_dir: Path, action: ToolAction, log: Callable[[str], Non
192
180
 
193
181
 
194
182
  def app_dir() -> Path:
195
- return Path(os.path.expanduser(APP_DIR))
183
+ override = os.environ.get("LOCALMODELS_BIFROST_DIR", "").strip()
184
+ return Path(os.path.expanduser(override or APP_DIR))
196
185
 
197
186
 
198
187
  def _seal(app: Path) -> None:
@@ -217,160 +206,6 @@ def admin_password(app: Path | None = None) -> str:
217
206
  return value
218
207
 
219
208
 
220
- def render(
221
- gw: GatewayPlan,
222
- llm_key: str,
223
- decision_key: str | None,
224
- aux: list[AuxEndpoint],
225
- app: Path,
226
- password: str,
227
- keep: dict[str, Any] | None = None,
228
- *,
229
- fast_key: str | None = None,
230
- ) -> dict[str, Any]:
231
- """The config.json for one approved plan, before ``bifrost_search.inject``. ``keep`` carries
232
- providers of an earlier config this call does not manage (a re-sync keeps the STT provider)."""
233
- llm = gw["llm"]
234
- providers: dict[str, Any] = dict(keep or {})
235
- providers[gw["llm_provider"]] = bifrost_provider.render(
236
- "llm", llm["url"], llm["model"], llm_key, gw["llm_provider"]
237
- )
238
- decision = gw["decision"] if decision_key is not None else None
239
- if decision is not None and decision_key is not None:
240
- providers[gw["decision_provider"]] = bifrost_provider.render(
241
- "decision", decision["url"], decision["model"], decision_key, gw["decision_provider"]
242
- )
243
- for ep in aux:
244
- pid = AUX_PROVIDERS.get(str(ep.get("contract")))
245
- if pid:
246
- providers[pid] = bifrost_provider.render(
247
- str(ep["contract"]), str(ep["url"]), str(ep["model"]), str(ep["key"]), pid
248
- )
249
- target = {"provider": gw["llm_provider"], "model": llm["model"], "weight": 1}
250
- default_target = target
251
- if fast := gw.get("llm_fast"):
252
- if decision is None or not fast_key:
253
- raise HarnessError("two-LLM routing requires both LLM keys and a ready decision model")
254
- providers[FAST_PROVIDER] = bifrost_provider.render(
255
- "llm", fast["url"], fast["model"], fast_key, FAST_PROVIDER
256
- )
257
- default_target = {"provider": FAST_PROVIDER, "model": fast["model"], "weight": 1}
258
- rules: list[dict[str, Any]] = []
259
- governance: dict[str, Any] = {
260
- "auth_config": {
261
- "is_enabled": True,
262
- "admin_username": ADMIN_USER,
263
- "admin_password": password,
264
- "disable_auth_on_inference": True,
265
- },
266
- }
267
- if decision is not None:
268
- rules.append(
269
- {
270
- "id": COMPLEX_RULE,
271
- "name": COMPLEX_RULE,
272
- "description": "hard turns, as the decision model classifies them",
273
- "cel_expression": f"{_AGENT_MATCH} && complexity_tier == 'COMPLEX'",
274
- "targets": [target],
275
- "priority": 0,
276
- }
277
- )
278
- governance["complexity_analyzer_config"] = {
279
- "keywords": _KEYWORDS,
280
- "classifier": "decision",
281
- "decision": {
282
- "provider": gw["decision_provider"],
283
- "model": decision["model"],
284
- "timeout": DECISION_TIMEOUT,
285
- "previous_message_count": 1,
286
- },
287
- }
288
- rules.append(
289
- {
290
- "id": AGENT_RULE,
291
- "name": AGENT_RULE,
292
- "description": "local agent turns sent to the local LLM",
293
- "cel_expression": _AGENT_MATCH,
294
- "targets": [default_target],
295
- "priority": 1,
296
- }
297
- )
298
- governance["routing_rules"] = rules
299
- config = render_config(providers, governance, app)
300
- config["framework"] = bifrost_datasheet.framework(app)
301
- return config
302
-
303
-
304
- def render_config(
305
- providers: dict[str, Any], governance: dict[str, Any], app: Path
306
- ) -> dict[str, Any]:
307
- """Shared private storage, management authentication and content logging policy."""
308
- return {
309
- "$schema": "https://www.getbifrost.ai/schema",
310
- "source_of_truth": "config.json",
311
- "client": {
312
- "enable_logging": True,
313
- "disable_content_logging": True,
314
- "allow_per_request_content_storage_override": False,
315
- "allow_per_request_raw_override": False,
316
- "dump_errors_in_console_logs": False,
317
- "enforce_auth_on_inference": False,
318
- "max_request_body_size_mb": 32,
319
- },
320
- "config_store": {
321
- "enabled": True,
322
- "type": "sqlite",
323
- "config": {"path": str(app / "config.db")},
324
- },
325
- "logs_store": {
326
- "enabled": True,
327
- "type": "sqlite",
328
- "config": {"path": str(app / "logs.db")},
329
- # Bifrost writes its request log in batches, 5 s apart by default; `stack view`
330
- # reads that log to show calls, so a short interval keeps it close to real time.
331
- # Measured on the pinned v2.3.0: a call is in the log 5.0 s after it ends by
332
- # default, 0.2-0.25 s with this (2026-11-03, WHI-511).
333
- "writer": {"batch_interval": LOG_BATCH_INTERVAL},
334
- },
335
- "providers": providers,
336
- "governance": governance,
337
- }
338
-
339
-
340
- def read_config(app: Path) -> dict[str, Any]:
341
- try:
342
- value = json.loads((app / "config.json").read_text(encoding="utf-8"))
343
- except (OSError, ValueError):
344
- return {}
345
- return value if isinstance(value, dict) else {}
346
-
347
-
348
- def _write_config(app: Path, config: dict[str, Any], sheets: dict[str, Any] | None = None) -> bool:
349
- """Write config.json (0600), and the datasheets it names when given, where any differs; the
350
- derived config store goes with them, so providers or windows a new config leaves out cannot
351
- linger in it, and Bifrost loads the datasheets into the empty store before it answers."""
352
- files = (sheets or {}) | {"config.json": config}
353
- changed = False
354
- for name, value in files.items():
355
- text = json.dumps(value, ensure_ascii=False, indent=1) + "\n"
356
- path = app / name
357
- with contextlib.suppress(OSError):
358
- if path.read_text(encoding="utf-8") == text:
359
- continue
360
- app.mkdir(parents=True, exist_ok=True)
361
- app.chmod(0o700)
362
- tmp = path.with_name(f"{name}.tmp")
363
- fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
364
- with os.fdopen(fd, "w", encoding="utf-8") as f:
365
- f.write(text)
366
- os.replace(tmp, path)
367
- changed = True
368
- if changed:
369
- for name in STORE:
370
- (app / name).unlink(missing_ok=True)
371
- return changed
372
-
373
-
374
209
  # ---------------------------------------------------------------------------- running it
375
210
 
376
211
 
@@ -384,7 +219,7 @@ def _addr(plan: ToolPlan) -> str:
384
219
 
385
220
 
386
221
  def opener() -> urllib.request.OpenerDirector:
387
- return urllib.request.build_opener(urllib.request.ProxyHandler({}))
222
+ return http_local.no_proxy_opener()
388
223
 
389
224
 
390
225
  def owned_listener(record: hosts.OwnedBifrost) -> bool:
@@ -552,7 +387,7 @@ def _start(record: hosts.OwnedBifrost, restart: bool) -> None:
552
387
  process_identity.save(app / "bifrost.pid", proc.pid)
553
388
  except (OSError, RuntimeError, subprocess.TimeoutExpired) as exc:
554
389
  with contextlib.suppress(OSError): # not yet reaped, so the group is still ours
555
- os.killpg(proc.pid, signal.SIGKILL)
390
+ process_identity.kill_started(proc.pid) # its group; its tree on Windows
556
391
  proc.wait(timeout=10)
557
392
  raise HarnessError(f"cannot record Bifrost process identity ({exc}); stopped it") from None
558
393
 
@@ -19,7 +19,14 @@ import urllib.request
19
19
  from pathlib import Path
20
20
  from typing import Any
21
21
 
22
- from localmodels import cli_help, gateway_bifrost, harness, runtime_auth, runtime_cli, runtime_io
22
+ from localmodels import (
23
+ cli_help,
24
+ gateway_bifrost,
25
+ harness,
26
+ http_local,
27
+ runtime_cli,
28
+ runtime_io,
29
+ )
23
30
 
24
31
  SCHEMA = "localmodels.gateway-owned/v1"
25
32
 
@@ -191,9 +198,9 @@ def _request(
191
198
  headers={"Authorization": "Bearer " + key},
192
199
  method=method,
193
200
  )
194
- with urllib.request.build_opener(
195
- runtime_auth._NoRedirect(), urllib.request.ProxyHandler({})
196
- ).open(request, timeout=timeout) as response:
201
+ with http_local.no_proxy_opener(allow_redirects=False).open(
202
+ request, timeout=timeout
203
+ ) as response:
197
204
  value: dict[str, Any] = json.load(response)
198
205
  return value
199
206
 
@@ -8,7 +8,7 @@ import urllib.request
8
8
  from pathlib import Path
9
9
  from typing import Any
10
10
 
11
- from localmodels import gateway, harness, runtime_auth, runtime_io
11
+ from localmodels import gateway, harness, http_local, runtime_io
12
12
  from localmodels.service_jobs import selected_roles
13
13
 
14
14
 
@@ -35,9 +35,7 @@ def status(port: int, key: str) -> dict[str, Any]:
35
35
  f"http://127.0.0.1:{port}/v1/model-services",
36
36
  headers={"Authorization": "Bearer " + key},
37
37
  )
38
- with urllib.request.build_opener(
39
- runtime_auth._NoRedirect(), urllib.request.ProxyHandler({})
40
- ).open(request, timeout=2) as response:
38
+ with http_local.no_proxy_opener(allow_redirects=False).open(request, timeout=2) as response:
41
39
  value: dict[str, Any] = json.load(response)
42
40
  return value
43
41
 
@@ -53,7 +53,6 @@ def finding(check: str, level: Level, detail: str, fix: str = "") -> Finding:
53
53
  return {"check": check, "level": level, "detail": detail, "fix": fix}
54
54
 
55
55
 
56
- MARKS = {"pass": "✓", "warn": "!", "fail": "✗"}
57
56
  _LEVELS = {"pass": "ok", "warn": "warn", "fail": "fail"}
58
57
 
59
58
 
@@ -25,6 +25,7 @@ from localmodels import (
25
25
  gateway_cli,
26
26
  gateway_foundations,
27
27
  harness,
28
+ http_local,
28
29
  runtime_auth,
29
30
  runtime_cli,
30
31
  runtime_io,
@@ -229,9 +230,7 @@ def model_ids(port: int) -> list[str]:
229
230
  request = urllib.request.Request(
230
231
  f"http://127.0.0.1:{port}/v1/models", headers={"Authorization": "Bearer magpie"}
231
232
  )
232
- with urllib.request.build_opener(
233
- runtime_auth._NoRedirect(), urllib.request.ProxyHandler({})
234
- ).open(request, timeout=2) as response:
233
+ with http_local.no_proxy_opener(allow_redirects=False).open(request, timeout=2) as response:
235
234
  value = json.load(response)
236
235
  return [
237
236
  row["id"]
@@ -77,6 +77,18 @@ def normalized(name: str) -> str:
77
77
  return " ".join(_DROPPED.sub(" ", name.lower().replace("-", " ")).split())
78
78
 
79
79
 
80
+ def device_class(name: str) -> str:
81
+ """Canonical device model class for calibration and lower-bound joins; empty when unnamed."""
82
+ key = normalized(name)
83
+ if not key:
84
+ return ""
85
+ if re.fullmatch(r"rtx pro 6000 blackwell( max q)?( workstation| server)?( edition)?", key):
86
+ return "rtx pro 6000 blackwell"
87
+ if key in ("rtx 4090", "rtx 4090 d"):
88
+ return "rtx 4090"
89
+ return key
90
+
91
+
80
92
  def bandwidth_gb_s(name: str) -> float | None:
81
93
  """The published memory bandwidth of the card nvidia-smi names ``name``; None: not listed."""
82
94
  key = normalized(name)
@@ -15,7 +15,7 @@ import sys
15
15
  from pathlib import Path
16
16
  from typing import Literal, TypedDict
17
17
 
18
- from localmodels import cli_help, probe
18
+ from localmodels import cli_help, http_local, probe
19
19
  from localmodels.catalog import ComponentRecipe, component_recipe
20
20
  from localmodels.contracts import decode
21
21
  from localmodels.privacy import PrivacyError, PrivacySession, Span, parse_spans, strict_json
@@ -46,12 +46,7 @@ class ArtifactPlan(TypedDict):
46
46
  plan_id: str
47
47
 
48
48
 
49
- def _sha(path: Path) -> str:
50
- digest = hashlib.sha256()
51
- with path.open("rb") as stream:
52
- for chunk in iter(lambda: stream.read(1 << 20), b""):
53
- digest.update(chunk)
54
- return digest.hexdigest()
49
+ _sha = http_local.sha256_file
55
50
 
56
51
 
57
52
  def _digest(plan: ArtifactPlan) -> str: