@simplexai/localmodels-win32-x64 0.1.0-dev.59 → 0.1.0-dev.61
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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +126 -107
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +107 -44
- package/modules/localmodels/apple_sensors.py +431 -0
- package/modules/localmodels/auth_proxy.py +185 -19
- package/modules/localmodels/bifrost_admin.py +30 -0
- package/modules/localmodels/bifrost_checks.py +2 -2
- package/modules/localmodels/bifrost_config.py +132 -9
- package/modules/localmodels/bifrost_models.py +1 -1
- package/modules/localmodels/catalog.json +509 -54
- package/modules/localmodels/catalog.py +21 -4
- package/modules/localmodels/catalog_add.py +42 -11
- package/modules/localmodels/catalog_license.py +2 -0
- package/modules/localmodels/catalog_recipes.py +2 -0
- package/modules/localmodels/cli_parser.py +6 -2
- package/modules/localmodels/context_policy.py +40 -4
- package/modules/localmodels/custom_hub.py +983 -0
- package/modules/localmodels/custom_hub_http.py +579 -0
- package/modules/localmodels/custom_probe.py +451 -0
- package/modules/localmodels/debug_mode.py +13 -0
- package/modules/localmodels/debug_stub_server.py +156 -1
- package/modules/localmodels/deploy.py +38 -7
- package/modules/localmodels/deploy_steps.py +5 -0
- package/modules/localmodels/download-mirrors.json +20 -0
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
- package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
- package/modules/localmodels/engines-whisper-b5454.json +120 -1
- package/modules/localmodels/engines.py +38 -8
- package/modules/localmodels/estimator.py +60 -7
- package/modules/localmodels/gateway.py +48 -3
- package/modules/localmodels/gateway_app_bifrost.py +18 -18
- package/modules/localmodels/gateway_bifrost.py +102 -16
- package/modules/localmodels/gateway_cli.py +14 -80
- package/modules/localmodels/gateway_server.py +88 -16
- package/modules/localmodels/gguf.py +6 -0
- package/modules/localmodels/gpu_specs.py +35 -1
- package/modules/localmodels/harness.py +1 -2
- package/modules/localmodels/hf_repo.py +12 -4
- package/modules/localmodels/host_sensors.py +704 -0
- package/modules/localmodels/install.py +4 -4
- package/modules/localmodels/library_cli.py +181 -3
- package/modules/localmodels/library_custom.py +831 -0
- package/modules/localmodels/library_elastic.py +35 -7
- package/modules/localmodels/library_gateway.py +94 -32
- package/modules/localmodels/library_jobs.py +76 -11
- package/modules/localmodels/library_kept.py +50 -6
- package/modules/localmodels/library_model.py +254 -2
- package/modules/localmodels/library_pricing.py +83 -4
- package/modules/localmodels/library_serve.py +178 -60
- package/modules/localmodels/library_smoke.py +315 -0
- package/modules/localmodels/library_state.py +77 -1
- package/modules/localmodels/library_status.py +126 -4
- package/modules/localmodels/npm_transport.py +4 -58
- package/modules/localmodels/nvml_ctypes.py +431 -0
- package/modules/localmodels/plan_envelope.py +14 -6
- package/modules/localmodels/recommend_cli.py +2 -1
- package/modules/localmodels/records.py +1 -0
- package/modules/localmodels/remote_ops.py +120 -665
- package/modules/localmodels/remote_ops_common.py +729 -0
- package/modules/localmodels/remote_ops_download.py +396 -241
- package/modules/localmodels/remote_ops_mirrors.py +26 -65
- package/modules/localmodels/remote_ops_prepare.py +43 -35
- package/modules/localmodels/remote_ops_ranges.py +98 -65
- package/modules/localmodels/remote_ops_remove.py +30 -22
- package/modules/localmodels/remote_ops_service.py +103 -95
- package/modules/localmodels/remote_ops_verify.py +113 -65
- package/modules/localmodels/runtime-lock.json +19 -19
- package/modules/localmodels/runtime_cli.py +15 -5
- package/modules/localmodels/runtime_io.py +54 -1
- package/modules/localmodels/service_control.py +32 -1
- package/modules/localmodels/service_wiring.py +2 -3
- package/modules/localmodels/service_worker.py +6 -2
- package/modules/localmodels/services_cli.py +35 -27
- package/modules/localmodels/source_byok.py +3 -5
- package/modules/localmodels/speech-sv.txt +93 -0
- package/modules/localmodels/speech_admission.py +437 -0
- package/modules/localmodels/speech_catalog.py +170 -0
- package/modules/localmodels/speech_cli.py +273 -0
- package/modules/localmodels/speech_jobs.py +772 -0
- package/modules/localmodels/speech_model.py +404 -0
- package/modules/localmodels/speech_serve.py +287 -0
- package/modules/localmodels/speech_server.py +837 -0
- package/modules/localmodels/speech_state.py +697 -0
- package/modules/localmodels/speech_worker_sensevoice.py +255 -0
- package/modules/localmodels/speech_workers.py +783 -0
- package/modules/localmodels/stack.py +0 -33
- package/modules/localmodels/stack_auto.py +5 -3
- package/modules/localmodels/stack_aux_gpu.py +45 -4
- package/modules/localmodels/stack_capacity.py +77 -8
- package/modules/localmodels/stack_cli.py +16 -1
- package/modules/localmodels/stack_compose.py +1 -1
- package/modules/localmodels/stack_down.py +24 -1
- package/modules/localmodels/stack_hardware.py +57 -88
- package/modules/localmodels/stack_hardware_text.py +4 -59
- package/modules/localmodels/stack_lifecycle.py +2 -2
- package/modules/localmodels/stack_memory.py +14 -3
- package/modules/localmodels/stack_suite.py +9 -10
- package/modules/localmodels/stack_summary.py +4 -4
- package/modules/localmodels/stack_view.py +77 -53
- package/modules/localmodels/stack_view_demo.py +36 -5
- package/modules/localmodels/stack_view_events.py +147 -12
- package/modules/localmodels/stack_view_gpu.py +97 -17
- package/modules/localmodels/stack_view_llm.py +16 -1
- package/modules/localmodels/stack_view_measure.py +4 -1
- package/modules/localmodels/stack_view_schema.py +54 -8
- package/modules/localmodels/stack_view_serve.py +40 -3
- package/modules/localmodels/stack_view_slots.py +89 -10
- package/modules/localmodels/stack_view_telemetry.py +163 -0
- package/modules/localmodels/stack_view_text.py +5 -2
- package/modules/localmodels/stack_view_tick.py +658 -0
- package/modules/localmodels/stack_view_words.py +4 -0
- package/modules/localmodels/{strata-poly-serve-0.2.20-poly.5.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
- package/modules/localmodels/suite.py +3 -1
- package/modules/localmodels/telemetry_math.py +538 -0
- package/modules/localmodels/transport.py +3 -2
- package/modules/localmodels/tui_views.py +2 -2
- package/modules/localmodels/web/view/view.js +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +123 -104
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/NOTICE +9 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/bifrost_datasheet.py +0 -53
- package/modules/localmodels/bifrost_provider.py +0 -88
- package/modules/localmodels/bifrost_unit.py +0 -99
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +0 -94
- package/modules/localmodels/gateway_switch.py +0 -51
- package/modules/localmodels/library_floor.py +0 -78
- package/modules/localmodels/service_stop.py +0 -52
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -98,6 +98,24 @@ def engine_lock_path(tag: str | None = None) -> Path:
|
|
|
98
98
|
return ENGINE_LOCK if tag is None else ENGINE_LOCK.with_name(f"engines-{tag}.json")
|
|
99
99
|
|
|
100
100
|
|
|
101
|
+
def engine_lock_commit(tag: str | None) -> str | None:
|
|
102
|
+
"""Full commit hash pinned by ``engines-<tag>.json`` (or ``engines.json`` for None), if present."""
|
|
103
|
+
path = engine_lock_path(tag)
|
|
104
|
+
return _load_engine_lock(path)["commit"] if path.is_file() else None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def commit_matches(expected: str | None, found: str | None) -> bool:
|
|
108
|
+
"""True when ``found`` is a >=7-hex-char prefix of ``expected``."""
|
|
109
|
+
if not expected or not found:
|
|
110
|
+
return False
|
|
111
|
+
cand = found.strip().lower()
|
|
112
|
+
return (
|
|
113
|
+
len(cand) >= 7
|
|
114
|
+
and all(ch in "0123456789abcdef" for ch in cand)
|
|
115
|
+
and expected.lower().startswith(cand)
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
101
119
|
_ENGINE_LOCK_CACHE: dict[Path, tuple[int, int, EngineLock]] = {}
|
|
102
120
|
|
|
103
121
|
|
|
@@ -227,21 +245,33 @@ def host_engine(
|
|
|
227
245
|
itself, so that check reads the local filesystem."""
|
|
228
246
|
wanted = {a for a in argv[1:] if re.fullmatch(r"--?[A-Za-z][\w-]*", a)}
|
|
229
247
|
least = cat.build_number(min_build)
|
|
248
|
+
least_prism = cat.prism_build_number(min_build)
|
|
230
249
|
for engine in facts.get("engines") or []:
|
|
231
250
|
tag, built = engine["build"], cat.build_number(engine["build"])
|
|
251
|
+
built_prism = cat.prism_build_number(tag)
|
|
232
252
|
flags = set(engine.get("flags") or [])
|
|
233
253
|
if not engine["runs"] or not flags or not wanted <= flags:
|
|
234
254
|
continue
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
255
|
+
same = commit_matches(commit, engine.get("commit"))
|
|
256
|
+
if least_prism is not None:
|
|
257
|
+
newer = built_prism is not None and built_prism >= least_prism
|
|
258
|
+
if not (newer or same):
|
|
259
|
+
continue
|
|
260
|
+
else:
|
|
261
|
+
built_num = built if built is not None else built_prism
|
|
262
|
+
newer = built is not None and (least is None or built >= least)
|
|
263
|
+
if need_build and not (newer or same):
|
|
264
|
+
continue
|
|
265
|
+
if not need_build and least is not None and built_num is not None and built_num < least:
|
|
266
|
+
continue
|
|
241
267
|
if cuda and not any(Path(engine["path"]).parent.glob("libggml-cuda.so*")):
|
|
242
268
|
continue
|
|
243
|
-
label =
|
|
244
|
-
|
|
269
|
+
label = (
|
|
270
|
+
min_build
|
|
271
|
+
if same and (not tag or (least_prism is not None and built_prism is None))
|
|
272
|
+
else tag
|
|
273
|
+
)
|
|
274
|
+
where = f"commit {engine.get('commit') or 'unknown'}"
|
|
245
275
|
warnings.append(
|
|
246
276
|
f"{why}; using the {label} CUDA build already on this host, {engine['path']} ({where}); "
|
|
247
277
|
if cuda
|
|
@@ -417,22 +417,67 @@ def _kv_dtype_scale(profile: ModelProfile, kv_types: tuple[str, str]) -> float:
|
|
|
417
417
|
return (k_bpe + v_bpe) / (2 * _F16_BYTES_PER_ELEM)
|
|
418
418
|
|
|
419
419
|
|
|
420
|
-
|
|
421
|
-
|
|
420
|
+
# llama.cpp pads the SWA KV cache cell count to 256 for backend kernel performance
|
|
421
|
+
# (src/llama-kv-cache-iswa.cpp, ggml-org/llama.cpp#17037).
|
|
422
|
+
_SWA_KV_PAD = 256
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _ggml_pad(n: int, align: int = _SWA_KV_PAD) -> int:
|
|
426
|
+
if n <= 0:
|
|
427
|
+
return 0
|
|
428
|
+
return ((n + align - 1) // align) * align
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _swa_kv_tokens(
|
|
432
|
+
window: int, swa_window: int, *, slots: int = 1, ubatch: int = 0, unified: bool = True
|
|
433
|
+
) -> int:
|
|
434
|
+
"""SWA KV cells allocated across all streams, matching llama.cpp's ``llama-kv-cache-iswa.cpp``:
|
|
435
|
+
``size_swa = GGML_PAD(min(size_base, n_swa * (unified ? n_seq_max : 1) + n_ubatch), 256)``.
|
|
436
|
+
In unified mode (``--kv-unified``) there is one stream of ``window`` cells; in split mode
|
|
437
|
+
(``unified=False``), ``slots`` streams each hold ``ceil(window / slots)`` base cells."""
|
|
438
|
+
if window <= 0 or swa_window <= 0:
|
|
439
|
+
return 0
|
|
440
|
+
n_seq = max(1, slots)
|
|
441
|
+
ub = max(0, ubatch)
|
|
442
|
+
if unified:
|
|
443
|
+
return _ggml_pad(min(window, swa_window * n_seq + ub))
|
|
444
|
+
size_base = (window + n_seq - 1) // n_seq
|
|
445
|
+
return n_seq * _ggml_pad(min(size_base, swa_window + ub))
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def kv_pool_bytes(
|
|
449
|
+
profile: ModelProfile,
|
|
450
|
+
window: int,
|
|
451
|
+
kv_types: tuple[str, str],
|
|
452
|
+
*,
|
|
453
|
+
slots: int = 1,
|
|
454
|
+
ubatch: int = 0,
|
|
455
|
+
unified: bool = True,
|
|
456
|
+
) -> int:
|
|
457
|
+
"""KV cache bytes of a ``window``-token pool at the given K/V dtypes. Full layers hold
|
|
458
|
+
``window`` tokens; SWA layers follow llama.cpp's ``llama-kv-cache-iswa.cpp`` sizing
|
|
459
|
+
``GGML_PAD(min(size_base, swa_window * (unified ? slots : 1) + ubatch), 256)`` per stream
|
|
460
|
+
(WHI-676)."""
|
|
422
461
|
scale = _kv_dtype_scale(profile, kv_types)
|
|
462
|
+
swa_tokens = _swa_kv_tokens(
|
|
463
|
+
window, profile.swa_window, slots=slots, ubatch=ubatch, unified=unified
|
|
464
|
+
)
|
|
423
465
|
kv = 0.0
|
|
424
466
|
for kind, per_token_f16 in profile.layers:
|
|
425
467
|
if kind == LayerKind.RECURRENT:
|
|
426
468
|
continue
|
|
427
|
-
tokens =
|
|
469
|
+
tokens = swa_tokens if kind == LayerKind.SWA else window
|
|
428
470
|
kv += per_token_f16 * tokens * scale
|
|
429
471
|
return int(kv)
|
|
430
472
|
|
|
431
473
|
|
|
432
474
|
def session_state_bytes(profile: ModelProfile, window: int, kv_types: tuple[str, str]) -> int:
|
|
433
475
|
"""What one agent session holding the whole ``window`` saves when it leaves the shared pool:
|
|
434
|
-
its KV and one recurrent state (llama-server's
|
|
435
|
-
|
|
476
|
+
its KV (one slot, no ubatch scratch) and one recurrent state (llama-server's ``--cache-ram``
|
|
477
|
+
stores exactly this)."""
|
|
478
|
+
return kv_pool_bytes(profile, window, kv_types, slots=1, ubatch=0) + recurrent_state_bytes(
|
|
479
|
+
profile, slots=1
|
|
480
|
+
)
|
|
436
481
|
|
|
437
482
|
|
|
438
483
|
# A CUDA llama-server with every layer on the card holds host RAM besides its --cache-ram.
|
|
@@ -474,6 +519,7 @@ def agent_footprint_parts(
|
|
|
474
519
|
kv_types: tuple[str, str],
|
|
475
520
|
ubatch: int,
|
|
476
521
|
mtp: bool = False,
|
|
522
|
+
unified: bool = True,
|
|
477
523
|
) -> dict[str, int]:
|
|
478
524
|
"""``agent_footprint_bytes`` split into its FOOTPRINT_PARTS, for a view that shows where
|
|
479
525
|
the card's memory goes; the parts sum to exactly that footprint."""
|
|
@@ -486,7 +532,7 @@ def agent_footprint_parts(
|
|
|
486
532
|
)
|
|
487
533
|
return {
|
|
488
534
|
"weights": int(weights_gpu),
|
|
489
|
-
"kv": kv_pool_bytes(profile, window, kv_types),
|
|
535
|
+
"kv": kv_pool_bytes(profile, window, kv_types, slots=slots, ubatch=ubatch, unified=unified),
|
|
490
536
|
"state": recurrent_state_bytes(profile, slots=slots),
|
|
491
537
|
"compute": int(
|
|
492
538
|
_agent_compute_base_bytes(profile.n_embd)
|
|
@@ -505,6 +551,7 @@ def agent_footprint_bytes(
|
|
|
505
551
|
kv_types: tuple[str, str],
|
|
506
552
|
ubatch: int,
|
|
507
553
|
mtp: bool = False,
|
|
554
|
+
unified: bool = True,
|
|
508
555
|
) -> int:
|
|
509
556
|
"""What one agent-posture llama-server holds on the card (VP1 c4 + VP2, five
|
|
510
557
|
configurations): GPU-resident weights — untied models keep the token_embd table only
|
|
@@ -516,6 +563,12 @@ def agent_footprint_bytes(
|
|
|
516
563
|
draft context, no vocab logits buffer (VP2 measured it at 1.89 MiB on CUDA_Host) and
|
|
517
564
|
the MTP blocks stay unloaded."""
|
|
518
565
|
parts = agent_footprint_parts(
|
|
519
|
-
profile,
|
|
566
|
+
profile,
|
|
567
|
+
window,
|
|
568
|
+
slots=slots,
|
|
569
|
+
kv_types=kv_types,
|
|
570
|
+
ubatch=ubatch,
|
|
571
|
+
mtp=mtp,
|
|
572
|
+
unified=unified,
|
|
520
573
|
)
|
|
521
574
|
return sum(parts.values())
|
|
@@ -365,6 +365,51 @@ def wire_foundations(
|
|
|
365
365
|
return done
|
|
366
366
|
|
|
367
367
|
|
|
368
|
+
def leave_magpie(tools_dir: str) -> list[str]:
|
|
369
|
+
"""Before a Bifrost wiring: undo what this tool wired into Magpie (the stack moved). The
|
|
370
|
+
plan being wired is already the latest run record, so both the unwiring and the shutdown are
|
|
371
|
+
checked against the earlier approved plan that ran Magpie (``magpie_target``); without one
|
|
372
|
+
they fail closed and leave Magpie and its records as they are."""
|
|
373
|
+
from localmodels import bifrost_clients
|
|
374
|
+
|
|
375
|
+
doc = hosts.load_owned(tools_dir)
|
|
376
|
+
started = doc["gateway"]["started"]
|
|
377
|
+
if not bifrost_clients.magpie_wired(doc) and not started:
|
|
378
|
+
return []
|
|
379
|
+
if started: # a restored handoff receipt can precede a failed Magpie shutdown
|
|
380
|
+
bifrost_clients.refuse_changed_handoff(doc, tools_dir)
|
|
381
|
+
magpie = magpie_binary(doc)
|
|
382
|
+
previous = harness_gateway.magpie_target(tools_dir)
|
|
383
|
+
results = _unwire_magpie(magpie, tools_dir, plan=previous)
|
|
384
|
+
if all(r["ok"] for r in results) and started:
|
|
385
|
+
results.append(
|
|
386
|
+
stop_gateway(magpie, started, tools_dir, plan=previous)
|
|
387
|
+
if magpie is not None
|
|
388
|
+
else {"check": "magpie", "ok": False, "detail": "no Magpie started by this tool"}
|
|
389
|
+
)
|
|
390
|
+
if any(not r["ok"] for r in results):
|
|
391
|
+
raise HarnessError(
|
|
392
|
+
"undoing this tool's wiring in Magpie failed, not switched to Bifrost: "
|
|
393
|
+
+ "; ".join(r["check"] for r in results if not r["ok"])
|
|
394
|
+
)
|
|
395
|
+
return [f"Magpie wiring undone ({len(results)} items)"]
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def leave(tools_dir: str) -> list[str]:
|
|
399
|
+
"""Before a Magpie wiring: stop this tool's Bifrost and give pi and the clients back."""
|
|
400
|
+
from localmodels import gateway_bifrost
|
|
401
|
+
|
|
402
|
+
if not hosts.load_owned(tools_dir)["gateway"].get("bifrost"):
|
|
403
|
+
return []
|
|
404
|
+
results = gateway_bifrost.unwire(tools_dir)
|
|
405
|
+
if any(not r["ok"] for r in results):
|
|
406
|
+
raise HarnessError(
|
|
407
|
+
"undoing this tool's Bifrost gateway failed, not switched to Magpie: "
|
|
408
|
+
+ "; ".join(r["check"] for r in results if not r["ok"])
|
|
409
|
+
)
|
|
410
|
+
return ["Bifrost gateway stopped, pi and the clients restored"]
|
|
411
|
+
|
|
412
|
+
|
|
368
413
|
def wire(
|
|
369
414
|
plan: HarnessPlan,
|
|
370
415
|
llm_key: str,
|
|
@@ -377,13 +422,13 @@ def wire(
|
|
|
377
422
|
point pi at it. Idempotent: providers are updated by id, and adding a group by its name
|
|
378
423
|
replaces it with its rules. A re-sync (``select_pi=False``) leaves the gateway keys alone, so a
|
|
379
424
|
key the user removed stays removed. A Bifrost plan goes to ``gateway_bifrost.wire``."""
|
|
380
|
-
from localmodels import gateway_bifrost
|
|
425
|
+
from localmodels import gateway_bifrost
|
|
381
426
|
|
|
382
427
|
tools_dir = plan["tools_dir"]
|
|
383
428
|
if _bifrost(plan):
|
|
384
|
-
done =
|
|
429
|
+
done = leave_magpie(tools_dir) if select_pi else []
|
|
385
430
|
return done + gateway_bifrost.wire(plan, llm_key, decision_key, aux, select_pi=select_pi)
|
|
386
|
-
done =
|
|
431
|
+
done = leave(tools_dir) if select_pi else []
|
|
387
432
|
if select_pi and (key := gateway_keys.ensure(plan)):
|
|
388
433
|
done.append(key)
|
|
389
434
|
|
|
@@ -4,13 +4,13 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import os
|
|
6
6
|
import subprocess
|
|
7
|
+
from collections.abc import Callable
|
|
7
8
|
from pathlib import Path
|
|
8
9
|
from typing import Any
|
|
9
10
|
|
|
10
11
|
from localmodels import (
|
|
11
|
-
|
|
12
|
+
bifrost_config,
|
|
12
13
|
gateway_bifrost,
|
|
13
|
-
gateway_cli,
|
|
14
14
|
gateway_foundations,
|
|
15
15
|
harness,
|
|
16
16
|
process_identity,
|
|
@@ -26,7 +26,7 @@ def render(
|
|
|
26
26
|
if provider is not None:
|
|
27
27
|
field = next(name for name in ("chat", "responses", "anthropic") if name in provider)
|
|
28
28
|
pid = provider["id"]
|
|
29
|
-
native =
|
|
29
|
+
native = bifrost_config.render_provider("llm", provider[field], "*", provider["key"], pid)
|
|
30
30
|
native["keys"][0]["models"] = provider["models"] or ["*"]
|
|
31
31
|
custom = native["custom_provider_config"]
|
|
32
32
|
if field == "anthropic":
|
|
@@ -45,13 +45,13 @@ def render(
|
|
|
45
45
|
except (OSError, ValueError, KeyError, TypeError):
|
|
46
46
|
decision, key, aux = None, None, []
|
|
47
47
|
if decision is not None and key is not None:
|
|
48
|
-
providers["localmodels-jev"] =
|
|
48
|
+
providers["localmodels-jev"] = bifrost_config.render_provider(
|
|
49
49
|
"decision", decision["url"], decision["model"], key, "localmodels-jev"
|
|
50
50
|
)
|
|
51
51
|
for ep in aux:
|
|
52
52
|
aux_pid = gateway_bifrost.AUX_PROVIDERS.get(ep["contract"])
|
|
53
53
|
if aux_pid:
|
|
54
|
-
providers[aux_pid] =
|
|
54
|
+
providers[aux_pid] = bifrost_config.render_provider(
|
|
55
55
|
ep["contract"], ep["url"], ep["model"], ep["key"], aux_pid
|
|
56
56
|
)
|
|
57
57
|
return gateway_bifrost.render_config(
|
|
@@ -69,9 +69,15 @@ def render(
|
|
|
69
69
|
|
|
70
70
|
|
|
71
71
|
class Upstream:
|
|
72
|
-
def __init__(
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
root: Path,
|
|
75
|
+
state: dict[str, Any],
|
|
76
|
+
resolve: Callable[[], tuple[dict[str, Any] | None, bool]],
|
|
77
|
+
):
|
|
73
78
|
self.root = root
|
|
74
79
|
self.state = state
|
|
80
|
+
self._resolve = resolve
|
|
75
81
|
self.app = root / "bifrost"
|
|
76
82
|
runtime_io.private_directory(self.app)
|
|
77
83
|
for name in ("admin-password", "config.json", "config.json.tmp"):
|
|
@@ -83,25 +89,19 @@ class Upstream:
|
|
|
83
89
|
self.authenticated = False
|
|
84
90
|
|
|
85
91
|
def refresh(self) -> None:
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
row = gateway_cli.selected_runtime(
|
|
89
|
-
Path(self.state["harnessRoot"]), self.state["runtime"], self.state.get("node")
|
|
90
|
-
)
|
|
91
|
-
env = gateway_cli.gateway_environment(self.root / "home", row)
|
|
92
|
-
provider = gateway_server.api_provider(row, env, self.state)
|
|
92
|
+
provider, authed = self._resolve()
|
|
93
93
|
source = self.state.get("foundationsRoot")
|
|
94
94
|
config = render(provider, Path(source) if source else None, self.app, self.password)
|
|
95
95
|
if config != gateway_bifrost.read_config(self.app):
|
|
96
96
|
running = self.child is not None
|
|
97
97
|
self.stop()
|
|
98
|
-
gateway_bifrost.
|
|
98
|
+
gateway_bifrost.write_config(self.app, config)
|
|
99
99
|
if running:
|
|
100
100
|
self.start()
|
|
101
|
-
self.authenticated = provider is not None and
|
|
101
|
+
self.authenticated = provider is not None and authed
|
|
102
102
|
|
|
103
103
|
def start(self) -> None:
|
|
104
|
-
gateway_bifrost.
|
|
104
|
+
gateway_bifrost.stop_serve(self.app)
|
|
105
105
|
env = dict(os.environ, NO_PROXY="*", no_proxy="*")
|
|
106
106
|
# Explicit config owns all providers; inherited credential variables must not add any.
|
|
107
107
|
for name in tuple(env):
|
|
@@ -131,12 +131,12 @@ class Upstream:
|
|
|
131
131
|
try:
|
|
132
132
|
process_identity.save(self.app / "bifrost.pid", self.child.pid)
|
|
133
133
|
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError):
|
|
134
|
-
runtime_process.
|
|
134
|
+
runtime_process.terminate_tree(self.child)
|
|
135
135
|
self.child = None
|
|
136
136
|
raise harness.HarnessError("Cannot record Bifrost process identity") from None
|
|
137
137
|
|
|
138
138
|
def stop(self) -> None:
|
|
139
|
-
gateway_bifrost.
|
|
139
|
+
gateway_bifrost.stop_serve(self.app)
|
|
140
140
|
if self.child is not None:
|
|
141
141
|
self.child.wait(timeout=10)
|
|
142
142
|
self.child = None
|
|
@@ -18,9 +18,8 @@ from pathlib import Path
|
|
|
18
18
|
from typing import Any
|
|
19
19
|
|
|
20
20
|
from localmodels import (
|
|
21
|
-
|
|
21
|
+
bifrost_config,
|
|
22
22
|
bifrost_log,
|
|
23
|
-
bifrost_unit,
|
|
24
23
|
gateway_home,
|
|
25
24
|
gateway_keys,
|
|
26
25
|
harness,
|
|
@@ -28,6 +27,7 @@ from localmodels import (
|
|
|
28
27
|
harness_probe,
|
|
29
28
|
hosts,
|
|
30
29
|
http_local,
|
|
30
|
+
plan_envelope,
|
|
31
31
|
process_identity,
|
|
32
32
|
remote_ops_service,
|
|
33
33
|
)
|
|
@@ -40,13 +40,12 @@ from localmodels.bifrost_config import FAST_PROVIDER as FAST_PROVIDER
|
|
|
40
40
|
from localmodels.bifrost_config import LOG_BATCH_INTERVAL as LOG_BATCH_INTERVAL
|
|
41
41
|
from localmodels.bifrost_config import STORE as STORE
|
|
42
42
|
from localmodels.bifrost_config import differs as _config_differs
|
|
43
|
+
from localmodels.bifrost_config import origin as origin
|
|
43
44
|
from localmodels.bifrost_config import read_config as read_config
|
|
44
45
|
from localmodels.bifrost_config import render as render
|
|
45
46
|
from localmodels.bifrost_config import render_config as render_config
|
|
46
47
|
from localmodels.bifrost_config import sanitize_governance as sanitize_governance
|
|
47
48
|
from localmodels.bifrost_config import write_config as write_config
|
|
48
|
-
from localmodels.bifrost_provider import origin as origin
|
|
49
|
-
from localmodels.bifrost_unit import unit, unit_file, unit_for
|
|
50
49
|
from localmodels.gateway_requests import AuxEndpoint, Check
|
|
51
50
|
from localmodels.harness import (
|
|
52
51
|
HarnessError,
|
|
@@ -71,6 +70,92 @@ CALLER_KEY = gateway_keys.CALLER_KEY # clients send it; loopback inference chec
|
|
|
71
70
|
HEALTH_TIMEOUT_S = 180.0
|
|
72
71
|
# Windows cannot delete config.db while a running Bifrost holds it open: stop it before a change.
|
|
73
72
|
STOP_BEFORE_CONFIG_CHANGE = os.name == "nt"
|
|
73
|
+
LEGACY_UNIT = "localmodels-gateway" # the one name every install shared before 2026-11-10
|
|
74
|
+
UNIT_DIR = harness.UNIT_DIR
|
|
75
|
+
|
|
76
|
+
Systemctl = Callable[..., "subprocess.CompletedProcess[str]"]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def unit_for(app: Path) -> str:
|
|
80
|
+
"""``localmodels-<tag>-gateway``, the tag naming the directory the instance runs from."""
|
|
81
|
+
return f"localmodels-{plan_envelope.root_tag(str(app))}-gateway"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def unit(record: hosts.OwnedBifrost) -> str:
|
|
85
|
+
"""The unit a record's instance runs under; records from before the tag name the old one."""
|
|
86
|
+
return record.get("unit") or LEGACY_UNIT
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def unit_file(name: str) -> Path:
|
|
90
|
+
return Path(os.path.expanduser(UNIT_DIR)) / f"{name}.service"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def unit_text(binary: str, app: Path, addr: str) -> str:
|
|
94
|
+
host, _, port = addr.rpartition(":")
|
|
95
|
+
return (
|
|
96
|
+
"# localmodels: Bifrost gateway of the local stack; stack remove deletes this unit\n"
|
|
97
|
+
"[Unit]\n"
|
|
98
|
+
"Description=localmodels Bifrost gateway\n"
|
|
99
|
+
"After=network.target\n\n"
|
|
100
|
+
"[Service]\n"
|
|
101
|
+
f"WorkingDirectory={app}\n"
|
|
102
|
+
"Environment=NO_PROXY=127.0.0.1,localhost no_proxy=127.0.0.1,localhost\n"
|
|
103
|
+
f"ExecStart={binary} -app-dir {app} -host {host} -port {port} -log-style json "
|
|
104
|
+
"-log-level warn\n"
|
|
105
|
+
"Restart=on-failure\n"
|
|
106
|
+
"RestartSec=5\n"
|
|
107
|
+
"UMask=0077\n\n"
|
|
108
|
+
"[Install]\n"
|
|
109
|
+
"WantedBy=default.target\n"
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def retire_legacy_unit(name: str, app: Path, systemctl: Systemctl) -> None:
|
|
114
|
+
"""Stop, disable and delete the untagged unit when it runs this instance's directory; a unit
|
|
115
|
+
of that name running any other directory belongs to another install and is kept."""
|
|
116
|
+
old = unit_file(LEGACY_UNIT)
|
|
117
|
+
if name == LEGACY_UNIT or old.is_symlink() or not old.is_file():
|
|
118
|
+
return
|
|
119
|
+
try:
|
|
120
|
+
body = old.read_text(encoding="utf-8")
|
|
121
|
+
except (OSError, UnicodeDecodeError):
|
|
122
|
+
return
|
|
123
|
+
if old.stat().st_uid != os.getuid() or f" -app-dir {app} -host " not in body:
|
|
124
|
+
return
|
|
125
|
+
if systemctl("disable", "--now", f"{LEGACY_UNIT}.service").returncode != 0:
|
|
126
|
+
raise HarnessError(f"systemctl --user disable --now {LEGACY_UNIT} failed")
|
|
127
|
+
old.unlink()
|
|
128
|
+
systemctl("daemon-reload")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _require_owned_unit(record: hosts.OwnedBifrost, path: Path, systemctl: Systemctl) -> None:
|
|
132
|
+
"""Require both the private unit's exact content and systemd's loaded fragment."""
|
|
133
|
+
try:
|
|
134
|
+
info = path.lstat()
|
|
135
|
+
expected = unit_text(record["binary"], Path(record["app_dir"]), record["addr"])
|
|
136
|
+
fragment = systemctl("show", "-p", "FragmentPath", "--value", unit(record) + ".service")
|
|
137
|
+
if (
|
|
138
|
+
path.is_symlink()
|
|
139
|
+
or info.st_uid != os.getuid()
|
|
140
|
+
or info.st_mode & 0o022
|
|
141
|
+
or path.read_text() != expected
|
|
142
|
+
or fragment.returncode
|
|
143
|
+
or os.path.realpath(fragment.stdout.strip()) != os.path.realpath(path)
|
|
144
|
+
):
|
|
145
|
+
raise HarnessError("cannot verify ownership of the Bifrost unit; left untouched")
|
|
146
|
+
except OSError:
|
|
147
|
+
raise HarnessError("cannot verify ownership of the Bifrost unit; left untouched") from None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _pause_unit(record: hosts.OwnedBifrost, path: Path, systemctl: Systemctl) -> None:
|
|
151
|
+
"""Stop the verified unit and confirm that systemd no longer has its process."""
|
|
152
|
+
_require_owned_unit(record, path, systemctl)
|
|
153
|
+
name = unit(record) + ".service"
|
|
154
|
+
if systemctl("stop", name).returncode:
|
|
155
|
+
raise HarnessError("Bifrost unit could not stop")
|
|
156
|
+
pid = systemctl("show", "-p", "MainPID", "--value", name)
|
|
157
|
+
if pid.returncode or pid.stdout.strip() != "0":
|
|
158
|
+
raise HarnessError("Bifrost unit did not stop")
|
|
74
159
|
|
|
75
160
|
|
|
76
161
|
def plan_tools(
|
|
@@ -277,7 +362,7 @@ def owned_listener(record: hosts.OwnedBifrost) -> bool:
|
|
|
277
362
|
path.is_symlink()
|
|
278
363
|
or info.st_uid != os.getuid()
|
|
279
364
|
or info.st_mode & 0o022
|
|
280
|
-
or path.read_text() !=
|
|
365
|
+
or path.read_text() != unit_text(record["binary"], app, addr)
|
|
281
366
|
):
|
|
282
367
|
return False
|
|
283
368
|
out = _systemctl("show", "-p", "MainPID", "--value", f"{unit(record)}.service")
|
|
@@ -397,11 +482,9 @@ def _start(record: hosts.OwnedBifrost, restart: bool) -> None:
|
|
|
397
482
|
app, addr = Path(record["app_dir"]), record["addr"]
|
|
398
483
|
if record["how"] == "unit":
|
|
399
484
|
name = unit(record)
|
|
400
|
-
|
|
401
|
-
name, app, _systemctl
|
|
402
|
-
) # it holds the port the new unit listens on
|
|
485
|
+
retire_legacy_unit(name, app, _systemctl) # it holds the port the new unit listens on
|
|
403
486
|
path = unit_file(name)
|
|
404
|
-
text =
|
|
487
|
+
text = unit_text(record["binary"], app, addr)
|
|
405
488
|
if not path.is_file() or path.read_text(encoding="utf-8") != text:
|
|
406
489
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
407
490
|
path.write_text(text, encoding="utf-8")
|
|
@@ -500,7 +583,7 @@ def _stop_owned_serve(record: hosts.OwnedBifrost) -> None:
|
|
|
500
583
|
_stop_orphaned_serve(record)
|
|
501
584
|
|
|
502
585
|
|
|
503
|
-
def
|
|
586
|
+
def stop_serve(app: Path) -> None:
|
|
504
587
|
"""Only the process group the identity receipt proves is ours; anything else is kept."""
|
|
505
588
|
try:
|
|
506
589
|
outcome = process_identity.stop(app / "bifrost.pid")
|
|
@@ -513,11 +596,14 @@ def _stop_serve(app: Path) -> None:
|
|
|
513
596
|
_stop_orphaned_serve(record)
|
|
514
597
|
|
|
515
598
|
|
|
599
|
+
_stop_serve = stop_serve
|
|
600
|
+
|
|
601
|
+
|
|
516
602
|
def pause(record: hosts.OwnedBifrost) -> str:
|
|
517
603
|
"""Stop the proven instance, retaining its unit, configuration and ownership record."""
|
|
518
604
|
running = owned_listener(record)
|
|
519
605
|
if record["how"] == "unit":
|
|
520
|
-
|
|
606
|
+
_pause_unit(record, unit_file(unit(record)), _systemctl)
|
|
521
607
|
else:
|
|
522
608
|
_retire(record)
|
|
523
609
|
return "stopped" if running else "not-running"
|
|
@@ -613,12 +699,12 @@ def wire(
|
|
|
613
699
|
gw, llm_key, decision_key, aux, app, admin_password(app), keep, fast_key=fast_key
|
|
614
700
|
)
|
|
615
701
|
names = (gw["llm"]["model"], AGENT_MODEL)
|
|
616
|
-
sheets =
|
|
702
|
+
sheets = bifrost_config.sheets(gw["llm_provider"], names, gw.get("context"))
|
|
617
703
|
if fast := gw.get("llm_fast"):
|
|
618
|
-
extra =
|
|
704
|
+
extra = bifrost_config.sheets(
|
|
619
705
|
FAST_PROVIDER, (fast["model"], AGENT_MODEL), gw.get("context")
|
|
620
706
|
)
|
|
621
|
-
sheets[
|
|
707
|
+
sheets[bifrost_config.DATASHEET].update(extra[bifrost_config.DATASHEET])
|
|
622
708
|
if (
|
|
623
709
|
STOP_BEFORE_CONFIG_CHANGE
|
|
624
710
|
and record["how"] != "unit"
|
|
@@ -670,7 +756,7 @@ def stop(tools_dir: str = hosts.TOOLS_DIR) -> Check:
|
|
|
670
756
|
path.unlink()
|
|
671
757
|
_systemctl("daemon-reload")
|
|
672
758
|
try:
|
|
673
|
-
|
|
759
|
+
retire_legacy_unit(name, app, _systemctl)
|
|
674
760
|
except HarnessError as exc:
|
|
675
761
|
return {"check": "bifrost", "ok": False, "detail": str(exc)}
|
|
676
762
|
else:
|
|
@@ -678,7 +764,7 @@ def stop(tools_dir: str = hosts.TOOLS_DIR) -> Check:
|
|
|
678
764
|
_stop_owned_serve(record)
|
|
679
765
|
except HarnessError as exc:
|
|
680
766
|
return {"check": "bifrost", "ok": False, "detail": str(exc)}
|
|
681
|
-
for name in ("config.json", *
|
|
767
|
+
for name in ("config.json", *bifrost_config.FILES, *STORE, "admin-password"):
|
|
682
768
|
(app / name).unlink(missing_ok=True)
|
|
683
769
|
|
|
684
770
|
def forget(doc: hosts.Owned) -> None:
|