@simplexai/localmodels-linux-x64 0.1.0-dev.36 → 0.1.0-dev.38

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 (134) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +132 -110
  3. package/kit.py +1 -0
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +9 -3
  6. package/modules/localmodels/bifrost_checks.py +9 -6
  7. package/modules/localmodels/bifrost_config.py +203 -0
  8. package/modules/localmodels/bifrost_datasheet.py +12 -2
  9. package/modules/localmodels/budget.py +13 -2
  10. package/modules/localmodels/catalog.json +137 -2
  11. package/modules/localmodels/catalog.py +70 -321
  12. package/modules/localmodels/catalog_add.py +2 -8
  13. package/modules/localmodels/catalog_recipes.py +352 -0
  14. package/modules/localmodels/cli_parser.py +4 -1
  15. package/modules/localmodels/console.py +5 -4
  16. package/modules/localmodels/contracts.py +13 -3
  17. package/modules/localmodels/debug_cli.py +158 -0
  18. package/modules/localmodels/debug_mode.py +727 -0
  19. package/modules/localmodels/debug_stub_server.py +192 -0
  20. package/modules/localmodels/decode_calibration.json +1 -1
  21. package/modules/localmodels/decode_calibration.py +34 -17
  22. package/modules/localmodels/gateway.py +21 -155
  23. package/modules/localmodels/gateway_accept.py +201 -0
  24. package/modules/localmodels/gateway_bifrost.py +30 -193
  25. package/modules/localmodels/gateway_cli.py +15 -6
  26. package/modules/localmodels/gateway_foundations.py +2 -4
  27. package/modules/localmodels/gateway_probe.py +0 -1
  28. package/modules/localmodels/gateway_server.py +2 -3
  29. package/modules/localmodels/gpu_specs.py +12 -0
  30. package/modules/localmodels/guard.py +2 -7
  31. package/modules/localmodels/harness.py +16 -129
  32. package/modules/localmodels/harness_cleanup.py +135 -0
  33. package/modules/localmodels/harness_gateway.py +16 -14
  34. package/modules/localmodels/harness_probe.py +12 -4
  35. package/modules/localmodels/hosts.py +25 -2
  36. package/modules/localmodels/http_local.py +59 -0
  37. package/modules/localmodels/install.py +23 -8
  38. package/modules/localmodels/library_gateway.py +20 -9
  39. package/modules/localmodels/library_jobs.py +125 -28
  40. package/modules/localmodels/library_model.py +10 -0
  41. package/modules/localmodels/library_pricing.py +29 -22
  42. package/modules/localmodels/library_serve.py +17 -1
  43. package/modules/localmodels/library_state.py +15 -2
  44. package/modules/localmodels/library_status.py +30 -0
  45. package/modules/localmodels/llm_rank.py +185 -39
  46. package/modules/localmodels/probe.py +108 -174
  47. package/modules/localmodels/process_identity.py +120 -154
  48. package/modules/localmodels/process_windows.py +86 -0
  49. package/modules/localmodels/recommend.py +6 -3
  50. package/modules/localmodels/recommend_cli.py +14 -6
  51. package/modules/localmodels/remote_ops.py +65 -0
  52. package/modules/localmodels/remote_ops_service.py +14 -2
  53. package/modules/localmodels/runtime_args.py +10 -3
  54. package/modules/localmodels/runtime_auth.py +5 -9
  55. package/modules/localmodels/runtime_cli.py +128 -129
  56. package/modules/localmodels/runtime_discovery.py +84 -0
  57. package/modules/localmodels/runtime_install.py +101 -0
  58. package/modules/localmodels/runtime_releases.py +302 -0
  59. package/modules/localmodels/search_server.py +5 -1
  60. package/modules/localmodels/service_stop.py +8 -108
  61. package/modules/localmodels/service_upgrade.py +394 -63
  62. package/modules/localmodels/services_cli.py +24 -14
  63. package/modules/localmodels/setup_inspection.py +97 -9
  64. package/modules/localmodels/setup_text.py +7 -0
  65. package/modules/localmodels/sizecalc.py +0 -1
  66. package/modules/localmodels/stack.py +45 -235
  67. package/modules/localmodels/stack_arena.py +732 -0
  68. package/modules/localmodels/stack_args.py +21 -12
  69. package/modules/localmodels/stack_auto.py +384 -3
  70. package/modules/localmodels/stack_aux_gpu.py +4 -3
  71. package/modules/localmodels/stack_capacity.py +138 -0
  72. package/modules/localmodels/stack_cleanup.py +9 -4
  73. package/modules/localmodels/stack_cli.py +288 -0
  74. package/modules/localmodels/stack_compose.py +63 -30
  75. package/modules/localmodels/stack_console.py +9 -6
  76. package/modules/localmodels/stack_hardware.py +95 -265
  77. package/modules/localmodels/stack_hardware_text.py +263 -0
  78. package/modules/localmodels/stack_journal.py +3 -9
  79. package/modules/localmodels/stack_ledger.py +48 -18
  80. package/modules/localmodels/stack_lifecycle.py +33 -312
  81. package/modules/localmodels/stack_llm_ram.py +16 -6
  82. package/modules/localmodels/stack_mcp.py +729 -0
  83. package/modules/localmodels/stack_memory.py +0 -2
  84. package/modules/localmodels/stack_picks.py +62 -15
  85. package/modules/localmodels/stack_plan.py +19 -1
  86. package/modules/localmodels/stack_preflight.py +11 -19
  87. package/modules/localmodels/stack_progress.py +9 -1
  88. package/modules/localmodels/stack_remove.py +373 -0
  89. package/modules/localmodels/stack_route.py +101 -17
  90. package/modules/localmodels/stack_run.py +29 -0
  91. package/modules/localmodels/stack_suite.py +21 -10
  92. package/modules/localmodels/stack_summary.py +14 -0
  93. package/modules/localmodels/stack_try.py +238 -24
  94. package/modules/localmodels/stack_try_client.py +53 -15
  95. package/modules/localmodels/stack_try_docs.py +2 -2
  96. package/modules/localmodels/stack_view.py +24 -171
  97. package/modules/localmodels/stack_view_access.py +114 -1
  98. package/modules/localmodels/stack_view_agent.py +3 -13
  99. package/modules/localmodels/stack_view_hub.py +9 -10
  100. package/modules/localmodels/stack_view_llm.py +1 -1
  101. package/modules/localmodels/stack_view_sandbox.py +2 -2
  102. package/modules/localmodels/stack_view_schema.py +183 -0
  103. package/modules/localmodels/stack_view_serve.py +7 -1
  104. package/modules/localmodels/stack_view_service.py +1 -2
  105. package/modules/localmodels/stack_view_text.py +13 -9
  106. package/modules/localmodels/stack_warm.py +48 -4
  107. package/modules/localmodels/stack_warm_store.py +517 -0
  108. package/modules/localmodels/tools.json +32 -18
  109. package/modules/localmodels/transport.py +38 -13
  110. package/modules/localmodels/tui.py +28 -4
  111. package/modules/localmodels/tui_dialogs.py +136 -0
  112. package/modules/localmodels/tui_modals.py +279 -0
  113. package/modules/localmodels/tui_screen.py +113 -154
  114. package/modules/localmodels/tui_views.py +134 -203
  115. package/modules/localmodels/web/index.html +510 -101
  116. package/modules/localmodels/web/sizecalc/app.js +363 -10
  117. package/modules/localmodels/web/sizecalc/page.html +27 -3
  118. package/modules/localmodels/web/view/fleet.html +11 -2
  119. package/modules/localmodels/web/view/fleet.js +191 -17
  120. package/modules/localmodels/web/view/i18n.js +3 -2
  121. package/modules/localmodels/web/view/index.html +1 -1
  122. package/modules/localmodels/web/view/nav.js +22 -3
  123. package/modules/localmodels/web/view/view.css +63 -18
  124. package/modules/localmodels/web/view/view.js +169 -32
  125. package/modules/localmodels/windows_job.py +69 -0
  126. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/METADATA +1 -1
  127. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/RECORD +128 -106
  128. package/package.json +1 -1
  129. package/tool.json +1 -1
  130. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  131. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/WHEEL +0 -0
  132. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/entry_points.txt +0 -0
  133. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/NOTICE +0 -0
  134. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -9,7 +9,6 @@ artifacts, with ownership recorded for safe removal. The controller must be the
9
9
  from __future__ import annotations
10
10
 
11
11
  import contextlib
12
- import hashlib
13
12
  import json
14
13
  import os
15
14
  import re
@@ -22,6 +21,21 @@ from typing import Any, Literal, TypedDict, cast
22
21
 
23
22
  from localmodels import harness_probe, hosts
24
23
  from localmodels.contracts import decode
24
+ from localmodels.harness_cleanup import (
25
+ changed as changed,
26
+ )
27
+ from localmodels.harness_cleanup import (
28
+ digest as digest,
29
+ )
30
+ from localmodels.harness_cleanup import (
31
+ keep_reason as keep_reason,
32
+ )
33
+ from localmodels.harness_cleanup import (
34
+ remove_tools as remove_tools,
35
+ )
36
+ from localmodels.harness_cleanup import (
37
+ unit_users as unit_users,
38
+ )
25
39
  from localmodels.harness_probe import (
26
40
  ClientConfig,
27
41
  ClientState,
@@ -605,134 +619,7 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
605
619
  return owned
606
620
 
607
621
 
608
- # ---------------------------------------------------------------------------- removal
609
-
610
-
611
- def digest(path: str) -> str | None:
612
- """sha256 of a file, or of a directory tree's names, file contents and link targets;
613
- None when nothing is there."""
614
- top = Path(path)
615
- if top.is_symlink() or top.is_file():
616
- return _file_digest(top)
617
- if not top.is_dir():
618
- return None
619
- tree = hashlib.sha256()
620
- for root, dirs, names in os.walk(top):
621
- dirs.sort()
622
- for name in sorted([*dirs, *names]):
623
- entry = Path(root, name)
624
- if entry.is_dir() and not entry.is_symlink():
625
- tree.update(f"d {entry.relative_to(top)}\n".encode())
626
- else:
627
- tree.update(f"f {entry.relative_to(top)} {_file_digest(entry)}\n".encode())
628
- return tree.hexdigest()
629
-
630
-
631
- def _file_digest(path: Path) -> str:
632
- if path.is_symlink():
633
- return hashlib.sha256(b"link " + os.readlink(path).encode()).hexdigest()
634
- sha = hashlib.sha256()
635
- with path.open("rb") as f:
636
- for chunk in iter(lambda: f.read(1 << 20), b""):
637
- sha.update(chunk)
638
- return sha.hexdigest()
639
-
640
-
641
- def unit_users(path: str, unit_dir: str = UNIT_DIR) -> list[str]:
642
- """systemd --user units, other than this tool's localmodels-* ones, whose ExecStart or
643
- ExecStartPre runs ``path`` or something inside it."""
644
- units = Path(os.path.expanduser(unit_dir))
645
- home = os.path.expanduser("~")
646
- targets = {os.path.normpath(path), os.path.realpath(path)}
647
- users = set()
648
- for unit in [*units.glob("*.service"), *units.glob("*.service.d/*.conf")]:
649
- name = unit.name if unit.suffix == ".service" else unit.parent.name.removesuffix(".d")
650
- if name.startswith("localmodels-"):
651
- continue
652
- try:
653
- text = unit.read_text(encoding="utf-8")
654
- except (OSError, UnicodeDecodeError):
655
- continue
656
- for line in text.splitlines():
657
- key, _, value = line.strip().partition("=")
658
- if key.strip() not in ("ExecStart", "ExecStartPre"):
659
- continue
660
- for word in value.replace("%h", home).split():
661
- word = word.lstrip("@-:+!").strip("\"'")
662
- if not word.startswith("/"):
663
- continue
664
- for candidate in {os.path.normpath(word), os.path.realpath(word)}:
665
- if any(candidate == t or candidate.startswith(t + "/") for t in targets):
666
- users.add(name)
667
- return sorted(users)
668
-
669
-
670
- def changed(tool: hosts.OwnedTool) -> str | None:
671
- """Why a recorded tool is no longer verifiably the one this tool created, or None."""
672
- if tool["sha256"] is None:
673
- return "the manifest only recorded the path (legacy, unverified); not deleted"
674
- if digest(tool["path"]) != tool["sha256"]:
675
- return "sha256 differs from install time (self-updated or modified); not deleted"
676
- return None
677
-
678
-
679
- def keep_reason(tool: hosts.OwnedTool, unit_dir: str = UNIT_DIR) -> str | None:
680
- """Why removal must keep this tool, or None when it may delete it."""
681
- if not os.path.lexists(tool["path"]):
682
- return None
683
- reason = changed(tool)
684
- if reason:
685
- return reason
686
- users = unit_users(tool["path"], unit_dir)
687
- return f"in use by systemd user service {', '.join(users)}; not deleted" if users else None
688
-
689
-
690
- def remove_tools(
691
- doc: hosts.Owned, purge: bool, unit_dir: str = UNIT_DIR
692
- ) -> tuple[list[str], dict[str, str]]:
693
- """Delete each tool this tool installed that is still the file it created and that no
694
- other user unit runs; with ``purge`` also the downloaded archives. Returns what was deleted
695
- and, by path, why each kept tool was kept."""
696
- kept = {t["path"]: r for t in doc["tools"] if (r := keep_reason(t, unit_dir))}
697
- _keep_what_kept_tools_run(doc["tools"], kept)
698
- gone = [t["path"] for t in doc["tools"] if t["path"] not in kept and _delete(t["path"])]
699
- gone += [path for path in (doc["archives"] if purge else []) if _delete(path)]
700
- return gone, kept
701
-
702
-
703
- def _keep_what_kept_tools_run(tools: list[hosts.OwnedTool], kept: dict[str, str]) -> None:
704
- """A kept pi wrapper names the Node.js and pi trees it runs: they stay with it."""
705
- while True:
706
- texts = {p: _head(p) for p in kept}
707
- more = {
708
- t["path"]: f"the kept {p} uses it; not deleted"
709
- for t in tools
710
- if t["path"] not in kept
711
- for p, text in texts.items()
712
- if t["path"] in text
713
- }
714
- if not more:
715
- return
716
- kept.update(more)
717
-
718
-
719
- def _head(path: str) -> str:
720
- try:
721
- with open(path, encoding="utf-8") as f:
722
- return f.read(4096)
723
- except (OSError, UnicodeDecodeError):
724
- return ""
725
-
726
-
727
- def _delete(path: str) -> bool:
728
- target = Path(path)
729
- if target.is_dir() and not target.is_symlink():
730
- shutil.rmtree(target)
731
- elif os.path.lexists(target):
732
- target.unlink()
733
- else:
734
- return False
735
- return True
622
+ # ---------------------------------------------------------------------------- inspect
736
623
 
737
624
 
738
625
  def inspect(
@@ -0,0 +1,135 @@
1
+ """Digest, systemd user-unit reference checks and safe tool removal helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import shutil
8
+ from pathlib import Path
9
+
10
+ from localmodels import hosts, http_local
11
+
12
+ UNIT_DIR = "~/.config/systemd/user"
13
+
14
+
15
+ def digest(path: str) -> str | None:
16
+ """sha256 of a file, or of a directory tree's names, file contents and link targets;
17
+ None when nothing is there."""
18
+ top = Path(path)
19
+ if top.is_symlink() or top.is_file():
20
+ return _file_digest(top)
21
+ if not top.is_dir():
22
+ return None
23
+ tree = hashlib.sha256()
24
+ for root, dirs, names in os.walk(top):
25
+ dirs.sort()
26
+ for name in sorted([*dirs, *names]):
27
+ entry = Path(root, name)
28
+ if entry.is_dir() and not entry.is_symlink():
29
+ tree.update(f"d {entry.relative_to(top)}\n".encode())
30
+ else:
31
+ tree.update(f"f {entry.relative_to(top)} {_file_digest(entry)}\n".encode())
32
+ return tree.hexdigest()
33
+
34
+
35
+ def _file_digest(path: Path) -> str:
36
+ if path.is_symlink():
37
+ return hashlib.sha256(b"link " + os.readlink(path).encode()).hexdigest()
38
+ return http_local.sha256_file(path)
39
+
40
+
41
+ def unit_users(path: str, unit_dir: str = UNIT_DIR) -> list[str]:
42
+ """systemd --user units, other than this tool's localmodels-* ones, whose ExecStart or
43
+ ExecStartPre runs ``path`` or something inside it."""
44
+ units = Path(os.path.expanduser(unit_dir))
45
+ home = os.path.expanduser("~")
46
+ targets = {os.path.normpath(path), os.path.realpath(path)}
47
+ users = set()
48
+ for unit in [*units.glob("*.service"), *units.glob("*.service.d/*.conf")]:
49
+ name = unit.name if unit.suffix == ".service" else unit.parent.name.removesuffix(".d")
50
+ if name.startswith("localmodels-"):
51
+ continue
52
+ try:
53
+ text = unit.read_text(encoding="utf-8")
54
+ except (OSError, UnicodeDecodeError):
55
+ continue
56
+ for line in text.splitlines():
57
+ key, _, value = line.strip().partition("=")
58
+ if key.strip() not in ("ExecStart", "ExecStartPre"):
59
+ continue
60
+ for word in value.replace("%h", home).split():
61
+ word = word.lstrip("@-:+!").strip("\"'")
62
+ if not word.startswith("/"):
63
+ continue
64
+ for candidate in {os.path.normpath(word), os.path.realpath(word)}:
65
+ if any(candidate == t or candidate.startswith(t + "/") for t in targets):
66
+ users.add(name)
67
+ return sorted(users)
68
+
69
+
70
+ def changed(tool: hosts.OwnedTool) -> str | None:
71
+ """Why a recorded tool is no longer verifiably the one this tool created, or None."""
72
+ if tool["sha256"] is None:
73
+ return "the manifest only recorded the path (legacy, unverified); not deleted"
74
+ if digest(tool["path"]) != tool["sha256"]:
75
+ return "sha256 differs from install time (self-updated or modified); not deleted"
76
+ return None
77
+
78
+
79
+ def keep_reason(tool: hosts.OwnedTool, unit_dir: str = UNIT_DIR) -> str | None:
80
+ """Why removal must keep this tool, or None when it may delete it."""
81
+ if not os.path.lexists(tool["path"]):
82
+ return None
83
+ reason = changed(tool)
84
+ if reason:
85
+ return reason
86
+ users = unit_users(tool["path"], unit_dir)
87
+ return f"in use by systemd user service {', '.join(users)}; not deleted" if users else None
88
+
89
+
90
+ def remove_tools(
91
+ doc: hosts.Owned, purge: bool, unit_dir: str = UNIT_DIR
92
+ ) -> tuple[list[str], dict[str, str]]:
93
+ """Delete each tool this tool installed that is still the file it created and that no
94
+ other user unit runs; with ``purge`` also the downloaded archives. Returns what was deleted
95
+ and, by path, why each kept tool was kept."""
96
+ kept = {t["path"]: r for t in doc["tools"] if (r := keep_reason(t, unit_dir))}
97
+ _keep_what_kept_tools_run(doc["tools"], kept)
98
+ gone = [t["path"] for t in doc["tools"] if t["path"] not in kept and _delete(t["path"])]
99
+ gone += [path for path in (doc["archives"] if purge else []) if _delete(path)]
100
+ return gone, kept
101
+
102
+
103
+ def _keep_what_kept_tools_run(tools: list[hosts.OwnedTool], kept: dict[str, str]) -> None:
104
+ """A kept pi wrapper names the Node.js and pi trees it runs: they stay with it."""
105
+ while True:
106
+ texts = {p: _head(p) for p in kept}
107
+ more = {
108
+ t["path"]: f"the kept {p} uses it; not deleted"
109
+ for t in tools
110
+ if t["path"] not in kept
111
+ for p, text in texts.items()
112
+ if t["path"] in text
113
+ }
114
+ if not more:
115
+ return
116
+ kept.update(more)
117
+
118
+
119
+ def _head(path: str) -> str:
120
+ try:
121
+ with open(path, encoding="utf-8") as f:
122
+ return f.read(4096)
123
+ except (OSError, UnicodeDecodeError):
124
+ return ""
125
+
126
+
127
+ def _delete(path: str) -> bool:
128
+ target = Path(path)
129
+ if target.is_dir() and not target.is_symlink():
130
+ shutil.rmtree(target)
131
+ elif os.path.lexists(target):
132
+ target.unlink()
133
+ else:
134
+ return False
135
+ return True
@@ -22,6 +22,13 @@ from localmodels import (
22
22
  )
23
23
  from localmodels.gateway_search import Check
24
24
 
25
+ SERVE_PID = "magpie-serve.pid" # with magpie-serve.pid.identity.json: process_identity.save
26
+ SERVE_STOPPED = {
27
+ "stopped": "magpie serve stopped",
28
+ "gone": "magpie serve no longer running, process receipt cleared",
29
+ "none": "magpie serve has no process receipt, no signal sent",
30
+ }
31
+
25
32
 
26
33
  def address_port(addr: str) -> int:
27
34
  host, separator, value = addr.rpartition(":")
@@ -40,7 +47,7 @@ def owned_address(addr: str, tools_dir: str, magpie: str | None) -> bool:
40
47
  """A socket is ours only with this private context's live process receipt."""
41
48
  if not magpie or hosts.load_owned(tools_dir)["gateway"]["started"] not in ("serve", "daemon"):
42
49
  return False
43
- receipt = Path(tools_dir).expanduser() / "magpie-serve.pid"
50
+ receipt = Path(tools_dir).expanduser() / SERVE_PID
44
51
  state, pid = process_identity.status(receipt)
45
52
  if state != "active" and process_identity.adopt_successor(receipt, magpie):
46
53
  state, pid = process_identity.status(receipt) # restarted into an updated binary
@@ -335,12 +342,7 @@ def stop_gateway(
335
342
  }
336
343
  if forget:
337
344
  hosts.own_gateway(tools_dir, "started", None)
338
- details = {
339
- "stopped": "magpie serve stopped",
340
- "gone": "magpie serve no longer running, process receipt cleared",
341
- "none": "magpie serve has no process receipt, no signal sent",
342
- }
343
- return {"check": "gateway", "ok": True, "detail": details[outcome]}
345
+ return {"check": "gateway", "ok": True, "detail": SERVE_STOPPED[outcome]}
344
346
 
345
347
 
346
348
  def private_home(plan: harness.ToolPlan) -> None:
@@ -349,20 +351,20 @@ def private_home(plan: harness.ToolPlan) -> None:
349
351
  never loosened or repaired automatically, the user is told how to fix it."""
350
352
  if "environment" in plan:
351
353
  return
352
- home = Path(plan["tools_dir"]).expanduser() / "gateway-home"
354
+ home = harness_probe.gateway_home(plan["tools_dir"])
353
355
  try:
354
356
  runtime_io.private_directory(home)
355
357
  except ValueError as exc:
356
358
  raise harness.HarnessError(
357
- f"{home} is not a directory private to the current user (should be 0700); no config"
358
- f" changed. Once you confirm this tool created it, run chmod 700 {home} and retry"
359
+ f"{home} is not a directory private to the current user ({exc}; should be 0700); no"
360
+ f" config changed. Once you confirm this tool created it, run chmod 700 {home} and retry"
359
361
  ) from exc
360
362
 
361
363
 
362
364
  def gateway_profile(plan: harness.ToolPlan | None) -> Path | None:
363
365
  if plan is None or "environment" in plan:
364
366
  return None
365
- profile = Path(plan["tools_dir"]).expanduser() / "gateway-home"
367
+ profile = harness_probe.gateway_home(plan["tools_dir"])
366
368
  environment = harness.gateway_environment(plan)
367
369
  gateway = plan.get("gateway")
368
370
  if isinstance(gateway, dict) and harness.gateway_kind(gateway) == "bifrost":
@@ -397,7 +399,7 @@ def purge_gateway_profile(plan: harness.ToolPlan | None, notes: list[str]) -> No
397
399
  )
398
400
  return
399
401
  else:
400
- pid_file = Path(plan["tools_dir"]).expanduser() / "magpie-serve.pid"
402
+ pid_file = Path(plan["tools_dir"]).expanduser() / SERVE_PID
401
403
  if process_identity.status(pid_file)[0] != "inactive":
402
404
  notes.append("- private gateway config kept: process still running or of unknown owner")
403
405
  return
@@ -411,7 +413,7 @@ def purge_gateway_profile(plan: harness.ToolPlan | None, notes: list[str]) -> No
411
413
 
412
414
 
413
415
  def require_inactive(tools_dir: Path) -> None:
414
- if process_identity.status(tools_dir / "magpie-serve.pid")[0] != "inactive":
416
+ if process_identity.status(tools_dir / SERVE_PID)[0] != "inactive":
415
417
  raise harness.HarnessError(
416
418
  "private gateway process still running or of unknown owner; no second process started"
417
419
  )
@@ -420,7 +422,7 @@ def require_inactive(tools_dir: Path) -> None:
420
422
  def record_started_child(proc: subprocess.Popen[bytes], tools_dir: Path) -> None:
421
423
  """A failed receipt cannot leave the child this exact launch just created alive."""
422
424
  try:
423
- process_identity.save(tools_dir / "magpie-serve.pid", proc.pid)
425
+ process_identity.save(tools_dir / SERVE_PID, proc.pid)
424
426
  except BaseException as exc:
425
427
  process_identity.kill_started(proc.pid)
426
428
  proc.wait(timeout=10)
@@ -13,6 +13,8 @@ import sys
13
13
  from pathlib import Path
14
14
  from typing import TYPE_CHECKING, TypedDict
15
15
 
16
+ from localmodels import hosts
17
+
16
18
  if TYPE_CHECKING:
17
19
  from localmodels import harness
18
20
 
@@ -147,9 +149,15 @@ def _listdir(path: str) -> list[str]:
147
149
  return []
148
150
 
149
151
 
152
+ def gateway_home(tools_dir: str | Path) -> Path:
153
+ """The private gateway client context under ``tools_dir``. Existing parent links such as a
154
+ relocated ``~/.local`` resolve first; ``gateway-home`` itself is never resolved."""
155
+ return Path(hosts.tools_dir(tools_dir)).expanduser().resolve() / "gateway-home"
156
+
157
+
150
158
  def client_environment(tools_dir: str) -> dict[str, str]:
151
159
  """Settings written by an automatic stack stay in its private gateway context."""
152
- home = Path(tools_dir).expanduser() / "gateway-home"
160
+ home = gateway_home(tools_dir)
153
161
  return {
154
162
  "PI_CODING_AGENT_DIR": str(home / ".pi/agent"),
155
163
  "CODEX_HOME": str(home / ".codex"),
@@ -177,9 +185,9 @@ def gateway_environment(
177
185
  env.update(harness.client_environment(plan["tools_dir"]))
178
186
  return env
179
187
  env["MAGPIE_ADDR"] = action["path"]
188
+ home = Path(env.get("HOME", str(Path.home())))
180
189
  if "environment" not in plan and action["action"] != "daemon":
181
- home = Path(env.get("HOME", str(Path.home())))
182
- private = Path(plan["tools_dir"]).expanduser() / "gateway-home"
190
+ private = gateway_home(plan["tools_dir"])
183
191
  env.update(
184
192
  HOME=str(private),
185
193
  USERPROFILE=str(private),
@@ -278,7 +286,7 @@ def inspect(
278
286
  )
279
287
  )
280
288
  if private_clients:
281
- pi_model = pi_settings_model(str(Path(tools_dir) / "gateway-home"))
289
+ pi_model = pi_settings_model(str(gateway_home(tools_dir)))
282
290
  for client, seen in clients.items():
283
291
  seen["files"] = stack_clients.config_files(client, gateway_env)
284
292
  if gateway_up and magpie and next(iter(seen["files"].values()), None) is not None:
@@ -133,6 +133,20 @@ def stack_apply_lock() -> Iterator[None]:
133
133
  yield
134
134
 
135
135
 
136
+ def stack_apply_running() -> bool:
137
+ """Whether another ``stack apply`` holds its lock now, probed with the same primitive it
138
+ takes (flock on POSIX, msvcrt on Windows) and released at once."""
139
+ path = stacks_dir() / ".apply.lock"
140
+ if not path.exists():
141
+ return False
142
+ with path.open("a+") as lock:
143
+ try:
144
+ _lock_file(lock, blocking=False)
145
+ except BlockingIOError:
146
+ return True
147
+ return False
148
+
149
+
136
150
  def _plan_path(dev_id: str, plan_id: str) -> Path:
137
151
  return state_dir() / "plans" / dev_id / f"{plan_id[:12]}.json"
138
152
 
@@ -408,8 +422,17 @@ def empty_owned() -> Owned:
408
422
  }
409
423
 
410
424
 
411
- def owned_path(tools_dir: str | Path = TOOLS_DIR) -> Path:
412
- return Path(os.path.expanduser(str(tools_dir)), "owned.json")
425
+ def tools_dir(given: str | Path = TOOLS_DIR) -> str:
426
+ """The tools root: ``LOCALMODELS_TOOLS_DIR`` overrides the default ``TOOLS_DIR``."""
427
+ if str(given) == TOOLS_DIR and (
428
+ override := os.environ.get("LOCALMODELS_TOOLS_DIR", "").strip()
429
+ ):
430
+ return override
431
+ return str(given)
432
+
433
+
434
+ def owned_path(given: str | Path = TOOLS_DIR) -> Path:
435
+ return Path(os.path.expanduser(tools_dir(given)), "owned.json")
413
436
 
414
437
 
415
438
  def load_owned(tools_dir: str | Path = TOOLS_DIR) -> Owned:
@@ -0,0 +1,59 @@
1
+ """Small Layer-0 stdlib helpers shared across controller modules.
2
+
3
+ Keeps no-proxy/no-redirect urllib openers, chunked SHA256 digests and 0600 private writes in one
4
+ ASCII/English-only place so higher modules avoid repeating the same boilerplate.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import os
11
+ import urllib.request
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ CHUNK_BYTES = 1 << 20
16
+
17
+
18
+ class NoRedirectHandler(urllib.request.HTTPRedirectHandler):
19
+ """Refuse HTTP redirects so local tokens and credentials never follow a redirect."""
20
+
21
+ def redirect_request(
22
+ self,
23
+ req: urllib.request.Request,
24
+ fp: Any,
25
+ code: int,
26
+ msg: str,
27
+ headers: Any,
28
+ newurl: str,
29
+ ) -> None:
30
+ return None
31
+
32
+
33
+ def no_proxy_opener(
34
+ *handlers: urllib.request.BaseHandler, allow_redirects: bool = True
35
+ ) -> urllib.request.OpenerDirector:
36
+ """Build an opener that bypasses environment HTTP proxies (and redirects when requested)."""
37
+ extra = () if allow_redirects else (NoRedirectHandler(),)
38
+ return urllib.request.build_opener(urllib.request.ProxyHandler({}), *extra, *handlers)
39
+
40
+
41
+ def sha256_file(path: Path, chunk_bytes: int = CHUNK_BYTES) -> str:
42
+ """Streaming SHA256 hex digest of ``path`` compatible with Python 3.10+."""
43
+ digest = hashlib.sha256()
44
+ with path.open("rb") as handle:
45
+ for chunk in iter(lambda: handle.read(chunk_bytes), b""):
46
+ digest.update(chunk)
47
+ return digest.hexdigest()
48
+
49
+
50
+ def write_private_text(path: Path, text: str) -> None:
51
+ """Atomically write UTF-8 ``text`` to ``path`` inside a 0700 parent with 0600 permissions."""
52
+ path.parent.mkdir(parents=True, exist_ok=True)
53
+ path.parent.chmod(0o700)
54
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
55
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
56
+ fd = os.open(temporary, flags, 0o600)
57
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
58
+ handle.write(text)
59
+ os.replace(temporary, path)
@@ -27,6 +27,25 @@ from localmodels.stack_summary import styled
27
27
  _REFUSED = (StackError, PlanError, harness.HarnessError, ValueError, KeyError)
28
28
 
29
29
 
30
+ def _refusal_hint(exc: Exception) -> str | None:
31
+ """Follow-up English command hint shown after an install refusal when none is embedded yet."""
32
+ text = str(exc).lower()
33
+ if "--" in text:
34
+ return None
35
+ if "no longer matches" in text:
36
+ return f"run `{command()} install --replan` to build a fresh plan for this host"
37
+ if any(word in text for word in ("not enough", "memory", "vram", "gpu", "already")):
38
+ return f"run `{command()} stack hardware` to inspect free memory, or try `--prefer fastest`"
39
+ return None
40
+
41
+
42
+ def _fail(exc: Exception) -> int:
43
+ print(f"install: {exc}", file=sys.stderr)
44
+ if hint := _refusal_hint(exc):
45
+ print(f" hint: {hint}", file=sys.stderr)
46
+ return 2
47
+
48
+
30
49
  def cli(args: argparse.Namespace) -> int:
31
50
  options = stack.options_from_args(args)
32
51
  explicit = getattr(args, "gateway", None) is not None
@@ -47,8 +66,7 @@ def cli(args: argparse.Namespace) -> int:
47
66
  report = stack_up.up(installed, share_gpu=args.share_gpu, out=shown.print)
48
67
  return stack_up.print_report(report)
49
68
  except _REFUSED as exc:
50
- print(f"install: {exc}", file=sys.stderr)
51
- return 2
69
+ return _fail(exc)
52
70
  try:
53
71
  with console.status("Probing this computer and pricing the whole stack…"):
54
72
  if (
@@ -59,8 +77,7 @@ def cli(args: argparse.Namespace) -> int:
59
77
  plan = stack.build(options)
60
78
  path = stack.save(plan)
61
79
  except _REFUSED as exc:
62
- print(f"install: {exc}", file=sys.stderr)
63
- return 2
80
+ return _fail(exc)
64
81
  print(styled(stack.summary(plan, path, apply_line=False)))
65
82
  seen = plan.get("hardware")
66
83
  offered = seen.get("picks", []) if seen else []
@@ -81,8 +98,7 @@ def cli(args: argparse.Namespace) -> int:
81
98
  plan = stack.build(options)
82
99
  path = stack.save(plan)
83
100
  except _REFUSED as exc:
84
- print(f"install: {exc}", file=sys.stderr)
85
- return 2
101
+ return _fail(exc)
86
102
  print(styled(stack.summary(plan, path, apply_line=False)))
87
103
  answer = _confirm(None)
88
104
  if answer != "y":
@@ -96,8 +112,7 @@ def cli(args: argparse.Namespace) -> int:
96
112
  with board:
97
113
  record = stack.apply(plan, plan["plan_id"], log=board)
98
114
  except _REFUSED as exc:
99
- print(f"install: {exc}", file=sys.stderr)
100
- return 2
115
+ return _fail(exc)
101
116
  return stack.report(record, timing=board.timing())
102
117
 
103
118
 
@@ -23,6 +23,7 @@ from pathlib import Path
23
23
  from typing import Any
24
24
 
25
25
  from localmodels import (
26
+ bifrost_config,
26
27
  bifrost_datasheet,
27
28
  bifrost_models,
28
29
  bifrost_unit,
@@ -39,6 +40,8 @@ from localmodels.probe import HostFacts
39
40
  from localmodels.records import Plan
40
41
 
41
42
  PROVIDER_PREFIX = "localmodels-lib-"
43
+ # Windows cannot delete the config store a running Bifrost holds open: stop it before a change.
44
+ STOP_BEFORE_CONFIG_CHANGE = os.name == "nt"
42
45
  PI_PROVIDER = "localmodels-library"
43
46
 
44
47
 
@@ -60,7 +63,7 @@ def pi_profile() -> Path:
60
63
  given = os.environ.get("PI_CODING_AGENT_DIR")
61
64
  if given:
62
65
  return Path(given).expanduser()
63
- return Path(harness_probe.client_environment(hosts.TOOLS_DIR)["PI_CODING_AGENT_DIR"])
66
+ return Path(harness_probe.client_environment(hosts.tools_dir())["PI_CODING_AGENT_DIR"])
64
67
 
65
68
 
66
69
  def _fail(detail: str) -> LibraryError:
@@ -80,16 +83,15 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
80
83
  }
81
84
  platform = "linux" if facts["platform"].startswith("linux") else facts["platform"]
82
85
  systemd = facts["service_manager"]["kind"] == "systemd-user"
83
- actions, _ = gateway_bifrost.plan_tools(
84
- state, platform, facts["arch"], systemd, hosts.TOOLS_DIR
85
- )
86
+ tools_root = hosts.tools_dir()
87
+ actions, _ = gateway_bifrost.plan_tools(state, platform, facts["arch"], systemd, tools_root)
86
88
  plan: harness.ToolPlan = {
87
- "tools_dir": hosts.TOOLS_DIR,
89
+ "tools_dir": tools_root,
88
90
  "tools": actions,
89
91
  "download_bytes": 0,
90
92
  "warnings": [],
91
93
  }
92
- tools = Path(os.path.expanduser(hosts.TOOLS_DIR))
94
+ tools = Path(os.path.expanduser(tools_root))
93
95
  binary = next(a for a in actions if a["tool"] == "bifrost")
94
96
  if binary["action"] == "install":
95
97
  made = gateway_bifrost.install_binary(tools, binary, lambda _line: None)
@@ -150,6 +152,14 @@ def _apply(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict[str,
150
152
  and config kept, and the next load starts it again."""
151
153
  app = Path(record["app_dir"])
152
154
  params = {bifrost_datasheet.DATASHEET: sheet, bifrost_datasheet.PARAMETERS: {}}
155
+ if (
156
+ STOP_BEFORE_CONFIG_CHANGE
157
+ and record["how"] != "unit"
158
+ and bifrost_config.differs(app, config, params)
159
+ ):
160
+ # A change drops the config store, which Windows cannot delete while Bifrost holds it
161
+ # open (WinError 32 on unload, homewin): stop it first; it restarts on the change.
162
+ gateway_bifrost._stop_serve(app)
153
163
  changed = gateway_bifrost._write_config(app, config, params)
154
164
  if not config.get("providers"):
155
165
  _stop(record)
@@ -456,9 +466,10 @@ def _unwire_member(registration: Registration) -> None:
456
466
  providers = config.get("providers") or {}
457
467
  providers.pop(registration["provider"], None)
458
468
  if not any(p in providers for p in STACK_PROVIDERS): # the last stack LLM
459
- environment = {**os.environ, **harness_probe.client_environment(hosts.TOOLS_DIR)}
460
- checks = bifrost_clients.unwire(hosts.TOOLS_DIR, environment=environment)
461
- checks += bifrost_pi.unpoint_pi(hosts.TOOLS_DIR, environment=environment)
469
+ tools_root = hosts.tools_dir()
470
+ environment = {**os.environ, **harness_probe.client_environment(tools_root)}
471
+ checks = bifrost_clients.unwire(tools_root, environment=environment)
472
+ checks += bifrost_pi.unpoint_pi(tools_root, environment=environment)
462
473
  failed = [c["detail"] for c in checks if not c["ok"]]
463
474
  if failed:
464
475
  raise _fail("; ".join(failed))