@simplexai/localmodels-linux-x64 0.1.0-dev.32.build.git0f60eee490864cf83e343f8db13a335676a19dd8 → 0.1.0-dev.35

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 (140) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +138 -97
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/app.py +7 -2
  6. package/modules/localmodels/approval.py +4 -4
  7. package/modules/localmodels/bifrost_checks.py +121 -3
  8. package/modules/localmodels/bifrost_provider.py +53 -0
  9. package/modules/localmodels/bifrost_unit.py +32 -1
  10. package/modules/localmodels/budget.py +5 -1
  11. package/modules/localmodels/catalog.json +51 -10
  12. package/modules/localmodels/catalog.py +30 -29
  13. package/modules/localmodels/catalog_add.py +1 -0
  14. package/modules/localmodels/cli_parser.py +10 -2
  15. package/modules/localmodels/component.py +7 -1
  16. package/modules/localmodels/decode_calibration.json +6 -0
  17. package/modules/localmodels/decode_calibration.py +104 -0
  18. package/modules/localmodels/deploy.py +44 -7
  19. package/modules/localmodels/deploy_steps.py +10 -1
  20. package/modules/localmodels/engines-strata-0.1.49.2.json +31 -0
  21. package/modules/localmodels/engines.json +57 -1
  22. package/modules/localmodels/engines.py +6 -2
  23. package/modules/localmodels/estimator.py +21 -7
  24. package/modules/localmodels/frontend.py +4 -4
  25. package/modules/localmodels/gateway.py +14 -4
  26. package/modules/localmodels/gateway_app_bifrost.py +4 -3
  27. package/modules/localmodels/gateway_bifrost.py +70 -57
  28. package/modules/localmodels/gateway_probe.py +3 -4
  29. package/modules/localmodels/gguf.py +7 -0
  30. package/modules/localmodels/harness.py +24 -25
  31. package/modules/localmodels/harness_gateway.py +19 -10
  32. package/modules/localmodels/harness_probe.py +33 -6
  33. package/modules/localmodels/hosts.py +73 -9
  34. package/modules/localmodels/install.py +36 -6
  35. package/modules/localmodels/library_cli.py +179 -0
  36. package/modules/localmodels/library_convert.py +132 -0
  37. package/modules/localmodels/library_gateway.py +471 -0
  38. package/modules/localmodels/library_jobs.py +314 -0
  39. package/modules/localmodels/library_model.py +246 -0
  40. package/modules/localmodels/library_pricing.py +347 -0
  41. package/modules/localmodels/library_serve.py +348 -0
  42. package/modules/localmodels/library_state.py +373 -0
  43. package/modules/localmodels/library_status.py +349 -0
  44. package/modules/localmodels/llm_rank.py +16 -2
  45. package/modules/localmodels/memcalc.py +7 -30
  46. package/modules/localmodels/metal.py +26 -0
  47. package/modules/localmodels/plan_envelope.py +4 -1
  48. package/modules/localmodels/preparation.py +49 -0
  49. package/modules/localmodels/probe.py +8 -8
  50. package/modules/localmodels/process_identity.py +536 -9
  51. package/modules/localmodels/quant_formats.py +123 -0
  52. package/modules/localmodels/recommend_cli.py +8 -4
  53. package/modules/localmodels/records.py +1 -0
  54. package/modules/localmodels/remote_ops.py +104 -6
  55. package/modules/localmodels/remote_ops_download.py +17 -2
  56. package/modules/localmodels/remote_ops_prepare.py +406 -0
  57. package/modules/localmodels/remote_ops_remove.py +40 -7
  58. package/modules/localmodels/remote_ops_service.py +110 -8
  59. package/modules/localmodels/remote_ops_verify.py +15 -2
  60. package/modules/localmodels/runtime_auth.py +31 -1
  61. package/modules/localmodels/runtime_cli.py +3 -4
  62. package/modules/localmodels/runtime_io.py +50 -6
  63. package/modules/localmodels/service_autostart.py +45 -1
  64. package/modules/localmodels/service_control.py +13 -0
  65. package/modules/localmodels/service_deployment.py +12 -3
  66. package/modules/localmodels/service_jobs.py +33 -4
  67. package/modules/localmodels/service_probe.py +67 -13
  68. package/modules/localmodels/service_stop.py +152 -0
  69. package/modules/localmodels/service_worker.py +9 -1
  70. package/modules/localmodels/services_cli.py +50 -6
  71. package/modules/localmodels/setup_inspection.py +34 -25
  72. package/modules/localmodels/setup_text.py +118 -0
  73. package/modules/localmodels/sizecalc.py +625 -0
  74. package/modules/localmodels/sizecalc_cli.py +249 -0
  75. package/modules/localmodels/stack.py +69 -17
  76. package/modules/localmodels/stack_args.py +91 -19
  77. package/modules/localmodels/stack_auto.py +78 -0
  78. package/modules/localmodels/stack_binding.py +23 -35
  79. package/modules/localmodels/stack_card.py +195 -0
  80. package/modules/localmodels/stack_cleanup.py +379 -0
  81. package/modules/localmodels/stack_clients.py +4 -1
  82. package/modules/localmodels/stack_compose.py +150 -194
  83. package/modules/localmodels/stack_console.py +2 -0
  84. package/modules/localmodels/stack_decision.py +3 -2
  85. package/modules/localmodels/stack_down.py +189 -0
  86. package/modules/localmodels/stack_events.py +54 -0
  87. package/modules/localmodels/stack_hardware.py +22 -23
  88. package/modules/localmodels/stack_journal.py +29 -8
  89. package/modules/localmodels/stack_ledger.py +411 -0
  90. package/modules/localmodels/stack_lifecycle.py +162 -167
  91. package/modules/localmodels/stack_llm_ram.py +57 -5
  92. package/modules/localmodels/stack_memory.py +721 -0
  93. package/modules/localmodels/stack_picks.py +139 -0
  94. package/modules/localmodels/stack_plan.py +140 -22
  95. package/modules/localmodels/stack_ports.py +22 -0
  96. package/modules/localmodels/stack_preflight.py +699 -0
  97. package/modules/localmodels/stack_review.py +123 -5
  98. package/modules/localmodels/stack_rollback.py +2 -0
  99. package/modules/localmodels/stack_route.py +256 -0
  100. package/modules/localmodels/stack_run.py +11 -0
  101. package/modules/localmodels/stack_suite.py +102 -17
  102. package/modules/localmodels/stack_summary.py +65 -4
  103. package/modules/localmodels/stack_try.py +354 -0
  104. package/modules/localmodels/stack_try_client.py +194 -0
  105. package/modules/localmodels/stack_try_docs.py +139 -0
  106. package/modules/localmodels/stack_up.py +8 -1
  107. package/modules/localmodels/stack_update.py +29 -4
  108. package/modules/localmodels/stack_verify.py +3 -1
  109. package/modules/localmodels/stack_view.py +10 -11
  110. package/modules/localmodels/stack_view_apply.py +4 -2
  111. package/modules/localmodels/stack_view_events.py +2 -1
  112. package/modules/localmodels/stack_view_serve.py +3 -0
  113. package/modules/localmodels/stack_view_text.py +1 -1
  114. package/modules/localmodels/stack_view_words.py +4 -1
  115. package/modules/localmodels/stack_warm.py +574 -0
  116. package/modules/localmodels/stack_whatif.py +558 -0
  117. package/modules/localmodels/suite.py +48 -39
  118. package/modules/localmodels/tool_archive.py +40 -0
  119. package/modules/localmodels/tools.json +8 -0
  120. package/modules/localmodels/transport.py +1 -0
  121. package/modules/localmodels/vision.py +8 -1
  122. package/modules/localmodels/web/sizecalc/app.js +431 -0
  123. package/modules/localmodels/web/sizecalc/calc.js +269 -0
  124. package/modules/localmodels/web/sizecalc/page.html +362 -0
  125. package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
  126. package/modules/localmodels/web/view/i18n.js +1 -1
  127. package/modules/localmodels/web/view/logo-claude.svg +3 -0
  128. package/modules/localmodels/web/view/logo-codex.png +0 -0
  129. package/modules/localmodels/web/view/logo-pi.svg +6 -0
  130. package/modules/localmodels/web/view/view.css +4 -0
  131. package/modules/localmodels/web/view/view.js +15 -6
  132. package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/METADATA +1 -1
  133. package/modules/simplex_localmodels-0.1.0.dev35.dist-info/RECORD +241 -0
  134. package/package.json +1 -1
  135. package/tool.json +1 -1
  136. package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
  137. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/WHEEL +0 -0
  138. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/entry_points.txt +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/NOTICE +0 -0
  140. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -8,6 +8,7 @@ from pathlib import Path
8
8
  from typing import Any
9
9
 
10
10
  from localmodels import (
11
+ bifrost_provider,
11
12
  gateway_bifrost,
12
13
  gateway_cli,
13
14
  gateway_foundations,
@@ -25,7 +26,7 @@ def render(
25
26
  if provider is not None:
26
27
  field = next(name for name in ("chat", "responses", "anthropic") if name in provider)
27
28
  pid = provider["id"]
28
- native = gateway_bifrost._provider("llm", provider[field], "*", provider["key"], pid)
29
+ native = bifrost_provider.render("llm", provider[field], "*", provider["key"], pid)
29
30
  native["keys"][0]["models"] = provider["models"] or ["*"]
30
31
  custom = native["custom_provider_config"]
31
32
  if field == "anthropic":
@@ -44,13 +45,13 @@ def render(
44
45
  except (OSError, ValueError, KeyError, TypeError):
45
46
  decision, key, aux = None, None, []
46
47
  if decision is not None and key is not None:
47
- providers["localmodels-jev"] = gateway_bifrost._provider(
48
+ providers["localmodels-jev"] = bifrost_provider.render(
48
49
  "decision", decision["url"], decision["model"], key, "localmodels-jev"
49
50
  )
50
51
  for ep in aux:
51
52
  aux_pid = gateway_bifrost.AUX_PROVIDERS.get(ep["contract"])
52
53
  if aux_pid:
53
- providers[aux_pid] = gateway_bifrost._provider(
54
+ providers[aux_pid] = bifrost_provider.render(
54
55
  ep["contract"], ep["url"], ep["model"], ep["key"], aux_pid
55
56
  )
56
57
  return gateway_bifrost.render_config(
@@ -1,7 +1,4 @@
1
- """Own the stack's Bifrost instance, configuration, lifecycle and client wiring.
2
-
3
- Magpie remains available explicitly; gateway_bifrost is the default for new stacks.
4
- """
1
+ """Own the default Bifrost gateway's configuration, lifecycle and client wiring."""
5
2
 
6
3
  from __future__ import annotations
7
4
 
@@ -22,6 +19,7 @@ from typing import Any
22
19
 
23
20
  from localmodels import (
24
21
  bifrost_datasheet,
22
+ bifrost_provider,
25
23
  bifrost_search,
26
24
  bifrost_unit,
27
25
  gateway_keys,
@@ -32,6 +30,7 @@ from localmodels import (
32
30
  process_identity,
33
31
  remote_ops_service,
34
32
  )
33
+ from localmodels.bifrost_provider import origin as origin
35
34
  from localmodels.bifrost_unit import unit, unit_file, unit_for
36
35
  from localmodels.gateway_requests import AuxEndpoint
37
36
  from localmodels.gateway_search import Check
@@ -58,6 +57,7 @@ LOG_BATCH_INTERVAL = "250ms" # logs_store.writer.batch_interval; Bifrost's defa
58
57
  STORE = ("config.db", "config.db-wal", "config.db-shm") # derived from config.json and datasheets
59
58
  COMPLEX_RULE = "localmodels-agent-complex"
60
59
  AGENT_RULE = "localmodels-agent"
60
+ FAST_PROVIDER = "localmodels-llm-fast"
61
61
  DECISION_TIMEOUT = "10s"
62
62
  HEALTH_TIMEOUT_S = 180.0
63
63
  # The auxiliaries Bifrost serves, by endpoint contract, under the provider ids Magpie used.
@@ -66,19 +66,6 @@ AUX_PROVIDERS = {
66
66
  "rerank": "localmodels-rerank",
67
67
  "stt": "localmodels-stt",
68
68
  }
69
- # What each provider may be asked: everything else Bifrost refuses before it reaches the
70
- # service. The LLM speaks chat only, so Bifrost turns Responses (Codex) and Anthropic Messages
71
- # (Claude Code) requests into chat completions instead of calling /v1/responses upstream.
72
- _ALLOWED = {
73
- "llm": {"list_models": True, "chat_completion": True, "chat_completion_stream": True},
74
- "decision": {"list_models": True, "decisions": True},
75
- "embedding": {"list_models": True, "embedding": True},
76
- # Bifrost's openai-type rerank sends documents as {"text": ...} objects, which llama-server
77
- # refuses; its cohere type sends the plain strings llama-server reads.
78
- "rerank": {"rerank": True},
79
- "stt": {"list_models": True, "transcription": True, "transcription_stream": True},
80
- }
81
- _BASE_TYPE = {"decision": "typesafe", "rerank": "cohere"}
82
69
  # The analyzer requires keyword lists even when the decision model classifies; they only decide
83
70
  # when it does not answer, so a few plain words suffice.
84
71
  _KEYWORDS = {
@@ -195,7 +182,7 @@ def install_binary(tools_dir: Path, action: ToolAction, log: Callable[[str], Non
195
182
  staging = target.with_name(f".{target.name}.tmp")
196
183
  staging.unlink(missing_ok=True)
197
184
  try:
198
- os.link(archive, staging) # one copy on disk; the archive stays until --purge
185
+ os.link(archive, staging) # one copy on disk; stack remove deletes the archive
199
186
  except OSError:
200
187
  shutil.copyfile(archive, staging)
201
188
  staging.chmod(0o755)
@@ -208,36 +195,11 @@ def app_dir() -> Path:
208
195
  return Path(os.path.expanduser(APP_DIR))
209
196
 
210
197
 
211
- def origin(url: str) -> str:
212
- """Bifrost appends the API path (/v1/...) to a provider's base URL itself."""
213
- url = url.rstrip("/")
214
- return url[: -len("/v1")] if url.endswith("/v1") else url
215
-
216
-
217
- def _provider(role: str, url: str, model: str, key: str, pid: str) -> dict[str, Any]:
218
- custom: dict[str, Any] = {
219
- "base_provider_type": _BASE_TYPE.get(role, "openai"),
220
- "allowed_requests": _ALLOWED[role],
221
- }
222
- if role == "rerank":
223
- custom["request_path_overrides"] = {"rerank": "/v1/rerank"}
224
- entry: dict[str, Any] = {"id": pid, "name": pid, "value": key, "models": [model], "weight": 1}
225
- if role == "llm":
226
- # Bifrost v2.3.0 lists (/v1/models as <pid>/<name>, /anthropic/v1/models bare) and routes
227
- # a name only when the key has it in both ``models`` and ``aliases``; either alone does not.
228
- entry["models"] = [model, AGENT_MODEL]
229
- entry["aliases"] = {AGENT_MODEL: model}
230
- return {
231
- "keys": [entry],
232
- "network_config": {
233
- "base_url": origin(url),
234
- "allow_private_network": True,
235
- "max_retries": 0,
236
- "default_request_timeout_in_seconds": 600,
237
- "stream_idle_timeout_in_seconds": 600,
238
- },
239
- "custom_provider_config": custom,
240
- }
198
+ def _seal(app: Path) -> None:
199
+ """Bifrost creates its SQLite stores and log with the umask; keep them 0600."""
200
+ for path in (*app.glob("*.db*"), app / "bifrost.log"):
201
+ with contextlib.suppress(OSError):
202
+ path.chmod(0o600)
241
203
 
242
204
 
243
205
  def admin_password(app: Path | None = None) -> str:
@@ -263,26 +225,36 @@ def render(
263
225
  app: Path,
264
226
  password: str,
265
227
  keep: dict[str, Any] | None = None,
228
+ *,
229
+ fast_key: str | None = None,
266
230
  ) -> dict[str, Any]:
267
231
  """The config.json for one approved plan, before ``bifrost_search.inject``. ``keep`` carries
268
232
  providers of an earlier config this call does not manage (a re-sync keeps the STT provider)."""
269
233
  llm = gw["llm"]
270
234
  providers: dict[str, Any] = dict(keep or {})
271
- providers[gw["llm_provider"]] = _provider(
235
+ providers[gw["llm_provider"]] = bifrost_provider.render(
272
236
  "llm", llm["url"], llm["model"], llm_key, gw["llm_provider"]
273
237
  )
274
238
  decision = gw["decision"] if decision_key is not None else None
275
239
  if decision is not None and decision_key is not None:
276
- providers[gw["decision_provider"]] = _provider(
240
+ providers[gw["decision_provider"]] = bifrost_provider.render(
277
241
  "decision", decision["url"], decision["model"], decision_key, gw["decision_provider"]
278
242
  )
279
243
  for ep in aux:
280
244
  pid = AUX_PROVIDERS.get(str(ep.get("contract")))
281
245
  if pid:
282
- providers[pid] = _provider(
246
+ providers[pid] = bifrost_provider.render(
283
247
  str(ep["contract"]), str(ep["url"]), str(ep["model"]), str(ep["key"]), pid
284
248
  )
285
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}
286
258
  rules: list[dict[str, Any]] = []
287
259
  governance: dict[str, Any] = {
288
260
  "auth_config": {
@@ -319,7 +291,7 @@ def render(
319
291
  "name": AGENT_RULE,
320
292
  "description": "local agent turns sent to the local LLM",
321
293
  "cel_expression": _AGENT_MATCH,
322
- "targets": [target],
294
+ "targets": [default_target],
323
295
  "priority": 1,
324
296
  }
325
297
  )
@@ -526,7 +498,9 @@ def _record(plan: ToolPlan, how: str) -> hosts.OwnedBifrost:
526
498
  def change(doc: hosts.Owned) -> None:
527
499
  previous = doc["gateway"].get("bifrost")
528
500
  doc["gateway"]["bifrost"] = {**previous, **record} if previous else record
529
- doc["archives"] = sorted(set(doc["archives"]) | {str(app)}) # logs; only --purge
501
+ doc["archives"] = sorted(
502
+ set(doc["archives"]) | {str(app)}
503
+ ) # logs; stack remove deletes them
530
504
 
531
505
  hosts.update_owned(change, plan["tools_dir"])
532
506
  return record
@@ -572,6 +546,7 @@ def _start(record: hosts.OwnedBifrost, restart: bool) -> None:
572
546
  stdout=log,
573
547
  stderr=log,
574
548
  start_new_session=True,
549
+ umask=0o077, # its SQLite stores and log stay private
575
550
  )
576
551
  try:
577
552
  process_identity.save(app / "bifrost.pid", proc.pid)
@@ -590,6 +565,16 @@ def _stop_serve(app: Path) -> None:
590
565
  raise HarnessError(f"Bifrost {exc}; process and config kept, rerun once resolved") from None
591
566
 
592
567
 
568
+ def pause(record: hosts.OwnedBifrost) -> str:
569
+ """Stop the proven instance, retaining its unit, configuration and ownership record."""
570
+ running = owned_listener(record)
571
+ if record["how"] == "unit":
572
+ bifrost_unit.pause(record, unit_file(unit(record)), _systemctl)
573
+ else:
574
+ _retire(record)
575
+ return "stopped" if running else "not-running"
576
+
577
+
593
578
  def _retire(record: hosts.OwnedBifrost) -> None:
594
579
  """Stop this tool's instance on an earlier pinned binary while its own record can still prove
595
580
  it ours; a record naming the new binary could not, so wire would refuse the held port."""
@@ -614,6 +599,7 @@ def ensure(plan: ToolPlan) -> str:
614
599
  app.mkdir(parents=True, exist_ok=True)
615
600
  app.chmod(0o700)
616
601
  admin_password(app)
602
+ _seal(app)
617
603
  return "reused" if _healthy_owned(record) else "installed"
618
604
 
619
605
 
@@ -627,6 +613,7 @@ def revive(plan: HarnessPlan) -> str:
627
613
  raise HarnessError("the ownership manifest has no record of this tool's Bifrost gateway")
628
614
  _start(record, restart=False)
629
615
  _await(addr, record=record)
616
+ _seal(Path(record["app_dir"]))
630
617
  return "started"
631
618
 
632
619
 
@@ -646,23 +633,49 @@ def wire(
646
633
  app = Path(record["app_dir"])
647
634
  keep: dict[str, Any] = {}
648
635
  if not select_pi:
649
- managed = {gw["llm_provider"], gw["decision_provider"], *AUX_PROVIDERS.values()}
636
+ managed = {
637
+ gw["llm_provider"],
638
+ gw["decision_provider"],
639
+ FAST_PROVIDER,
640
+ *AUX_PROVIDERS.values(),
641
+ }
650
642
  managed -= {AUX_PROVIDERS["stt"]}
651
643
  current = (written := read_config(app)).get("providers")
652
644
  if isinstance(current, dict):
653
645
  keep = {k: v for k, v in current.items() if k not in managed}
654
646
  aux = bifrost_search.kept(aux, written)
655
- config = render(gw, llm_key, decision_key, aux, app, admin_password(app), keep)
647
+ fast_key = None
648
+ if gw.get("llm_fast"):
649
+ try:
650
+ fast_key = (
651
+ Path(gw["llm_fast_key_file"]).expanduser().read_text(encoding="utf-8").strip()
652
+ )
653
+ except OSError as exc:
654
+ raise HarnessError("cannot read the fastest LLM deployment key") from exc
655
+ config = render(
656
+ gw, llm_key, decision_key, aux, app, admin_password(app), keep, fast_key=fast_key
657
+ )
656
658
  bifrost_search.inject(config, gw["llm_provider"], aux)
659
+ if gw.get("llm_fast"):
660
+ bifrost_search.inject(config, FAST_PROVIDER, aux)
657
661
  names = (gw["llm"]["model"], AGENT_MODEL)
658
662
  sheets = bifrost_datasheet.sheets(gw["llm_provider"], names, gw.get("context"))
663
+ if fast := gw.get("llm_fast"):
664
+ extra = bifrost_datasheet.sheets(
665
+ FAST_PROVIDER, (fast["model"], AGENT_MODEL), gw.get("context")
666
+ )
667
+ sheets[bifrost_datasheet.DATASHEET].update(extra[bifrost_datasheet.DATASHEET])
659
668
  changed = _write_config(app, config, sheets)
660
669
  if changed or not _healthy_owned(record):
661
670
  _start(record, restart=changed)
662
671
  _await(record["addr"], record=record)
672
+ _seal(app)
663
673
  done = [f"provider {pid}" for pid in config["providers"]]
674
+ default = gw.get("llm_fast") or gw["llm"]
675
+ provider = FAST_PROVIDER if gw.get("llm_fast") else gw["llm_provider"]
664
676
  done += [
665
- f"route {AGENT_MODEL} → {gw['llm_provider']}/{gw['llm']['model']}"
677
+ f"route {AGENT_MODEL} → {provider}/{default['model']}"
678
+ + (f"; COMPLEX → {gw['llm_provider']}/{gw['llm']['model']}" if gw.get("llm_fast") else "")
666
679
  + (
667
680
  f" (decision tiers {gw['decision_provider']}/{gw['decision']['model']})"
668
681
  if gw["decision"] is not None and decision_key is not None
@@ -681,7 +694,7 @@ def wire(
681
694
 
682
695
  def stop(tools_dir: str = hosts.TOOLS_DIR) -> Check:
683
696
  """Stop this tool's instance and delete its unit and its config (which holds the services'
684
- keys); the request logs stay until ``--purge``."""
697
+ keys); ``stack remove`` then deletes the request logs with the owned archives."""
685
698
  record = hosts.load_owned(tools_dir)["gateway"].get("bifrost")
686
699
  if not record:
687
700
  return {"check": "bifrost", "ok": True, "detail": "no Bifrost gateway of this tool"}
@@ -12,13 +12,12 @@ from __future__ import annotations
12
12
  import collections
13
13
  import csv
14
14
  import io
15
- import os
16
15
  import re
17
16
  import sys
18
17
  from collections.abc import Callable
19
18
  from typing import Literal, TypedDict
20
19
 
21
- from localmodels import console, harness, hosts
20
+ from localmodels import console, harness, hosts, process_identity
22
21
  from localmodels.gateway import AUX_PROVIDERS
23
22
  from localmodels.gateway import magpie_binary as magpie_binary
24
23
  from localmodels.harness_probe import first_line, listener_uids, shown_pi_model
@@ -176,10 +175,10 @@ def _health(ask: Ask, addr: str, started: str | None, reapply: str) -> Finding:
176
175
 
177
176
 
178
177
  def _listener(addr: str) -> Finding | None:
179
- if not (sys.platform.startswith("linux") or sys.platform == "darwin"):
178
+ if not (sys.platform.startswith("linux") or sys.platform in ("darwin", "win32")):
180
179
  return None
181
180
  try:
182
- others = listener_uids(addr) - {os.getuid()}
181
+ others = listener_uids(addr) - {process_identity.current_uid()}
183
182
  except (harness.HarnessError, ValueError):
184
183
  return None
185
184
  if not others:
@@ -199,6 +199,13 @@ class GGUFHeader:
199
199
  """Every Nth layer is full attention, zero when not declared."""
200
200
  return _integer(self._arch_key("full_attention_interval"))
201
201
 
202
+ @property
203
+ def key_length_mla(self) -> int:
204
+ """Per-head key width of an MLA model converted for llama.cpp's latent cache (deepseek2:
205
+ llama_hparams::is_mla); zero otherwise, including older deepseek2 files that cache full
206
+ K/V heads although they declare kv_lora_rank."""
207
+ return _integer(self._arch_key("attention.key_length_mla"))
208
+
202
209
  @property
203
210
  def key_length_swa(self) -> int:
204
211
  return _integer(self._arch_key("attention.key_length_swa"))
@@ -13,7 +13,6 @@ import hashlib
13
13
  import json
14
14
  import os
15
15
  import re
16
- import shlex
17
16
  import shutil
18
17
  import subprocess
19
18
  import tempfile
@@ -27,6 +26,8 @@ from localmodels.harness_probe import (
27
26
  ClientConfig,
28
27
  ClientState,
29
28
  )
29
+ from localmodels.harness_probe import client_environment as client_environment
30
+ from localmodels.harness_probe import gateway_environment as gateway_environment
30
31
  from localmodels.harness_probe import listener_uids as listener_uids
31
32
  from localmodels.harness_probe import shown_pi_model as shown_pi_model
32
33
  from localmodels.npm_transport import Artifact as Artifact
@@ -35,7 +36,13 @@ from localmodels.npm_transport import install_bifrost
35
36
  from localmodels.remote_ops import fetch
36
37
  from localmodels.runtime_io import error_cause
37
38
  from localmodels.stack_events import ToolEvents
38
- from localmodels.tool_archive import ArchiveError, safe_extract
39
+ from localmodels.tool_archive import (
40
+ ArchiveError,
41
+ launcher_name,
42
+ node_member,
43
+ safe_extract,
44
+ write_launcher,
45
+ )
39
46
 
40
47
  _Events = ToolEvents
41
48
 
@@ -148,6 +155,9 @@ class _GatewayOptional(TypedDict, total=False):
148
155
  clients: dict[str, ClientConfig]
149
156
  # Since 2026-11-02: which gateway carries the stack. Absent: Magpie, as every plan before.
150
157
  kind: str # one of GATEWAYS
158
+ llm_fast: Endpoint # optional fastest provider, only on a two-LLM Bifrost plan
159
+ llm_fast_key_file: str # private deployment credential, never its content
160
+ llm_key_file: str # direct readiness credential path, only present on two-LLM plans
151
161
  context: int # the LLM's context window per request, for the clients' model entries
152
162
 
153
163
 
@@ -244,7 +254,8 @@ def search_path(env: dict[str, str]) -> str:
244
254
 
245
255
 
246
256
  def tool_build(builds: list[ToolBuild], platform: str, arch: str, tool: str) -> ToolBuild:
247
- match = next((b for b in builds if b["platform"] == platform and b["arch"] == arch), None)
257
+ names = {platform, "windows"} if platform == "win32" else {platform} # the lock: windows
258
+ match = next((b for b in builds if b["platform"] in names and b["arch"] == arch), None)
248
259
  if match is None:
249
260
  raise HarnessError(f"{tool} has no pinned version for {platform}/{arch}")
250
261
  return match
@@ -288,7 +299,7 @@ def plan_tools(
288
299
  actions.append(reuse_tool("node", state["node"], state["node_version"]))
289
300
  else:
290
301
  build = tool_build(lock["node"]["builds"], platform, arch, "Node.js")
291
- node = f"{tools_dir}/node-v{lock['node']['version']}/bin/node"
302
+ node = f"{tools_dir}/node-v{lock['node']['version']}/{node_member(platform)}"
292
303
  actions.append(
293
304
  {
294
305
  "tool": "node",
@@ -298,23 +309,23 @@ def plan_tools(
298
309
  "artifacts": [tool_artifact(build)],
299
310
  }
300
311
  )
301
- pi = lock["pi"]
312
+ pi, wrapper = lock["pi"], f"{bin_dir}/{launcher_name(platform)}"
302
313
  actions.append(
303
314
  {
304
315
  "tool": "pi",
305
316
  "action": "install",
306
- "path": f"{bin_dir}/pi",
317
+ "path": wrapper,
307
318
  "version": pi["version"],
308
319
  "artifacts": [tool_artifact(pi), *(tool_artifact(m) for m in pi["modules"])],
309
320
  }
310
321
  )
311
322
  if (
312
323
  state["inspection"] == "complete"
313
- and os.path.lexists(os.path.expanduser(f"{bin_dir}/pi"))
314
- and not _owned_wrapper(f"{bin_dir}/pi")
324
+ and os.path.lexists(os.path.expanduser(wrapper))
325
+ and not _owned_wrapper(wrapper)
315
326
  ):
316
327
  raise HarnessError(
317
- f"{bin_dir}/pi exists but does not run and localmodels did not create it;"
328
+ f"{wrapper} exists but does not run and localmodels did not create it;"
318
329
  " deal with it first"
319
330
  )
320
331
  if not state["bin_on_path"]:
@@ -514,7 +525,7 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
514
525
  lambda d: _safe_extract(archive, d),
515
526
  actions["node"]["artifacts"][0]["sha256"],
516
527
  )
517
- node = str(tree / "bin" / "node")
528
+ node = str(tree / node_member())
518
529
  owned.append(str(tree))
519
530
  log(f"Node.js {lock['node']['version']} installed to {tree}")
520
531
  if actions["pi"]["action"] == "install":
@@ -535,18 +546,14 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
535
546
  ",".join(a["sha256"] for a in actions["pi"]["artifacts"]),
536
547
  )
537
548
  owned.append(str(tree))
538
- wrapper = bin_dir / "pi"
549
+ wrapper = bin_dir / launcher_name()
539
550
  bin_dir.mkdir(parents=True, exist_ok=True)
540
551
  if wrapper.exists() and not _owned_wrapper(str(wrapper)):
541
552
  raise HarnessError(
542
553
  f"{wrapper} exists and localmodels did not create it; not overwritten"
543
554
  )
544
- wrapper.write_text(
545
- f"#!/bin/sh\n{OWNED_WRAPPER} for {pi['package']}@{pi['version']}; "
546
- f"remove this file and {tree}\n"
547
- f'exec {shlex.quote(node)} {shlex.quote(str(tree / pi["entry"]))} "$@"\n',
548
- encoding="utf-8",
549
- )
555
+ about = f"{OWNED_WRAPPER} for {pi['package']}@{pi['version']}; remove this file and {tree}"
556
+ write_launcher(wrapper, [node, str(tree / pi["entry"])], about)
550
557
  wrapper.chmod(0o755)
551
558
  owned.append(str(wrapper))
552
559
  log(f"pi {pi['version']} installed: {wrapper}")
@@ -728,14 +735,6 @@ def _delete(path: str) -> bool:
728
735
  return True
729
736
 
730
737
 
731
- def client_environment(tools_dir: str) -> dict[str, str]:
732
- return harness_probe.client_environment(tools_dir)
733
-
734
-
735
- def gateway_environment(plan: ToolPlan, *, base: dict[str, str] | None = None) -> dict[str, str]:
736
- return harness_probe.gateway_environment(plan, base=base)
737
-
738
-
739
738
  def inspect(
740
739
  env: dict[str, str] | None = None,
741
740
  *,
@@ -6,9 +6,9 @@ import errno
6
6
  import json
7
7
  import os
8
8
  import shutil
9
- import signal
10
9
  import socket
11
10
  import subprocess
11
+ import sys
12
12
  from collections.abc import Callable
13
13
  from pathlib import Path
14
14
 
@@ -40,7 +40,10 @@ def owned_address(addr: str, tools_dir: str, magpie: str | None) -> bool:
40
40
  """A socket is ours only with this private context's live process receipt."""
41
41
  if not magpie or hosts.load_owned(tools_dir)["gateway"]["started"] not in ("serve", "daemon"):
42
42
  return False
43
- state, pid = process_identity.status(Path(tools_dir).expanduser() / "magpie-serve.pid")
43
+ receipt = Path(tools_dir).expanduser() / "magpie-serve.pid"
44
+ state, pid = process_identity.status(receipt)
45
+ if state != "active" and process_identity.adopt_successor(receipt, magpie):
46
+ state, pid = process_identity.status(receipt) # restarted into an updated binary
44
47
  if state != "active" or pid is None:
45
48
  return False
46
49
  if not remote_ops_service.command_matches(pid, [magpie, "serve"]):
@@ -57,6 +60,8 @@ def address_listening(
57
60
  return listening(port)
58
61
  if host == "localhost" and listening(port):
59
62
  return True
63
+ if sys.platform == "win32": # the listener table covers IPv6 as well
64
+ return listening(port)
60
65
  with socket.socket(socket.AF_INET6) as sock:
61
66
  sock.settimeout(1)
62
67
  result = sock.connect_ex(("::1", port))
@@ -125,7 +130,7 @@ def plan_gateway(
125
130
  actions.append(harness.reuse_tool("magpie", state["magpie"], state["magpie_version"]))
126
131
  else:
127
132
  build = harness.tool_build(lock["magpie"]["builds"], platform, arch, "Magpie")
128
- magpie = f"{bin_dir}/magpie"
133
+ magpie = f"{bin_dir}/magpie" + (".exe" if platform == "win32" else "")
129
134
  if state["inspection"] == "complete" and os.path.lexists(os.path.expanduser(magpie)):
130
135
  raise harness.HarnessError(f"{magpie} exists but does not run; deal with it first")
131
136
  actions.append(
@@ -284,8 +289,10 @@ def stop_gateway(
284
289
  tools_dir: str = hosts.TOOLS_DIR,
285
290
  *,
286
291
  plan: harness.ToolPlan | None = None,
292
+ forget: bool = True,
287
293
  ) -> Check:
288
- """Signal only a process whose private receipt still proves the approved gateway."""
294
+ """Signal only a process whose private receipt still proves the approved gateway.
295
+ ``forget=False`` (``stack down``) keeps it recorded as started, so ``stack up`` starts it."""
289
296
  target = plan or accepted_plan(tools_dir)
290
297
  failure: Check = {
291
298
  "check": "gateway",
@@ -306,6 +313,8 @@ def stop_gateway(
306
313
  pid_file = Path(os.path.expanduser(tools_dir), "magpie-serve.pid")
307
314
  try:
308
315
  state, pid = process_identity.status(pid_file)
316
+ if state != "active" and process_identity.adopt_successor(pid_file, magpie):
317
+ state, pid = process_identity.status(pid_file)
309
318
  if state == "active" and pid is not None:
310
319
  require_target(target)
311
320
  if not remote_ops_service.command_matches(pid, [magpie, "serve"]):
@@ -324,7 +333,8 @@ def stop_gateway(
324
333
  "detail": ("legacy PID file lacks a valid identity receipt; " if legacy else "")
325
334
  + "cannot confirm the stop; gateway and ownership records kept",
326
335
  }
327
- hosts.own_gateway(tools_dir, "started", None)
336
+ if forget:
337
+ hosts.own_gateway(tools_dir, "started", None)
328
338
  details = {
329
339
  "stopped": "magpie serve stopped",
330
340
  "gone": "magpie serve no longer running, process receipt cleared",
@@ -391,7 +401,9 @@ def purge_gateway_profile(plan: harness.ToolPlan | None, notes: list[str]) -> No
391
401
  if process_identity.status(pid_file)[0] != "inactive":
392
402
  notes.append("- private gateway config kept: process still running or of unknown owner")
393
403
  return
394
- if any(path.lstat().st_uid != os.getuid() for path in profile.rglob("*")):
404
+ if hasattr(os, "getuid") and any(
405
+ path.lstat().st_uid != os.getuid() for path in profile.rglob("*")
406
+ ):
395
407
  raise harness.HarnessError(
396
408
  "the private gateway directory holds another user's files; not cleaned"
397
409
  )
@@ -410,10 +422,7 @@ def record_started_child(proc: subprocess.Popen[bytes], tools_dir: Path) -> None
410
422
  try:
411
423
  process_identity.save(tools_dir / "magpie-serve.pid", proc.pid)
412
424
  except BaseException as exc:
413
- try:
414
- os.killpg(proc.pid, signal.SIGKILL)
415
- except ProcessLookupError:
416
- pass
425
+ process_identity.kill_started(proc.pid)
417
426
  proc.wait(timeout=10)
418
427
  if isinstance(exc, Exception):
419
428
  raise harness.HarnessError(
@@ -27,6 +27,17 @@ class ClientState(ClientConfig):
27
27
  version: str | None
28
28
 
29
29
 
30
+ def windows_program(path: str | None) -> str | None:
31
+ """Windows: the program behind a ``name.com`` console shim beside ``name.exe`` (the Magpie
32
+ app installs both). The shim starts the program as a child, so a receipt of the shim's PID
33
+ would not name the process that listens."""
34
+ if path and sys.platform == "win32" and path.lower().endswith(".com"):
35
+ program = path[:-4] + ".exe"
36
+ if os.path.isfile(program):
37
+ return program
38
+ return path
39
+
40
+
30
41
  def first_line(out: subprocess.CompletedProcess[str]) -> str | None:
31
42
  lines = [line.strip() for line in out.stdout.splitlines() if line.strip()]
32
43
  return lines[0] if out.returncode == 0 and lines else None
@@ -57,6 +68,16 @@ def listener_uids(addr: str, tables: tuple[str, ...] | None = None) -> set[int]:
57
68
 
58
69
  port = int(addr.rpartition(":")[2])
59
70
  uids: set[int] = set()
71
+ if tables is None and sys.platform == "win32":
72
+ from localmodels import process_identity
73
+
74
+ pids = process_identity.listener_pids(port)
75
+ if pids is None:
76
+ raise HarnessError("cannot confirm who owns the Windows gateway listener")
77
+ for pid in pids:
78
+ found = process_identity.inspect(pid)
79
+ uids.add(found["uid"] if found else -1) # 0: this user's process
80
+ return uids
60
81
  if tables is None and sys.platform == "darwin":
61
82
  out = run_tool(
62
83
  ["/usr/sbin/lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpu"], timeout=10
@@ -185,12 +206,10 @@ def inspect(
185
206
  """Read-only facts about the tools on this computer, found on ``harness.search_path``."""
186
207
  from localmodels import harness
187
208
 
188
- if not (sys.platform.startswith("linux") or sys.platform == "darwin") or not hasattr(
189
- os, "getuid"
190
- ):
209
+ if not (sys.platform.startswith("linux") or sys.platform in ("darwin", "win32")):
191
210
  raise harness.HarnessError(
192
- "the local stack tool check supports only Linux for now; cannot confirm gateway"
193
- " ownership on this platform."
211
+ "the local stack tool check supports Linux, macOS and Windows; cannot confirm"
212
+ " gateway ownership on this platform."
194
213
  )
195
214
  from localmodels import harness_gateway, stack_clients
196
215
 
@@ -201,6 +220,7 @@ def inspect(
201
220
  bin_dir = os.path.join(home, harness.BIN_DIR.removeprefix("~/"))
202
221
  search = harness.search_path(env)
203
222
  node, pi, magpie = (shutil.which(name, path=search) for name in ("node", "pi", "magpie"))
223
+ magpie = windows_program(magpie)
204
224
  bifrost = bool(approved and harness.gateway_kind(approved.get("gateway")) == "bifrost")
205
225
  bifrost_address = (
206
226
  str(approved["gateway"]["addr"]) if bifrost and approved else harness.bifrost_addr(env)
@@ -287,7 +307,14 @@ def inspect(
287
307
 
288
308
 
289
309
  def loopback_listening(port: int) -> bool:
290
- """Only connection refusal proves that a loopback port has no TCP listener."""
310
+ """Only connection refusal proves that a loopback port has no TCP listener. Windows reads
311
+ its listener table instead: a refused loopback connect retries there for about two seconds."""
312
+ if sys.platform == "win32":
313
+ from localmodels import process_identity
314
+
315
+ if (pids := process_identity.listener_pids(port)) is None:
316
+ raise OSError(f"cannot confirm whether port {port} is free")
317
+ return bool(pids)
291
318
  with socket.socket() as sock:
292
319
  sock.settimeout(1)
293
320
  result = sock.connect_ex(("127.0.0.1", port))