@simplexai/localmodels-linux-x64 0.1.0-dev.35 → 0.1.0-dev.37

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 (126) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +124 -102
  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_config.py +188 -0
  7. package/modules/localmodels/budget.py +15 -2
  8. package/modules/localmodels/catalog.json +235 -2
  9. package/modules/localmodels/catalog.py +51 -320
  10. package/modules/localmodels/catalog_add.py +2 -8
  11. package/modules/localmodels/catalog_recipes.py +321 -0
  12. package/modules/localmodels/cli_parser.py +4 -1
  13. package/modules/localmodels/console.py +5 -4
  14. package/modules/localmodels/contracts.py +13 -3
  15. package/modules/localmodels/debug_cli.py +158 -0
  16. package/modules/localmodels/debug_mode.py +727 -0
  17. package/modules/localmodels/debug_stub_server.py +192 -0
  18. package/modules/localmodels/decode_calibration.json +1 -1
  19. package/modules/localmodels/decode_calibration.py +34 -17
  20. package/modules/localmodels/engines-strata-0.1.59.1.json +31 -0
  21. package/modules/localmodels/gateway.py +21 -155
  22. package/modules/localmodels/gateway_accept.py +201 -0
  23. package/modules/localmodels/gateway_bifrost.py +19 -184
  24. package/modules/localmodels/gateway_cli.py +11 -4
  25. package/modules/localmodels/gateway_foundations.py +2 -4
  26. package/modules/localmodels/gateway_probe.py +0 -1
  27. package/modules/localmodels/gateway_server.py +2 -3
  28. package/modules/localmodels/gpu_specs.py +12 -0
  29. package/modules/localmodels/guard.py +2 -7
  30. package/modules/localmodels/harness.py +16 -129
  31. package/modules/localmodels/harness_cleanup.py +135 -0
  32. package/modules/localmodels/harness_gateway.py +16 -14
  33. package/modules/localmodels/harness_probe.py +12 -4
  34. package/modules/localmodels/hosts.py +25 -2
  35. package/modules/localmodels/http_local.py +59 -0
  36. package/modules/localmodels/install.py +23 -8
  37. package/modules/localmodels/library_gateway.py +9 -9
  38. package/modules/localmodels/library_jobs.py +76 -27
  39. package/modules/localmodels/library_serve.py +12 -1
  40. package/modules/localmodels/library_state.py +6 -1
  41. package/modules/localmodels/llm_rank.py +155 -7
  42. package/modules/localmodels/metal_probe.py +11 -7
  43. package/modules/localmodels/probe.py +108 -174
  44. package/modules/localmodels/process_identity.py +109 -154
  45. package/modules/localmodels/process_windows.py +86 -0
  46. package/modules/localmodels/recommend.py +32 -3
  47. package/modules/localmodels/recommend_cli.py +14 -6
  48. package/modules/localmodels/remote_ops.py +65 -0
  49. package/modules/localmodels/remote_ops_download.py +2 -2
  50. package/modules/localmodels/remote_ops_prepare.py +19 -0
  51. package/modules/localmodels/remote_ops_service.py +14 -2
  52. package/modules/localmodels/runtime_args.py +10 -3
  53. package/modules/localmodels/runtime_auth.py +5 -9
  54. package/modules/localmodels/runtime_cli.py +128 -129
  55. package/modules/localmodels/runtime_discovery.py +84 -0
  56. package/modules/localmodels/runtime_install.py +101 -0
  57. package/modules/localmodels/runtime_releases.py +302 -0
  58. package/modules/localmodels/service_stop.py +8 -108
  59. package/modules/localmodels/service_upgrade.py +394 -63
  60. package/modules/localmodels/services_cli.py +24 -14
  61. package/modules/localmodels/setup_inspection.py +97 -9
  62. package/modules/localmodels/setup_text.py +7 -0
  63. package/modules/localmodels/sizecalc.py +0 -1
  64. package/modules/localmodels/stack.py +14 -221
  65. package/modules/localmodels/stack_arena.py +732 -0
  66. package/modules/localmodels/stack_args.py +15 -9
  67. package/modules/localmodels/stack_auto.py +384 -3
  68. package/modules/localmodels/stack_aux_gpu.py +4 -3
  69. package/modules/localmodels/stack_capacity.py +138 -0
  70. package/modules/localmodels/stack_cleanup.py +9 -4
  71. package/modules/localmodels/stack_cli.py +286 -0
  72. package/modules/localmodels/stack_compose.py +76 -32
  73. package/modules/localmodels/stack_console.py +9 -6
  74. package/modules/localmodels/stack_hardware.py +96 -270
  75. package/modules/localmodels/stack_hardware_text.py +263 -0
  76. package/modules/localmodels/stack_journal.py +3 -9
  77. package/modules/localmodels/stack_ledger.py +48 -18
  78. package/modules/localmodels/stack_lifecycle.py +33 -312
  79. package/modules/localmodels/stack_mcp.py +729 -0
  80. package/modules/localmodels/stack_memory.py +0 -2
  81. package/modules/localmodels/stack_picks.py +73 -18
  82. package/modules/localmodels/stack_plan.py +23 -5
  83. package/modules/localmodels/stack_preflight.py +11 -19
  84. package/modules/localmodels/stack_remove.py +373 -0
  85. package/modules/localmodels/stack_route.py +101 -17
  86. package/modules/localmodels/stack_suite.py +16 -10
  87. package/modules/localmodels/stack_summary.py +14 -0
  88. package/modules/localmodels/stack_try.py +238 -24
  89. package/modules/localmodels/stack_try_client.py +53 -15
  90. package/modules/localmodels/stack_try_docs.py +2 -2
  91. package/modules/localmodels/stack_view.py +24 -171
  92. package/modules/localmodels/stack_view_access.py +114 -1
  93. package/modules/localmodels/stack_view_agent.py +3 -13
  94. package/modules/localmodels/stack_view_hub.py +9 -10
  95. package/modules/localmodels/stack_view_llm.py +1 -1
  96. package/modules/localmodels/stack_view_sandbox.py +2 -2
  97. package/modules/localmodels/stack_view_schema.py +183 -0
  98. package/modules/localmodels/stack_view_serve.py +7 -1
  99. package/modules/localmodels/stack_view_service.py +1 -2
  100. package/modules/localmodels/stack_view_text.py +13 -9
  101. package/modules/localmodels/stack_warm.py +3 -0
  102. package/modules/localmodels/stack_warm_store.py +517 -0
  103. package/modules/localmodels/tui.py +28 -4
  104. package/modules/localmodels/tui_dialogs.py +136 -0
  105. package/modules/localmodels/tui_modals.py +279 -0
  106. package/modules/localmodels/tui_screen.py +113 -154
  107. package/modules/localmodels/tui_views.py +134 -203
  108. package/modules/localmodels/web/index.html +510 -101
  109. package/modules/localmodels/web/sizecalc/app.js +363 -10
  110. package/modules/localmodels/web/sizecalc/page.html +27 -3
  111. package/modules/localmodels/web/view/fleet.html +11 -2
  112. package/modules/localmodels/web/view/fleet.js +191 -17
  113. package/modules/localmodels/web/view/i18n.js +3 -2
  114. package/modules/localmodels/web/view/index.html +1 -1
  115. package/modules/localmodels/web/view/nav.js +22 -3
  116. package/modules/localmodels/web/view/view.css +63 -18
  117. package/modules/localmodels/web/view/view.js +169 -32
  118. package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/METADATA +1 -1
  119. package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/RECORD +120 -98
  120. package/package.json +1 -1
  121. package/tool.json +1 -1
  122. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  123. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/WHEEL +0 -0
  124. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/entry_points.txt +0 -0
  125. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/NOTICE +0 -0
  126. /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -8,7 +8,6 @@ import os
8
8
  import sys
9
9
  import urllib.error
10
10
  import urllib.request
11
- from collections.abc import Callable
12
11
  from pathlib import Path
13
12
  from typing import TypedDict
14
13
 
@@ -21,28 +20,31 @@ from localmodels import (
21
20
  gateway_probe,
22
21
  gateway_speed,
23
22
  harness,
24
- harness_gateway,
25
23
  hosts,
24
+ http_local,
26
25
  process_identity,
27
26
  remote_ops_launchd,
28
27
  stack_cleanup,
28
+ stack_remove,
29
29
  stack_run,
30
30
  )
31
31
  from localmodels.budget import gib
32
- from localmodels.contracts import decode
33
32
  from localmodels.records import FinishedRecord, Plan, ProgressEvent
34
- from localmodels.remote_ops import RemoveParams, StrataPreparation
33
+ from localmodels.remote_ops import RemoveParams
35
34
  from localmodels.remote_ops_service import listener_problem
36
- from localmodels.stack_plan import StackError, command, deployments, platform_error, start_here
35
+ from localmodels.stack_plan import command, start_here
36
+ from localmodels.stack_remove import plan_params as plan_params
37
37
  from localmodels.transport import Executor
38
38
 
39
39
  COMMANDS = ("status", "remove", "prune")
40
- CONFIRM_WORD = "purge"
40
+ CONFIRM_WORD = stack_remove.CONFIRM_WORD
41
41
  UNIT_DIR = harness.UNIT_DIR
42
42
 
43
- Out = Callable[[str], None]
44
- Listing = stack_cleanup.Listing
45
- Confirm = Callable[[str], bool]
43
+ Out = stack_remove.Out
44
+ Listing = stack_remove.Listing
45
+ Confirm = stack_remove.Confirm
46
+ _ask = stack_remove.ask
47
+ _owned_params = stack_remove.owned_params
46
48
 
47
49
 
48
50
  class Row(TypedDict):
@@ -146,7 +148,7 @@ def _health(plan: Plan) -> str:
146
148
  key = Path(os.path.expanduser(svc["deploy_dir"]), "api-key")
147
149
  if key.is_file():
148
150
  req.add_header("Authorization", "Bearer " + key.read_text(encoding="utf-8").strip())
149
- opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
151
+ opener = http_local.no_proxy_opener()
150
152
  try:
151
153
  with opener.open(req, timeout=3) as resp:
152
154
  body = json.loads(resp.read() or b"{}")
@@ -335,83 +337,6 @@ def _act(executor: Executor, params: RemoveParams) -> dict[str, object]:
335
337
  return executor.run_action("remove", params, timeout=600)[0]
336
338
 
337
339
 
338
- def _params(name: str, kind: str, deploy_dir: str, port: int) -> RemoveParams:
339
- return {
340
- "deploy_dir": deploy_dir,
341
- "service": name,
342
- "service_kind": kind,
343
- "port": port,
344
- "api_key": "",
345
- }
346
-
347
-
348
- def _owned_params(name: str, entry: hosts.OwnedDeployment) -> RemoveParams:
349
- """From the manifest; the deployment's record, when there is one, names its config files."""
350
- params = _params(entry["service"], entry["kind"], entry["deploy_dir"], entry["port"])
351
- try:
352
- params = {**plan_params(hosts.record(hosts.LOCAL_ID, name)["plan"]), **params}
353
- except KeyError:
354
- pass
355
- if entry.get("preparation_dir"):
356
- params["preparation_dir"] = entry["preparation_dir"]
357
- return params
358
-
359
-
360
- def plan_params(plan: Plan) -> RemoveParams:
361
- svc = plan["service"]
362
- params = _params(svc["name"], svc["kind"], svc["deploy_dir"], svc["port"])
363
- params["config_files"] = list(svc.get("config_files") or {})
364
- if raw := plan["launch"].get("preparation"):
365
- params["preparation_dir"] = decode(raw, StrataPreparation)["model_dir"]
366
- return params
367
-
368
-
369
- def _plan_purge(params: RemoveParams, files: list[str], keep: set[str]) -> None:
370
- """List removable model files; shared inputs also keep their preparation workspace."""
371
- expanded = [os.path.expanduser(f) for f in files]
372
- if any(f in keep for f in expanded):
373
- params.pop("preparation_dir", None)
374
- kept = (".sha256", ".part", ".part.ranges") # .part.ranges: a parallel download's record
375
- params["purge_files"] = [
376
- p for f in expanded if f not in keep for p in (f, *(f + k for k in kept))
377
- ]
378
-
379
-
380
- def _in_use(records: list[FinishedRecord], skip: set[str]) -> set[str]:
381
- return {
382
- os.path.expanduser(f["dest"])
383
- for r in records
384
- if r["plan"]["name"] not in skip
385
- for f in r["plan"]["files"]
386
- }
387
-
388
-
389
- def _listing(event: dict[str, object]) -> Listing:
390
- if event.get("event") != "result":
391
- raise OSError(str(event.get("message") or "cannot list the files to delete"))
392
- rows = decode(event.get("files", []), list[list[object]])
393
- return [(str(r[0]), int(str(r[1])), int(str(r[2]))) for r in rows]
394
-
395
-
396
- def _ask(prompt: str) -> bool:
397
- if not sys.stdin.isatty():
398
- return False
399
- return input(prompt).strip() == CONFIRM_WORD
400
-
401
-
402
- def _approve(listing: Listing, yes: bool, out: Out, confirm: Confirm) -> bool:
403
- """Show every file a purge deletes and its total; go on only with --yes or the word."""
404
- total = sum(size for _, size, _ in listing)
405
- out(f"--purge will delete these {len(listing)} files, {gib(total)} ({total} bytes):")
406
- for path, size, links in listing:
407
- shared = ", hard link, deleting it frees no space" if links > 1 else ""
408
- out(f" {path} ({size} bytes{shared})")
409
- if yes or confirm(f"Type {CONFIRM_WORD} to delete (anything else cancels): "):
410
- return True
411
- out(f"Nothing deleted: type {CONFIRM_WORD} to confirm, or add --yes when not interactive")
412
- return False
413
-
414
-
415
340
  def service_remove(
416
341
  dev_id: str,
417
342
  name: str,
@@ -426,61 +351,21 @@ def service_remove(
426
351
  executor = hosts.executor(hosts.get_device(dev_id))
427
352
  params = plan_params(record["plan"])
428
353
  if purge:
429
- keep = _in_use(hosts.records(dev_id), {name})
354
+ keep = stack_remove.in_use(hosts.records(dev_id), {name})
430
355
  if dev_id == hosts.LOCAL_ID:
431
356
  others = hosts.load_owned()["deployments"]
432
357
  keep |= {f for n, d in others.items() if n != name for f in d["files"]}
433
- _plan_purge(params, [f["dest"] for f in record["plan"]["files"]], keep)
434
- listing = _listing(_act(executor, {**params, "dry_run": True}))
435
- if not _approve(listing, yes, out, confirm):
358
+ stack_remove.plan_purge(params, [f["dest"] for f in record["plan"]["files"]], keep)
359
+ found = stack_remove.listing(_act(executor, {**params, "dry_run": True}))
360
+ if not stack_remove.approve(found, yes, out, confirm):
436
361
  return None
437
- params["purge"] = [path for path, _, _ in listing]
362
+ params["purge"] = [path for path, _, _ in found]
438
363
  result = _act(executor, params)
439
364
  if result.get("event") == "result":
440
365
  hosts.delete_record(dev_id, name, purged=purge)
441
366
  return result
442
367
 
443
368
 
444
- def _drop_slices(doc: hosts.Owned) -> list[gateway.Check]:
445
- """A suite slice file goes once no unit runs in it (remote_ops does the same per unit)."""
446
- units = Path(os.path.expanduser(UNIT_DIR))
447
- texts = [p.read_text(encoding="utf-8") for p in units.glob("*.service")]
448
- checks: list[gateway.Check] = []
449
- for name in doc["slices"]:
450
- path = units / name
451
- if any(f"Slice={name}\n" in t for t in texts):
452
- checks.append({"check": f"slice {name}", "ok": False, "detail": "in use, kept"})
453
- continue
454
- if path.is_file() and "Description=localmodels suite" in path.read_text(encoding="utf-8"):
455
- path.unlink()
456
- harness.run_tool(["systemctl", "--user", "daemon-reload"], timeout=30)
457
- checks.append({"check": f"slice {name}", "ok": True, "detail": "deleted"})
458
-
459
- def drop(d: hosts.Owned, name: str = name) -> None:
460
- d["slices"] = [s for s in d["slices"] if s != name]
461
-
462
- hosts.update_owned(drop)
463
- return checks
464
-
465
-
466
- def _list_files(
467
- executor: Executor,
468
- entries: dict[str, hosts.OwnedDeployment],
469
- plans: dict[str, RemoveParams],
470
- keep: set[str],
471
- weights: bool,
472
- ) -> Listing:
473
- """Each deployment's dry run fills in the files its removal deletes: everything in its
474
- directory, and with ``weights`` its model files that nothing else uses."""
475
- listing: Listing = []
476
- for name, entry in entries.items():
477
- _plan_purge(plans[name], entry["files"] if weights else [], keep)
478
- found = _listing(_act(executor, {**plans[name], "dry_run": True}))
479
- plans[name]["purge"] = [path for path, _, _ in found]
480
- listing += found
481
- return listing
482
-
483
-
484
369
  def _remove_services(
485
370
  executor: Executor,
486
371
  entries: dict[str, hosts.OwnedDeployment],
@@ -488,68 +373,15 @@ def _remove_services(
488
373
  weights: bool,
489
374
  unwire_checks: list[gateway.Check],
490
375
  ) -> list[gateway.Check]:
491
- """Stop and remove each service with its directory. A deployment whose model files stay
492
- remains in the manifest as removed, so a later ``--purge`` finds them."""
493
- if not all(check["ok"] for check in unwire_checks):
494
- return []
495
- checks: list[gateway.Check] = []
496
- for name, entry in entries.items():
497
- result = _act(executor, plans[name])
498
- ok = result.get("event") == "result"
499
- kept = (
500
- [] if weights else [f for f in entry["files"] if os.path.lexists(os.path.expanduser(f))]
501
- )
502
- done = f"removed with its directory ({result.get('purged', 0)} files)"
503
- done += f", {len(kept)} model file(s) kept" if kept else ""
504
- checks.append(
505
- {"check": name, "ok": ok, "detail": done if ok else str(result.get("message"))}
506
- )
507
- if ok:
508
- hosts.delete_record(hosts.LOCAL_ID, name, purged=not kept)
509
- return checks
510
-
511
-
512
- def _remove_tools(
513
- doc: hosts.Owned, magpie: str | None, plan: harness.ToolPlan | None = None
514
- ) -> tuple[list[gateway.Check], list[str]]:
515
- """The gateway this tool started goes before the Magpie it runs, then the tools and the
516
- archives they were installed from. A Magpie that changed since install (it updates itself)
517
- keeps its gateway: other providers may use it. Every tool leaves the manifest, deleted or
518
- kept with the reason printed."""
519
- checks: list[gateway.Check] = []
520
- notes: list[str] = []
521
- started = doc["gateway"]["started"]
522
- ours = next((t for t in doc["tools"] if Path(t["path"]).name == "magpie"), None)
523
- drift = harness.changed(ours) if ours and os.path.lexists(ours["path"]) else None
524
- if started and magpie and ours and drift:
525
- hosts.own_gateway(hosts.TOOLS_DIR, "started", None)
526
- notes.append(
527
- f"- gateway ({started}) kept: {ours['path']} {drift}; it may serve other providers"
528
- )
529
- elif started and magpie:
530
- gateway_check = gateway.stop_gateway(magpie, started, plan=plan)
531
- checks.append(gateway_check)
532
- if not gateway_check["ok"]:
533
- notes.append("- tools kept: stopping the gateway failed; fix it and rerun stack remove")
534
- return checks, notes
535
- gone, kept = harness.remove_tools(doc, True)
536
- tools = {t["path"] for t in doc["tools"]}
537
- archives = set(doc["archives"])
538
-
539
- def forget(d: hosts.Owned) -> None:
540
- d["tools"] = [t for t in d["tools"] if t["path"] not in tools]
541
- d["archives"] = [a for a in d["archives"] if a not in archives]
542
-
543
- hosts.update_owned(forget)
544
- notes += [f"- kept {path}: {reason}" for path, reason in kept.items()]
545
- if gone:
546
- checks.append({"check": "tools", "ok": True, "detail": "deleted " + ", ".join(gone)})
547
- return checks, notes
376
+ """Stop and remove each service with its directory."""
377
+ return stack_remove.remove_services(executor, entries, plans, weights, unwire_checks, act=_act)
548
378
 
549
379
 
550
380
  def stack_members() -> set[str]:
551
381
  """Names of the deployments ``stack apply`` deployed on this computer: each run record lists
552
382
  them; one written before it did is read through the saved plan beside it."""
383
+ from localmodels.stack_plan import deployments
384
+
553
385
  names: set[str] = set()
554
386
  for run, plan in hosts.stack_runs():
555
387
  listed = run.get("deployments")
@@ -562,64 +394,6 @@ def stack_members() -> set[str]:
562
394
  return names
563
395
 
564
396
 
565
- def _outside(members: set[str], doc: hosts.Owned) -> dict[str, bool]:
566
- """Deployments this computer has that no stack apply deployed, and whether each still has
567
- a record (``service local NAME remove`` needs one)."""
568
- found = {r["plan"]["name"]: True for r in hosts.records(hosts.LOCAL_ID)}
569
- found |= {n: found.get(n, False) for n in doc["deployments"]}
570
- return {n: has for n, has in sorted(found.items()) if n not in members}
571
-
572
-
573
- def _chosen(members: set[str], doc: hosts.Owned, everything: bool, out: Out) -> set[str]:
574
- """The deployments this uninstall takes: the stack's; those an earlier remove left only
575
- model files of; one whose directory is gone (cleared from the manifest); and with
576
- ``everything`` the rest. A deployment of another kind, or one recorded under another state
577
- directory, is named and left alone: it may be serving."""
578
- chosen = set(members)
579
- for name, has_record in _outside(members, doc).items():
580
- entry = doc["deployments"].get(name)
581
- live = entry is not None and not entry["removed"]
582
- here = live and os.path.isdir(os.path.expanduser(doc["deployments"][name]["deploy_dir"]))
583
- if everything or (entry is not None and not has_record and not here):
584
- if live and not here:
585
- out(f"- {name}: its directory is gone; cleared from the manifest")
586
- chosen.add(name)
587
- continue
588
- how = (
589
- f"use service local {name} remove"
590
- if has_record
591
- else "it has no deployment record here (another state directory may manage it)"
592
- )
593
- out(f"- {name}: not part of this stack, left unchanged; {how}, or stack remove --all")
594
- return chosen
595
-
596
-
597
- def _teardown(
598
- doc: hosts.Owned,
599
- entries: dict[str, hosts.OwnedDeployment],
600
- plans: dict[str, RemoveParams],
601
- executor: Executor,
602
- target: harness.ToolPlan | None,
603
- weights: bool,
604
- serve_log: str,
605
- ) -> tuple[list[gateway.Check], list[str]]:
606
- """Clients, services, then gateway and tools, each only when the step before succeeded."""
607
- magpie = gateway_probe.magpie_binary(doc)
608
- magpie_plan = harness_gateway.magpie_target(hosts.TOOLS_DIR) # past a verified Bifrost move
609
- checks = gateway.unwire(magpie, plan=target, magpie_plan=magpie_plan)
610
- checks += _remove_services(executor, entries, plans, weights, checks)
611
- if all(check["ok"] for check in checks):
612
- tool_checks, notes = _remove_tools(doc, magpie, magpie_plan or target)
613
- else:
614
- tool_checks, notes = [], ["- tools kept: earlier step failed; fix and rerun stack remove"]
615
- checks += tool_checks
616
- if all(check["ok"] for check in checks):
617
- harness_gateway.purge_gateway_profile(target, notes)
618
- if os.path.isfile(serve_log):
619
- os.remove(serve_log)
620
- return checks + _drop_slices(hosts.load_owned()), notes
621
-
622
-
623
397
  def remove(
624
398
  purge: bool,
625
399
  yes: bool,
@@ -629,72 +403,19 @@ def remove(
629
403
  everything: bool = False,
630
404
  dry_run: bool = False,
631
405
  ) -> int:
632
- """``stack remove``: uninstall the stack in dependency order and leave only its model files:
633
- client wiring, services with their directories and logs, the gateway with its data, the
634
- tools and their archives, then the engines and saved plans nothing else uses
635
- (stack_cleanup.sweep). ``purge`` deletes the model files too, after the confirmation word.
636
- A stack component's deployment record that predates the manifest is adopted first;
637
- deployments no stack apply made are listed and left alone unless ``everything``."""
638
- if sys.platform != "darwin" and (error := platform_error(sys.platform)):
639
- raise StackError(error)
640
- members = stack_members()
641
- doc = stack_cleanup.adopted(members, dry_run, out)
642
- target = harness_gateway.accepted_plan(hosts.TOOLS_DIR)
643
- profile = harness_gateway.gateway_profile(target)
644
- chosen = _chosen(members, doc, everything, out)
645
- if any(t["sha256"] is None for t in doc["tools"]):
646
- out(
647
- f"- {hosts.owned_path()} lists tools by path only (manifest format before v1), "
648
- "treated as legacy, unverified; neither remove nor --purge deletes them"
649
- )
650
- entries = {n: d for n, d in doc["deployments"].items() if n in chosen}
651
- doc = stack_cleanup.without_others_archives(doc, chosen, out)
652
- engines = stack_cleanup.engines_in_use() # before anything goes: what the stack ran
653
- bases = {Path(os.path.expanduser(d["deploy_dir"])).parent.parent for d in entries.values()}
654
- bases.add(Path(os.path.expanduser(deploy.DEFAULT_BASE_DIR)))
655
- last = not set(_outside(chosen, doc)) # no deployment of another kind is left to read state
656
- # A plain uninstall keeps the verified downloads beside the model files; a purge takes them.
657
- downloads = [] if purge else stack_cleanup.kept_downloads(doc, engines, chosen, last)
658
- doc = {**doc, "archives": [a for a in doc["archives"] if a not in downloads]}
659
- if hosts.owns_nothing({**doc, "deployments": entries}) and not (profile and profile.exists()):
660
- return stack_cleanup.finish(engines, chosen, bases, last, dry_run, out, downloads=purge)
661
- executor = hosts.executor(hosts.get_device(hosts.LOCAL_ID))
662
- plans = {n: _owned_params(n, d) for n, d in entries.items()}
663
- serve_log = str(hosts.owned_path().parent / "magpie-serve.log")
664
- keep = _in_use(hosts.records(hosts.LOCAL_ID), chosen)
665
- keep |= {f for n, d in doc["deployments"].items() if n not in chosen for f in d["files"]}
666
- listing = _list_files(executor, entries, plans, keep, purge)
667
- listing += stack_cleanup.local_listing(
668
- [*doc["archives"], serve_log, *([str(profile)] if profile else [])]
669
- )
670
- kept_weights = stack_cleanup.kept_weights(entries, listing)
671
- if dry_run:
672
- swept = stack_cleanup.sweep(engines, chosen, state=last, downloads=purge, dry_run=True)
673
- kept = stack_cleanup.local_listing(downloads)
674
- stack_cleanup.preview(listing, kept_weights, swept, doc, out, kept)
675
- return 0
676
- if purge and not _approve(listing, yes, out, confirm):
677
- return 1
678
- checks, notes = _teardown(doc, entries, plans, executor, target, purge, serve_log)
679
- for check in checks:
680
- out(f"{'✓' if check['ok'] else '✗'} {check['check']}: {check['detail']}")
681
- for note in notes:
682
- out(note)
683
- if not all(c["ok"] for c in checks):
684
- out(f"Not all removed; still recorded in {hosts.owned_path()}; fix and rerun stack remove")
685
- return 1
686
- stack_cleanup.finish(engines, chosen, bases, last, False, out, quiet=True, downloads=purge)
687
- stack_cleanup.record_downloads(downloads)
688
- kept = stack_cleanup.local_listing(downloads)
689
- weight = sum(size for _, size, _ in [*kept_weights, *kept])
690
- out(
691
- f"Removed. Kept {len(kept_weights)} model files and {len(kept)} downloaded archives, "
692
- f"{gib(weight)}: the next install reuses them; {command()} stack remove --purge "
693
- "deletes them"
694
- if kept_weights or kept
695
- else "Removed. Nothing this tool installed is left but the manifest's empty lock file"
406
+ """``stack remove``: uninstall the stack in dependency order and leave only its model files."""
407
+ return stack_remove.run_remove(
408
+ purge,
409
+ yes,
410
+ out,
411
+ confirm,
412
+ everything=everything,
413
+ dry_run=dry_run,
414
+ act=_act,
415
+ remove_services_fn=_remove_services,
416
+ members_fn=stack_members,
417
+ owned_params_fn=_owned_params,
696
418
  )
697
- return 0
698
419
 
699
420
 
700
421
  # ---------------------------------------------------------------------------- command line