uninstall.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. """Hermes Agent Uninstaller."""
  2. import os
  3. import shutil
  4. import subprocess
  5. import sys
  6. from pathlib import Path
  7. from hermes_constants import get_hermes_home
  8. from hermes_cli.colors import Colors, color
  9. def _logger(mark: str, col: str):
  10. return lambda msg: print(f"{color(mark, col)} {msg}")
  11. log_info = _logger("→", Colors.CYAN)
  12. log_success = _logger("✓", Colors.GREEN)
  13. log_warn = _logger("⚠", Colors.YELLOW)
  14. def _print_box(middle: str, col: str) -> None:
  15. """Print the 3-line framed heading used by the uninstall screens."""
  16. print(color("┌─────────────────────────────────────────────────────────┐", col, Colors.BOLD))
  17. print(color(middle, col, Colors.BOLD))
  18. print(color("└─────────────────────────────────────────────────────────┘", col, Colors.BOLD))
  19. def _prompt(text: str):
  20. """``input(text).strip().lower()``; None (after printing "Cancelled.") on Ctrl-C/EOF."""
  21. try:
  22. return input(text).strip().lower()
  23. except (KeyboardInterrupt, EOFError):
  24. print()
  25. print("Cancelled.")
  26. return None
  27. def _cancelled() -> None:
  28. print()
  29. print("Uninstall cancelled.")
  30. def _confirm_yes(text: str) -> bool:
  31. """Ask the user to type ``yes``; False (after the cancel line, unless Ctrl-C/EOF) otherwise."""
  32. confirm = _prompt(f"Type '{color('yes', Colors.YELLOW)}' {text}: ")
  33. if confirm != "yes" and confirm is not None:
  34. _cancelled()
  35. return confirm == "yes"
  36. def _remove_each(candidates, remove) -> list:
  37. """Run ``remove(path)`` per candidate, collecting the ones it reports removed; failures become
  38. the shared ``Could not remove <path>: <err>`` warning."""
  39. removed = []
  40. for path in candidates:
  41. try:
  42. if remove(path):
  43. removed.append(path)
  44. except Exception as e:
  45. log_warn(f"Could not remove {path}: {e}")
  46. return removed
  47. def get_project_root() -> Path:
  48. """Get the project installation directory."""
  49. return Path(__file__).parent.parent.resolve()
  50. def code_removal_refusal() -> str | None:
  51. """Why the uninstaller must not remove this tree's code, or ``None``.
  52. A git checkout (the install.sh / install.ps1 / `hermes desktop` layout)
  53. is ours to remove. A sealed tree (no ``.git``) belongs to a steward —
  54. the Nix store, the bundled desktop app, a Docker image — and only the
  55. steward removes it. Returns the user-facing refusal text for sealed
  56. trees; the text always points at ``hermes uninstall --data`` for the
  57. user-data cleanup that IS allowed everywhere.
  58. """
  59. from hermes_cli.steward import sealed_steward, steward_uninstall_message
  60. steward = sealed_steward(get_project_root())
  61. if steward is None:
  62. return None
  63. return steward_uninstall_message(steward)
  64. def _refuse_if_steward_owned() -> None:
  65. """Exit with the steward's instructions when code removal is forbidden."""
  66. refusal = code_removal_refusal()
  67. if refusal is None:
  68. return
  69. print()
  70. print(refusal)
  71. print()
  72. raise SystemExit(1)
  73. def find_shell_configs() -> list:
  74. """Find shell configuration files that might have PATH entries."""
  75. home = Path.home()
  76. configs = []
  77. candidates = [
  78. home / ".bashrc",
  79. home / ".bash_profile",
  80. home / ".profile",
  81. home / ".zshrc",
  82. home / ".zprofile",
  83. ]
  84. for config in candidates:
  85. if config.exists():
  86. configs.append(config)
  87. return configs
  88. def remove_path_from_shell_configs():
  89. """Remove Hermes PATH entries from shell configuration files."""
  90. removed_from = []
  91. for config_path in find_shell_configs():
  92. try:
  93. content = config_path.read_text(encoding="utf-8-sig")
  94. original_content = content
  95. # Remove lines containing hermes-agent or hermes PATH entries
  96. new_lines = []
  97. skip_next = False
  98. for line in content.split('\n'):
  99. # Skip the "# Hermes Agent" comment and following line
  100. if '# Hermes Agent' in line or '# hermes-agent' in line:
  101. skip_next = True
  102. continue
  103. if skip_next and ('hermes' in line.lower() and 'PATH' in line):
  104. skip_next = False
  105. continue
  106. skip_next = False
  107. # Remove any PATH line containing hermes
  108. if 'hermes' in line.lower() and ('PATH=' in line or 'path=' in line.lower()):
  109. continue
  110. new_lines.append(line)
  111. new_content = '\n'.join(new_lines)
  112. # Clean up multiple blank lines
  113. while '\n\n\n' in new_content:
  114. new_content = new_content.replace('\n\n\n', '\n\n')
  115. if new_content != original_content:
  116. from utils import atomic_write_text
  117. # The user's own rc, never backed up: a bare write_text() truncates before the new
  118. # content lands and a crash mid-write would leave an empty ~/.zshrc. Atomic replace
  119. # also follows a symlinked rc; preserve_mode keeps its bits/owner (sudo-run uninstalls).
  120. atomic_write_text(config_path, new_content, preserve_mode=True)
  121. removed_from.append(config_path)
  122. except Exception as e:
  123. log_warn(f"Could not update {config_path}: {e}")
  124. return removed_from
  125. def remove_wrapper_script():
  126. """Remove the hermes wrapper script if it exists."""
  127. wrapper_paths = [
  128. Path.home() / ".local" / "bin" / "hermes",
  129. Path.home() / ".local" / "bin" / "hermes-acp",
  130. Path.home() / ".local" / "bin" / "hermes-agent",
  131. Path("/usr/local/bin/hermes"),
  132. Path("/usr/local/bin/hermes-acp"),
  133. Path("/usr/local/bin/hermes-agent"),
  134. ]
  135. removed = []
  136. for wrapper in wrapper_paths:
  137. if wrapper.exists():
  138. try:
  139. # Check if it's our wrapper (contains hermes_cli reference)
  140. content = wrapper.read_text(encoding="utf-8-sig")
  141. if 'hermes_cli' in content or 'hermes-agent' in content:
  142. wrapper.unlink()
  143. removed.append(wrapper)
  144. except Exception as e:
  145. log_warn(f"Could not remove {wrapper}: {e}")
  146. return removed
  147. def _node_symlink_candidate_dirs() -> list[Path]:
  148. """Directories where the installer may have placed node/npm/npx symlinks."""
  149. dirs: list[Path] = [Path.home() / ".local" / "bin"]
  150. if sys.platform == "linux": # root FHS installs put links in /usr/local/bin
  151. dirs.append(Path("/usr/local/bin"))
  152. return dirs
  153. def remove_node_symlinks(hermes_home: Path) -> list:
  154. """Remove the node/npm/npx symlinks the installer placed on PATH.
  155. Historical POSIX installs (``scripts/install.sh`` before pm owned the
  156. Node runtime) symlinked node/npm/npx into the same directory as the
  157. ``hermes`` command:
  158. - ``/usr/local/bin/`` on root FHS installs (Linux, uid 0)
  159. - ``~/.local/bin/`` otherwise (the common non-root case)
  160. We check all candidate directories so that uninstall works regardless of
  161. how the install was done (e.g. a root FHS install that placed links in
  162. ``/usr/local/bin``, or an older install that used ``~/.local/bin`` before
  163. the FHS fix). Only symlinks that resolve into this Hermes home's ``node``
  164. directory are removed — links the user has repointed elsewhere (nvm, fnm,
  165. etc.) are left untouched.
  166. """
  167. node_dir = (hermes_home / "node").resolve()
  168. def _unlink_ours(link: Path) -> bool:
  169. # Only act on symlinks — never delete a real binary the user put here.
  170. if not link.is_symlink():
  171. return False
  172. # resolve() normalizes native Windows extended-path prefixes too.
  173. target = link.resolve()
  174. if target != node_dir and node_dir not in target.parents:
  175. return False
  176. link.unlink()
  177. return True
  178. candidates = (bin_dir / name for name in ("node", "npm", "npx") for bin_dir in _node_symlink_candidate_dirs())
  179. return _remove_each(candidates, _unlink_ours)
  180. def uninstall_gateway_service():
  181. """Stop and uninstall the gateway service (systemd, launchd, Windows
  182. Scheduled Task / Startup folder) and kill any standalone gateway processes.
  183. Delegates to the gateway module which handles:
  184. - Linux: user + system systemd services (with proper DBUS env setup)
  185. - macOS: launchd plists
  186. - Windows: Scheduled Task + Startup-folder fallback, via ``gateway_windows``
  187. - All platforms: standalone ``hermes gateway run`` processes
  188. """
  189. import platform
  190. stopped_something = False
  191. # 1. Kill any standalone gateway processes (all platforms)
  192. try:
  193. from hermes_cli.gateway import kill_gateway_processes, find_gateway_pids
  194. killed = kill_gateway_processes() if find_gateway_pids() else 0
  195. if killed:
  196. log_success(f"Killed {killed} running gateway process(es)")
  197. stopped_something = True
  198. except Exception as e:
  199. log_warn(f"Could not check for gateway processes: {e}")
  200. # Termux/Android has no systemd and no launchd — nothing left to do.
  201. if os.getenv("TERMUX_VERSION") or "com.termux/files/usr" in os.getenv("PREFIX", ""):
  202. return stopped_something
  203. # 2. Per-platform service removal (systemd / launchd / Scheduled Task).
  204. remover, warn_label = _GATEWAY_SERVICE_REMOVERS.get(platform.system(), (None, ""))
  205. if remover is not None:
  206. try:
  207. stopped_something = remover() or stopped_something
  208. except Exception as e:
  209. log_warn(f"{warn_label}: {e}")
  210. return stopped_something
  211. def _remove_systemd_gateway() -> bool:
  212. """Linux: uninstall systemd services (both user and system scopes)."""
  213. from hermes_cli.gateway import (
  214. _systemctl_cmd, _systemd_unit_belongs_to_current_home, get_service_name, get_systemd_unit_path,
  215. )
  216. svc_name = get_service_name()
  217. removed_any = False
  218. for is_system, scope in ((False, "user"), (True, "system")):
  219. unit_path = get_systemd_unit_path(system=is_system)
  220. if not unit_path.exists() or not _systemd_unit_belongs_to_current_home(is_system):
  221. continue
  222. try:
  223. if is_system and os.geteuid() != 0: # windows-footgun: ok — Linux-only systemd path
  224. log_warn(f"System gateway service exists at {unit_path} but needs sudo to remove")
  225. continue
  226. cmd = _systemctl_cmd(is_system)
  227. for verb in ("stop", "disable"):
  228. subprocess.run(cmd + [verb, svc_name], capture_output=True, check=False)
  229. unit_path.unlink()
  230. subprocess.run(cmd + ["daemon-reload"], capture_output=True, check=False)
  231. log_success(f"Removed {scope} gateway service ({unit_path})")
  232. removed_any = True
  233. except Exception as e:
  234. log_warn(f"Could not remove {scope} gateway service: {e}")
  235. return removed_any
  236. # Both gateway LaunchAgent naming schemes: the current ``ai.hermes.gateway*``
  237. # label and the ``io.nousresearch.hermes-agent.gateway*`` label older builds
  238. # installed. An uninstall must sweep BOTH — a stale agent keeps respawning the
  239. # gateway after the code tree is gone (#62209).
  240. _LAUNCHD_GATEWAY_PLIST_PATTERNS = (
  241. "ai.hermes.gateway*.plist",
  242. "io.nousresearch.hermes-agent.gateway*.plist",
  243. )
  244. def _launchd_gateway_plists() -> list[Path]:
  245. """Every gateway LaunchAgent plist on disk, under the real account home."""
  246. from hermes_cli.gateway import get_launchd_plist_path
  247. launch_agents = get_launchd_plist_path().parent
  248. return sorted({p for pattern in _LAUNCHD_GATEWAY_PLIST_PATTERNS for p in launch_agents.glob(pattern)})
  249. def _remove_launchd_gateway() -> bool:
  250. """macOS: boot out and uninstall every gateway LaunchAgent plist.
  251. Sweeps BOTH label patterns (see ``_LAUNCHD_GATEWAY_PLIST_PATTERNS``):
  252. uninstalling only the current label's plist left older-label agents
  253. registered, and launchd kept respawning the gateway after removal.
  254. ``bootout`` (both Aqua and per-user domains, whichever holds the job) plus
  255. the legacy ``unload`` run before the unlink so launchd never respawns a
  256. job whose plist is gone.
  257. """
  258. plists = _launchd_gateway_plists()
  259. uid = os.getuid() # windows-footgun: ok — darwin-only (called from the macOS branch)
  260. for plist_path in plists:
  261. label = plist_path.stem
  262. for domain in (f"gui/{uid}", f"user/{uid}"):
  263. subprocess.run(["launchctl", "bootout", f"{domain}/{label}"], capture_output=True, check=False)
  264. subprocess.run(["launchctl", "unload", str(plist_path)], capture_output=True, check=False)
  265. plist_path.unlink()
  266. log_success(f"Removed macOS gateway service ({plist_path})")
  267. return bool(plists)
  268. def _remove_windows_gateway() -> bool:
  269. """Windows: uninstall Scheduled Task + Startup-folder entry via ``gateway_windows`` (it owns
  270. schtasks /Delete, the .cmd unlink and stopping the detached pythonw gateway)."""
  271. from hermes_cli import gateway_windows as gw
  272. if not any(probe() for probe in (gw.is_installed, gw.is_task_registered, gw.is_startup_entry_installed)):
  273. return False
  274. try:
  275. gw.stop()
  276. except Exception as e:
  277. log_warn(f"Could not stop Windows gateway cleanly: {e}")
  278. try:
  279. gw.uninstall()
  280. log_success("Removed Windows gateway (Scheduled Task + Startup entry)")
  281. return True
  282. except Exception as e:
  283. log_warn(f"Could not fully uninstall Windows gateway: {e}")
  284. return False
  285. # platform.system() -> (remover, warning label when the remover itself blows up)
  286. _GATEWAY_SERVICE_REMOVERS = {
  287. "Linux": (_remove_systemd_gateway, "Could not check systemd gateway services"),
  288. "Darwin": (_remove_launchd_gateway, "Could not remove launchd gateway service"),
  289. "Windows": (_remove_windows_gateway, "Could not check Windows gateway service")}
  290. # Windows helpers. install.ps1 leaves four things no rc file covers: User-scope env vars
  291. # HERMES_HOME / HERMES_GIT_BASH_PATH (HKCU\Environment), User-scope PATH entries
  292. # (%LOCALAPPDATA%\hermes\git\{cmd,bin,usr\bin}, ...\hermes\node), PortableGit + Node copies
  293. # (~200MB) and the gateway-service dir. Direct winreg writes (not PowerShell): no subprocess, and
  294. # they work under Constrained Language Mode; new shells see them without WM_SETTINGCHANGE.
  295. def _hermes_path_markers(hermes_home: Path, *, include_managed_bin: bool = False) -> list[str]:
  296. r"""Prefixes identifying Hermes-owned User-PATH entries (prefix match sweeps git\cmd, git\bin,
  297. node...). ``include_managed_bin`` adds ``<root>\bin`` (launchers + managed uv) — only when that
  298. dir is about to be deleted, so a keep-data uninstall keeps the working uv resolvable."""
  299. root = str(hermes_home).rstrip("\\/")
  300. subs = ("hermes-agent", "git", "node", "venv") + (("bin",) if include_managed_bin else ())
  301. return [f"{root}\\{sub}" for sub in subs]
  302. def remove_path_from_windows_registry(hermes_home: Path, *, include_managed_bin: bool = False) -> list[str]:
  303. """Strip Hermes-owned entries from User-scope PATH in the registry (see ``_hermes_path_markers``)."""
  304. markers = tuple(m.lower() for m in _hermes_path_markers(hermes_home, include_managed_bin=include_managed_bin))
  305. def edit(winreg, key, removed):
  306. try:
  307. path_value, path_type = winreg.QueryValueEx(key, "Path")
  308. except FileNotFoundError:
  309. return
  310. # Preserve REG_EXPAND_SZ vs REG_SZ so unexpanded %VARS% survive.
  311. kept: list[str] = []
  312. for entry in (e for e in path_value.split(";") if e):
  313. is_ours = entry.rstrip("\\/").lower().startswith(markers)
  314. (removed if is_ours else kept).append(entry)
  315. if removed:
  316. winreg.SetValueEx(key, "Path", 0, path_type, ";".join(kept))
  317. return _edit_user_environment(edit, warn_label="Could not edit User PATH in registry")
  318. def remove_hermes_env_vars_windows() -> list[str]:
  319. """Delete HERMES_HOME and HERMES_GIT_BASH_PATH from User-scope env vars."""
  320. def edit(winreg, key, removed):
  321. for name in ("HERMES_HOME", "HERMES_GIT_BASH_PATH"):
  322. try:
  323. winreg.QueryValueEx(key, name)
  324. except FileNotFoundError:
  325. continue
  326. try:
  327. winreg.DeleteValue(key, name)
  328. removed.append(name)
  329. except OSError as e:
  330. log_warn(f"Could not delete {name} from User env: {e}")
  331. return _edit_user_environment(edit, warn_label="Could not open User Environment key")
  332. def _edit_user_environment(edit, *, warn_label: str) -> list[str]:
  333. """Open HKCU\\Environment read/write and run ``edit(winreg, key, removed)``. Returns what
  334. ``edit`` appended to ``removed`` even if a later registry call raised (callers report exactly
  335. what was touched); ``[]`` off-Windows (no ``winreg``)."""
  336. removed: list[str] = []
  337. try:
  338. import winreg
  339. except ImportError:
  340. return removed # not on Windows, nothing to do
  341. try:
  342. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0,
  343. winreg.KEY_READ | winreg.KEY_WRITE) as key:
  344. edit(winreg, key, removed)
  345. except OSError as e:
  346. log_warn(f"{warn_label}: {e}")
  347. return removed
  348. def remove_portable_tooling_windows(hermes_home: Path) -> list[Path]:
  349. """Delete the PortableGit / Node / gateway-service dirs the Windows installer created under
  350. ``hermes_home`` (isolated from any system Git / Node, so nothing else breaks)."""
  351. targets = (hermes_home / sub for sub in ("git", "node", "gateway-service"))
  352. return _remove_each((t for t in targets if t.exists()), lambda t: shutil.rmtree(t) or True)
  353. def _xdg_leftover_paths(full_uninstall: bool) -> tuple[list[Path], list[Path]]:
  354. """The XDG cache/data dirs an install scatters outside HERMES_HOME.
  355. Returns (removable, data_preserved): the cache dir is always removable;
  356. the XDG data dir is user data, so it is only removed on a full uninstall
  357. and otherwise reported as intentionally preserved.
  358. """
  359. home = Path.home()
  360. cache = home / ".cache" / "hermes"
  361. data = home / ".local" / "share" / "hermes"
  362. removable = [cache] if cache.exists() else []
  363. if data.exists() and full_uninstall:
  364. removable.append(data)
  365. preserved = [data] if data.exists() and not full_uninstall else []
  366. return removable, preserved
  367. def remove_desktop_app_leftovers(*, full_uninstall: bool) -> list[Path]:
  368. """Remove per-user app leftovers that live outside HERMES_HOME and the
  369. checkout, which earlier uninstallers left behind (#62209): the macOS
  370. Library caches/logs/browser-store/state entries the packaged app and
  371. Electron scatter, and the XDG cache dir on every platform. On a full
  372. uninstall the XDG data dir (``~/.local/share/hermes``) goes too.
  373. Only well-known Hermes-named entries are touched — never a glob of the
  374. whole Library.
  375. """
  376. import sys as _sys
  377. targets: list[Path] = []
  378. home = Path.home()
  379. if _sys.platform == "darwin":
  380. library = home / "Library"
  381. for parent in ("Caches", "Logs", "WebKit", "HTTPStorages", "Saved Application State"):
  382. parent_dir = library / parent
  383. if not parent_dir.is_dir():
  384. continue
  385. try:
  386. entries = list(parent_dir.iterdir())
  387. except OSError:
  388. continue
  389. targets.extend(e for e in entries if "hermes" in e.name.lower())
  390. removable, _ = _xdg_leftover_paths(full_uninstall=full_uninstall)
  391. targets.extend(removable)
  392. return _remove_each((t for t in targets if t.exists()), _remove_path_or_tree)
  393. def _remove_path_or_tree(path: Path) -> bool:
  394. try:
  395. if path.is_symlink() or path.is_file():
  396. path.unlink()
  397. else:
  398. shutil.rmtree(path)
  399. return True
  400. except OSError:
  401. return False
  402. def remove_legacy_runtime_trees(hermes_home: Path) -> list[Path]:
  403. """Delete managed-runtime trees a PRE-SPLIT install left in HERMES_HOME.
  404. Runtime artifacts are install-scoped now, so the current locations go
  405. away with ``rmtree(project_root)``. But a checkout OUTSIDE the home
  406. (the common case: ``~/src/hermes-agent``) used to put its node/uv
  407. under ``$HERMES_HOME`` — that tree survives removing the checkout and
  408. survives "keep my data" uninstalls, because it is not data.
  409. Only the exact managed layout is removed: ``node/`` (a tree the
  410. installer owned wholesale) and ``bin/uv`` (the single binary, NOT the
  411. whole ``bin/`` dir — a user's own scripts can live there). Profile
  412. state is never touched.
  413. """
  414. removed: list[Path] = []
  415. node_tree = hermes_home / "node"
  416. if node_tree.is_dir():
  417. try:
  418. shutil.rmtree(node_tree, ignore_errors=False)
  419. removed.append(node_tree)
  420. except Exception as e:
  421. log_warn(f"Could not remove {node_tree}: {e}")
  422. for uv_name in ("uv", "uv.exe"):
  423. uv_binary = hermes_home / "bin" / uv_name
  424. if uv_binary.is_file():
  425. try:
  426. uv_binary.unlink()
  427. removed.append(uv_binary)
  428. except Exception as e:
  429. log_warn(f"Could not remove {uv_binary}: {e}")
  430. return removed
  431. def remove_windows_bin_launchers(*, windows: bool | None = None) -> list[Path]:
  432. """Delete the managed binary dir (the default Hermes root's ``bin``).
  433. The dir holds only hermes-owned launcher copies (the relocatable venv's
  434. console scripts, staged onto PATH by first-run repair) — pm keeps uv in
  435. its own store entry, so nothing shared lives here and the whole dir goes.
  436. Every uninstall mode deletes the code checkout, so a surviving launcher
  437. would dangle: ``hermes`` in a new terminal resolves and then errors on
  438. its missing venv target, which reads worse than command-not-found.
  439. A launcher that IS this process's own trampoline is mandatory-locked
  440. against deletion but not rename, so removal falls back to renaming it
  441. aside with a non-executable suffix.
  442. *windows* is an injectable platform verdict for tests (same pattern as
  443. ``_install_repair.ensure_windows_bin_launchers``).
  444. """
  445. if windows is None:
  446. windows = _is_windows()
  447. if not windows:
  448. return []
  449. try:
  450. from hermes_constants import get_default_hermes_root
  451. bin_dir = get_default_hermes_root() / "bin"
  452. except Exception as e:
  453. log_warn(f"Could not locate the managed binary dir: {e}")
  454. return []
  455. if not bin_dir.is_dir():
  456. return []
  457. removed: list[Path] = []
  458. for launcher in sorted(bin_dir.iterdir()):
  459. if not launcher.is_file():
  460. continue
  461. try:
  462. launcher.unlink()
  463. removed.append(launcher)
  464. except OSError:
  465. aside = launcher.with_name(f"{launcher.name}.uninstalled.{os.getpid()}")
  466. try:
  467. os.rename(launcher, aside)
  468. removed.append(launcher)
  469. except OSError as e:
  470. log_warn(f"Could not remove {launcher}: {e}")
  471. try:
  472. bin_dir.rmdir()
  473. except OSError:
  474. pass # leftovers (renamed-aside trampolines) keep the dir until next run
  475. return removed
  476. def _is_windows() -> bool:
  477. return sys.platform == "win32"
  478. def _is_default_hermes_home(hermes_home: Path) -> bool:
  479. """Return True when ``hermes_home`` points at the default (non-profile) root."""
  480. try:
  481. from hermes_constants import get_default_hermes_root
  482. return hermes_home.resolve() == get_default_hermes_root().resolve()
  483. except Exception:
  484. return False
  485. def _discover_named_profiles():
  486. """``ProfileInfo`` for every non-default profile; ``[]`` when profile support is unavailable."""
  487. try:
  488. from hermes_cli.profiles import list_profiles
  489. except Exception:
  490. return []
  491. try:
  492. return [p for p in list_profiles() if not getattr(p, "is_default", False)]
  493. except Exception as e:
  494. log_warn(f"Could not enumerate profiles: {e}")
  495. return []
  496. def _uninstall_profile(profile) -> None:
  497. """Fully uninstall a named profile: stop its gateway, remove its alias, wipe its home. Shells
  498. out to ``hermes -p <name> gateway stop|uninstall`` because service names / unit paths derive
  499. from the current HERMES_HOME and can't be switched in-process."""
  500. name = profile.name
  501. log_info(f"Uninstalling profile '{name}'...")
  502. # 1. Gateway service, via `python -m hermes_cli.main` (the `hermes` wrapper may be half-gone).
  503. hermes_invocation = [sys.executable, "-P", "-m", "hermes_cli.main", "--profile", name]
  504. for subcmd in ("stop", "uninstall"):
  505. try:
  506. subprocess.run(
  507. hermes_invocation + ["gateway", subcmd], capture_output=True, text=True,
  508. encoding='utf-8', errors='replace', timeout=60, check=False)
  509. except subprocess.TimeoutExpired:
  510. log_warn(f" Gateway {subcmd} timed out for '{name}'")
  511. except Exception as e:
  512. log_warn(f" Could not run gateway {subcmd} for '{name}': {e}")
  513. # 2. Remove the wrapper alias script at ~/.local/bin/<name> (if any).
  514. alias_path = getattr(profile, "alias_path", None)
  515. if alias_path and alias_path.exists():
  516. try:
  517. alias_path.unlink()
  518. log_success(f" Removed alias {alias_path}")
  519. except Exception as e:
  520. log_warn(f" Could not remove alias {alias_path}: {e}")
  521. # 3. Wipe the profile's HERMES_HOME directory.
  522. _rmtree_step(profile.path, indent=" ", fully=False)
  523. def run_data_uninstall(args):
  524. """Erase this home's data, preserving installed runtimes and sibling profiles."""
  525. from hermes_cli.data_cleanup import plan_data_removal, remove_data
  526. from hermes_cli.gui_uninstall import desktop_userdata_dir
  527. home = get_hermes_home()
  528. try:
  529. userdata = getattr(args, "desktop_userdata", None)
  530. plan = plan_data_removal(home, get_project_root(), Path(userdata) if userdata else desktop_userdata_dir())
  531. except (OSError, ValueError, RuntimeError) as exc:
  532. log_warn(str(exc))
  533. raise SystemExit(1) from exc
  534. if not plan.remove:
  535. print(f"No Hermes user data found in {home}.")
  536. return
  537. print("Data-only removal: installed code and other profiles stay intact.")
  538. print("Will remove:")
  539. for path in plan.remove:
  540. print(f" {path}")
  541. if plan.keep:
  542. print("Kept intact:")
  543. for path in plan.keep:
  544. print(f" {path}")
  545. if bool(getattr(args, "dry_run", False)):
  546. print("Dry run: no data or processes changed.")
  547. return
  548. if not bool(getattr(args, "yes", False)) and not _confirm_yes("to remove this home's data"):
  549. return
  550. from hermes_cli.data_cleanup_holders import quiescent_home
  551. try:
  552. with quiescent_home(plan.home):
  553. removed, failed = remove_data(plan)
  554. except (OSError, ValueError, RuntimeError) as exc:
  555. log_warn(f"No data removed: {exc}")
  556. raise SystemExit(1) from exc
  557. for path in removed:
  558. log_success(f"Removed {path}")
  559. if failed:
  560. print("Hermes data was only partially removed. Surviving targets:")
  561. for path, reason in failed:
  562. log_warn(f"{path}: {reason}")
  563. raise SystemExit(1)
  564. log_success("Hermes data removed.")
  565. def run_gui_uninstall(args):
  566. """GUI-only uninstall: remove the Chat GUI, leave the agent + data intact.
  567. Mirrors ``hermes uninstall --gui``. Removes the desktop app's built
  568. artifacts, the packaged app bundle (best-effort), and the Electron
  569. userData dir — nothing under ``$HERMES_HOME`` config/sessions/.env, and
  570. never the Python agent or its venv.
  571. """
  572. from hermes_cli.gui_uninstall import (
  573. agent_is_installed,
  574. desktop_install_record,
  575. gui_install_summary,
  576. uninstall_gui,
  577. )
  578. _refuse_if_steward_owned()
  579. hermes_home = get_hermes_home()
  580. summary = gui_install_summary(hermes_home)
  581. skip_confirm = bool(getattr(args, "yes", False))
  582. print()
  583. _print_box("│ ☤ Hermes Chat GUI Uninstaller │", Colors.MAGENTA)
  584. print()
  585. if not summary["gui_installed"]:
  586. print("No Hermes Chat GUI installation was found.")
  587. print(f" Checked: {hermes_home}, and the standard app locations for this OS.")
  588. return
  589. print(color("This removes the Chat GUI only. The Hermes agent stays installed.", Colors.CYAN))
  590. print()
  591. print(color("Will remove:", Colors.YELLOW, Colors.BOLD))
  592. for p in (*summary["source_built_artifacts"], *summary["packaged_app_paths"]):
  593. print(f" • {p}")
  594. if (install_record := desktop_install_record()).exists():
  595. print(f" • {install_record} (desktop install record)")
  596. if summary["userdata_exists"]:
  597. print(f" • {summary['userdata_dir']} (desktop app data)")
  598. print()
  599. if agent_is_installed(hermes_home):
  600. print(color("Kept intact:", Colors.GREEN, Colors.BOLD))
  601. print(f" • The Hermes agent at {hermes_home / 'hermes-agent'}")
  602. print(f" • Your config, sessions, and secrets under {hermes_home}")
  603. if (shared_modules := hermes_home / "hermes-agent" / "node_modules").exists():
  604. print(f" • Shared workspace dependencies at {shared_modules}")
  605. print()
  606. if bool(getattr(args, "dry_run", False)):
  607. print("Dry run: no files or processes changed.")
  608. return
  609. if not skip_confirm and not _confirm_yes("to remove the Chat GUI"):
  610. return
  611. print()
  612. print(color("Uninstalling Chat GUI...", Colors.CYAN, Colors.BOLD))
  613. print()
  614. uninstall_gui(hermes_home)
  615. print()
  616. _print_box("│ ✓ Chat GUI Uninstalled! │", Colors.GREEN)
  617. print()
  618. print("The Hermes agent is still installed. Run 'hermes' to use the CLI,")
  619. print("or 'hermes uninstall' to remove the agent too.")
  620. print()
  621. def run_uninstall(args):
  622. """
  623. Run the uninstall process.
  624. Options:
  625. - Full uninstall: removes code + ~/.hermes/ (configs, data, logs)
  626. - Keep data: removes code but keeps ~/.hermes/ for future reinstall
  627. """
  628. _refuse_if_steward_owned()
  629. project_root = get_project_root()
  630. hermes_home = get_hermes_home()
  631. full_flag = bool(getattr(args, "full", False))
  632. if bool(getattr(args, "dry_run", False)):
  633. _print_uninstall_dry_run(
  634. project_root=project_root, hermes_home=hermes_home, full_uninstall=full_flag)
  635. return
  636. # Named profiles (only when uninstalling from the default root) are offered for cleanup too,
  637. # instead of leaving zombie HERMES_HOMEs and systemd units behind.
  638. is_default_profile = _is_default_hermes_home(hermes_home)
  639. named_profiles = _discover_named_profiles() if is_default_profile else []
  640. # ``--yes`` (the desktop app's detached cleanup script): no prompts; ``--full`` = full wipe.
  641. # Named profiles are NOT auto-removed here — too destructive a default for an unattended run.
  642. if bool(getattr(args, "yes", False)):
  643. _perform_uninstall(
  644. project_root=project_root, hermes_home=hermes_home, full_uninstall=full_flag,
  645. remove_profiles=False, named_profiles=named_profiles)
  646. return
  647. print()
  648. _print_box("│ ☤ Hermes Agent Uninstaller │", Colors.MAGENTA)
  649. print()
  650. # Show what will be affected
  651. print(color("Current Installation:", Colors.CYAN, Colors.BOLD))
  652. print(f" Code: {project_root}")
  653. print(f" Config: {hermes_home / 'config.yaml'}")
  654. print(f" Secrets: {hermes_home / '.env'}")
  655. print(f" Data: {hermes_home / 'cron/'}, {hermes_home / 'sessions/'}, {hermes_home / 'logs/'}")
  656. from hermes_cli.gui_uninstall import desktop_userdata_dir
  657. if (desktop_userdata := desktop_userdata_dir()).exists():
  658. print(f" Desktop: {desktop_userdata} (app data - kept by 'Keep data', removed by 'Full uninstall')")
  659. print()
  660. if named_profiles:
  661. print(color("Other profiles detected:", Colors.CYAN, Colors.BOLD))
  662. for p in named_profiles:
  663. print(f" • {p.name}{' (gateway running)' if getattr(p, 'gateway_running', False) else ''}: {p.path}")
  664. print()
  665. # Ask for confirmation
  666. print(color("Uninstall Options:", Colors.YELLOW, Colors.BOLD))
  667. print()
  668. print(" 1) " + color("Keep data", Colors.GREEN) + " - Remove code only, keep configs/sessions/logs")
  669. print(" (Recommended - you can reinstall later with your settings intact)")
  670. print()
  671. print(" 2) " + color("Full uninstall", Colors.RED) + " - Remove everything including all data")
  672. print(" (Warning: This deletes all configs, sessions, and logs permanently)")
  673. print()
  674. print(" 3) " + color("Cancel", Colors.CYAN) + " - Don't uninstall")
  675. print()
  676. choice = _prompt(color("Select option [1/2/3]: ", Colors.BOLD))
  677. if choice is None:
  678. return
  679. if choice in {"3", "c", "cancel", "q", "quit", "n", "no"}:
  680. _cancelled()
  681. return
  682. full_uninstall = (choice == "2")
  683. # Full uninstall from the default profile: offer to remove named profiles too (gateway
  684. # services, alias wrappers, HERMES_HOME dirs) — otherwise they leave zombie services behind.
  685. remove_profiles = False
  686. n_profiles = len(named_profiles)
  687. profile_names = ", ".join(p.name for p in named_profiles)
  688. if full_uninstall and named_profiles:
  689. print()
  690. print(color("Other profiles will NOT be removed by default.", Colors.YELLOW))
  691. print(f"Found {n_profiles} named profile(s): {profile_names}")
  692. print()
  693. resp = _prompt(color(f"Also stop and remove these {n_profiles} profile(s)? [y/N]: ", Colors.BOLD))
  694. if resp is None:
  695. return
  696. remove_profiles = resp in {"y", "yes"}
  697. # Final confirmation
  698. print()
  699. if full_uninstall:
  700. print(color("⚠️ WARNING: This will permanently delete ALL Hermes data!", Colors.RED, Colors.BOLD))
  701. print(color(" Including: configs, API keys, sessions, scheduled jobs, logs", Colors.RED))
  702. if remove_profiles:
  703. print(color(f" Plus {n_profiles} profile(s): {profile_names}", Colors.RED))
  704. else:
  705. print("This will remove the Hermes code but keep your configuration and data.")
  706. print()
  707. if not _confirm_yes("to confirm"):
  708. return
  709. _perform_uninstall(
  710. project_root=project_root, hermes_home=hermes_home, full_uninstall=full_uninstall,
  711. remove_profiles=remove_profiles, named_profiles=named_profiles)
  712. def _print_uninstall_dry_run(*, project_root: Path, hermes_home: Path, full_uninstall: bool) -> None:
  713. """Print the uninstall plan without stopping services or deleting files."""
  714. print()
  715. print(color("Dry run: no files, services, or environment entries will be changed.", Colors.CYAN, Colors.BOLD))
  716. print()
  717. print(color("Would inspect/remove:", Colors.YELLOW, Colors.BOLD))
  718. print(" • Gateway services and standalone gateway processes")
  719. print(" • Hermes PATH entries from shell configs / Windows User PATH")
  720. print(" • Hermes wrapper scripts and Hermes-managed node/npm/npx symlinks")
  721. print(" • Desktop Chat GUI artifacts")
  722. print(f" • Code checkout: {project_root}")
  723. from hermes_cli.gui_uninstall import desktop_userdata_dir
  724. userdata = desktop_userdata_dir()
  725. if not full_uninstall:
  726. print(f" • Keep Hermes config/data: {hermes_home}")
  727. if userdata.exists():
  728. print(f" • Keep desktop app data: {userdata}")
  729. else:
  730. print(f" • Hermes config/data: {hermes_home}")
  731. if sys.platform == "darwin":
  732. print(" • macOS: dashboard/serve launchd jobs, Electron + setup caches")
  733. if userdata.exists():
  734. print(f" • Desktop app data: {userdata}")
  735. profiles = _discover_named_profiles() if _is_default_hermes_home(hermes_home) else []
  736. if profiles:
  737. print(" • Named profiles (interactive uninstall asks before removing):")
  738. for prof in profiles:
  739. print(f" - {prof.name}: {prof.path}")
  740. print()
  741. def _remove_step(label: str, remove, success_fmt: str, none_msg: str) -> None:
  742. """Announce ``label``, run ``remove()``, log one success line per removed item (or ``none_msg``)."""
  743. log_info(label)
  744. removed = remove()
  745. for item in removed:
  746. log_success(success_fmt.format(item))
  747. if not removed:
  748. log_info(none_msg)
  749. def _rmtree_step(path: Path, *, indent: str = "", fully: bool = True) -> None:
  750. """Best-effort ``rmtree`` with the shared success/warning lines."""
  751. try:
  752. if path.exists():
  753. shutil.rmtree(path)
  754. log_success(f"{indent}Removed {path}")
  755. except Exception as e:
  756. log_warn(f"{indent}Could not {'fully ' if fully else ''}remove {path}: {e}")
  757. if fully:
  758. log_info("You may need to manually remove it")
  759. def _macos_cache_leftover_dirs() -> list[Path]:
  760. """Cache dirs Electron/Chromium and the setup binary write OUTSIDE HERMES_HOME on
  761. macOS. Chromium splits the desktop app's HTTP/script caches under ``~/Library/Caches``
  762. keyed by both the product name and the app id, and the Tauri setup binary does the
  763. same under its own pair of identifiers. ``gui_uninstall`` removes the userData dir
  764. (``Application Support/Hermes``) but never these (#62209)."""
  765. caches = Path.home() / "Library" / "Caches"
  766. return [
  767. caches / "Hermes",
  768. caches / "com.nousresearch.hermes",
  769. caches / "hermes-setup",
  770. caches / "com.nousresearch.hermes.setup",
  771. ]
  772. def _rmtree_if_exists(path: Path) -> bool:
  773. """``_remove_each`` remover: True (after removing) when *path* exists, else False."""
  774. if not path.exists():
  775. return False
  776. shutil.rmtree(path)
  777. return True
  778. def remove_dashboard_launchd_jobs() -> list[Path]:
  779. """macOS: boot out and delete every launchd job whose ``ProgramArguments`` runs a
  780. ``hermes dashboard`` / ``hermes serve`` backend, returning the removed plist paths.
  781. The gateway uninstall only reaches the gateway label, so a dashboard/serve
  782. LaunchAgent survives a full uninstall and launchd keeps respawning its backend.
  783. Mirrors the enumeration ``hermes_cli.main_dashboard`` uses to find those jobs
  784. (``_launchd_plist_dirs`` + ``_parse_dashboard_runtime``): read each plist, match the
  785. arguments, ``launchctl bootout`` the job's domains (launchd takes the process down;
  786. booting out an already-unloaded job is fine and never checked), then delete the
  787. plist — a stale, not-loaded plist is still Hermes-created and still goes. A missing,
  788. unreadable, or malformed plist is skipped, never fatal. macOS only (empty list
  789. elsewhere)."""
  790. if sys.platform != "darwin":
  791. return []
  792. import plistlib
  793. import shlex
  794. from xml.parsers.expat import ExpatError
  795. from hermes_cli.main_dashboard import _launchd_plist_dirs, _parse_dashboard_runtime
  796. uid = os.getuid() # windows-footgun: ok — darwin-only branch
  797. removed: list[Path] = []
  798. for kind, plist_dir in _launchd_plist_dirs():
  799. try:
  800. plists = sorted(plist_dir.glob("*.plist"))
  801. except OSError:
  802. continue
  803. for plist_path in plists:
  804. try:
  805. with open(plist_path, "rb") as f:
  806. data = plistlib.load(f)
  807. # ExpatError is NOT a ValueError: plistlib propagates it unwrapped for XML
  808. # that is not well-formed; one malformed operator file must skip — not
  809. # abort — the sweep (same contract as main_dashboard's scan).
  810. except (OSError, ValueError, plistlib.InvalidFileException, ExpatError):
  811. continue
  812. if not isinstance(data, dict):
  813. continue
  814. label = str(data.get("Label") or "").strip()
  815. args = data.get("ProgramArguments")
  816. if not label or not isinstance(args, list) or not args:
  817. continue
  818. if _parse_dashboard_runtime(shlex.join([str(a) for a in args])) is None:
  819. continue
  820. domains = ("system",) if kind == "daemon" else (f"gui/{uid}", f"user/{uid}")
  821. for domain in domains:
  822. try:
  823. subprocess.run(
  824. ["launchctl", "bootout", f"{domain}/{label}"],
  825. capture_output=True, check=False, timeout=90)
  826. except (OSError, subprocess.TimeoutExpired) as e:
  827. log_warn(f"Could not boot out {domain}/{label}: {e}")
  828. try:
  829. plist_path.unlink()
  830. removed.append(plist_path)
  831. except OSError as e:
  832. log_warn(f"Could not remove {plist_path}: {e}")
  833. return removed
  834. def _perform_uninstall(
  835. *,
  836. project_root: Path,
  837. hermes_home: Path,
  838. full_uninstall: bool,
  839. remove_profiles: bool,
  840. named_profiles: list) -> None:
  841. """The uninstall steps shared by the interactive and ``--yes`` paths: stop gateway -> strip PATH
  842. (rc files + Windows registry) -> wrapper/launchers/node symlinks -> Chat GUI artifacts -> delete
  843. the checkout -> (Windows) PortableGit/Node -> optionally ``$HERMES_HOME`` and named profiles."""
  844. print()
  845. print(color("Uninstalling...", Colors.CYAN, Colors.BOLD))
  846. print()
  847. # 1. Stop and uninstall gateway service + kill standalone processes
  848. log_info("Checking for running gateway...")
  849. if not uninstall_gateway_service():
  850. log_info("No gateway service or processes found")
  851. # 2-3b. PATH entries, wrapper, Windows launchers, node symlinks. Windows: hermes_home is
  852. # %VAR%-expanded because install.ps1 writes literal C:\Users\<u>\...; hermes\bin (launchers +
  853. # managed uv) leaves the PATH only when the full wipe below deletes it (keep-data keeps uv
  854. # resolvable), while the launchers themselves always go. Symlinks go only when they still
  855. # point into this home's node dir (never clobber nvm / user-managed Node).
  856. windows = _is_windows()
  857. sweep_managed_bin = windows and full_uninstall and _is_default_hermes_home(hermes_home)
  858. for on_this_platform, label, remove, success_fmt, none_msg in (
  859. (True, "Removing PATH entries from shell configs...",
  860. remove_path_from_shell_configs, "Updated {}", "No PATH entries found to remove in shell rc files"),
  861. (windows, "Removing PATH entries from Windows User environment...",
  862. lambda: remove_path_from_windows_registry(
  863. Path(os.path.expandvars(str(hermes_home))), include_managed_bin=sweep_managed_bin),
  864. "Removed from User PATH: {}", "No Hermes-owned PATH entries in User environment"),
  865. (windows, "Removing HERMES_HOME / HERMES_GIT_BASH_PATH User env vars...",
  866. remove_hermes_env_vars_windows, "Removed User env var: {}", "No Hermes-set User env vars to remove"),
  867. (True, "Removing hermes command...", remove_wrapper_script, "Removed {}", "No wrapper script found"),
  868. (windows, "Removing Windows hermes launchers...",
  869. remove_windows_bin_launchers, "Removed {}", "No Windows hermes launchers found"),
  870. (True, "Removing Hermes-managed node/npm/npx symlinks...",
  871. lambda: remove_node_symlinks(hermes_home), "Removed {}", "No Hermes-managed node/npm/npx symlinks found"),
  872. ):
  873. if on_this_platform:
  874. _remove_step(label, remove, success_fmt, none_msg)
  875. # 3c. Chat GUI artifacts go with the agent code. uninstall_gui() never touches config/sessions/
  876. # .env (safe in keep-data mode); the packaged app + Electron userData live OUTSIDE HERMES_HOME.
  877. # The userData dir is user configuration (connections.json, OAuth partitions, renderer
  878. # state), so keep-data preserves it — only the full wipe removes it.
  879. log_info("Removing desktop Chat GUI artifacts...")
  880. try:
  881. from hermes_cli.gui_uninstall import uninstall_gui
  882. if not uninstall_gui(hermes_home, remove_userdata=full_uninstall):
  883. log_info("No desktop GUI artifacts found")
  884. except Exception as e:
  885. log_warn(f"Could not remove desktop GUI artifacts: {e}")
  886. # 3d. Per-user app leftovers outside HERMES_HOME: macOS Library caches/logs/
  887. # browser-store/state entries, the XDG cache dir, and (full mode) the XDG
  888. # data dir. Only Hermes-named entries are touched (#62209).
  889. log_info("Removing app caches and leftovers outside the install...")
  890. removed_leftovers = remove_desktop_app_leftovers(full_uninstall=full_uninstall)
  891. if removed_leftovers:
  892. for path in removed_leftovers:
  893. log_success(f"Removed {path}")
  894. else:
  895. log_info("No app caches or leftovers found")
  896. # 4. Remove installation directory (code) — we may be running from inside it.
  897. log_info("Removing installation directory...")
  898. _rmtree_step(project_root)
  899. # 4b. Windows installer tooling (PortableGit, Node, gateway-service) is not user data:
  900. # safe to remove in keep-data mode too.
  901. if windows:
  902. _remove_step(
  903. "Removing Windows installer artifacts (PortableGit, Node, gateway-service)...",
  904. lambda: remove_portable_tooling_windows(hermes_home), "Removed {}",
  905. "No Windows installer artifacts to remove")
  906. # 4c. Remove managed-runtime trees a PRE-SPLIT install left in
  907. # HERMES_HOME. Current installs keep these inside the checkout, so
  908. # step 4 already removed them — but a checkout outside the home
  909. # (~/src/hermes-agent) used to leave its node/uv behind, surviving
  910. # both the checkout removal and a "keep my data" uninstall. They
  911. # are install tooling, not data, so removing them is correct in
  912. # either mode.
  913. log_info("Removing managed runtime trees...")
  914. removed_runtimes = remove_legacy_runtime_trees(hermes_home)
  915. if removed_runtimes:
  916. for path in removed_runtimes:
  917. log_success(f"Removed {path}")
  918. else:
  919. log_info("No legacy runtime trees to remove")
  920. # 5. Optionally remove ~/.hermes/ data directory (and named profiles)
  921. if full_uninstall:
  922. # 5a. Named profiles' homes live under <default>/profiles/ (swept by the rmtree below),
  923. # but their services + alias scripts live OUTSIDE the default root.
  924. for prof in named_profiles if remove_profiles else ():
  925. _uninstall_profile(prof)
  926. # 5b. macOS: dashboard/serve launchd jobs the gateway uninstall never reaches (it
  927. # only removes the gateway label) — boot them out and delete their plists,
  928. # mirroring the enumeration main_dashboard uses to find them (#62209).
  929. if sys.platform == "darwin":
  930. _remove_step(
  931. "Removing dashboard/serve launchd jobs...",
  932. remove_dashboard_launchd_jobs, "Removed {}",
  933. "No dashboard/serve launchd jobs found")
  934. # 5c. macOS: Electron/Chromium and setup cache dirs written OUTSIDE HERMES_HOME
  935. # survive both the checkout removal and the home rmtree below (#62209).
  936. if sys.platform == "darwin":
  937. _remove_step(
  938. "Removing Electron and setup caches...",
  939. lambda: _remove_each(_macos_cache_leftover_dirs(), _rmtree_if_exists), "Removed {}",
  940. "No Electron or setup caches found")
  941. log_info("Removing configuration and data...")
  942. _rmtree_step(hermes_home)
  943. else:
  944. log_info(f"Keeping configuration and data in {hermes_home}")
  945. print()
  946. _print_box("│ ✓ Uninstall Complete! │", Colors.GREEN)
  947. print()
  948. if not full_uninstall:
  949. print(color("Your configuration and data have been preserved:", Colors.CYAN))
  950. print(f" {hermes_home}/")
  951. from hermes_cli.gui_uninstall import desktop_userdata_dir
  952. if (desktop_userdata := desktop_userdata_dir()).exists():
  953. print(f" {desktop_userdata} (desktop app data)")
  954. _, preserved = _xdg_leftover_paths(full_uninstall=False)
  955. for path in preserved:
  956. print(f" {path}/")
  957. print()
  958. print("To reinstall later with your existing settings:")
  959. print(color(_REINSTALL_HINT[windows], Colors.DIM))
  960. print()
  961. for line, col in _RELOAD_HINT[windows]:
  962. print(color(line, col) if col else line)
  963. print()
  964. print("Thank you for using Hermes Agent! ☤")
  965. print()
  966. _REINSTALL_HINT = {
  967. True: " iex (irm https://hermes-agent.nousresearch.com/install.ps1)",
  968. False: " curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash"}
  969. # windows -> [(line, color or None)]
  970. _RELOAD_HINT = {
  971. True: [("Open a new terminal (PowerShell / Windows Terminal) to pick up", Colors.YELLOW),
  972. ("the updated User PATH and environment variables.", Colors.YELLOW)],
  973. False: [("Reload your shell to complete the process:", Colors.YELLOW),
  974. (" source ~/.bashrc # or ~/.zshrc", None)]}
  975. class _UninstallArgs:
  976. """Lightweight args namespace for the module entrypoint below."""
  977. def __init__(self, *, mode: str, desktop_userdata: Path | None = None):
  978. self.gui = mode == "gui"
  979. self.gui_summary = False
  980. self.full = mode == "full"
  981. self.data = mode == "data"
  982. self.yes = True # the module entrypoint is always non-interactive
  983. self.desktop_userdata = desktop_userdata
  984. def main(argv=None) -> int:
  985. """Module entrypoint: ``python -m hermes_cli.uninstall --mode <gui|lite|full|data>``.
  986. Exists so the desktop app can run the uninstall under a Python interpreter
  987. OUTSIDE the venv being deleted. On Windows, ``lite``/``full`` rmtree the
  988. venv that contains the running ``python.exe`` — and a running .exe is
  989. mandatory-locked, so doing that from the venv's own interpreter half-fails.
  990. The desktop launches this with the system Python + ``PYTHONPATH=<agentRoot>``
  991. so ``import hermes_cli`` resolves from source while the venv is torn down.
  992. ``data`` removes user data only (no code) and is the one mode allowed on
  993. steward-owned installs (Nix, the bundled desktop app, Docker); the
  994. code-removing modes hard-fail there with the steward's instructions.
  995. Data-only mode keeps the runtime installed and uses its dependencies to
  996. coordinate live writers. Code-removing modes can still run outside the
  997. environment being removed.
  998. """
  999. import argparse
  1000. parser = argparse.ArgumentParser(prog="python -m hermes_cli.uninstall")
  1001. parser.add_argument(
  1002. "--mode",
  1003. choices=["gui", "lite", "full", "data"],
  1004. required=True,
  1005. help="gui = Chat GUI only; lite = GUI + agent, keep data; "
  1006. "full = everything; data = user data only, keep code",
  1007. )
  1008. parser.add_argument("--desktop-userdata", type=Path, help=argparse.SUPPRESS)
  1009. ns = parser.parse_args(argv)
  1010. if ns.desktop_userdata is not None and ns.mode != "data":
  1011. parser.error("--desktop-userdata requires --mode data")
  1012. args = _UninstallArgs(mode=ns.mode, desktop_userdata=ns.desktop_userdata)
  1013. if args.data:
  1014. run_data_uninstall(args)
  1015. elif args.gui:
  1016. run_gui_uninstall(args)
  1017. else:
  1018. run_uninstall(args)
  1019. return 0
  1020. if __name__ == "__main__":
  1021. sys.exit(main())