@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
@@ -49,8 +49,6 @@ GIB, MIB = 1 << 30, 1 << 20
49
49
  DEFAULT_CONTEXTS = (65536, 131072, 262144)
50
50
  MAX_SLOTS = 64 # the largest concurrency max_slots searches
51
51
  MAX_CONTEXT = 1 << 24 # the longest per-slot context max_context searches
52
- DEVICE_PARTS = ("weights", "kv", "state", "compute", "draft", "process", "vision")
53
- HOST_PARTS = ("embedding", "process", "checkpoints", "prompt_cache", "vision")
54
52
 
55
53
 
56
54
  @dataclass(frozen=True)
@@ -17,7 +17,7 @@ from collections.abc import Sequence
17
17
  from typing import TypedDict
18
18
 
19
19
  from localmodels import catalog as cat
20
- from localmodels import llm_rank
20
+ from localmodels import catalog_recipes, llm_rank
21
21
 
22
22
  # A second choice has to be worth offering: at least this much faster than the smartest.
23
23
  WORTH_FASTER = 1.2
@@ -35,8 +35,8 @@ class Fit(_FitPolicy):
35
35
  id: str
36
36
  quant: str
37
37
  quality: int
38
- decode_tok_s: float # calibrated estimate, or a same-device measurement
39
- decode_basis: str # a catalog.DECODE_BASES key
38
+ decode_tok_s: float | None # calibrated estimate, same-device measurement, or None (Strata)
39
+ decode_basis: str # a catalog.DECODE_BASES key, or "unavailable"
40
40
 
41
41
 
42
42
  class Pick(Fit):
@@ -56,10 +56,10 @@ class CardFits(TypedDict):
56
56
  llm: list[Fit]
57
57
 
58
58
 
59
- def picks(cards: Sequence[CardFits], default: str | None = None) -> list[Pick]:
59
+ def picks(cards: Sequence[CardFits], ladder: llm_rank.MacLadder | None = None) -> list[Pick]:
60
60
  """The smartest fitting LLM, then the fastest when it is another model and worth it. Each
61
61
  model counts on the first card that holds it, in the order ``--llm auto`` tries cards (most
62
- free memory first); ``default`` is the small-Mac default (llm_rank.mac_default). When every
62
+ free memory first); ``ladder`` is the Mac small-memory ladder (llm_rank.mac_ladder). When every
63
63
  card that holds a model runs another program's service (a shared Mac's one GPU), the picks
64
64
  are what sharing it would install and say so. Empty when nothing eligible fits."""
65
65
  free = [c for c in cards if c["auto"] and c["llm"]]
@@ -69,16 +69,46 @@ def picks(cards: Sequence[CardFits], default: str | None = None) -> list[Pick]:
69
69
  found.setdefault(
70
70
  fit["id"], {**fit, "role": "", "card": card["index"], "shared": not free}
71
71
  )
72
- if not found:
72
+ strata_ids = {
73
+ c["id"] for c in catalog_recipes.components() if c["runtime"] in ("strata", "strata-poly")
74
+ }
75
+ llama_scores = [
76
+ p["quality"]
77
+ for p in found.values()
78
+ if p["decode_tok_s"] is not None
79
+ and p["id"] not in strata_ids
80
+ and not p.get("candidate_fallback")
81
+ ]
82
+ bar = llm_rank.strata_bar(max(llama_scores, default=-1), {})
83
+ eligible = [
84
+ p
85
+ for p in found.values()
86
+ if (p["decode_tok_s"] is not None and p["id"] not in strata_ids) or p["quality"] >= bar
87
+ ]
88
+ if not eligible:
73
89
  return []
74
- ranked = [((p["quality"], p["decode_tok_s"]), p["id"], p["card"]) for p in found.values()]
75
- fallback_ids = {p["id"] for p in found.values() if p.get("candidate_fallback")}
76
- smartest = found[llm_rank.choose(ranked, "smartest", default, fallback_ids=fallback_ids)[0]]
77
- fastest = found[llm_rank.choose(ranked, "fastest", fallback_ids=fallback_ids)[0]]
90
+ ranked = [
91
+ (
92
+ (p["quality"], -1.0 if p["decode_tok_s"] is None else p["decode_tok_s"]),
93
+ p["id"],
94
+ p["card"],
95
+ )
96
+ for p in eligible
97
+ ]
98
+ fallback_ids = {p["id"] for p in eligible if p.get("candidate_fallback")}
99
+ smartest = found[llm_rank.choose(ranked, "smartest", ladder, fallback_ids=fallback_ids)[0]]
100
+ llama_ranked = [row for row in ranked if row[1] not in strata_ids]
101
+ fastest = (
102
+ found[llm_rank.choose(llama_ranked, "fastest", ladder, fallback_ids=fallback_ids)[0]]
103
+ if llama_ranked
104
+ else smartest
105
+ )
78
106
  offered: list[Pick] = [{**smartest, "role": "smartest"}]
107
+ fast_speed, smart_speed = fastest["decode_tok_s"], smartest["decode_tok_s"]
79
108
  if (
80
109
  fastest["id"] != smartest["id"]
81
- and fastest["decode_tok_s"] >= smartest["decode_tok_s"] * WORTH_FASTER
110
+ and fast_speed is not None
111
+ and (smart_speed is None or fast_speed >= smart_speed * WORTH_FASTER)
82
112
  ):
83
113
  offered.append({**fastest, "role": "fastest"})
84
114
  return offered
@@ -97,8 +127,12 @@ def second(offered: list[Pick], chosen: str) -> Pick | None:
97
127
  def label(pick: Fit) -> str:
98
128
  """One pick in a line: model, score, speed and what the speed rests on."""
99
129
  score = f"score {pick['quality']}" if pick["quality"] else "no SimplexAI score"
100
- measured = pick["decode_basis"] == "measured-decode"
101
- speed = f"{pick['decode_tok_s']:.0f} tok/s " + ("measured" if measured else "estimated")
130
+ tok_s = pick["decode_tok_s"]
131
+ if tok_s is None:
132
+ speed = "speed unavailable"
133
+ else:
134
+ measured = pick["decode_basis"] == "measured-decode"
135
+ speed = f"{tok_s:.0f} tok/s " + ("measured" if measured else "estimated")
102
136
  candidate = " · candidate product fallback" if pick.get("candidate_fallback") else ""
103
137
  return f"{pick['id']} {pick['quant']} · {score} · {speed}{candidate}"
104
138
 
@@ -126,13 +160,26 @@ def lines(offered: list[Pick], command: str | None) -> list[str]:
126
160
  )
127
161
  if any(p.get("candidate_fallback") for p in offered):
128
162
  out.append(f" {llm_rank.WINDOWS_FALLBACK_WARNING}")
129
- if any(p["decode_basis"] != "measured-decode" for p in offered):
130
- bases = sorted({p["decode_basis"] for p in offered} - {"measured-decode"})
163
+ bases = sorted(
164
+ {
165
+ p["decode_basis"]
166
+ for p in offered
167
+ if p["decode_tok_s"] is not None
168
+ and p["decode_basis"] != "measured-decode"
169
+ and p["decode_basis"] in cat.DECODE_BASES
170
+ }
171
+ )
172
+ if bases:
131
173
  out.append(
132
174
  " estimated speeds come from "
133
175
  + "; ".join(cat.DECODE_BASES[b] for b in bases)
134
176
  + ", without speculative decoding; stack warm measures the installed one"
135
177
  )
178
+ if any(p["decode_tok_s"] is None for p in offered):
179
+ out.append(
180
+ " Strata/PolyStrata decode speed is not estimated; "
181
+ "stack warm measures the installed one"
182
+ )
136
183
  return out
137
184
 
138
185
 
@@ -192,8 +192,26 @@ class DecisionOption(TypedDict):
192
192
  LlmFit = Fit
193
193
 
194
194
 
195
+ class CapacityFit(TypedDict):
196
+ """GPU-only reference; never permission to install or new validation evidence."""
197
+
198
+ id: str
199
+ quant: str
200
+ status: str
201
+ validated_on: list[str]
202
+ admission: str
203
+ fits_now: bool
204
+ fits_total: bool
205
+ window: int
206
+ slots: int
207
+ vision: str
208
+ kv_types: list[str]
209
+ needed_free_bytes: int
210
+
211
+
195
212
  class _CardSince20261028(TypedDict, total=False):
196
213
  uuid: str # added after hardware snapshots were introduced
214
+ capacity: list[CapacityFit] # inspection only; absent from saved plan snapshots
197
215
 
198
216
 
199
217
  class Card(_CardSince20261028):
@@ -412,7 +430,7 @@ def default_options() -> StackOptions:
412
430
  "offline": False,
413
431
  "slots": 2,
414
432
  "tts": False,
415
- "search": True,
433
+ "search": False,
416
434
  "reasoning_budget": REASONING_BUDGET,
417
435
  "gateway": default_gateway(),
418
436
  "vision": vision.DEFAULT,
@@ -631,27 +631,19 @@ def _running(plan: StackPlan) -> list[Finding]:
631
631
 
632
632
 
633
633
  def _apply_lock() -> list[Finding]:
634
- path = hosts.stacks_dir() / ".apply.lock"
635
- if not path.exists():
636
- return [finding("preflight.apply", "pass", "no other stack apply is running")]
637
634
  try:
638
- import fcntl
639
-
640
- with path.open("a") as lock:
641
- try:
642
- fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
643
- except BlockingIOError:
644
- return [
645
- finding(
646
- "preflight.apply",
647
- "warn",
648
- "another stack apply is running; its services and memory are changing",
649
- "wait for it to finish, then run stack plan again",
650
- )
651
- ]
652
- fcntl.flock(lock, fcntl.LOCK_UN)
653
- except (OSError, ImportError):
635
+ running = hosts.stack_apply_running()
636
+ except OSError:
654
637
  return []
638
+ if running:
639
+ return [
640
+ finding(
641
+ "preflight.apply",
642
+ "warn",
643
+ "another stack apply is running; its services and memory are changing",
644
+ "wait for it to finish, then run stack plan again",
645
+ )
646
+ ]
655
647
  return [finding("preflight.apply", "pass", "no other stack apply is running")]
656
648
 
657
649
 
@@ -26,7 +26,14 @@ class JsonlObserver:
26
26
  self.output.flush()
27
27
 
28
28
 
29
- def result(ok: bool, components: Iterable[tuple[str, str]], *, profile: str | None = None) -> int:
29
+ def result(
30
+ ok: bool,
31
+ components: Iterable[tuple[str, str]],
32
+ *,
33
+ profile: str | None = None,
34
+ cause: str | None = None,
35
+ ) -> int:
36
+ """The final JSONL line; ``cause`` is the fixed public code of a run that did not pass."""
30
37
  print(
31
38
  json.dumps(
32
39
  {
@@ -35,6 +42,7 @@ def result(ok: bool, components: Iterable[tuple[str, str]], *, profile: str | No
35
42
  "components": [
36
43
  {"component": component, "status": status} for component, status in components
37
44
  ],
45
+ **({"causeCode": cause} if cause is not None and not ok else {}),
38
46
  **(
39
47
  {"profile": "macos-mlx-preview", "product_acceptance": "incomplete"}
40
48
  if profile == "macos-mlx-preview"
@@ -0,0 +1,373 @@
1
+ """Dependency-ordered uninstall, purge confirmation and orphan adoption helpers for stack remove."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from collections.abc import Callable
8
+ from pathlib import Path
9
+
10
+ from localmodels import (
11
+ deploy,
12
+ gateway,
13
+ gateway_probe,
14
+ harness,
15
+ harness_gateway,
16
+ hosts,
17
+ stack_cleanup,
18
+ )
19
+ from localmodels.budget import gib
20
+ from localmodels.contracts import decode
21
+ from localmodels.records import FinishedRecord, Plan
22
+ from localmodels.remote_ops import RemoveParams, StrataPreparation
23
+ from localmodels.stack_plan import StackError, command, platform_error
24
+ from localmodels.transport import Executor
25
+
26
+ CONFIRM_WORD = "purge"
27
+ UNIT_DIR = harness.UNIT_DIR
28
+
29
+ Out = Callable[[str], None]
30
+ Listing = stack_cleanup.Listing
31
+ Confirm = Callable[[str], bool]
32
+ ActFn = Callable[[Executor, RemoveParams], dict[str, object]]
33
+ RemoveServicesFn = Callable[
34
+ [
35
+ Executor,
36
+ dict[str, hosts.OwnedDeployment],
37
+ dict[str, RemoveParams],
38
+ bool,
39
+ list[gateway.Check],
40
+ ],
41
+ list[gateway.Check],
42
+ ]
43
+
44
+
45
+ def _params(name: str, kind: str, deploy_dir: str, port: int) -> RemoveParams:
46
+ return {
47
+ "deploy_dir": deploy_dir,
48
+ "service": name,
49
+ "service_kind": kind,
50
+ "port": port,
51
+ "api_key": "",
52
+ }
53
+
54
+
55
+ def plan_params(plan: Plan) -> RemoveParams:
56
+ svc = plan["service"]
57
+ params = _params(svc["name"], svc["kind"], svc["deploy_dir"], svc["port"])
58
+ params["config_files"] = list(svc.get("config_files") or {})
59
+ if raw := plan["launch"].get("preparation"):
60
+ params["preparation_dir"] = decode(raw, StrataPreparation)["model_dir"]
61
+ return params
62
+
63
+
64
+ def owned_params(name: str, entry: hosts.OwnedDeployment) -> RemoveParams:
65
+ """From the manifest; the deployment's record, when there is one, names its config files."""
66
+ params = _params(entry["service"], entry["kind"], entry["deploy_dir"], entry["port"])
67
+ try:
68
+ params = {**plan_params(hosts.record(hosts.LOCAL_ID, name)["plan"]), **params}
69
+ except KeyError:
70
+ pass
71
+ if entry.get("preparation_dir"):
72
+ params["preparation_dir"] = entry["preparation_dir"]
73
+ return params
74
+
75
+
76
+ def plan_purge(params: RemoveParams, files: list[str], keep: set[str]) -> None:
77
+ """List removable model files; shared inputs also keep their preparation workspace."""
78
+ expanded = [os.path.expanduser(f) for f in files]
79
+ if any(f in keep for f in expanded):
80
+ params.pop("preparation_dir", None)
81
+ kept = (".sha256", ".part", ".part.ranges") # .part.ranges: a parallel download's record
82
+ params["purge_files"] = [
83
+ p for f in expanded if f not in keep for p in (f, *(f + k for k in kept))
84
+ ]
85
+
86
+
87
+ def in_use(records: list[FinishedRecord], skip: set[str]) -> set[str]:
88
+ return {
89
+ os.path.expanduser(f["dest"])
90
+ for r in records
91
+ if r["plan"]["name"] not in skip
92
+ for f in r["plan"]["files"]
93
+ }
94
+
95
+
96
+ def listing(event: dict[str, object]) -> Listing:
97
+ if event.get("event") != "result":
98
+ raise OSError(str(event.get("message") or "cannot list the files to delete"))
99
+ rows = decode(event.get("files", []), list[list[object]])
100
+ return [(str(r[0]), int(str(r[1])), int(str(r[2]))) for r in rows]
101
+
102
+
103
+ def ask(prompt: str) -> bool:
104
+ if not sys.stdin.isatty():
105
+ return False
106
+ return input(prompt).strip() == CONFIRM_WORD
107
+
108
+
109
+ def approve(found: Listing, yes: bool, out: Out, confirm: Confirm) -> bool:
110
+ """Show every file a purge deletes and its total; go on only with --yes or the word."""
111
+ total = sum(size for _, size, _ in found)
112
+ out(f"--purge will delete these {len(found)} files, {gib(total)} ({total} bytes):")
113
+ for path, size, links in found:
114
+ shared = ", hard link, deleting it frees no space" if links > 1 else ""
115
+ out(f" {path} ({size} bytes{shared})")
116
+ if yes or confirm(f"Type {CONFIRM_WORD} to delete (anything else cancels): "):
117
+ return True
118
+ out(f"Nothing deleted: type {CONFIRM_WORD} to confirm, or add --yes when not interactive")
119
+ return False
120
+
121
+
122
+ def drop_slices(doc: hosts.Owned) -> list[gateway.Check]:
123
+ """A suite slice file goes once no unit runs in it (remote_ops does the same per unit)."""
124
+ units = Path(os.path.expanduser(UNIT_DIR))
125
+ texts = [p.read_text(encoding="utf-8") for p in units.glob("*.service")]
126
+ checks: list[gateway.Check] = []
127
+ for name in doc["slices"]:
128
+ path = units / name
129
+ if any(f"Slice={name}\n" in t for t in texts):
130
+ checks.append({"check": f"slice {name}", "ok": False, "detail": "in use, kept"})
131
+ continue
132
+ if path.is_file() and "Description=localmodels suite" in path.read_text(encoding="utf-8"):
133
+ path.unlink()
134
+ harness.run_tool(["systemctl", "--user", "daemon-reload"], timeout=30)
135
+ checks.append({"check": f"slice {name}", "ok": True, "detail": "deleted"})
136
+
137
+ def drop(d: hosts.Owned, name: str = name) -> None:
138
+ d["slices"] = [s for s in d["slices"] if s != name]
139
+
140
+ hosts.update_owned(drop)
141
+ return checks
142
+
143
+
144
+ def list_files(
145
+ executor: Executor,
146
+ entries: dict[str, hosts.OwnedDeployment],
147
+ plans: dict[str, RemoveParams],
148
+ keep: set[str],
149
+ weights: bool,
150
+ *,
151
+ act: ActFn,
152
+ ) -> Listing:
153
+ """Each deployment's dry run fills in the files its removal deletes: everything in its
154
+ directory, and with ``weights`` its model files that nothing else uses."""
155
+ found_all: Listing = []
156
+ for name, entry in entries.items():
157
+ plan_purge(plans[name], entry["files"] if weights else [], keep)
158
+ found = listing(act(executor, {**plans[name], "dry_run": True}))
159
+ plans[name]["purge"] = [path for path, _, _ in found]
160
+ found_all += found
161
+ return found_all
162
+
163
+
164
+ def remove_services(
165
+ executor: Executor,
166
+ entries: dict[str, hosts.OwnedDeployment],
167
+ plans: dict[str, RemoveParams],
168
+ weights: bool,
169
+ unwire_checks: list[gateway.Check],
170
+ *,
171
+ act: ActFn,
172
+ ) -> list[gateway.Check]:
173
+ """Stop and remove each service with its directory. A deployment whose model files stay
174
+ remains in the manifest as removed, so a later ``--purge`` finds them."""
175
+ if not all(check["ok"] for check in unwire_checks):
176
+ return []
177
+ checks: list[gateway.Check] = []
178
+ for name, entry in entries.items():
179
+ result = act(executor, plans[name])
180
+ ok = result.get("event") == "result"
181
+ kept = (
182
+ [] if weights else [f for f in entry["files"] if os.path.lexists(os.path.expanduser(f))]
183
+ )
184
+ done = f"removed with its directory ({result.get('purged', 0)} files)"
185
+ done += f", {len(kept)} model file(s) kept" if kept else ""
186
+ checks.append(
187
+ {"check": name, "ok": ok, "detail": done if ok else str(result.get("message"))}
188
+ )
189
+ if ok:
190
+ hosts.delete_record(hosts.LOCAL_ID, name, purged=not kept)
191
+ return checks
192
+
193
+
194
+ def remove_tools(
195
+ doc: hosts.Owned, magpie: str | None, plan: harness.ToolPlan | None = None
196
+ ) -> tuple[list[gateway.Check], list[str]]:
197
+ """The gateway this tool started goes before the Magpie it runs, then the tools and the
198
+ archives they were installed from. A Magpie that changed since install (it updates itself)
199
+ keeps its gateway: other providers may use it. Every tool leaves the manifest, deleted or
200
+ kept with the reason printed."""
201
+ checks: list[gateway.Check] = []
202
+ notes: list[str] = []
203
+ started = doc["gateway"]["started"]
204
+ ours = next((t for t in doc["tools"] if Path(t["path"]).name == "magpie"), None)
205
+ drift = harness.changed(ours) if ours and os.path.lexists(ours["path"]) else None
206
+ if started and magpie and ours and drift:
207
+ hosts.own_gateway(hosts.TOOLS_DIR, "started", None)
208
+ notes.append(
209
+ f"- gateway ({started}) kept: {ours['path']} {drift}; it may serve other providers"
210
+ )
211
+ elif started and magpie:
212
+ gateway_check = gateway.stop_gateway(magpie, started, plan=plan)
213
+ checks.append(gateway_check)
214
+ if not gateway_check["ok"]:
215
+ notes.append("- tools kept: stopping the gateway failed; fix it and rerun stack remove")
216
+ return checks, notes
217
+ gone, kept = harness.remove_tools(doc, True)
218
+ tools = {t["path"] for t in doc["tools"]}
219
+ archives = set(doc["archives"])
220
+
221
+ def forget(d: hosts.Owned) -> None:
222
+ d["tools"] = [t for t in d["tools"] if t["path"] not in tools]
223
+ d["archives"] = [a for a in d["archives"] if a not in archives]
224
+
225
+ hosts.update_owned(forget)
226
+ notes += [f"- kept {path}: {reason}" for path, reason in kept.items()]
227
+ if gone:
228
+ checks.append({"check": "tools", "ok": True, "detail": "deleted " + ", ".join(gone)})
229
+ return checks, notes
230
+
231
+
232
+ def outside(members: set[str], doc: hosts.Owned) -> dict[str, bool]:
233
+ """Deployments this computer has that no stack apply deployed, and whether each still has
234
+ a record (``service local NAME remove`` needs one)."""
235
+ found = {r["plan"]["name"]: True for r in hosts.records(hosts.LOCAL_ID)}
236
+ found |= {n: found.get(n, False) for n in doc["deployments"]}
237
+ return {n: has for n, has in sorted(found.items()) if n not in members}
238
+
239
+
240
+ def chosen(members: set[str], doc: hosts.Owned, everything: bool, out: Out) -> set[str]:
241
+ """The deployments this uninstall takes: the stack's; those an earlier remove left only
242
+ model files of; one whose directory is gone (cleared from the manifest); and with
243
+ ``everything`` the rest. A deployment of another kind, or one recorded under another state
244
+ directory, is named and left alone: it may be serving."""
245
+ selected = set(members)
246
+ for name, has_record in outside(members, doc).items():
247
+ entry = doc["deployments"].get(name)
248
+ live = entry is not None and not entry["removed"]
249
+ here = live and os.path.isdir(os.path.expanduser(doc["deployments"][name]["deploy_dir"]))
250
+ if everything or (entry is not None and not has_record and not here):
251
+ if live and not here:
252
+ out(f"- {name}: its directory is gone; cleared from the manifest")
253
+ selected.add(name)
254
+ continue
255
+ how = (
256
+ f"use service local {name} remove"
257
+ if has_record
258
+ else "it has no deployment record here (another state directory may manage it)"
259
+ )
260
+ out(f"- {name}: not part of this stack, left unchanged; {how}, or stack remove --all")
261
+ return selected
262
+
263
+
264
+ def teardown(
265
+ doc: hosts.Owned,
266
+ entries: dict[str, hosts.OwnedDeployment],
267
+ plans: dict[str, RemoveParams],
268
+ executor: Executor,
269
+ target: harness.ToolPlan | None,
270
+ weights: bool,
271
+ serve_log: str,
272
+ *,
273
+ remove_services_fn: RemoveServicesFn,
274
+ ) -> tuple[list[gateway.Check], list[str]]:
275
+ """Clients, services, then gateway and tools, each only when the step before succeeded."""
276
+ magpie = gateway_probe.magpie_binary(doc)
277
+ magpie_plan = harness_gateway.magpie_target(hosts.TOOLS_DIR) # past a verified Bifrost move
278
+ checks = gateway.unwire(magpie, plan=target, magpie_plan=magpie_plan)
279
+ checks += remove_services_fn(executor, entries, plans, weights, checks)
280
+ if all(check["ok"] for check in checks):
281
+ tool_checks, notes = remove_tools(doc, magpie, magpie_plan or target)
282
+ else:
283
+ tool_checks, notes = [], ["- tools kept: earlier step failed; fix and rerun stack remove"]
284
+ checks += tool_checks
285
+ if all(check["ok"] for check in checks):
286
+ harness_gateway.purge_gateway_profile(target, notes)
287
+ if os.path.isfile(serve_log):
288
+ os.remove(serve_log)
289
+ return checks + drop_slices(hosts.load_owned()), notes
290
+
291
+
292
+ def run_remove(
293
+ purge: bool,
294
+ yes: bool,
295
+ out: Out = print,
296
+ confirm: Confirm = ask,
297
+ *,
298
+ everything: bool = False,
299
+ dry_run: bool = False,
300
+ act: ActFn,
301
+ remove_services_fn: RemoveServicesFn,
302
+ members_fn: Callable[[], set[str]],
303
+ owned_params_fn: Callable[[str, hosts.OwnedDeployment], RemoveParams] = owned_params,
304
+ ) -> int:
305
+ if sys.platform != "darwin" and (error := platform_error(sys.platform)):
306
+ raise StackError(error)
307
+ members = members_fn()
308
+ doc = stack_cleanup.adopted(members, dry_run, out)
309
+ target = harness_gateway.accepted_plan(hosts.TOOLS_DIR)
310
+ profile = harness_gateway.gateway_profile(target)
311
+ selected = chosen(members, doc, everything, out)
312
+ if any(t["sha256"] is None for t in doc["tools"]):
313
+ out(
314
+ f"- {hosts.owned_path()} lists tools by path only (manifest format before v1), "
315
+ "treated as legacy, unverified; neither remove nor --purge deletes them"
316
+ )
317
+ entries = {n: d for n, d in doc["deployments"].items() if n in selected}
318
+ doc = stack_cleanup.without_others_archives(doc, selected, out)
319
+ engines = stack_cleanup.engines_in_use() # before anything goes: what the stack ran
320
+ bases = {Path(os.path.expanduser(d["deploy_dir"])).parent.parent for d in entries.values()}
321
+ bases.add(Path(os.path.expanduser(deploy.DEFAULT_BASE_DIR)))
322
+ last = not set(outside(selected, doc)) # no deployment of another kind is left to read state
323
+ # A plain uninstall keeps the verified downloads beside the model files; a purge takes them.
324
+ downloads = [] if purge else stack_cleanup.kept_downloads(doc, engines, selected, last)
325
+ doc = {**doc, "archives": [a for a in doc["archives"] if a not in downloads]}
326
+ if hosts.owns_nothing({**doc, "deployments": entries}) and not (profile and profile.exists()):
327
+ return stack_cleanup.finish(engines, selected, bases, last, dry_run, out, downloads=purge)
328
+ executor = hosts.executor(hosts.get_device(hosts.LOCAL_ID))
329
+ plans = {n: owned_params_fn(n, d) for n, d in entries.items()}
330
+ serve_log = str(hosts.owned_path().parent / "magpie-serve.log")
331
+ keep = in_use(hosts.records(hosts.LOCAL_ID), selected)
332
+ keep |= {f for n, d in doc["deployments"].items() if n not in selected for f in d["files"]}
333
+ found = list_files(executor, entries, plans, keep, purge, act=act)
334
+ found += stack_cleanup.local_listing(
335
+ [*doc["archives"], serve_log, *([str(profile)] if profile else [])]
336
+ )
337
+ kept_weights = stack_cleanup.kept_weights(entries, found)
338
+ if dry_run:
339
+ swept = stack_cleanup.sweep(engines, selected, state=last, downloads=purge, dry_run=True)
340
+ kept = stack_cleanup.local_listing(downloads)
341
+ stack_cleanup.preview(found, kept_weights, swept, doc, out, kept)
342
+ return 0
343
+ if purge and not approve(found, yes, out, confirm):
344
+ return 1
345
+ checks, notes = teardown(
346
+ doc,
347
+ entries,
348
+ plans,
349
+ executor,
350
+ target,
351
+ purge,
352
+ serve_log,
353
+ remove_services_fn=remove_services_fn,
354
+ )
355
+ for check in checks:
356
+ out(f"{'✓' if check['ok'] else '✗'} {check['check']}: {check['detail']}")
357
+ for note in notes:
358
+ out(note)
359
+ if not all(c["ok"] for c in checks):
360
+ out(f"Not all removed; still recorded in {hosts.owned_path()}; fix and rerun stack remove")
361
+ return 1
362
+ stack_cleanup.finish(engines, selected, bases, last, False, out, quiet=True, downloads=purge)
363
+ stack_cleanup.record_downloads(downloads)
364
+ kept = stack_cleanup.local_listing(downloads)
365
+ weight = sum(size for _, size, _ in [*kept_weights, *kept])
366
+ out(
367
+ f"Removed. Kept {len(kept_weights)} model files and {len(kept)} downloaded archives, "
368
+ f"{gib(weight)}: the next install reuses them; {command()} stack remove --purge "
369
+ "deletes them"
370
+ if kept_weights or kept
371
+ else "Removed. Nothing this tool installed is left but the manifest's empty lock file"
372
+ )
373
+ return 0