@simplexai/localmodels-linux-x64 0.1.0-dev.32.build.git9f03dd7a81cec1338df8eaf613ec9e3013365c9c → 0.1.0-dev.36

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 (143) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +141 -99
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/app.py +7 -2
  6. package/modules/localmodels/approval.py +4 -4
  7. package/modules/localmodels/bifrost_checks.py +121 -3
  8. package/modules/localmodels/bifrost_provider.py +53 -0
  9. package/modules/localmodels/bifrost_unit.py +32 -1
  10. package/modules/localmodels/budget.py +7 -1
  11. package/modules/localmodels/catalog.json +286 -12
  12. package/modules/localmodels/catalog.py +30 -29
  13. package/modules/localmodels/catalog_add.py +1 -0
  14. package/modules/localmodels/cli_parser.py +10 -2
  15. package/modules/localmodels/component.py +7 -1
  16. package/modules/localmodels/decode_calibration.json +6 -0
  17. package/modules/localmodels/decode_calibration.py +104 -0
  18. package/modules/localmodels/deploy.py +44 -7
  19. package/modules/localmodels/deploy_steps.py +10 -1
  20. package/modules/localmodels/engines-strata-0.1.49.2.json +31 -0
  21. package/modules/localmodels/engines-strata-0.1.59.1.json +31 -0
  22. package/modules/localmodels/engines.json +57 -1
  23. package/modules/localmodels/engines.py +6 -2
  24. package/modules/localmodels/estimator.py +21 -7
  25. package/modules/localmodels/frontend.py +4 -4
  26. package/modules/localmodels/gateway.py +14 -4
  27. package/modules/localmodels/gateway_app_bifrost.py +4 -3
  28. package/modules/localmodels/gateway_bifrost.py +70 -57
  29. package/modules/localmodels/gateway_probe.py +3 -4
  30. package/modules/localmodels/gguf.py +7 -0
  31. package/modules/localmodels/harness.py +24 -25
  32. package/modules/localmodels/harness_gateway.py +19 -10
  33. package/modules/localmodels/harness_probe.py +33 -6
  34. package/modules/localmodels/hosts.py +73 -9
  35. package/modules/localmodels/install.py +36 -6
  36. package/modules/localmodels/library_cli.py +179 -0
  37. package/modules/localmodels/library_convert.py +132 -0
  38. package/modules/localmodels/library_gateway.py +471 -0
  39. package/modules/localmodels/library_jobs.py +314 -0
  40. package/modules/localmodels/library_model.py +246 -0
  41. package/modules/localmodels/library_pricing.py +347 -0
  42. package/modules/localmodels/library_serve.py +348 -0
  43. package/modules/localmodels/library_state.py +373 -0
  44. package/modules/localmodels/library_status.py +349 -0
  45. package/modules/localmodels/llm_rank.py +77 -8
  46. package/modules/localmodels/memcalc.py +7 -30
  47. package/modules/localmodels/metal.py +26 -0
  48. package/modules/localmodels/metal_probe.py +11 -7
  49. package/modules/localmodels/plan_envelope.py +4 -1
  50. package/modules/localmodels/preparation.py +49 -0
  51. package/modules/localmodels/probe.py +8 -8
  52. package/modules/localmodels/process_identity.py +536 -9
  53. package/modules/localmodels/quant_formats.py +123 -0
  54. package/modules/localmodels/recommend.py +32 -3
  55. package/modules/localmodels/recommend_cli.py +8 -4
  56. package/modules/localmodels/records.py +1 -0
  57. package/modules/localmodels/remote_ops.py +104 -6
  58. package/modules/localmodels/remote_ops_download.py +17 -2
  59. package/modules/localmodels/remote_ops_prepare.py +425 -0
  60. package/modules/localmodels/remote_ops_remove.py +40 -7
  61. package/modules/localmodels/remote_ops_service.py +110 -8
  62. package/modules/localmodels/remote_ops_verify.py +15 -2
  63. package/modules/localmodels/runtime_auth.py +31 -1
  64. package/modules/localmodels/runtime_cli.py +3 -4
  65. package/modules/localmodels/runtime_io.py +50 -6
  66. package/modules/localmodels/service_autostart.py +45 -1
  67. package/modules/localmodels/service_control.py +13 -0
  68. package/modules/localmodels/service_deployment.py +12 -3
  69. package/modules/localmodels/service_jobs.py +33 -4
  70. package/modules/localmodels/service_probe.py +67 -13
  71. package/modules/localmodels/service_stop.py +152 -0
  72. package/modules/localmodels/service_worker.py +9 -1
  73. package/modules/localmodels/services_cli.py +50 -6
  74. package/modules/localmodels/setup_inspection.py +34 -25
  75. package/modules/localmodels/setup_text.py +118 -0
  76. package/modules/localmodels/sizecalc.py +625 -0
  77. package/modules/localmodels/sizecalc_cli.py +249 -0
  78. package/modules/localmodels/stack.py +69 -17
  79. package/modules/localmodels/stack_args.py +91 -19
  80. package/modules/localmodels/stack_auto.py +78 -0
  81. package/modules/localmodels/stack_binding.py +23 -35
  82. package/modules/localmodels/stack_card.py +195 -0
  83. package/modules/localmodels/stack_cleanup.py +379 -0
  84. package/modules/localmodels/stack_clients.py +4 -1
  85. package/modules/localmodels/stack_compose.py +173 -206
  86. package/modules/localmodels/stack_console.py +2 -0
  87. package/modules/localmodels/stack_decision.py +3 -2
  88. package/modules/localmodels/stack_down.py +189 -0
  89. package/modules/localmodels/stack_events.py +54 -0
  90. package/modules/localmodels/stack_hardware.py +30 -34
  91. package/modules/localmodels/stack_journal.py +29 -8
  92. package/modules/localmodels/stack_ledger.py +411 -0
  93. package/modules/localmodels/stack_lifecycle.py +162 -167
  94. package/modules/localmodels/stack_llm_ram.py +57 -5
  95. package/modules/localmodels/stack_memory.py +721 -0
  96. package/modules/localmodels/stack_picks.py +147 -0
  97. package/modules/localmodels/stack_plan.py +143 -25
  98. package/modules/localmodels/stack_ports.py +22 -0
  99. package/modules/localmodels/stack_preflight.py +699 -0
  100. package/modules/localmodels/stack_review.py +123 -5
  101. package/modules/localmodels/stack_rollback.py +2 -0
  102. package/modules/localmodels/stack_route.py +256 -0
  103. package/modules/localmodels/stack_run.py +11 -0
  104. package/modules/localmodels/stack_suite.py +107 -20
  105. package/modules/localmodels/stack_summary.py +65 -4
  106. package/modules/localmodels/stack_try.py +354 -0
  107. package/modules/localmodels/stack_try_client.py +194 -0
  108. package/modules/localmodels/stack_try_docs.py +139 -0
  109. package/modules/localmodels/stack_up.py +8 -1
  110. package/modules/localmodels/stack_update.py +29 -4
  111. package/modules/localmodels/stack_verify.py +3 -1
  112. package/modules/localmodels/stack_view.py +10 -11
  113. package/modules/localmodels/stack_view_apply.py +4 -2
  114. package/modules/localmodels/stack_view_events.py +2 -1
  115. package/modules/localmodels/stack_view_serve.py +3 -0
  116. package/modules/localmodels/stack_view_text.py +1 -1
  117. package/modules/localmodels/stack_view_words.py +4 -1
  118. package/modules/localmodels/stack_warm.py +574 -0
  119. package/modules/localmodels/stack_whatif.py +558 -0
  120. package/modules/localmodels/suite.py +48 -39
  121. package/modules/localmodels/tool_archive.py +40 -0
  122. package/modules/localmodels/tools.json +8 -0
  123. package/modules/localmodels/transport.py +1 -0
  124. package/modules/localmodels/vision.py +8 -1
  125. package/modules/localmodels/web/sizecalc/app.js +431 -0
  126. package/modules/localmodels/web/sizecalc/calc.js +269 -0
  127. package/modules/localmodels/web/sizecalc/page.html +362 -0
  128. package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
  129. package/modules/localmodels/web/view/i18n.js +1 -1
  130. package/modules/localmodels/web/view/logo-claude.svg +3 -0
  131. package/modules/localmodels/web/view/logo-codex.png +0 -0
  132. package/modules/localmodels/web/view/logo-pi.svg +6 -0
  133. package/modules/localmodels/web/view/view.css +4 -0
  134. package/modules/localmodels/web/view/view.js +15 -6
  135. package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/METADATA +1 -1
  136. package/modules/simplex_localmodels-0.1.0.dev36.dist-info/RECORD +242 -0
  137. package/package.json +1 -1
  138. package/tool.json +1 -1
  139. package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
  140. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/WHEEL +0 -0
  141. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/entry_points.txt +0 -0
  142. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/licenses/NOTICE +0 -0
  143. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -1,21 +1,14 @@
1
- """Inspect, remove and purge resources owned by this tool.
2
-
3
- Status reads service identity, health, acceptance, disk usage and the owned manifest.
4
- Remove restores pi, removes owned gateway entries and services, and deletes unused slices
5
- and tools only when their recorded SHA256 still matches. Legacy unverified tools stay.
6
- Purge lists model, deployment and tool files before confirmation; shared files always stay.
7
- """
1
+ """Inspect, remove and purge owned resources while preserving shared and unverified files."""
8
2
 
9
3
  from __future__ import annotations
10
4
 
11
5
  import argparse
12
6
  import json
13
7
  import os
14
- import shutil
15
8
  import sys
16
9
  import urllib.error
17
10
  import urllib.request
18
- from collections.abc import Callable, Iterator
11
+ from collections.abc import Callable
19
12
  from pathlib import Path
20
13
  from typing import TypedDict
21
14
 
@@ -32,12 +25,13 @@ from localmodels import (
32
25
  hosts,
33
26
  process_identity,
34
27
  remote_ops_launchd,
28
+ stack_cleanup,
35
29
  stack_run,
36
30
  )
37
31
  from localmodels.budget import gib
38
32
  from localmodels.contracts import decode
39
33
  from localmodels.records import FinishedRecord, Plan, ProgressEvent
40
- from localmodels.remote_ops import RemoveParams
34
+ from localmodels.remote_ops import RemoveParams, StrataPreparation
41
35
  from localmodels.remote_ops_service import listener_problem
42
36
  from localmodels.stack_plan import StackError, command, deployments, platform_error, start_here
43
37
  from localmodels.transport import Executor
@@ -47,6 +41,7 @@ CONFIRM_WORD = "purge"
47
41
  UNIT_DIR = harness.UNIT_DIR
48
42
 
49
43
  Out = Callable[[str], None]
44
+ Listing = stack_cleanup.Listing
50
45
  Confirm = Callable[[str], bool]
51
46
 
52
47
 
@@ -72,7 +67,7 @@ def _run(argv: list[str]) -> str:
72
67
 
73
68
 
74
69
  def _service(plan: Plan) -> tuple[str, int | None]:
75
- if not sys.platform.startswith("linux") and sys.platform != "darwin":
70
+ if not sys.platform.startswith("linux") and sys.platform not in ("darwin", "win32"):
76
71
  return "unknown", None
77
72
  svc = plan["service"]
78
73
  if svc["kind"] == "launchd-user":
@@ -84,7 +79,7 @@ def _service(plan: Plan) -> tuple[str, int | None]:
84
79
  return state.stdout.strip() or "unknown", int(pid) if pid.isdigit() and pid != "0" else None
85
80
  try:
86
81
  pid_file = Path(os.path.expanduser(svc["deploy_dir"]), "server.pid")
87
- if sys.platform == "darwin":
82
+ if sys.platform in ("darwin", "win32"):
88
83
  return process_identity.status(pid_file)
89
84
  number = int(pid_file.read_text(encoding="utf-8").strip())
90
85
  os.kill(number, 0)
@@ -239,7 +234,7 @@ def _last_apply(view: stack_run.RunView | None) -> str | None:
239
234
  outcome = f"MLX install preview {view['state']}; full agent acceptance not done"
240
235
  return (
241
236
  f"Last stack apply: plan {view['plan_id'][:12]}, "
242
- f"{view['finished_at'] or view['started_at']}, {outcome}; service liveness unknown"
237
+ f"{view['finished_at'] or view['started_at']}, {outcome}; the rows above are the live state"
243
238
  )
244
239
 
245
240
 
@@ -354,11 +349,11 @@ def _owned_params(name: str, entry: hosts.OwnedDeployment) -> RemoveParams:
354
349
  """From the manifest; the deployment's record, when there is one, names its config files."""
355
350
  params = _params(entry["service"], entry["kind"], entry["deploy_dir"], entry["port"])
356
351
  try:
357
- params["config_files"] = list(
358
- hosts.record(hosts.LOCAL_ID, name)["plan"]["service"].get("config_files") or {}
359
- )
352
+ params = {**plan_params(hosts.record(hosts.LOCAL_ID, name)["plan"]), **params}
360
353
  except KeyError:
361
354
  pass
355
+ if entry.get("preparation_dir"):
356
+ params["preparation_dir"] = entry["preparation_dir"]
362
357
  return params
363
358
 
364
359
 
@@ -366,14 +361,20 @@ def plan_params(plan: Plan) -> RemoveParams:
366
361
  svc = plan["service"]
367
362
  params = _params(svc["name"], svc["kind"], svc["deploy_dir"], svc["port"])
368
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"]
369
366
  return params
370
367
 
371
368
 
372
- def _purge_files(files: list[str], keep: set[str]) -> list[str]:
373
- """Model files with their verification marker and partial download, unless in use."""
374
- expanded = (os.path.expanduser(f) for f in files)
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)
375
374
  kept = (".sha256", ".part", ".part.ranges") # .part.ranges: a parallel download's record
376
- return [p for f in expanded if f not in keep for p in (f, *(f + k for k in kept))]
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
+ ]
377
378
 
378
379
 
379
380
  def _in_use(records: list[FinishedRecord], skip: set[str]) -> set[str]:
@@ -385,9 +386,6 @@ def _in_use(records: list[FinishedRecord], skip: set[str]) -> set[str]:
385
386
  }
386
387
 
387
388
 
388
- Listing = list[tuple[str, int, int]] # path, bytes, hard links
389
-
390
-
391
389
  def _listing(event: dict[str, object]) -> Listing:
392
390
  if event.get("event") != "result":
393
391
  raise OSError(str(event.get("message") or "cannot list the files to delete"))
@@ -395,19 +393,6 @@ def _listing(event: dict[str, object]) -> Listing:
395
393
  return [(str(r[0]), int(str(r[1])), int(str(r[2]))) for r in rows]
396
394
 
397
395
 
398
- def _local_listing(paths: list[str]) -> Listing:
399
- """Each file, and each file inside a directory (a front's venv), that ``paths`` name."""
400
- found = []
401
- for path in paths:
402
- if os.path.isdir(path) and not os.path.islink(path):
403
- inner = sorted(str(p) for p in Path(path).rglob("*") if p.is_file() or p.is_symlink())
404
- found += _local_listing(inner)
405
- elif os.path.lexists(path):
406
- st = os.lstat(path)
407
- found.append((path, st.st_size, st.st_nlink))
408
- return found
409
-
410
-
411
396
  def _ask(prompt: str) -> bool:
412
397
  if not sys.stdin.isatty():
413
398
  return False
@@ -445,7 +430,7 @@ def service_remove(
445
430
  if dev_id == hosts.LOCAL_ID:
446
431
  others = hosts.load_owned()["deployments"]
447
432
  keep |= {f for n, d in others.items() if n != name for f in d["files"]}
448
- params["purge_files"] = _purge_files([f["dest"] for f in record["plan"]["files"]], keep)
433
+ _plan_purge(params, [f["dest"] for f in record["plan"]["files"]], keep)
449
434
  listing = _listing(_act(executor, {**params, "dry_run": True}))
450
435
  if not _approve(listing, yes, out, confirm):
451
436
  return None
@@ -478,16 +463,18 @@ def _drop_slices(doc: hosts.Owned) -> list[gateway.Check]:
478
463
  return checks
479
464
 
480
465
 
481
- def _list_purge(
466
+ def _list_files(
482
467
  executor: Executor,
483
468
  entries: dict[str, hosts.OwnedDeployment],
484
469
  plans: dict[str, RemoveParams],
485
470
  keep: set[str],
471
+ weights: bool,
486
472
  ) -> Listing:
487
- """Each deployment's dry run fills in the files its purge deletes."""
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."""
488
475
  listing: Listing = []
489
476
  for name, entry in entries.items():
490
- plans[name]["purge_files"] = _purge_files(entry["files"], keep)
477
+ _plan_purge(plans[name], entry["files"] if weights else [], keep)
491
478
  found = _listing(_act(executor, {**plans[name], "dry_run": True}))
492
479
  plans[name]["purge"] = [path for path, _, _ in found]
493
480
  listing += found
@@ -498,32 +485,37 @@ def _remove_services(
498
485
  executor: Executor,
499
486
  entries: dict[str, hosts.OwnedDeployment],
500
487
  plans: dict[str, RemoveParams],
501
- purge: bool,
488
+ weights: bool,
502
489
  unwire_checks: list[gateway.Check],
503
490
  ) -> 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."""
504
493
  if not all(check["ok"] for check in unwire_checks):
505
494
  return []
506
495
  checks: list[gateway.Check] = []
507
496
  for name, entry in entries.items():
508
- if entry["removed"] and not purge:
509
- continue
510
497
  result = _act(executor, plans[name])
511
498
  ok = result.get("event") == "result"
512
- done = f"deleted {result.get('purged', 0)} files" if purge else "removed, model/logs kept"
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 ""
513
504
  checks.append(
514
505
  {"check": name, "ok": ok, "detail": done if ok else str(result.get("message"))}
515
506
  )
516
507
  if ok:
517
- hosts.delete_record(hosts.LOCAL_ID, name, purged=purge)
508
+ hosts.delete_record(hosts.LOCAL_ID, name, purged=not kept)
518
509
  return checks
519
510
 
520
511
 
521
512
  def _remove_tools(
522
- doc: hosts.Owned, magpie: str | None, purge: bool, plan: harness.ToolPlan | None = None
513
+ doc: hosts.Owned, magpie: str | None, plan: harness.ToolPlan | None = None
523
514
  ) -> tuple[list[gateway.Check], list[str]]:
524
- """The gateway this tool started goes before the Magpie it runs, then the tools. A Magpie
525
- that changed since install (it updates itself) keeps its gateway: other providers may use it.
526
- Every tool leaves the manifest, deleted or kept with the reason printed."""
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."""
527
519
  checks: list[gateway.Check] = []
528
520
  notes: list[str] = []
529
521
  started = doc["gateway"]["started"]
@@ -540,9 +532,9 @@ def _remove_tools(
540
532
  if not gateway_check["ok"]:
541
533
  notes.append("- tools kept: stopping the gateway failed; fix it and rerun stack remove")
542
534
  return checks, notes
543
- gone, kept = harness.remove_tools(doc, purge)
535
+ gone, kept = harness.remove_tools(doc, True)
544
536
  tools = {t["path"] for t in doc["tools"]}
545
- archives = set(doc["archives"]) if purge else set()
537
+ archives = set(doc["archives"])
546
538
 
547
539
  def forget(d: hosts.Owned) -> None:
548
540
  d["tools"] = [t for t in d["tools"] if t["path"] not in tools]
@@ -578,59 +570,112 @@ def _outside(members: set[str], doc: hosts.Owned) -> dict[str, bool]:
578
570
  return {n: has for n, has in sorted(found.items()) if n not in members}
579
571
 
580
572
 
581
- def remove(purge: bool, yes: bool, out: Out = print, confirm: Confirm = _ask) -> int:
582
- """``stack remove [--purge]``: everything the manifest records for the stack, in dependency
583
- order. A stack component's deployment record that predates the manifest is adopted first;
584
- deployments no stack apply made are listed and left alone."""
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
+ def remove(
624
+ purge: bool,
625
+ yes: bool,
626
+ out: Out = print,
627
+ confirm: Confirm = _ask,
628
+ *,
629
+ everything: bool = False,
630
+ dry_run: bool = False,
631
+ ) -> 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``."""
585
638
  if sys.platform != "darwin" and (error := platform_error(sys.platform)):
586
639
  raise StackError(error)
587
640
  members = stack_members()
588
- for record in hosts.records(hosts.LOCAL_ID):
589
- name = record["plan"]["name"]
590
- if name in members and name not in hosts.load_owned()["deployments"]:
591
- hosts.own_deployment(record["plan"])
592
- doc = hosts.load_owned()
641
+ doc = stack_cleanup.adopted(members, dry_run, out)
593
642
  target = harness_gateway.accepted_plan(hosts.TOOLS_DIR)
594
643
  profile = harness_gateway.gateway_profile(target)
595
- outside = _outside(members, doc)
596
- for name, has_record in outside.items():
597
- how = f"use service local {name} remove" if has_record else "service removed, files kept"
598
- out(f"- {name}: not part of the stack, left unchanged; {how}")
644
+ chosen = _chosen(members, doc, everything, out)
599
645
  if any(t["sha256"] is None for t in doc["tools"]):
600
646
  out(
601
647
  f"- {hosts.owned_path()} lists tools by path only (manifest format before v1), "
602
648
  "treated as legacy, unverified; neither remove nor --purge deletes them"
603
649
  )
604
- entries = {n: d for n, d in doc["deployments"].items() if n in members}
605
- if hosts.owns_nothing({**doc, "deployments": entries}) and not (
606
- purge and profile and profile.exists()
607
- ):
608
- out("This tool owns no resources on this computer; nothing to remove.")
609
- return 0
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)
610
661
  executor = hosts.executor(hosts.get_device(hosts.LOCAL_ID))
611
662
  plans = {n: _owned_params(n, d) for n, d in entries.items()}
612
663
  serve_log = str(hosts.owned_path().parent / "magpie-serve.log")
613
- if purge:
614
- keep = _in_use(hosts.records(hosts.LOCAL_ID), members)
615
- keep |= {f for n, d in doc["deployments"].items() if n not in members for f in d["files"]}
616
- listing = _list_purge(executor, entries, plans, keep)
617
- extra = _local_listing([*doc["archives"], serve_log, *([str(profile)] if profile else [])])
618
- if not _approve(listing + extra, yes, out, confirm):
619
- return 1
620
- magpie = gateway_probe.magpie_binary(doc)
621
- magpie_plan = harness_gateway.magpie_target(hosts.TOOLS_DIR) # past a verified Bifrost move
622
- checks = gateway.unwire(magpie, plan=target, magpie_plan=magpie_plan)
623
- checks += _remove_services(executor, entries, plans, purge, checks)
624
- if all(check["ok"] for check in checks):
625
- tool_checks, notes = _remove_tools(doc, magpie, purge, magpie_plan or target)
626
- else:
627
- tool_checks, notes = [], ["- tools kept: earlier step failed; fix and rerun stack remove"]
628
- checks += tool_checks
629
- if purge and all(check["ok"] for check in checks):
630
- harness_gateway.purge_gateway_profile(target, notes)
631
- if os.path.isfile(serve_log):
632
- os.remove(serve_log)
633
- checks += _drop_slices(hosts.load_owned())
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)
634
679
  for check in checks:
635
680
  out(f"{'✓' if check['ok'] else '✗'} {check['check']}: {check['detail']}")
636
681
  for note in notes:
@@ -638,10 +683,17 @@ def remove(purge: bool, yes: bool, out: Out = print, confirm: Confirm = _ask) ->
638
683
  if not all(c["ok"] for c in checks):
639
684
  out(f"Not all removed; still recorded in {hosts.owned_path()}; fix and rerun stack remove")
640
685
  return 1
641
- kept = [
642
- n for n, d in hosts.load_owned()["deployments"].items() if d["removed"] and n in members
643
- ]
644
- out("Removed" + (f"; {', '.join(kept)} models and logs kept (--purge deletes)" if kept else ""))
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"
696
+ )
645
697
  return 0
646
698
 
647
699
 
@@ -655,10 +707,18 @@ def add_parsers(actions: argparse._SubParsersAction[argparse.ArgumentParser]) ->
655
707
  show.add_argument(
656
708
  "--json", action="store_true", help="print rows and the owned manifest as JSON"
657
709
  )
658
- drop = actions.add_parser(
659
- "remove", help="undo what the owned manifest records; model files and logs stay"
660
- )
710
+ drop = actions.add_parser("remove", help="uninstall the stack; only downloaded files stay")
661
711
  add_purge_flags(drop)
712
+ drop.add_argument(
713
+ "--all",
714
+ action="store_true",
715
+ help="also remove the deployments this tool made outside `stack` (deploy, service)",
716
+ )
717
+ drop.add_argument(
718
+ "--dry-run",
719
+ action="store_true",
720
+ help="list what would be deleted and what would stay; change nothing",
721
+ )
662
722
  clean = actions.add_parser(
663
723
  "prune", help="list engine directories no plan, run or record references; --yes deletes"
664
724
  )
@@ -669,7 +729,8 @@ def add_purge_flags(parser: argparse.ArgumentParser) -> None:
669
729
  parser.add_argument(
670
730
  "--purge",
671
731
  action="store_true",
672
- help="also delete owned model files and deployment directories (lists them first)",
732
+ help="also delete what was downloaded: the model files and the tool and engine "
733
+ "archives (lists every file first, then asks for a word)",
673
734
  )
674
735
  parser.add_argument(
675
736
  "--yes", action="store_true", help="purge without typing the confirmation word"
@@ -680,71 +741,5 @@ def cli(args: argparse.Namespace) -> int:
680
741
  if args.stack_command == "status":
681
742
  return status(as_json=args.json)
682
743
  if args.stack_command == "prune":
683
- return prune(args.yes)
684
- return remove(args.purge, args.yes)
685
-
686
-
687
- def _engine_binaries(doc: object) -> Iterator[str]:
688
- """Every ``binary`` path anywhere in a saved plan, run or deployment record."""
689
- if isinstance(doc, dict):
690
- for key, value in doc.items():
691
- if key == "binary" and isinstance(value, str):
692
- yield value
693
- else:
694
- yield from _engine_binaries(value)
695
- elif isinstance(doc, list):
696
- for item in doc:
697
- yield from _engine_binaries(item)
698
-
699
-
700
- def _referenced_engines() -> tuple[set[Path], set[Path]]:
701
- """(engine dirs still referenced, every engines root ever used): a stack plan, its run
702
- record or a deployment record keeps an engine alive; the default base dir's root always
703
- counts even before the first plan."""
704
- docs: list[object] = []
705
- for plan_path in hosts.stack_plans():
706
- try:
707
- docs.append(json.loads(plan_path.read_text(encoding="utf-8")))
708
- except (OSError, json.JSONDecodeError):
709
- continue
710
- for run, plan in hosts.stack_runs():
711
- docs += [run, plan]
712
- docs += list(hosts.records(hosts.LOCAL_ID))
713
- engine_dirs = {
714
- Path(binary).parent
715
- for doc in docs
716
- for binary in _engine_binaries(doc)
717
- if "/engines/" in binary
718
- }
719
- roots = {Path(deploy.DEFAULT_BASE_DIR).expanduser() / "engines"} | {
720
- d.parent for d in engine_dirs
721
- }
722
- return engine_dirs, roots
723
-
724
-
725
- def prune(yes: bool, out: Callable[[str], None] = print) -> int:
726
- """Engine directories nothing references: list them, delete them only under ``--yes``."""
727
- if sys.platform != "darwin" and (error := platform_error(sys.platform)):
728
- raise StackError(error)
729
- referenced, roots = _referenced_engines()
730
- resolved = {d.resolve() for d in referenced}
731
- stray = sorted(
732
- child
733
- for root in roots
734
- if root.is_dir()
735
- for child in root.iterdir()
736
- if child.is_dir() and child.resolve() not in resolved
737
- )
738
- if not stray:
739
- out("No unreferenced engine directories")
740
- return 0
741
- out("These engine directories are not referenced by any stack plan, run or deployment record:")
742
- for d in stray:
743
- out(f" {d}")
744
- if not yes:
745
- out("To delete them, run stack prune --yes")
746
- return 0
747
- for d in stray:
748
- shutil.rmtree(d)
749
- out(f"Deleted {d}")
750
- return 0
744
+ return stack_cleanup.prune(args.yes)
745
+ return remove(args.purge, args.yes, everything=args.all, dry_run=args.dry_run)
@@ -13,6 +13,7 @@ the floor deploy reserves inside unified memory (context_policy.cache_floor_byte
13
13
  from __future__ import annotations
14
14
 
15
15
  from collections.abc import Sequence
16
+ from typing import cast
16
17
 
17
18
  from localmodels import catalog as cat
18
19
  from localmodels.budget import gib
@@ -60,19 +61,70 @@ def prompt_cache_bytes(llm: Plan) -> int:
60
61
  return max(0, int(argv[argv.index("--cache-ram") + 1])) << 20
61
62
 
62
63
 
63
- def prompt_cache_fit(llm: Plan, room_bytes: int, posture: AgentPosture) -> list[str]:
64
- """Size the LLM's ``--cache-ram`` to the host RAM left for it, between the posture's minimum
65
- and its full cache. Returns the warning to show when the RAM left held it back."""
64
+ # What a cache grown into the RAM left leaves free, so the RAM may fall this far between plan
65
+ # and apply and the approved plan still fits: a desktop's free RAM moves by tens of MiB a minute,
66
+ # and a cache sized to the last megabyte made every apply on one fail its RAM check (WINSTK1).
67
+ DRIFT_MIB = 256
68
+
69
+
70
+ def prompt_cache_fit(
71
+ llm: Plan, room_bytes: int, posture: AgentPosture, *, approved_mib: int | None = None
72
+ ) -> list[str]:
73
+ """Size the LLM's ``--cache-ram`` to the host RAM left for it, less ``DRIFT_MIB``, between
74
+ the posture's minimum and its full cache. Returns the warning to show when the RAM left held
75
+ it back. ``approved_mib``: apply re-plans an approved plan, whose cache stays as approved
76
+ while the RAM left now still holds it."""
66
77
  if prompt_cache_bytes(llm) == 0:
67
78
  return []
68
79
  planned = posture.prompt_cache_mib << 20
69
- mib = max(posture.prompt_cache_min_mib, min(planned, room_bytes) >> 20)
80
+ fits = min(planned, room_bytes) >> 20
81
+ mib = max(posture.prompt_cache_min_mib, min(planned, room_bytes - (DRIFT_MIB << 20)) >> 20)
82
+ if approved_mib is not None and posture.prompt_cache_min_mib <= approved_mib <= fits:
83
+ mib = approved_mib
70
84
  argv = llm["service"]["argv"]
71
85
  argv[[str(a) for a in argv].index("--cache-ram") + 1] = str(mib)
72
- if room_bytes >= planned:
86
+ if mib << 20 >= planned:
73
87
  return []
74
88
  return [
75
89
  f"LLM: available RAM only holds a {gib(mib << 20)} prompt cache (--cache-ram {mib}), "
76
90
  f"less than the agent posture's {gib(planned)}; a session pushed out of the shared KV "
77
91
  "pool recomputes more of its prefix when it resumes"
78
92
  ]
93
+
94
+
95
+ def approved_cache_mib(approved: object, llm: Plan) -> int | None:
96
+ """The prompt cache an approved plan gave this same LLM (prompt_cache_fit's approved_mib)."""
97
+ if not isinstance(approved, dict) or approved.get("name") != llm["name"]:
98
+ return None
99
+ return prompt_cache_bytes(cast(Plan, approved)) >> 20
100
+
101
+
102
+ def memory_note(
103
+ llm: Plan, parts: list[Plan], suite_memory: str, suite_slice: str, *, metal: bool, windows: bool
104
+ ) -> list[str]:
105
+ """How the plan's memory limits are enforced on this platform."""
106
+ if metal:
107
+ return [
108
+ "memory: macOS has no cgroups, so the system does not enforce each service's memory "
109
+ "limit or disable swap; the whole stack is estimated against one unified memory pool "
110
+ "(the LLM's and decision model's VRAM is that memory). Watch other programs' memory "
111
+ "use before and after apply; memory pressure slows inference"
112
+ ]
113
+ if windows:
114
+ return [
115
+ "memory: Windows has no cgroups here, so no per-service memory limit is enforced;"
116
+ " the stack is estimated against the RAM available now. Watch other programs' memory"
117
+ " use; paging slows inference"
118
+ ]
119
+ if llm["service"].get("slice"):
120
+ return [
121
+ f"memory: each service has its own cgroup limit with swap disabled; the stack sits "
122
+ f"in {suite_slice}, limit {suite_memory}"
123
+ ]
124
+ if any(p["service"].get("slice") for p in parts):
125
+ return [
126
+ f"memory: the decision and auxiliary models each have a cgroup limit with swap "
127
+ f"disabled, in {suite_slice}, limit {suite_memory}; the LLM is outside "
128
+ "it but also has swap disabled"
129
+ ]
130
+ return []