@simplexai/localmodels-linux-arm64 0.1.0-dev.58 → 0.1.0-dev.60

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 (113) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +105 -98
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +104 -43
  5. package/modules/localmodels/app.py +1 -1
  6. package/modules/localmodels/apple_sensors.py +431 -0
  7. package/modules/localmodels/bifrost_admin.py +83 -8
  8. package/modules/localmodels/bifrost_checks.py +2 -2
  9. package/modules/localmodels/bifrost_config.py +235 -13
  10. package/modules/localmodels/bifrost_log.py +166 -0
  11. package/modules/localmodels/bifrost_models.py +1 -1
  12. package/modules/localmodels/budget.py +1 -1
  13. package/modules/localmodels/catalog.json +192 -77
  14. package/modules/localmodels/catalog.py +20 -3
  15. package/modules/localmodels/catalog_add.py +42 -11
  16. package/modules/localmodels/custom_hub.py +983 -0
  17. package/modules/localmodels/custom_hub_http.py +579 -0
  18. package/modules/localmodels/custom_probe.py +451 -0
  19. package/modules/localmodels/deploy.py +27 -5
  20. package/modules/localmodels/deploy_steps.py +5 -0
  21. package/modules/localmodels/download-mirrors.json +8 -0
  22. package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
  23. package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
  24. package/modules/localmodels/engines.py +38 -8
  25. package/modules/localmodels/estimator.py +60 -7
  26. package/modules/localmodels/frontend.py +26 -21
  27. package/modules/localmodels/gateway.py +48 -3
  28. package/modules/localmodels/gateway_app_bifrost.py +4 -4
  29. package/modules/localmodels/gateway_bifrost.py +128 -21
  30. package/modules/localmodels/gguf.py +6 -0
  31. package/modules/localmodels/host_sensors.py +704 -0
  32. package/modules/localmodels/hosts.py +99 -12
  33. package/modules/localmodels/library_cli.py +181 -3
  34. package/modules/localmodels/library_convert.py +34 -0
  35. package/modules/localmodels/library_custom.py +831 -0
  36. package/modules/localmodels/library_elastic.py +182 -127
  37. package/modules/localmodels/library_gateway.py +193 -40
  38. package/modules/localmodels/library_jobs.py +92 -18
  39. package/modules/localmodels/library_kept.py +50 -6
  40. package/modules/localmodels/library_model.py +254 -2
  41. package/modules/localmodels/library_pricing.py +97 -8
  42. package/modules/localmodels/library_serve.py +196 -66
  43. package/modules/localmodels/library_smoke.py +315 -0
  44. package/modules/localmodels/library_state.py +81 -2
  45. package/modules/localmodels/library_status.py +144 -8
  46. package/modules/localmodels/metal.py +1 -1
  47. package/modules/localmodels/metal_probe.py +4 -4
  48. package/modules/localmodels/nvml_ctypes.py +431 -0
  49. package/modules/localmodels/plan_envelope.py +18 -7
  50. package/modules/localmodels/process_identity_linux.py +39 -0
  51. package/modules/localmodels/records.py +1 -0
  52. package/modules/localmodels/remote_ops.py +57 -8
  53. package/modules/localmodels/remote_ops_download.py +205 -53
  54. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  55. package/modules/localmodels/remote_ops_ranges.py +2 -5
  56. package/modules/localmodels/remote_ops_service.py +95 -37
  57. package/modules/localmodels/remote_ops_verify.py +22 -5
  58. package/modules/localmodels/runtime-lock.json +19 -19
  59. package/modules/localmodels/runtime_auth.py +4 -1
  60. package/modules/localmodels/service_control.py +32 -1
  61. package/modules/localmodels/service_wiring.py +237 -12
  62. package/modules/localmodels/service_worker.py +6 -2
  63. package/modules/localmodels/services_cli.py +35 -27
  64. package/modules/localmodels/setup_inspection.py +47 -70
  65. package/modules/localmodels/setup_inspection_harness.py +159 -15
  66. package/modules/localmodels/setup_text.py +14 -0
  67. package/modules/localmodels/setup_upgrade.py +1 -1
  68. package/modules/localmodels/source_byok.py +9 -7
  69. package/modules/localmodels/source_byok_probe.py +6 -1
  70. package/modules/localmodels/stack.py +9 -1
  71. package/modules/localmodels/stack_binding.py +3 -35
  72. package/modules/localmodels/stack_cleanup.py +4 -0
  73. package/modules/localmodels/stack_compose.py +18 -2
  74. package/modules/localmodels/stack_lifecycle.py +26 -3
  75. package/modules/localmodels/stack_memory.py +1 -0
  76. package/modules/localmodels/stack_plan.py +6 -2
  77. package/modules/localmodels/stack_ports.py +2 -0
  78. package/modules/localmodels/stack_remove.py +10 -1
  79. package/modules/localmodels/stack_up.py +33 -7
  80. package/modules/localmodels/stack_update.py +3 -1
  81. package/modules/localmodels/stack_view.py +77 -53
  82. package/modules/localmodels/stack_view_demo.py +36 -5
  83. package/modules/localmodels/stack_view_events.py +147 -12
  84. package/modules/localmodels/stack_view_gpu.py +97 -17
  85. package/modules/localmodels/stack_view_llm.py +15 -0
  86. package/modules/localmodels/stack_view_measure.py +4 -1
  87. package/modules/localmodels/stack_view_schema.py +54 -8
  88. package/modules/localmodels/stack_view_serve.py +40 -3
  89. package/modules/localmodels/stack_view_slots.py +89 -10
  90. package/modules/localmodels/stack_view_telemetry.py +163 -0
  91. package/modules/localmodels/stack_view_text.py +5 -2
  92. package/modules/localmodels/stack_view_tick.py +658 -0
  93. package/modules/localmodels/stack_view_words.py +4 -0
  94. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
  95. package/modules/localmodels/suite.py +45 -27
  96. package/modules/localmodels/telemetry_math.py +538 -0
  97. package/modules/localmodels/transport.py +13 -2
  98. package/modules/localmodels/web/view/view.js +1 -1
  99. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/METADATA +1 -1
  100. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/RECORD +102 -95
  101. package/package.json +1 -1
  102. package/tool.json +1 -1
  103. package/modules/localmodels/bifrost_datasheet.py +0 -53
  104. package/modules/localmodels/bifrost_provider.py +0 -88
  105. package/modules/localmodels/bifrost_unit.py +0 -99
  106. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  107. package/modules/localmodels/gateway_switch.py +0 -51
  108. package/modules/localmodels/library_floor.py +0 -78
  109. package/modules/localmodels/service_stop.py +0 -52
  110. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/WHEEL +0 -0
  111. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/entry_points.txt +0 -0
  112. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/NOTICE +0 -0
  113. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -1,24 +1,34 @@
1
- """Configuration rendering and private config/datasheet storage for the Bifrost gateway."""
1
+ """Configuration, provider and datasheet rendering for the Bifrost gateway."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
5
  import contextlib
6
+ import copy
7
+ import ipaddress
6
8
  import json
7
9
  import os
10
+ import urllib.parse
11
+ from collections.abc import Iterable
8
12
  from pathlib import Path
9
13
  from typing import Any
10
14
 
11
- from localmodels import bifrost_datasheet, bifrost_provider
15
+ from localmodels import harness
12
16
  from localmodels.gateway_requests import AuxEndpoint
13
17
  from localmodels.harness import GatewayPlan, HarnessError
14
18
 
15
19
  ADMIN_USER = "localmodels"
16
20
  LOG_BATCH_INTERVAL = "250ms" # logs_store.writer.batch_interval; Bifrost's default is 5s
17
21
  STORE = ("config.db", "config.db-wal", "config.db-shm") # derived from config.json and datasheets
22
+ DATASHEET = "datasheet.json"
23
+ PARAMETERS = "model-parameters.json"
24
+ FILES = (DATASHEET, PARAMETERS)
18
25
  COMPLEX_RULE = "localmodels-agent-complex"
19
26
  AGENT_RULE = "localmodels-agent"
20
27
  BYOK_PROVIDER = "localmodels-byok"
21
28
  BYOK_RULE = "localmodels-byok-route"
29
+ COMPLEX_RULE_PRIORITY = 0
30
+ AGENT_RULE_PRIORITY = 1
31
+ BYOK_RULE_PRIORITY = 2
22
32
  FAST_PROVIDER = "localmodels-llm-fast"
23
33
  DECISION_TIMEOUT = "10s"
24
34
  AUX_PROVIDERS = {
@@ -26,6 +36,32 @@ AUX_PROVIDERS = {
26
36
  "rerank": "localmodels-rerank",
27
37
  "stt": "localmodels-stt",
28
38
  }
39
+ # Loopback upstreams (llama-server uses cpp-httplib's 5 s keep-alive timeout; auth_proxy fronts
40
+ # local services) sit on 127.0.0.1 where a fresh dial costs microseconds, while Bifrost's
41
+ # fasthttp pool defaults to a 30 s idle timeout and its StaleConnectionRetryIfErr only matches
42
+ # POSIX "broken pipe" / "connection reset by peer", not Windows Winsock WSAECONNABORTED (10053)
43
+ # or WSAECONNRESET (10054). Closing loopback connections after each response, capping idle
44
+ # keep-alive below 5 s, and allowing 2 fast retries on pre-response transport failures prevents
45
+ # Windows 502 wsasend aborts (evidence/2026-11-19-linger-agentic-batch1/REPORT.md, Issue #3).
46
+ LOOPBACK_KEEP_ALIVE_S = 2
47
+ LOOPBACK_MAX_RETRIES = 2
48
+ LOOPBACK_RETRY_INITIAL_MS = 100
49
+ LOOPBACK_RETRY_MAX_MS = 500
50
+
51
+ # What each provider may be asked: everything else Bifrost refuses before it reaches the
52
+ # service. The LLM speaks chat only, so Bifrost turns Responses (Codex) and Anthropic Messages
53
+ # (Claude Code) requests into chat completions instead of calling /v1/responses upstream.
54
+ _ALLOWED = {
55
+ "llm": {"list_models": True, "chat_completion": True, "chat_completion_stream": True},
56
+ "decision": {"list_models": True, "decisions": True},
57
+ "embedding": {"list_models": True, "embedding": True},
58
+ # Bifrost's openai-type rerank sends documents as {"text": ...} objects, which llama-server
59
+ # refuses; its cohere type sends the plain strings llama-server reads.
60
+ "rerank": {"rerank": True},
61
+ "stt": {"list_models": True, "transcription": True, "transcription_stream": True},
62
+ }
63
+ _BASE_TYPE = {"decision": "typesafe", "rerank": "cohere"}
64
+
29
65
  # The analyzer requires keyword lists even when the decision model classifies; they only decide
30
66
  # when it does not answer, so a few plain words suffice.
31
67
  _KEYWORDS = {
@@ -34,6 +70,93 @@ _KEYWORDS = {
34
70
  "complex_keywords": ["refactor", "debug", "design", "architecture"],
35
71
  }
36
72
  _AGENT_MATCH = "model == 'localmodels-agent'"
73
+ _MANAGED_RULES = frozenset({COMPLEX_RULE, AGENT_RULE, BYOK_RULE})
74
+
75
+
76
+ def _is_loopback(url: str) -> bool:
77
+ host = (urllib.parse.urlsplit(url).hostname or "").strip().lower()
78
+ if host == "localhost":
79
+ return True
80
+ try:
81
+ return ipaddress.ip_address(host).is_loopback
82
+ except ValueError:
83
+ return False
84
+
85
+
86
+ def origin(url: str) -> str:
87
+ """Bifrost appends the API path (/v1/...) to a provider's base URL itself."""
88
+ url = url.rstrip("/")
89
+ return url[: -len("/v1")] if url.endswith("/v1") else url
90
+
91
+
92
+ def render_provider(role: str, url: str, model: str, key: str, pid: str) -> dict[str, Any]:
93
+ """Render one Bifrost provider entry shared by stack and standalone app gateways."""
94
+ custom: dict[str, Any] = {
95
+ "base_provider_type": _BASE_TYPE.get(role, "openai"),
96
+ "allowed_requests": _ALLOWED[role],
97
+ }
98
+ if role == "rerank":
99
+ custom["request_path_overrides"] = {"rerank": "/v1/rerank"}
100
+ entry: dict[str, Any] = {"id": pid, "name": pid, "value": key, "models": [model], "weight": 1}
101
+ if role == "llm":
102
+ # Bifrost v2.3.0 lists (/v1/models as <pid>/<name>, /anthropic/v1/models bare) and routes
103
+ # a name only when the key has it in both ``models`` and ``aliases``; either alone does not.
104
+ entry["models"] = [model, harness.GROUP]
105
+ entry["aliases"] = {harness.GROUP: model}
106
+ network_config: dict[str, Any] = {
107
+ "base_url": origin(url),
108
+ "allow_private_network": True,
109
+ "max_retries": 0,
110
+ "default_request_timeout_in_seconds": 600,
111
+ "stream_idle_timeout_in_seconds": 600,
112
+ }
113
+ if _is_loopback(url):
114
+ network_config.update(
115
+ {
116
+ "max_retries": LOOPBACK_MAX_RETRIES,
117
+ "retry_backoff_initial": LOOPBACK_RETRY_INITIAL_MS,
118
+ "retry_backoff_max": LOOPBACK_RETRY_MAX_MS,
119
+ "keep_alive_timeout_in_seconds": LOOPBACK_KEEP_ALIVE_S,
120
+ "extra_headers": {"Connection": "close"},
121
+ }
122
+ )
123
+ return {
124
+ "keys": [entry],
125
+ "network_config": network_config,
126
+ "custom_provider_config": custom,
127
+ }
128
+
129
+
130
+ def file_url(app: Path, name: str, windows: bool = os.name == "nt") -> str:
131
+ """A file URL for a sheet in ``app`` that Bifrost can open. Bifrost reads a file URL's path
132
+ as it stands, so ``file:///C:/x/datasheet.json`` is ``/C:/x/...`` on Windows, which does
133
+ not open, and Bifrost exits at start (dev38 Windows library load). On Windows the URL is
134
+ relative to its working directory, ``app`` (gateway_bifrost._start, the only way Bifrost
135
+ runs there); elsewhere absolute, as a systemd unit's working directory is not ``app``."""
136
+ return f"file:./{name}" if windows else (app / name).as_uri()
137
+
138
+
139
+ def framework(app: Path) -> dict[str, Any]:
140
+ """config.json's ``framework``: the datasheets from ``app``, and no MCP library sync (0 is
141
+ Bifrost's off switch; any other interval fetches it)."""
142
+ return {
143
+ "pricing": {
144
+ "pricing_url": file_url(app, DATASHEET),
145
+ "model_parameters_url": file_url(app, PARAMETERS),
146
+ "mcp_library_sync_interval": 0,
147
+ }
148
+ }
149
+
150
+
151
+ def sheets(provider: str, names: Iterable[str], context: int | None) -> dict[str, Any]:
152
+ """The files ``framework`` names. One pricing row per name the LLM's key lists, keyed as
153
+ Bifrost looks rows up (provider, the name after the first slash, a mode), with the window the
154
+ LLM launches with (``-c``; one request may fill it); a plan without a window has none."""
155
+ row = {"provider": provider, "mode": "chat", "context_length": context}
156
+ return {
157
+ DATASHEET: {f"{provider}/{name}": row for name in names} if context else {},
158
+ PARAMETERS: {},
159
+ }
37
160
 
38
161
 
39
162
  def render(
@@ -51,18 +174,18 @@ def render(
51
174
  this call does not manage (a re-sync keeps the STT provider)."""
52
175
  llm = gw["llm"]
53
176
  providers: dict[str, Any] = dict(keep or {})
54
- providers[gw["llm_provider"]] = bifrost_provider.render(
177
+ providers[gw["llm_provider"]] = render_provider(
55
178
  "llm", llm["url"], llm["model"], llm_key, gw["llm_provider"]
56
179
  )
57
180
  decision = gw["decision"] if decision_key is not None else None
58
181
  if decision is not None and decision_key is not None:
59
- providers[gw["decision_provider"]] = bifrost_provider.render(
182
+ providers[gw["decision_provider"]] = render_provider(
60
183
  "decision", decision["url"], decision["model"], decision_key, gw["decision_provider"]
61
184
  )
62
185
  for ep in aux:
63
186
  pid = AUX_PROVIDERS.get(str(ep.get("contract")))
64
187
  if pid:
65
- providers[pid] = bifrost_provider.render(
188
+ providers[pid] = render_provider(
66
189
  str(ep["contract"]), str(ep["url"]), str(ep["model"]), str(ep["key"]), pid
67
190
  )
68
191
  target = {"provider": gw["llm_provider"], "model": llm["model"], "weight": 1}
@@ -70,7 +193,7 @@ def render(
70
193
  if fast := gw.get("llm_fast"):
71
194
  if decision is None or not fast_key:
72
195
  raise HarnessError("two-LLM routing requires both LLM keys and a ready decision model")
73
- providers[FAST_PROVIDER] = bifrost_provider.render(
196
+ providers[FAST_PROVIDER] = render_provider(
74
197
  "llm", fast["url"], fast["model"], fast_key, FAST_PROVIDER
75
198
  )
76
199
  default_target = {"provider": FAST_PROVIDER, "model": fast["model"], "weight": 1}
@@ -91,7 +214,7 @@ def render(
91
214
  "description": "hard turns, as the decision model classifies them",
92
215
  "cel_expression": f"{_AGENT_MATCH} && complexity_tier == 'COMPLEX'",
93
216
  "targets": [target],
94
- "priority": 0,
217
+ "priority": COMPLEX_RULE_PRIORITY,
95
218
  }
96
219
  )
97
220
  governance["complexity_analyzer_config"] = {
@@ -111,7 +234,7 @@ def render(
111
234
  "description": "local agent turns sent to the local LLM",
112
235
  "cel_expression": _AGENT_MATCH,
113
236
  "targets": [default_target],
114
- "priority": 1,
237
+ "priority": AGENT_RULE_PRIORITY,
115
238
  }
116
239
  )
117
240
  if byok := providers.get(BYOK_PROVIDER):
@@ -119,12 +242,106 @@ def render(
119
242
  models = keys[0].get("models") or []
120
243
  if models:
121
244
  rules.append(byok_rule(str(models[0])))
122
- governance["routing_rules"] = rules
245
+ governance["routing_rules"] = normalize_routing_rules(rules)
123
246
  config = render_config(providers, governance, app)
124
- config["framework"] = bifrost_datasheet.framework(app)
247
+ config["framework"] = framework(app)
125
248
  return config
126
249
 
127
250
 
251
+ def normalize_routing_rules(rules: list[dict[str, Any]]) -> list[dict[str, Any]]:
252
+ """Deduplicate routing rules by id (last wins) and assign unique non-negative global priorities.
253
+
254
+ Bifrost refuses to start or sync governance config if two global-scope rules share a priority.
255
+ """
256
+ dicts = [rule for rule in rules if isinstance(rule, dict)]
257
+ last_index: dict[str, int] = {}
258
+ for idx, rule in enumerate(dicts):
259
+ rid = str(rule.get("id") or "")
260
+ if rid:
261
+ last_index[rid] = idx
262
+ used: set[int] = set()
263
+ normalized: list[dict[str, Any]] = []
264
+ for idx, rule in enumerate(dicts):
265
+ rid = str(rule.get("id") or "")
266
+ if rid and last_index[rid] != idx:
267
+ continue
268
+ entry = dict(rule)
269
+ scope = str(entry.get("scope") or "global").strip().lower() or "global"
270
+ if scope == "global":
271
+ raw_prio = entry.get("priority", 0)
272
+ if isinstance(raw_prio, bool):
273
+ prio = 0
274
+ else:
275
+ try:
276
+ prio = max(0, int(raw_prio))
277
+ except (TypeError, ValueError):
278
+ prio = 0
279
+ while prio in used:
280
+ prio += 1
281
+ used.add(prio)
282
+ entry["priority"] = prio
283
+ normalized.append(entry)
284
+ return normalized
285
+
286
+
287
+ def _rule_targets_present(rule: dict[str, Any], providers: dict[str, Any]) -> bool:
288
+ """Whether every target provider named by a managed routing rule exists in ``providers``."""
289
+ targets = rule.get("targets")
290
+ if not isinstance(targets, list) or not targets:
291
+ return False
292
+ return all(
293
+ isinstance(target, dict)
294
+ and isinstance(target.get("provider"), str)
295
+ and target["provider"] in providers
296
+ for target in targets
297
+ )
298
+
299
+
300
+ def sanitize_governance(config: dict[str, Any]) -> bool:
301
+ """Prune dangling managed routing rules and complexity analyzer, then normalize priorities.
302
+
303
+ Mutates ``config`` in place and returns whether ``config["governance"]`` changed.
304
+ """
305
+ governance = config.get("governance")
306
+ if not isinstance(governance, dict):
307
+ return False
308
+ raw_providers = config.get("providers")
309
+ providers: dict[str, Any] = raw_providers if isinstance(raw_providers, dict) else {}
310
+ before = copy.deepcopy(governance)
311
+
312
+ raw_rules = governance.get("routing_rules")
313
+ if isinstance(raw_rules, list):
314
+ kept_rules: list[dict[str, Any]] = []
315
+ for rule in raw_rules:
316
+ if not isinstance(rule, dict):
317
+ continue
318
+ is_managed = rule.get("id") in _MANAGED_RULES or rule.get("name") in _MANAGED_RULES
319
+ if is_managed and not _rule_targets_present(rule, providers):
320
+ continue
321
+ kept_rules.append(rule)
322
+ governance["routing_rules"] = normalize_routing_rules(kept_rules)
323
+ elif raw_rules is not None:
324
+ governance["routing_rules"] = []
325
+
326
+ rules_after = governance.get("routing_rules")
327
+ has_complex = isinstance(rules_after, list) and any(
328
+ isinstance(r, dict) and (r.get("id") == COMPLEX_RULE or r.get("name") == COMPLEX_RULE)
329
+ for r in rules_after
330
+ )
331
+ if "complexity_analyzer_config" in governance:
332
+ ca = governance["complexity_analyzer_config"]
333
+ decision_cfg = ca.get("decision") if isinstance(ca, dict) else None
334
+ decision_provider = decision_cfg.get("provider") if isinstance(decision_cfg, dict) else None
335
+ if (
336
+ not has_complex
337
+ or not isinstance(decision_provider, str)
338
+ or decision_provider not in providers
339
+ ):
340
+ governance.pop("complexity_analyzer_config", None)
341
+
342
+ return bool(governance != before)
343
+
344
+
128
345
  def byok_rule(model: str) -> dict[str, Any]:
129
346
  """Route the fixed local BYOK model slug to the configured upstream model."""
130
347
  return {
@@ -133,7 +350,7 @@ def byok_rule(model: str) -> dict[str, Any]:
133
350
  "description": "agent turns routed to the BYOK upstream model",
134
351
  "cel_expression": f"model == '{BYOK_PROVIDER}'",
135
352
  "targets": [{"provider": BYOK_PROVIDER, "model": model, "weight": 1}],
136
- "priority": 1,
353
+ "priority": BYOK_RULE_PRIORITY,
137
354
  }
138
355
 
139
356
 
@@ -196,6 +413,12 @@ def _text(value: Any) -> str:
196
413
  return json.dumps(value, ensure_ascii=False, indent=1) + "\n"
197
414
 
198
415
 
416
+ def clear_store(app: Path) -> None:
417
+ """Delete Bifrost's derived SQLite config store so the next start rebuilds it from config.json."""
418
+ for name in STORE:
419
+ (app / name).unlink(missing_ok=True)
420
+
421
+
199
422
  def write_config(
200
423
  app: Path,
201
424
  config: dict[str, Any],
@@ -225,6 +448,5 @@ def write_config(
225
448
  os.replace(tmp, path)
226
449
  changed = True
227
450
  if changed and drop_store:
228
- for name in STORE:
229
- (app / name).unlink(missing_ok=True)
451
+ clear_store(app)
230
452
  return changed
@@ -0,0 +1,166 @@
1
+ """Bounded, redacted reading of Bifrost's startup log for early-exit diagnostics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import contextlib
7
+ import json
8
+ import re
9
+ import urllib.parse
10
+ from pathlib import Path
11
+
12
+ from localmodels import bifrost_config, gateway_keys
13
+
14
+ APP_DIR = "~/.local/share/localmodels/bifrost"
15
+ LOG_TAIL_BYTES = 16 * 1024
16
+ SUMMARY_MAX_CHARS = 240
17
+
18
+ _SECRET_KEY = r"[A-Za-z0-9_-]*(?:api[_-]?key|token|password|secret|authorization)[A-Za-z0-9_-]*"
19
+ _QUOTED_SECRET_RE = re.compile(
20
+ rf'(?i)(["\'])({_SECRET_KEY})\1(\s*[:=]\s*)(["\'])(?:\\.|(?!\4).)*(?:\4|$)'
21
+ )
22
+ _QUOTED_KEY_UNQUOTED_VAL_RE = re.compile(rf'(?i)(["\'])({_SECRET_KEY})\1(\s*[:=]\s*)[^\s"\',}}]+')
23
+ _UNQUOTED_KEY_QUOTED_VAL_RE = re.compile(
24
+ rf'(?i)(?<![A-Za-z0-9_"\'-])({_SECRET_KEY})\s*([:=])\s*(["\'])(?:\\.|(?!\3).)*(?:\3|$)'
25
+ )
26
+ _UNQUOTED_SECRET_RE = re.compile(
27
+ rf'(?i)(?<![A-Za-z0-9_"\'-])({_SECRET_KEY})\s*([:=])\s*(?!\[redacted\])[^\s"\',}}]+'
28
+ )
29
+ _PROVIDER_KEY_RE = re.compile(r"\b(?:sk-|gsk_|hf_|AIza)[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*")
30
+
31
+
32
+ def log_size(app: Path) -> int:
33
+ """Current byte size of ``bifrost.log`` inside ``app``, or 0 when absent."""
34
+ try:
35
+ return (app / "bifrost.log").stat().st_size
36
+ except OSError:
37
+ return 0
38
+
39
+
40
+ def known_secrets(app: Path) -> list[str]:
41
+ """Literal secrets from admin-password and config.json (longest first); never creates files."""
42
+ found: set[str] = set()
43
+ admin_user = bifrost_config.ADMIN_USER
44
+ caller_key = gateway_keys.CALLER_KEY
45
+
46
+ def add_password(raw: object) -> None:
47
+ if not isinstance(raw, str):
48
+ return
49
+ pw = raw.strip()
50
+ if not pw or pw in (caller_key, admin_user):
51
+ return
52
+ found.add(pw)
53
+ found.add(base64.b64encode(f"{admin_user}:{pw}".encode()).decode("ascii"))
54
+
55
+ pw_path = app / "admin-password"
56
+ with contextlib.suppress(OSError):
57
+ if pw_path.is_file():
58
+ add_password(pw_path.read_text(encoding="utf-8"))
59
+ config = bifrost_config.read_config(app)
60
+ gov = config.get("governance")
61
+ if isinstance(gov, dict) and isinstance(gov.get("auth_config"), dict):
62
+ add_password(gov["auth_config"].get("admin_password"))
63
+ providers = config.get("providers")
64
+ if isinstance(providers, dict):
65
+ for entry in providers.values():
66
+ if not isinstance(entry, dict):
67
+ continue
68
+ for key in entry.get("keys") or []:
69
+ val = key.get("value") if isinstance(key, dict) else None
70
+ if (
71
+ isinstance(val, str)
72
+ and len(val) >= 6
73
+ and val not in (caller_key, admin_user)
74
+ and not val.startswith("env.")
75
+ ):
76
+ found.add(val)
77
+ return sorted(found, key=len, reverse=True)
78
+
79
+
80
+ def _scrub_url(match: re.Match[str]) -> str:
81
+ try:
82
+ parsed = urllib.parse.urlsplit(match.group())
83
+ host = parsed.netloc.rsplit("@", 1)[-1]
84
+ return urllib.parse.urlunsplit((parsed.scheme, host, parsed.path, "", ""))
85
+ except ValueError:
86
+ return "[URL]"
87
+
88
+
89
+ def scrub_summary(text: str, app: Path, *, app_label: str = APP_DIR) -> str:
90
+ """Scrub credentials, URL query/userinfo, local paths and control characters from a log line."""
91
+ for secret in known_secrets(app):
92
+ text = text.replace(secret, "[redacted]")
93
+ text = re.sub(r"https?://[^\s\"'<>)]+", _scrub_url, text)
94
+ text = re.sub(r"(?<=[A-Za-z0-9/_~-])\?[^\s\"'<>#)]+", "", text)
95
+ text = re.sub(r"(?i)\b(Bearer|Basic)\s+[A-Za-z0-9+/=._-]+", r"\1 [redacted]", text)
96
+ text = _PROVIDER_KEY_RE.sub("[redacted]", text)
97
+ text = _QUOTED_SECRET_RE.sub(r"\1\2\1\3\4[redacted]\4", text)
98
+ text = _QUOTED_KEY_UNQUOTED_VAL_RE.sub(r"\1\2\1\3[redacted]", text)
99
+ text = _UNQUOTED_KEY_QUOTED_VAL_RE.sub(r"\1\2\3[redacted]\3", text)
100
+ text = _UNQUOTED_SECRET_RE.sub(r"\1\2[redacted]", text)
101
+ replacements: list[tuple[str, str]] = [(str(app), app_label)]
102
+ with contextlib.suppress(OSError):
103
+ replacements.append((str(app.resolve()), app_label))
104
+ home = Path.home()
105
+ replacements.append((str(home), "~"))
106
+ with contextlib.suppress(OSError):
107
+ replacements.append((str(home.resolve()), "~"))
108
+ for needle, repl in replacements:
109
+ if needle and needle not in ("/", "\\"):
110
+ text = text.replace(needle, repl)
111
+ text = "".join(
112
+ ch if ord(ch) >= 32 and ord(ch) != 127 else (" " if ch in "\t\n\r" else "") for ch in text
113
+ )
114
+ cleaned = " ".join(text.split())
115
+ if len(cleaned) > SUMMARY_MAX_CHARS:
116
+ cleaned = cleaned[: SUMMARY_MAX_CHARS - 3].rstrip() + "..."
117
+ return cleaned
118
+
119
+
120
+ def startup_failure_summary(app: Path, offset: int = 0, *, app_label: str = APP_DIR) -> str:
121
+ """Bounded, redacted summary of the last fatal/error line written to bifrost.log since offset."""
122
+ log_path = app / "bifrost.log"
123
+ try:
124
+ size = log_path.stat().st_size
125
+ start = 0 if offset < 0 or offset > size else offset
126
+ if size - start > LOG_TAIL_BYTES:
127
+ start = size - LOG_TAIL_BYTES
128
+ if size <= start:
129
+ return ""
130
+ with log_path.open("rb") as f:
131
+ f.seek(start)
132
+ chunk = f.read(LOG_TAIL_BYTES)
133
+ except OSError:
134
+ return ""
135
+ raw = ""
136
+ for line in reversed(chunk.decode("utf-8", errors="replace").splitlines()):
137
+ stripped = line.strip()
138
+ if not stripped:
139
+ continue
140
+ if stripped.startswith("{"):
141
+ try:
142
+ obj = json.loads(stripped)
143
+ except ValueError:
144
+ obj = None
145
+ if isinstance(obj, dict):
146
+ level = str(obj.get("level") or "").strip().lower()
147
+ if level in ("fatal", "error"):
148
+ msg = str(obj.get("message") or obj.get("msg") or "").strip()
149
+ err = str(obj.get("error") or "").strip()
150
+ if msg and err:
151
+ if err in msg:
152
+ raw = msg
153
+ elif msg in err:
154
+ raw = err
155
+ else:
156
+ raw = f"{msg}: {err}"
157
+ else:
158
+ raw = msg or err
159
+ if raw:
160
+ break
161
+ continue
162
+ lowered = stripped.lower()
163
+ if "fatal" in lowered or "error" in lowered:
164
+ raw = stripped
165
+ break
166
+ return scrub_summary(raw, app, app_label=app_label) if raw else ""
@@ -2,7 +2,7 @@
2
2
 
3
3
  Codex (``model_catalog_json``), pi (``models.json``) and Claude Code (its settings ``env``) each
4
4
  take their model and its window from their own settings, and Bifrost's ``/v1/models`` has ids,
5
- the LLM's window (``context_length``, from the datasheet ``bifrost_datasheet`` makes) and no
5
+ the LLM's window (``context_length``, from the datasheet ``bifrost_config`` makes) and no
6
6
  reasoning levels. This module is the one place that joins the live listing with the
7
7
  plan's LLM facts (display name, window, reasoning efforts), for the stack's own wiring
8
8
  (``bifrost_pi``, ``bifrost_clients``) and for ``stack clients`` (consumers on other machines).
@@ -597,7 +597,7 @@ def admission_budget(
597
597
  reclaimable_inactive_anon_bytes=reclaimable,
598
598
  pressure_level=level,
599
599
  critical_pressure=critical,
600
- allows_soft_overcommit=not critical,
600
+ allows_soft_overcommit=(not critical and level != metal.PRESSURE_WARN),
601
601
  physical_limit_bytes=phys_limit,
602
602
  )
603
603
  unified = unified_pool_bytes(facts)