diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f208d8..94cdf00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 0.2.0a2 — uninstall and route recovery + +- Add `/sloth uninstall` previews and `/sloth uninstall confirm`, with terminal equivalents for Hermes and standalone services. +- Save the original Hermes model route during setup and restore it on disconnect; preserve unrelated settings and refuse to guess missing backups. +- Disable plugin startup, drain and stop verified owned processes, and keep existing backend servers and saved data. +- Document package removal, optional archive/build cleanup, and manual uninstall for older alphas. + ## 0.2.0a1 — coordinated release updates - Add `/sloth update check` and `/sloth update`, plus equivalent terminal commands. diff --git a/README.md b/README.md index bccfc81..ac58f04 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,11 @@ sloth-memory saves a local model's conversation inference state to disk and rest it when you return. Built for people running open-weight models on their own hardware. MIT licensed. No cloud service or account. The portable runtime uses psutil. -**Alpha release `0.2.0a1`.** Supports Linux, macOS, and +**Alpha release `0.2.0a2`.** Supports Linux, macOS, and Windows startup, automatic free-port selection, and routing adapters for llama.cpp, Ollama, vLLM, and MLX-LM. Disk park/resume through this adapter still requires the managed patched llama.cpp runtime and one slot. See [backend capabilities](docs/backends.md). -Download the [current alpha](https://github.com/uncrayon/sloth-memory/releases/tag/v0.2.0a1). +Download the [current alpha](https://github.com/uncrayon/sloth-memory/releases/tag/v0.2.0a2). Existing users: follow the [update guide](docs/updates.md), including the one-time proxy replacement for installations older than this release. The service is independent of Hermes. A native Hermes adapter provides startup, @@ -37,7 +37,7 @@ Your agent → sloth-memory (local proxy) → inference server local archive files ``` -## Install from main +## Install the latest alpha Requirements: Linux, macOS, or Windows, Python 3.10+, and Git. Building the managed llama.cpp runtime also needs CMake, a C/C++ toolchain, and your own supported GGUF @@ -50,7 +50,7 @@ instead of creating the standalone environment below. Standalone installation on macOS/Linux: ```bash -git clone --branch v0.2.0a1 https://github.com/uncrayon/sloth-memory.git +git clone --branch v0.2.0a2 https://github.com/uncrayon/sloth-memory.git cd sloth-memory python3 -m venv .venv source .venv/bin/activate @@ -112,6 +112,9 @@ For terminal use on any OS: `python -m sloth_memory update check` and ## Use with Hermes +Before trying the plugin, read [uninstall and return to your original backend](docs/uninstall.md). +It covers `/sloth uninstall`, package removal, and optional archive/build cleanup. + Install sloth-memory in Hermes' Python environment, enable it with `hermes plugins enable sloth-memory`, and restart Hermes. Then run: diff --git a/docs/backends.md b/docs/backends.md index d429049..9d4f650 100644 --- a/docs/backends.md +++ b/docs/backends.md @@ -1,6 +1,6 @@ # Backends and operating systems -This describes alpha `0.2.0a1`. Older alpha.2 installations retain their original +This describes alpha `0.2.0a2`. Older alpha.2 installations retain their original Linux-only scope until upgraded. ## Capability contract diff --git a/docs/compatibility.md b/docs/compatibility.md index b60a853..fd96cda 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -1,6 +1,6 @@ # Runtime compatibility -This page describes alpha `0.2.0a1`. See [backends](backends.md) for routing +This page describes alpha `0.2.0a2`. See [backends](backends.md) for routing capabilities. Older alpha.2 installations retain their original Linux-only scope. ## Runtime diff --git a/docs/hermes.md b/docs/hermes.md index be2be14..c69225f 100644 --- a/docs/hermes.md +++ b/docs/hermes.md @@ -1,6 +1,6 @@ # Hermes adapter and onboarding -These instructions install alpha `0.2.0a1`, including portable startup, automatic +These instructions install alpha `0.2.0a2`, including portable startup, automatic port selection, and release updates. See [backend setup](backends.md) for capabilities. The adapter ships inside sloth-memory as a native Hermes plugin. It uses plugin @@ -13,7 +13,7 @@ Install into **the same Python environment that runs Hermes**: ```bash # With your Hermes virtual environment activated: -git clone --branch v0.2.0a1 https://github.com/uncrayon/sloth-memory.git +git clone --branch v0.2.0a2 https://github.com/uncrayon/sloth-memory.git cd sloth-memory python -m pip install --upgrade . hermes plugins enable sloth-memory @@ -26,7 +26,7 @@ Use `hermes plugins list --plain --no-bundled` to check that it is enabled. For an existing installation, follow [updates and recovery](updates.md). Versions older than `0.2.0a1` need a one-time package installation and proxy replacement; subsequent releases can use `/sloth update`. Run `sloth-memory --version` in -Hermes' environment to confirm `0.2.0a1`. Restart Hermes after installation to +Hermes' environment to confirm `0.2.0a2`. Restart Hermes after installation to load the entry point. The adapter is tested against Hermes 0.21.0, upstream commit `9dd6634c5635321cf38840cc30e9b51226689128`. Use Python 3.11–3.13 for Hermes; the standalone service also supports 3.10/3.14. @@ -56,6 +56,10 @@ backend. Connecting an existing server in routing mode requires no build. ## Persistence and updates +To remove the integration and return to your original model server, see +[uninstall and recovery](uninstall.md). Existing servers and model weights are +kept. The guide also includes manual removal for older versions. + The installed package, plugin enablement, profile configuration, and saved slots persist across a computer restart. When Hermes launches, the enabled plugin starts its managed services if autostart is on. Starting Hermes itself at boot or diff --git a/docs/uninstall.md b/docs/uninstall.md new file mode 100644 index 0000000..c173bfc --- /dev/null +++ b/docs/uninstall.md @@ -0,0 +1,168 @@ +# Uninstall and return to your original backend + +The automated commands below require **`0.2.0a2` or newer**. For `0.2.0a1`, +use `/sloth update` first or follow the manual procedure below. + +Uninstall has two steps: disconnect the integration, then remove the package and +any files you no longer want. Disconnect first so Hermes does not keep calling a +proxy that has been removed. No sudo is required for the standard installation. + +## What was installed? + +| Component | Location / owner | Removal | +| --- | --- | --- | +| Python package and Hermes entry point | The Python environment used for installation | `python -m pip uninstall sloth-memory` | +| Enabled plugin and model route | Active Hermes profile's `config.yaml` | Automated disconnect restores the saved route and disables the plugin | +| Proxy and hourly cleanup loop | A Sloth Python process | Automated disconnect stops the verified archive-owned proxy | +| Managed llama.cpp backend, if selected | Process started by Sloth | Automated disconnect stops the verified archive-owned backend | +| Existing llama.cpp, Ollama, vLLM, or MLX server | Your existing installation | Kept running | +| Saved slots, logs, update backups and metadata | Configured archive directory | Kept until you explicitly remove that directory | +| Optional patched llama.cpp build | `runtime/` in the source checkout, or your `--output` directory | Remove this separate build directory when no longer used | +| Model weights and Hermes transcripts | Your original locations | Kept | + +The adapter does not patch Hermes source. The build script patches an exported +copy of llama.cpp inside its output directory, including when `--source` points +to an existing checkout. It does not patch that original checkout or an existing +Gemma server. There is no system cron job to remove; cleanup runs inside the proxy. +Custom modifications made outside this repository's installer need their own +rollback procedure. + +## Disconnect from Hermes + +Finish active turns and close other clients sharing the proxy. For a shared bot, +restrict `/sloth` and `/sloth-memory` to administrators through Hermes' command +access controls. This operation changes the active profile's model route and +stops its owned services; it is not limited to the current chat. + +Preview without changing anything: + +```text +/sloth uninstall +``` + +Apply the preview: + +```text +/sloth uninstall confirm +``` + +The command drains current inference, saves verified resident state in native +mode, restores the model fields saved before setup, disables the plugin and its +automatic startup, and stops its owned services. A failed drain/save aborts before +changing the profile. Process IDs and creation times are checked along with launch +arguments; unrelated processes are not terminated. A stale PID is not enough to +claim a process. There is no force-kill fallback. + +An existing upstream server remains running. `--external` installations only +disconnect Hermes; their external proxy also remains under its service owner's +control. Use a separate archive per independent test stack. Other profiles sharing +an archive must be disconnected separately before removing the package or data. + +Restart Hermes and **start a new conversation** afterward. Existing sessions may +retain the old proxy URL. The uninstall command does not rewrite stored sessions +or automatically restart the gateway. + +Terminal equivalent, in the Python environment that runs Hermes: + +```bash +python -m sloth_memory uninstall --hermes +python -m sloth_memory uninstall --hermes --confirm +``` + +These commands use the active Hermes profile (`HERMES_HOME` when set). They read +its archive setting, so do not add `--archive-dir`. They also work after stopping +the gateway, as long as the package and Hermes are still installed. + +If setup predates route backups, or the model fields were edited afterward, +uninstall refuses to guess the previous connection. Run `hermes model` and select +your original backend first, then retry. If Hermes already points elsewhere, that +route is preserved. Unrelated profile settings are kept. Repeating disconnect is +safe; the disabled plugin's commands disappear after Hermes reloads its plugins. + +## Remove the package and optional data + +After disconnecting, close all Hermes processes using the installation (for a +gateway, `hermes gateway stop`). Activate that same Python environment, then run: + +```bash +python -m pip uninstall sloth-memory +``` + +This removes Sloth's installed package, command launcher, and plugin entry point. +It keeps dependencies that Hermes or other packages may also use. Do not delete +Hermes' virtual environment. Restart the gateway if you want Hermes running again. +Discord and Telegram menus update when Hermes synchronizes its command catalog; +cached menus may take longer to reflect removal. + +For a complete disk cleanup, remove these **only after all their services have +stopped**: + +1. The exact archive directory printed by the preview. On a default Mac setup it + is `~/Library/Application Support/sloth-memory`; `--archive-dir`, + `SLOTH_ARCHIVE_DIR`, or `XDG_DATA_HOME` can change it. This deletes saved KV + snapshots, logs, and update rollback backups. Inspect a custom directory first; + it may contain other files you placed there. +2. The optional `runtime/` build directory, or the custom build output you chose. + Removing this isolated source/build tree removes its patched runtime. Do not + remove your pre-existing inference server installation. +3. The `sloth-memory` source checkout if you no longer need it. Check for your own + changes, downloaded weights, or other files before removing the directory. + +Use Finder/Trash on macOS or your OS file manager to review these removals. The +chat command intentionally keeps them: paths can be shared or contain user data. +Model weights and conversation transcripts are not reconstructed by reinstalling +the plugin. + +The disabled profile entry and original route backup remain for recovery. After +the package is removed, you may delete `plugins.entries.sloth-memory` and the +`sloth-memory` item from `plugins.disabled` in the active profile's `config.yaml`. +Preserve other entries. If you manually added `sloth` to Telegram's command-menu +priority list, remove that one item too. Remove any Sloth-only environment +variables you added to the profile or shell; preserve variables needed by other +services. Do not restore an entire old config file over newer unrelated settings. + +## Standalone service + +Restore your agent's original backend URL and stop other clients first. Then: + +```bash +python -m sloth_memory uninstall --archive-dir "/absolute/path/to/archive" +python -m sloth_memory uninstall --archive-dir "/absolute/path/to/archive" --confirm +python -m pip uninstall sloth-memory +``` + +Standalone uninstall has no knowledge of an agent's configuration. It previews +and stops only the proxy and managed backend recorded in that archive. If a +supervisor outside Sloth starts them automatically, disable that supervisor first. +Services started with unrecognized launch arguments must be stopped through their +original terminal or service owner. Remove optional data/builds as described above. + +## Manual procedure for 0.2.0a1 + +1. Finish active turns. If using native snapshots, `/sloth park` can save the + current conversation before shutdown. +2. Run `/sloth autostart off`, then `hermes plugins disable sloth-memory` in the + terminal. Autostart off alone does not stop an existing process. +3. Use `hermes model` to select your original server URL and served model ID. + Consult your pre-install profile backup if necessary. Do not select Sloth's + proxy address. Then stop the gateway (`hermes gateway stop`) and close other + interactive Hermes clients. +4. Stop the Sloth proxy using its original terminal (Ctrl-C), supervisor, or OS + process manager. For a detached process, `proxy.json` inside the archive records + its PID. Inspect the running process's command and start time before terminating + it; a stale manifest can refer to a reused PID. Its command should be + `python -m sloth_memory serve` with your archive path. A managed backend is + recorded in `runtime.json`; its command must match the stored `argv` including + `--slot-save-path`. Stop only that managed instance. Keep any server you were + already running before installing Sloth. +5. Remove the Python package and optional files using the preceding section. + Restart Hermes and start a new conversation to check the direct backend route. + +## Reinstall after disconnecting + +Install the desired Sloth version in Hermes' environment, enable it again with +`hermes plugins enable sloth-memory`, then restart Hermes. Run `/sloth setup` with +the backend arguments again (see [backend setup](backends.md)). Explicit setup +clears the saved uninstall flag and re-enables automatic startup. A bare +`/sloth setup` only shows instructions. Reuse an archive only when its model and +runtime are compatible, or select a new archive for the next backend test. diff --git a/docs/updates.md b/docs/updates.md index 84abacc..86d6a9c 100644 --- a/docs/updates.md +++ b/docs/updates.md @@ -67,7 +67,7 @@ package reinstall alone leaves their old proxy process running. To bootstrap: 2. Activate the Python environment that runs Hermes and install the release: ```bash - python -m pip install --upgrade https://github.com/uncrayon/sloth-memory/releases/download/v0.2.0a1/sloth_memory-0.2.0a1-py3-none-any.whl + python -m pip install --upgrade https://github.com/uncrayon/sloth-memory/releases/download/v0.2.0a2/sloth_memory-0.2.0a2-py3-none-any.whl ``` 3. With all inference clients still stopped, save any resident state and stop diff --git a/pyproject.toml b/pyproject.toml index 9718e4e..1277783 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "sloth-memory" -version = "0.2.0a1" +version = "0.2.0a2" description = "Let your local AI nap. Resume long conversations from saved inference state." readme = "README.md" requires-python = ">=3.10" diff --git a/src/sloth_memory/__init__.py b/src/sloth_memory/__init__.py index 76ea0c2..174cf50 100644 --- a/src/sloth_memory/__init__.py +++ b/src/sloth_memory/__init__.py @@ -1,3 +1,3 @@ """Persistent inference state for local open-weight models.""" -__version__ = "0.2.0a1" +__version__ = "0.2.0a2" diff --git a/src/sloth_memory/cli.py b/src/sloth_memory/cli.py index 45cfc5d..1b5deeb 100644 --- a/src/sloth_memory/cli.py +++ b/src/sloth_memory/cli.py @@ -32,6 +32,10 @@ def main(): parser = argparse.ArgumentParser(description="Let your local AI nap. Save its work for later.") parser.add_argument("--version", action="version", version=__version__) sub = parser.add_subparsers(dest="command", required=True) + uninstall = sub.add_parser("uninstall", help="preview or disconnect services; keep packages and data until explicitly removed") + uninstall.add_argument("--confirm", action="store_true", help="apply the uninstall after previewing") + uninstall.add_argument("--hermes", action="store_true", help="restore routing and disable the plugin in the active Hermes profile") + uninstall.add_argument("--archive-dir", help="standalone archive; --hermes reads the profile's archive setting") update = sub.add_parser("update", help="check or install an official release, retaining rollback files") update.add_argument("action", nargs="?", choices=("check",)) update.add_argument("--archive-dir") @@ -65,7 +69,24 @@ def main(): cmd.add_argument("--cleanup", action=argparse.BooleanOptionalAction, default=None) args = parser.parse_args() try: - if args.command == "update": + if args.command == "uninstall": + if args.hermes: + if args.archive_dir: + parser.error("--hermes uses its profile's archive; do not pass --archive-dir") + try: + from .hermes_uninstall import run + print(run(confirm=args.confirm)) + except ImportError as exc: + raise RuntimeError("activate Hermes' Python environment to use --hermes") from exc + else: + from . import removal + archive = directory(args.archive_dir) + result = removal.stop(archive) if args.confirm else removal.plan(archive) + print(json.dumps({"applied": args.confirm, "archive_dir": str(archive), + "proxy_pid": result["proxy"]["pid"] if result["proxy"] else None, + "backend_pid": result["backend"]["pid"] if result["backend"] else None, + "note": "Packages, snapshots, weights and builds are kept. Restore agent routes and stop other clients before --confirm."}, indent=2)) + elif args.command == "update": from . import updates archive = directory(args.archive_dir) result = updates.check(archive) if args.action == "check" else updates.apply(archive) diff --git a/src/sloth_memory/hermes.py b/src/sloth_memory/hermes.py index b79fcb6..fcc9f84 100644 --- a/src/sloth_memory/hermes.py +++ b/src/sloth_memory/hermes.py @@ -69,6 +69,8 @@ def capture_command(self, *, command="", session_key=None, **kwargs): def middleware(self, *, request, session_id="", base_url="", api_mode="", **kwargs): config = self.settings() + if config["uninstalled"]: + return None routes = {url.rstrip("/") + "/v1" for url in [config["base_url"], *config["previous_urls"]]} if config["connected"]: routes.add(target(config).url + "/v1") @@ -135,7 +137,7 @@ def onboarding(self): else: lines += ["Next: /sloth-memory start, then /sloth-memory connect to select this route for future sessions."] lines += ["Commands:", " status | park | delete [k-…] | slots", - " update check | update", + " update check | update | uninstall [confirm]", " retention 7 | budget 32 | cleanup on|off|now", " base-url http://127.0.0.1:8080 | autostart on|off", "Setup also accepts --backend llama.cpp|ollama|vllm|mlx, --upstream-url, --model, --cache-mode native|routing,", @@ -147,6 +149,8 @@ def onboarding(self): def configure(self, args): import argparse + if self.settings()["uninstalled"] and self.service.closed.is_set(): + raise RuntimeError("Restart Hermes after re-enabling the plugin before running setup again") class Parser(argparse.ArgumentParser): def error(self, message): raise ValueError(message) @@ -157,6 +161,8 @@ def error(self, message): parser.add_argument("--external", action=argparse.BooleanOptionalAction, default=None) parsed = vars(parser.parse_args(args)) updates = {key: value for key, value in parsed.items() if value is not None} + if self.settings()["uninstalled"]: + updates.update(uninstalled=False, autostart=True) if "backend" in updates and updates["backend"] != self.settings()["backend"]: # A model ID and endpoint belong to one backend. Reusing them while # changing engines can silently route to the previous engine. @@ -209,25 +215,25 @@ def connect(self): def write_route(self, settings): # Explicit command selects the default for FUTURE sessions through Hermes' # normal config writer; live agents and prompt histories are not changed. - from hermes_cli import config - if config.is_managed(): - raise PermissionError("model routing is managed by your administrator") - from hermes_cli import managed_scope - fields = ("provider", "default", "base_url", "api_mode") - if any(managed_scope.is_key_managed("model." + field) for field in fields): - raise PermissionError("model routing is managed by your administrator") - config.read_user_config_raw() + from .hermes_uninstall import save_route model = "local" if settings["backend"] == "llama.cpp" and not settings["upstream_url"] else settings["model"] if not model: model = "local" # legacy external llama.cpp proxy - config.save_config({"model": {"provider": "custom", "default": model, - "base_url": settings["base_url"] + "/v1", "api_mode": "chat_completions"}}, - merge_existing=True) + save_route(settings, {"provider": "custom", "default": model, + "base_url": settings["base_url"] + "/v1", "api_mode": "chat_completions"}) def handle(self, raw_args): args = shlex.split(raw_args) action = args[0] if args else "setup" rest = args[1:] + if action == "uninstall" and rest in ([], ["confirm"]): + from .hermes_uninstall import run + result = run(confirm=bool(rest)) + if rest: + self.service.closed.set() + return result + if self.settings()["uninstalled"] and action not in {"setup", "onboarding", "help"}: + raise RuntimeError("Sloth is disconnected. Restart Hermes; see docs/uninstall.md to reinstall.") if action == "update" and rest in ([], ["check"]): from . import updates config = self.settings() @@ -315,7 +321,7 @@ def register(ctx): for name in ("sloth", "sloth-memory"): ctx.register_command(name, adapter.command, description="Set up conversation slots, park, delete, and configure cleanup", - args_hint="setup | status | park | delete | cleanup | retention | base-url | update", argument_mode="text") + args_hint="setup | status | park | delete | cleanup | retention | base-url | update | uninstall", argument_mode="text") ctx.register_hook("pre_gateway_dispatch", adapter.capture_gateway) ctx.register_hook("pre_command", adapter.capture_command) ctx.register_middleware("llm_request", adapter.middleware) diff --git a/src/sloth_memory/hermes_service.py b/src/sloth_memory/hermes_service.py index df2a66b..8d9e9a7 100644 --- a/src/sloth_memory/hermes_service.py +++ b/src/sloth_memory/hermes_service.py @@ -21,7 +21,7 @@ def defaults(): return dict(base_url="http://127.0.0.1:8080", upstream_port=8090, archive_dir=str(directory()), autostart=True, external=False, server="", model="", backend="llama.cpp", - upstream_url="", cache_mode="native", connected=False, previous_urls=[], + upstream_url="", cache_mode="native", connected=False, uninstalled=False, previous_urls=[], backend_args=["--ctx-size", "8192", "--cache-ram", "0", "--ctx-checkpoints", "8", "--checkpoint-min-step", "128", "--jinja"]) @@ -45,7 +45,7 @@ def validate_service(values): parsed_previous = urlsplit(normalize_url(url)) if parsed_previous.scheme != "http" or parsed_previous.hostname != "127.0.0.1": raise ValueError("previous proxy URLs must be local") - for key in ("autostart", "external", "connected"): + for key in ("autostart", "external", "connected", "uninstalled"): if type(result[key]) is not bool: raise ValueError(f"{key} must be true or false") for key in ("model", "server"): @@ -121,6 +121,8 @@ def _remember(self, config): self.error = None def ensure(self): + if self.settings().get("uninstalled", False): + raise RuntimeError("Sloth was uninstalled; follow docs/uninstall.md to reinstall") config = validate_service(self.settings()) if self.closed.is_set(): raise RuntimeError("Hermes adapter has been unloaded") @@ -132,6 +134,8 @@ def ensure(self): return existing archive = Path(config["archive_dir"]) with file_lock(archive / ".hermes-start.lock"): + if self.closed.is_set() or self.settings().get("uninstalled", False): + raise RuntimeError("Sloth startup was disabled while waiting for the archive") # The process that won startup publishes the actual bound address. # Read it again under the interprocess lock, including after a reboot. record = proxy_record(archive) diff --git a/src/sloth_memory/hermes_uninstall.py b/src/sloth_memory/hermes_uninstall.py new file mode 100644 index 0000000..6fe6d8d --- /dev/null +++ b/src/sloth_memory/hermes_uninstall.py @@ -0,0 +1,119 @@ +"""Record and restore the model fields selected by the Hermes adapter.""" + +import copy + +from . import removal +from .hermes_service import defaults + +FIELDS = ("provider", "default", "base_url", "api_mode") + + +def editable(): + from hermes_cli import config, managed_scope + paths = ["model." + field for field in FIELDS] + paths += ["plugins.enabled", "plugins.disabled", "plugins.entries.sloth-memory"] + managed = managed_scope.managed_config_keys() + overlaps = any(key == path or key.startswith(path + ".") or path.startswith(key + ".") + for key in managed for path in paths) + if config.is_managed() or overlaps: + raise PermissionError("model routing or plugin settings are managed by your administrator") + + +def save_route(settings, model): + from hermes_cli import config + from hermes_cli.plugins import _locked_plugin_state + editable() + with _locked_plugin_state(config.get_config_path()), config._CONFIG_LOCK: + raw = config.read_user_config_raw() + entry = raw.get("plugins", {}).get("entries", {}).get("sloth-memory", {}) + backup = entry.get("settings", {}).get("route_backup") + applied = entry.get("settings", {}).get("route_applied", {}) + current = raw.get("model", {}) + if isinstance(current, str): + current = {"default": current} + raw["model"] = current + urls = {url.rstrip("/") + "/v1" for url in [settings["base_url"], *settings["previous_urls"]]} + current_url = current.get("base_url", "").rstrip("/") + # A refused preferred port can belong to the user's original backend. + # Only an applied route (or an already-connected legacy install) proves + # that an address in previous_urls actually belonged to Sloth. + owned_route = (bool(applied) and current_url == applied.get("base_url", "").rstrip("/")) + legacy_route = not applied and settings["connected"] and current_url in urls + if not owned_route and not legacy_route: + backup = {field: copy.deepcopy(current[field]) for field in FIELDS if field in current} + saved = raw.setdefault("plugins", {}).setdefault("entries", {}).setdefault("sloth-memory", {}).setdefault("settings", {}) + saved.update(route_backup=backup, route_applied=model) + raw.setdefault("model", {}).update(model) + config.save_config(raw) + + +def restored_config(raw): + result = copy.deepcopy(raw) + plugins = result.setdefault("plugins", {}) + entry = plugins.setdefault("entries", {}).setdefault("sloth-memory", {}) + settings = entry.setdefault("settings", {}) + service = {**defaults(), **settings.get("service", entry.get("config", {}).get("service", {}))} + model = result.get("model", {}) + # Hermes also accepts the legacy shorthand model: "provider/model". + route_model = {"default": model} if isinstance(model, str) else model + applied = settings.get("route_applied", {}) + # Historical preferred ports may belong to upstream servers, not Sloth. + urls = {applied["base_url"].rstrip("/")} if applied.get("base_url") else {service["base_url"].rstrip("/") + "/v1"} + restore = route_model.get("base_url", "").rstrip("/") in urls + if restore: + backup = settings.get("route_backup") + if not isinstance(backup, dict): + raise ValueError("This installation has no original model-route backup. Select your original backend " + "in Hermes first, then retry uninstall. See docs/uninstall.md.") + if any(model.get(field) != applied.get(field) for field in FIELDS): + raise ValueError("Model routing changed after setup. Select your original backend in Hermes first, " + "then retry uninstall; your edits have been kept.") + for field in FIELDS: + model.pop(field, None) + if field in backup: + model[field] = copy.deepcopy(backup[field]) + service.update(autostart=False, connected=False, uninstalled=True) + settings["service"] = service + plugins["enabled"] = [name for name in plugins.get("enabled", []) if name != "sloth-memory"] + plugins["disabled"] = list(dict.fromkeys([*plugins.get("disabled", []), "sloth-memory"])) + return result, service, restore + + +def run(*, confirm=False): + from hermes_cli import config + from hermes_cli.plugins import _locked_plugin_state + editable() + raw = config.read_user_config_raw() + _, settings, restore = restored_config(raw) + options = dict(external=settings["external"], + managed_backend=settings["backend"] == "llama.cpp" and not settings["upstream_url"]) + processes = removal.plan(settings["archive_dir"], **options) + lines = ["Restore the previous Hermes model route." if restore else "Keep the current Hermes model route.", + "Disable the plugin and its automatic startup."] + for field in ("proxy", "backend"): + if processes[field]: + lines.append(f"Stop Sloth's {field} (PID {processes[field]['pid']}).") + if settings["external"]: + lines.append("The externally managed proxy remains running.") + lines += ["Keep saved snapshots, model weights, runtime builds, and transcripts.", + "Archive: " + settings["archive_dir"]] + if not confirm: + return "Uninstall preview (no changes made):\n" + "\n".join(lines) + "\nFinish other turns first, then run /sloth uninstall confirm." + + def disconnect(): + # Re-read under the same locks as Hermes' native plugin config writer. + with _locked_plugin_state(config.get_config_path()), config._CONFIG_LOCK: + editable() + current = config.read_user_config_raw() + if current != raw: + raise RuntimeError("Hermes configuration changed during uninstall; preview and retry.") + restored, _, _ = restored_config(current) + config.save_config(restored) + + removal.stop(settings["archive_dir"], disconnect=disconnect, **options) + return ("Sloth disconnected; owned services stopped and automatic startup disabled. " + "Restart Hermes and start a new conversation to use your restored route. " + "Existing conversations can retain the old proxy URL.\n" + "Snapshots and runtime builds are kept. Archive: " + settings["archive_dir"] + "\n" + "After closing every Hermes process using this Python environment, remove the package in a terminal:\n" + "python -m pip uninstall sloth-memory\nUse the same Python environment that runs Hermes.") diff --git a/src/sloth_memory/proxy.py b/src/sloth_memory/proxy.py index 6f4a4af..347ef2b 100755 --- a/src/sloth_memory/proxy.py +++ b/src/sloth_memory/proxy.py @@ -747,6 +747,7 @@ def main(): from .platforms import process_identity server = bind_server(Handler, LISTEN_PORT, backend().url) atomic_json(ARCHIVE / "proxy.json", dict(**process_identity(os.getpid()), + archive_dir=str(ARCHIVE), python_prefix=str(Path(sys.prefix).resolve()), launch_token=os.environ.get("SLOTH_LAUNCH_TOKEN"), base_url=f"http://{LISTEN_HOST}:{server.server_port}", upstream_url=backend().url, diff --git a/src/sloth_memory/removal.py b/src/sloth_memory/removal.py new file mode 100644 index 0000000..64c0bd8 --- /dev/null +++ b/src/sloth_memory/removal.py @@ -0,0 +1,89 @@ +"""Stop only archive-owned services, after draining inference and saving state.""" + +import json +import os +from pathlib import Path + +import psutil + +from .cli import request +from .platforms import lock_file, process_matches +from .updates import stop_proxy + + +def owned_process(archive, filename): + path = archive / filename + if not path.exists(): + return None + record = json.loads(path.read_text()) + if not process_matches(record): + return None + try: + argv = psutil.Process(record["pid"]).cmdline() + except psutil.NoSuchProcess: + return None + except psutil.Error as exc: + raise RuntimeError("Cannot inspect the recorded service; stop it through its service owner.") from exc + if filename == "proxy.json": + valid = (argv[1:4] == ["-m", "sloth_memory", "serve"] + or argv[1:5] == ["-I", "-m", "sloth_memory", "serve"] + or len(argv) > 2 and Path(argv[1]).name in {"sloth-memory", "sloth-memory.exe"} and argv[2] == "serve") + flag = "--archive-dir" + else: + valid = argv == record.get("argv") + flag = "--slot-save-path" + try: + valid = valid and Path(argv[argv.index(flag) + 1]).resolve() == archive + except (ValueError, IndexError): + valid = (valid and filename == "proxy.json" and bool(record.get("archive_dir")) + and Path(record["archive_dir"]).resolve() == archive) + if not valid: + raise RuntimeError(f"Cannot verify ownership of PID {record['pid']}; stop it through its service owner.") + return record + + +def plan(archive, *, external=False, managed_backend=True): + archive = Path(archive).resolve() + return dict(archive_dir=str(archive), + proxy=None if external else owned_process(archive, "proxy.json"), + backend=None if external or not managed_backend else owned_process(archive, "runtime.json")) + + +def stop(archive, *, external=False, managed_backend=True, disconnect=None): + archive = Path(archive).resolve() + # Nonblocking: a startup/update in progress should finish before uninstall. + fd = lock_file(archive / ".hermes-start.lock") + prepared = False + record = None + try: + result = plan(archive, external=external, managed_backend=managed_backend) + record = result["proxy"] + if record: + status = request(record["base_url"], "status", timeout=5) + if (status.get("service") != "sloth-memory" or status.get("control_version", 0) < 4 + or Path(status.get("archive_dir", "")).resolve() != archive): + raise RuntimeError("Proxy cannot drain safely; stop clients and follow the manual uninstall guide.") + request(record["base_url"], "prepare-update", {}, timeout=90) + prepared = True + # Restore the agent's route before removing the service it pointed at. + if disconnect: + disconnect() + for filename, field in (("proxy.json", "proxy"), ("runtime.json", "backend")): + if result[field]: + current = owned_process(archive, filename) + if current and current != result[field]: + raise RuntimeError("Service identity changed during uninstall; retry after stopping other clients.") + if current: + try: + stop_proxy(current) + except psutil.NoSuchProcess: + pass + except (psutil.Error, RuntimeError) as exc: + raise RuntimeError(f"Could not stop Sloth's {field}; inspect its process before retrying: {exc}") from exc + return result + except BaseException: + if prepared and record and process_matches(record): + request(record["base_url"], "cancel-update", {}, timeout=5) + raise + finally: + os.close(fd) diff --git a/tests/hermes/test_integration.py b/tests/hermes/test_integration.py index 8040e82..bc13790 100644 --- a/tests/hermes/test_integration.py +++ b/tests/hermes/test_integration.py @@ -105,6 +105,52 @@ def test_update_check_dispatches_without_installing_or_restarting(self): self.assertIn("Available: 0.2.0a2", text) install.assert_not_called() + def test_uninstall_restores_route_disables_plugin_and_does_not_restart_it(self): + from hermes_cli.config import read_user_config_raw, save_config + adapter = self.command.__self__ + # The original server occupied Sloth's preferred port, forcing fallback. + original = dict(provider="custom", default="gemma", base_url="http://127.0.0.1:8080/v1", context_length=12345) + adapter.ctx.set_config("service", {**adapter.settings(), "previous_urls": ["http://127.0.0.1:8080"]}) + save_config({"model": original}, merge_existing=True) + self.command_text("connect") + self.command_text("connect") # Reconnect must not overwrite the original route. + before = read_user_config_raw() + preview = asyncio.run(self.gateway_command("uninstall", command="sloth", platform="telegram")) + self.assertIn("no changes", preview) + self.assertEqual(before, read_user_config_raw()) + result = asyncio.run(self.gateway_command("uninstall confirm", command="sloth", platform="telegram")) + self.assertIn("Sloth disconnected", result) + current = read_user_config_raw() + self.assertEqual(current["model"], original) + self.assertEqual(current["agent"]["max_turns"], 12) + self.assertIn("sloth-memory", current["plugins"]["disabled"]) + self.assertNotIn("sloth-memory", current["plugins"]["enabled"]) + self.assertTrue(adapter.service.closed.is_set()) + self.assertIsNone(adapter.middleware(request={}, base_url=self.url + "/v1", api_mode="chat_completions")) + self.assertIn("Sloth is disconnected", self.command_text("status")) + self.assertIn("Sloth disconnected", self.command_text("uninstall confirm")) + self.manager.unload() + self.manager.discover_and_load(force=True) + from hermes_cli.plugins import get_plugin_command_handler + self.assertIsNone(get_plugin_command_handler("sloth")) + + def test_uninstall_without_route_backup_does_not_change_profile(self): + from hermes_cli.config import read_user_config_raw + before = read_user_config_raw() + result = self.command_text("uninstall confirm") + self.assertIn("no original model-route backup", result) + self.assertEqual(before, read_user_config_raw()) + + def test_uninstall_respects_managed_plugin_leaf_settings(self): + from hermes_cli.config import read_user_config_raw + before = read_user_config_raw() + for key in ("plugins.entries.sloth-memory.settings.service.autostart", + "plugins.entries.sloth-memory.settings.route_backup.base_url"): + with patch("hermes_cli.managed_scope.managed_config_keys", return_value={key}): + result = self.command_text("uninstall confirm") + self.assertIn("managed by your administrator", result) + self.assertEqual(before, read_user_config_raw()) + def test_successful_update_requests_native_gateway_restart_after_reply(self): from unittest.mock import Mock from hermes_cli.lifecycle import invoke_hook @@ -122,6 +168,7 @@ async def command(): gateway.request_restart.assert_called_once_with(detached=False, via_service=True) with patch.object(updates, "apply", return_value=dict(version="0.2.0a2", note="Updated.")), \ patch("importlib.metadata.version", return_value="0.2.0a2"), \ + patch("sloth_memory.__version__", "0.2.0a1"), \ patch("gateway.restart.is_gateway_supervisor_process", return_value=True): asyncio.run(command()) diff --git a/tests/test_backends.py b/tests/test_backends.py index e375524..3e08ba1 100644 --- a/tests/test_backends.py +++ b/tests/test_backends.py @@ -90,6 +90,23 @@ def start(self, backend): time.sleep(.05) self.fail("proxy did not publish its bound address: " + log.read_text(errors="replace")) + def test_uninstall_stops_each_proxy_and_keeps_existing_backend_available(self): + from sloth_memory import removal + from urllib.request import urlopen + for name in ("llama.cpp", "ollama", "vllm", "mlx"): + with self.subTest(backend=name): + record, archive = self.start(name) + snapshot = archive / "saved-test.bin" + snapshot.write_bytes(b"preserve") + self.assertEqual(removal.plan(archive)["proxy"]["pid"], record["pid"]) + self.assertTrue(request(record["base_url"], "doctor")["ok"]) + removal.stop(archive, managed_backend=False) + self.assertIsNone(proxy_record(archive)) + with urlopen(self.upstream_url + "/v1/models", timeout=5) as response: + self.assertEqual(response.status, 200) + self.assertEqual(snapshot.read_bytes(), b"preserve") + self.assertIsNone(removal.stop(archive, managed_backend=False)["proxy"]) + def test_four_backends_forward_models_streaming_tools_and_report_capabilities(self): for name in ("llama.cpp", "ollama", "vllm", "mlx"): with self.subTest(backend=name): diff --git a/tests/test_removal.py b/tests/test_removal.py new file mode 100644 index 0000000..e386637 --- /dev/null +++ b/tests/test_removal.py @@ -0,0 +1,154 @@ +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time +import unittest +from unittest.mock import patch + +import psutil + +from sloth_memory import removal +from sloth_memory.hermes_uninstall import restored_config +from sloth_memory.platforms import process_identity + + +class RestoreTests(unittest.TestCase): + def profile(self): + applied = dict(provider="custom", default="gemma", base_url="http://127.0.0.1:8080/v1", api_mode="chat_completions") + return dict(model={**applied, "context_length": 12345}, agent={"max_turns": 8}, plugins=dict( + enabled=["other", "sloth-memory"], entries={"sloth-memory": {"settings": { + "service": {"connected": True}, "route_applied": applied, + "route_backup": {"provider": "custom", "default": "gemma", "base_url": "http://127.0.0.1:11434/v1"}}}})) + + def test_restore_removes_added_fields_and_preserves_other_settings(self): + original = self.profile() + result, settings, restored = restored_config(original) + self.assertTrue(restored) + self.assertEqual(result["model"]["base_url"], "http://127.0.0.1:11434/v1") + self.assertNotIn("api_mode", result["model"]) + self.assertEqual(result["model"]["context_length"], 12345) + self.assertEqual(result["agent"], original["agent"]) + self.assertEqual(result["plugins"]["enabled"], ["other"]) + self.assertIn("sloth-memory", result["plugins"]["disabled"]) + self.assertFalse(settings["autostart"]) + self.assertTrue(settings["uninstalled"]) + self.assertEqual(original["model"]["base_url"], "http://127.0.0.1:8080/v1") + again, _, restored = restored_config(result) + self.assertFalse(restored) + self.assertEqual(result, again) + + def test_changed_route_is_preserved_and_missing_backup_fails_closed(self): + profile = self.profile() + profile["plugins"]["entries"]["sloth-memory"]["settings"].pop("route_backup") + with self.assertRaisesRegex(ValueError, "no original"): + restored_config(profile) + profile["model"]["base_url"] = "http://127.0.0.1:9999/v1" + result, _, restored = restored_config(profile) + self.assertFalse(restored) + self.assertEqual(result["model"], profile["model"]) + + def test_user_edits_on_proxy_route_are_not_overwritten(self): + profile = self.profile() + profile["model"]["default"] = "another-model" + with self.assertRaisesRegex(ValueError, "routing changed"): + restored_config(profile) + + def test_legacy_model_string_is_preserved_when_already_disconnected(self): + profile = self.profile() + profile["model"] = "provider/original-model" + result, _, restored = restored_config(profile) + self.assertFalse(restored) + self.assertEqual(result["model"], profile["model"]) + + +class RemovalTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.archive = Path(self.tmp.name).resolve() + + def test_preview_does_not_create_archive_and_external_never_inspects_processes(self): + missing = self.archive / "missing" + self.assertIsNone(removal.plan(missing)["proxy"]) + self.assertFalse(missing.exists()) + with patch.object(removal, "owned_process") as owned: + removal.stop(self.archive, external=True) + owned.assert_not_called() + + def test_live_unrelated_pid_and_reused_pid_are_not_stopped(self): + record = process_identity(os.getpid()) + path = self.archive / "proxy.json" + path.write_text(json.dumps(record)) + with self.assertRaisesRegex(RuntimeError, "ownership"): + removal.plan(self.archive) + record["created_at"] -= 1 + path.write_text(json.dumps(record)) + self.assertIsNone(removal.plan(self.archive)["proxy"]) + + def test_real_owned_backend_stops_and_unrelated_process_survives(self): + script = self.archive / "fake_backend.py" + script.write_text("import pathlib, sys, time; pathlib.Path(sys.argv[1]).touch(); time.sleep(60)") + ready = self.archive / "ready" + argv = [sys.executable, str(script), str(ready), "--slot-save-path", str(self.archive)] + children = [subprocess.Popen(argv), subprocess.Popen([sys.executable, str(script), str(self.archive / "other-ready")])] + def cleanup(): + for child in children: + if child.poll() is None: + child.terminate() + child.wait(10) + self.addCleanup(cleanup) + deadline = time.monotonic() + 10 + while not ready.exists() and time.monotonic() < deadline: + self.assertIsNone(children[0].poll()) + time.sleep(.01) + self.assertTrue(ready.exists(), "fake backend did not start") + # macOS framework Python can re-exec with a different argv[0]. This + # fixture records the ready Python stand-in, not its transient launcher. + actual = psutil.Process(children[0].pid).cmdline() + self.assertEqual(actual[1:], argv[1:]) + record = {**process_identity(children[0].pid), "argv": actual} + (self.archive / "runtime.json").write_text(json.dumps(record)) + (self.archive / "snapshot.bin").write_bytes(b"keep") + # The externally launched upstream mode does not own this backend. + self.assertIsNone(removal.plan(self.archive, managed_backend=False)["backend"]) + removal.stop(self.archive) + self.assertIsNotNone(children[0].poll()) + self.assertIsNone(children[1].poll()) + self.assertEqual((self.archive / "snapshot.bin").read_bytes(), b"keep") + self.assertIsNone(removal.stop(self.archive)["backend"]) + + def test_failed_drain_never_disconnects_or_stops_processes(self): + record = dict(pid=123, base_url="http://127.0.0.1:8080") + result = dict(proxy=record, backend=None) + status = dict(service="sloth-memory", control_version=4, archive_dir=str(self.archive)) + with patch.object(removal, "plan", return_value=result), \ + patch.object(removal, "request", side_effect=[status, RuntimeError("busy")]), \ + patch.object(removal, "stop_proxy") as stop, \ + patch.object(removal, "process_matches", return_value=True): + from unittest.mock import Mock + disconnect = Mock() + with self.assertRaisesRegex(RuntimeError, "busy"): + removal.stop(self.archive, disconnect=disconnect) + disconnect.assert_not_called() + stop.assert_not_called() + + def test_config_failure_reopens_proxy_without_stopping_it(self): + record = dict(pid=123, base_url="http://127.0.0.1:8080") + status = dict(service="sloth-memory", control_version=4, archive_dir=str(self.archive)) + def disconnect(): + raise RuntimeError("configuration changed") + with patch.object(removal, "plan", return_value=dict(proxy=record, backend=None)), \ + patch.object(removal, "request", side_effect=[status, {"ok": True}, {"ok": True}]) as request, \ + patch.object(removal, "stop_proxy") as stop, \ + patch.object(removal, "process_matches", return_value=True): + with self.assertRaisesRegex(RuntimeError, "configuration changed"): + removal.stop(self.archive, disconnect=disconnect) + self.assertEqual([call.args[1] for call in request.call_args_list], ["status", "prepare-update", "cancel-update"]) + stop.assert_not_called() + + +if __name__ == "__main__": + unittest.main()