profiles.py 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395
  1. """Profile management for multiple isolated Hermes instances."""
  2. import contextlib
  3. import json
  4. import logging
  5. import os
  6. import re
  7. import shlex
  8. import shutil
  9. import stat
  10. import subprocess
  11. import sys
  12. import threading
  13. import time
  14. from dataclasses import dataclass, field
  15. from pathlib import Path
  16. from typing import Dict, List, Optional, Tuple
  17. from agent.file_safety import HOME_CREDENTIAL_DIRS
  18. from hermes_cli.archive_safe import archive_root_dirs, make_targz, normalize_archive_parts, safe_extract_targz
  19. from hermes_cli import config_backend as _config_backend
  20. from hermes_cli.profiles_config import _migrate_profile_config_if_outdated
  21. from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS, SECRET_CACHE_STORES
  22. from hermes_cli.profiles_remove import _rmtree_make_writable, _rmtree_with_retry, wait_profile_unowned
  23. from hermes_constants import (
  24. LOCAL_RUNTIME_ROOT_DIRS, PROFILE_ID_RE, clear_named_profile_deleted, mark_named_profile_deleted,
  25. named_profile_has_identity, named_profile_is_deleted, named_profile_is_live,
  26. )
  27. from hermes_cli.config_backend import (
  28. config_cache_version, config_cache_version_or_none, config_exists, require_file_tooling)
  29. from hermes_cli.profiles_cache import _PROFILE_FILE_CACHE, _cached_profile_read
  30. logger = logging.getLogger(__name__)
  31. _PROFILE_ID_RE = PROFILE_ID_RE # legacy alias; hermes_constants.PROFILE_ID_RE is canonical
  32. # Directories bootstrapped inside every new profile. ``home`` is the back-compat/Docker
  33. # HOME for tool subprocesses (host subprocesses keep the real HOME so CLI credentials
  34. # stay visible; containers persist HOME state here). See hermes_constants.get_subprocess_home().
  35. _PROFILE_DIRS = ["memories", "sessions", "skills", "skins", "logs", "plans", "workspace", "cron", "home"]
  36. # Files copied during --clone (if they exist in the source).
  37. _CLONE_CONFIG_FILES = ["config.yaml", ".env", "SOUL.md"]
  38. # Subdirectory files copied during --clone: memory files are part of the agent's curated
  39. # identity, as important as SOUL.md for continuity.
  40. _CLONE_SUBDIR_FILES = ["memories/MEMORY.md", "memories/USER.md"]
  41. # Runtime files stripped after --clone-all. A post-copy step rather than an ignore filter
  42. # because they are created dynamically and may be absent at copy time.
  43. _CLONE_ALL_STRIP: list[str] = [
  44. "gateway.pid", "gateway_state.json", "processes.json",
  45. # Bot Desktop runtime identity: pid + create_time of the SOURCE's launcher, its DISPLAY/XAUTHORITY and
  46. # lease. Copied verbatim, `screen stop` on the clone would kill the source's X server. Browser user data
  47. # stays, but Chromium's process markers must not let the clone attach to the source's live browser.
  48. "bot-desktop/launcher.pid", "bot-desktop/env", "bot-desktop/rfb.sock",
  49. "bot-desktop/lease.json", "bot-desktop/lease.lock",
  50. "bot-desktop/browser-profile/DevToolsActivePort",
  51. "bot-desktop/browser-profile/SingletonLock",
  52. "bot-desktop/browser-profile/SingletonCookie",
  53. "bot-desktop/browser-profile/SingletonSocket",
  54. ]
  55. # Infrastructure excluded from --clone-all ONLY when the source is the default profile
  56. # (``~/.hermes``): git checkout (+ ~3 GB venv), worktrees, sibling profiles, shared bins,
  57. # npm packages, and the managed local-models trees — GGUF weights (tens of GB), the
  58. # llama.cpp runtime binaries and the managed Node install, all re-downloadable on demand
  59. # and resolved from the default root only. Named profiles never hold these at root, so the
  60. # gate avoids silently dropping user data from a named-profile source. Export uses a root
  61. # allow-list instead (``_DEFAULT_EXPORT_INCLUDE_ROOT``): an archive is a portable snapshot,
  62. # a clone must run. The runtime trio is ``LOCAL_RUNTIME_ROOT_DIRS``, shared with
  63. # ``hermes_cli.backup._EXCLUDED_ROOT_DIRS`` so the two lists cannot drift.
  64. _CLONE_ALL_DEFAULT_EXCLUDE_ROOT: frozenset[str] = frozenset({
  65. "hermes-agent",
  66. ".worktrees",
  67. "profiles",
  68. "bin",
  69. "node_modules",
  70. # Managed runtime trees — install artifacts, never profile state
  71. # (install/profile bucket split; see test_install_bucket_separation).
  72. ".hermes-runtime",
  73. "node",
  74. }) | LOCAL_RUNTIME_ROOT_DIRS
  75. # Per-profile history excluded from --clone-all for ANY source: SQLite session store
  76. # (+wal/shm, can reach many GB), session dirs, `hermes backup` archives, quick-backup
  77. # snapshots, checkpoints. Inheriting them is never useful (restoring one inside the
  78. # clone would resurrect the SOURCE profile's state) and can balloon the copy by tens of GB.
  79. # ``cron`` is scheduled work bound to the source profile and its origin channel: a clone
  80. # that inherits jobs.json runs every job twice (two gateways, same job ids, double spend,
  81. # duplicate deliveries) the moment its gateway starts. The empty dir is recreated below.
  82. _CLONE_ALL_HISTORY_EXCLUDE_ROOT: frozenset[str] = frozenset({
  83. "state.db", "state.db-wal", "state.db-shm", "sessions", "backups", "state-snapshots", "checkpoints",
  84. "cron", "webapp", # webapp/: the source gateway's sign-in state (credential, native grants, Portal callback)
  85. })
  86. # Marker written by `hermes profile create --no-skills`. When present at a profile root,
  87. # seed_profile_skills() callers (fresh-create, `hermes update` all-profile sync, the
  88. # dashboard) skip bundled-skill seeding. Delete the file to opt back in.
  89. NO_BUNDLED_SKILLS_MARKER = ".no-bundled-skills"
  90. # Header seeded into a profile's empty .env so it owns a credentials file from day one.
  91. _PLACEHOLDER_ENV = (
  92. "# Per-profile secrets for this Hermes profile.\n"
  93. "# API keys and tokens set here override the shell environment.\n"
  94. "# Behavioral settings belong in config.yaml, not here.\n"
  95. )
  96. def _non_exportable_entries(directory: str, contents: list) -> set:
  97. """Entries under *directory* that must never be copied out of a profile: bytecode caches,
  98. ``*.sock``/``*.tmp`` names, and anything that is not a regular file, directory, or symlink.
  99. :func:`shutil.copytree` cannot copy special files, so a single live Unix socket without a
  100. ``.sock`` name (or a FIFO, or a device node) would abort the whole export or clone with
  101. ``[Errno 6] No such device or address``. Symlinks survive — copytree recreates them."""
  102. ignored: set = set()
  103. for entry in contents:
  104. if entry == "__pycache__" or entry.endswith((".sock", ".tmp", ".pyc", ".pyo")):
  105. ignored.add(entry)
  106. continue
  107. try:
  108. mode = os.lstat(os.path.join(directory, entry)).st_mode
  109. except OSError:
  110. ignored.add(entry) # vanished mid-walk — copytree would fail on it anyway
  111. continue
  112. if not (stat.S_ISREG(mode) or stat.S_ISDIR(mode) or stat.S_ISLNK(mode)):
  113. ignored.add(entry)
  114. return ignored
  115. def _clone_all_copytree_ignore(source_dir: Path):
  116. """copytree ignore for --clone-all: history artifacts for any source, infrastructure
  117. only when the source is the default profile (see the two exclude sets above)."""
  118. source_resolved = source_dir.resolve()
  119. root_exclude = set(_CLONE_ALL_HISTORY_EXCLUDE_ROOT)
  120. if source_resolved == _get_default_hermes_home().resolve():
  121. root_exclude |= _CLONE_ALL_DEFAULT_EXCLUDE_ROOT
  122. def _ignore(directory: str, names: list[str]) -> set:
  123. try:
  124. at_root = Path(directory).resolve() == source_resolved
  125. except (OSError, ValueError):
  126. # resolve() can fail on odd FS layouts (broken symlinks, missing parents).
  127. # Fail open — better to over-copy than silently drop user data.
  128. at_root = False
  129. ignored = _non_exportable_entries(directory, names)
  130. if at_root:
  131. ignored.update(root_exclude & set(names))
  132. return ignored
  133. return _ignore
  134. # OS credential dirs (file_safety.HOME_CREDENTIAL_DIRS) + direnv .envrc (_BLOCKED_PROJECT_ENV_BASENAMES).
  135. _OS_CREDENTIAL_STORES = (*HOME_CREDENTIAL_DIRS, ".envrc")
  136. # Credential stores in a profile home, as paths relative to it, plus the directories where Hermes
  137. # keeps recovery copies of them. Never shipped in a profile export, and user-owned (never
  138. # overwritten) on a distribution install. Add a store here when a writer or loader starts using one.
  139. PROFILE_CREDENTIAL_PATHS = frozenset({
  140. "auth.json", ".env", "auth/google_oauth.json",
  141. ".op.env", # 1Password service-account token (env_loader)
  142. "npmrc", # npm registry auth (source_build)
  143. ".anthropic_oauth.json", # Anthropic OAuth tokens (credential_sources)
  144. "google_token.json", "google_oauth_pending.json", "google_client_secret.json",
  145. "google_chat_user_tokens", "google_chat_user_client_secret.json", "google_chat_user_oauth_pending.json",
  146. "google_chat_user_token.json", "google_chat_user_oauth_pending", # legacy single-user layouts
  147. "slack_tokens.json",
  148. "honcho.json", # Honcho apiKey + OAuth grant (oauth.refreshToken)
  149. "mem0.json", # Mem0 api_key (self-hosted server key) next to its settings
  150. "webhook_subscriptions.json", # per-route HMAC secrets
  151. "teams_pipeline_store.json", # Graph subscription client_state (webhook shared secret)
  152. "mcp-tokens", # MCP OAuth tokens
  153. "vault", # vault.key + vault.json.enc
  154. "browser-profile", "browser_auth", "bot-desktop", "webapp", # browser cookies / logins, Webapp sign-in
  155. "browser-profiles", "browser_profiles", # live CDP profiles, Browser Use CLI dir (Cookies, Login Data)
  156. "pairing", "platforms/pairing", "feishu_comment_pairing.json",
  157. "whatsapp/session", "platforms/whatsapp/session", "matrix/store", "platforms/matrix/store",
  158. *SECRET_CACHE_STORES, # Bitwarden / 1Password value caches, Photon sidecar token
  159. "workspace/meetings/node_token.json", # google_meet node RPC secret
  160. "weixin/accounts", # WeChat bot tokens + per-peer context tokens
  161. ".copilot_jwt.json", # exchanged Copilot API token
  162. "proxy", # iron-proxy CA key + proxy tokens
  163. "chrome-debug", # /browser connect Chrome profile (cookies, logins)
  164. "home", # subprocess HOME: gh, git, ssh, npm and skill-CLI credentials
  165. "backups", "state-snapshots", # pre-update zips, config copies, update snapshots of the stores
  166. *_OS_CREDENTIAL_STORES,
  167. })
  168. _CREDENTIAL_PATH_PARTS = tuple(tuple(p.casefold().split("/")) for p in PROFILE_CREDENTIAL_PATHS)
  169. # Copies Hermes' writers leave beside a store at the profile root, matched case-folded. Any
  170. # ``auth.json.*`` / ``.env.bak*`` is a credential store whoever named it; for config.yaml only the
  171. # writers' formats match (post_update ``.bak-<stamp>[.N]``, config_backups' legacy siblings), because a
  172. # hand-named ``config.yaml.bak-my-note`` is the user's and ships through the export scrub instead.
  173. _STORE_COPY_RE = re.compile(
  174. r"auth\.json\..+|\.env\.bak.*"
  175. r"|config\.yaml\.(?:bak-\d{8}t\d{6}z(?:\.\d+)?|bak\.\d+|corrupt\..*|bak-pre-migrate-.*)"
  176. )
  177. def _fold(parts: tuple[str, ...]) -> tuple[str, ...]:
  178. return tuple(part.casefold() for part in parts)
  179. def profile_path_is_private(parts: tuple[str, ...]) -> bool:
  180. """True for a PROFILE_CREDENTIAL_PATHS store, anything below one, or a root copy of one.
  181. Case-folded: on a case-insensitive filesystem ``Platforms/Pairing`` IS the pairing store."""
  182. folded = _fold(parts)
  183. if len(folded) == 1 and _STORE_COPY_RE.fullmatch(folded[0]):
  184. return True
  185. return any(folded[:len(store)] == store for store in _CREDENTIAL_PATH_PARTS)
  186. def profile_path_contains_private_store(parts: tuple[str, ...]) -> bool:
  187. """True for a strict ancestor of a store (``platforms`` holds ``platforms/pairing``)."""
  188. folded = _fold(parts)
  189. return any(len(store) > len(folded) and store[:len(folded)] == folded for store in _CREDENTIAL_PATH_PARTS)
  190. # Directories/files to exclude when exporting the default (~/.hermes) profile.
  191. # The default profile contains infrastructure (repo checkout, worktrees, DBs,
  192. # caches, binaries) that named profiles don't have. We exclude those so the
  193. # export is a portable, reasonable-size archive of actual profile data.
  194. # The ONE exclude-list authority for "infrastructure / runtime state that is
  195. # not profile data". The export path (``_default_export_ignore``) consumes it
  196. # directly; the distribution path (``profile_distribution.USER_OWNED_EXCLUDE``)
  197. # layers its distribution-specific additions on top of it. Keep new root
  198. # artifacts here — not in a downstream copy.
  199. _DEFAULT_EXPORT_EXCLUDE_ROOT = DEFAULT_EXPORT_EXCLUDE_ROOT = frozenset({
  200. # Infrastructure
  201. "hermes-agent", # repo checkout (multi-GB)
  202. ".worktrees", # git worktrees
  203. "profiles", # other profiles — never recursive-export
  204. "bin", # installed binaries
  205. "node_modules", # npm packages
  206. ".hermes-runtime", # managed runtime tree (install artifact)
  207. "node", # legacy pre-split managed Node tree
  208. # Databases & runtime state
  209. "state.db", "state.db-shm", "state.db-wal",
  210. "hermes_state.db",
  211. "response_store.db", "response_store.db-shm", "response_store.db-wal",
  212. "gateway.pid", "gateway_state.json", "processes.json",
  213. "auth.json", # API keys, OAuth tokens, credential pools
  214. ".env", # API keys (dotenv)
  215. "auth.lock", "active_profile", ".update_check", "source-checks",
  216. "errors.log",
  217. ".hermes_history",
  218. # Caches (regenerated on use)
  219. "image_cache", "audio_cache", "document_cache",
  220. "browser_screenshots", "checkpoints",
  221. "sandboxes",
  222. "logs", # gateway logs
  223. }) | PM_RUNTIME_ROOT_DIRS
  224. # Allow-list for ``export_profile("default")``: when HERMES_HOME equals the
  225. # cwd (Docker/custom deployments), the default profile home is the working
  226. # directory and contains arbitrary user files that should NOT be bundled
  227. # into the export. The set below identifies the *known Hermes profile
  228. # artifacts* at the root of HERMES_HOME; everything else is excluded.
  229. # Sensitive runtime infrastructure (``state.db``, ``logs/``, ``auth.*``,
  230. # other profiles) is intentionally *not* in this list so the export stays
  231. # a portable, credential-free snapshot of the user-facing surface
  232. # (#58394). Add new artifacts here when introduced in ``hermes_constants``.
  233. _DEFAULT_EXPORT_INCLUDE_ROOT = frozenset({
  234. # Configuration / persona
  235. "config.yaml", "SOUL.md", "MEMORY.md", "USER.md", "todo.json",
  236. "system_prompt.md", "AGENTS.md", "CLAUDE.md", ".cursorrules",
  237. # Desktop appearance overlay (written/applied by the desktop app's export/import).
  238. "desktop.json",
  239. # User-facing skill, cron, and session artifacts
  240. "skills", "cron", "scripts", "sessions",
  241. # Plugin / memory surfaces (per-profile overrides live here)
  242. "plugins", "memories", "knowledge", "preferences",
  243. })
  244. # Names that cannot be used as profile aliases
  245. _RESERVED_NAMES = frozenset({"hermes", "default", "test", "tmp", "root", "sudo"})
  246. # Hermes subcommands that cannot be used as profile names/aliases
  247. _HERMES_SUBCOMMANDS = frozenset({
  248. "chat", "model", "gateway", "setup", "whatsapp", "login", "logout",
  249. "status", "cron", "doctor", "dump", "config", "pairing", "skills", "tools",
  250. "mcp", "connectors", "sessions", "insights", "version", "update", "uninstall", "profile", "plugins", "honcho", "acp",
  251. })
  252. # Path helpers
  253. def _get_profiles_root() -> Path:
  254. """Named-profiles root, anchored to the hermes root (NOT the current HERMES_HOME, which
  255. may itself be a profile) so ``coder profile list`` sees all profiles."""
  256. return _get_default_hermes_home() / "profiles"
  257. def _get_default_hermes_home() -> Path:
  258. """Default (pre-profile) HERMES_HOME: ``~/.hermes``, or HERMES_HOME itself in
  259. Docker/custom deployments (e.g. ``/opt/data``)."""
  260. from hermes_constants import get_default_hermes_root
  261. return get_default_hermes_root()
  262. def _get_active_profile_path() -> Path:
  263. return _get_default_hermes_home() / "active_profile"
  264. def _get_wrapper_dir() -> Path:
  265. return Path.home() / ".local" / "bin"
  266. def _wrapper_path(alias: str) -> Path:
  267. """Wrapper script path for *alias*: ``<alias>.bat`` on Windows, bare name elsewhere."""
  268. return _get_wrapper_dir() / (f"{alias}.bat" if sys.platform == "win32" else alias)
  269. def _find_our_wrapper(alias: str) -> Optional[Path]:
  270. """The Hermes wrapper for *alias*: :func:`_wrapper_path`, else a pre-``.bat`` bare Windows one."""
  271. candidates = [_wrapper_path(alias), _get_wrapper_dir() / alias] if sys.platform == "win32" else [_wrapper_path(alias)]
  272. return next((p for p in candidates if _is_our_wrapper(p)), None)
  273. def _is_our_wrapper(path: Path) -> bool:
  274. """True when *path* reads as a Hermes-generated wrapper (``hermes -p`` in its head)."""
  275. try:
  276. with open(path, encoding="utf-8-sig") as f:
  277. return "hermes -p" in f.read(_WRAPPER_READ_LIMIT)
  278. except Exception:
  279. return False
  280. def _missing_profile_error(canon: str) -> FileNotFoundError:
  281. return FileNotFoundError(f"Profile '{canon}' does not exist. Create it with: hermes profile create {canon}")
  282. def _unknown_profile_error(canon: str) -> FileNotFoundError:
  283. """For delete/rename/export of a name that matches no profile (likely a typo)."""
  284. return FileNotFoundError(f"No profile named '{canon}'. See your profiles with: hermes profile list")
  285. def _profile_exists_error(canon: str) -> FileExistsError:
  286. return FileExistsError(
  287. f"A profile named '{canon}' already exists. Switch to it with `hermes profile use {canon}`, "
  288. "see all profiles with `hermes profile list`, or choose a different name."
  289. )
  290. _PROFILE_NAME_RULE = (
  291. "Use lowercase letters, numbers, '-' or '_', starting with a letter or number, "
  292. "up to 64 characters"
  293. )
  294. def _suggest_profile_name(name: str) -> str:
  295. """Best-effort valid id derived from *name* (``'My Work'`` -> ``'my-work'``); ``my-work`` if nothing usable."""
  296. candidate = re.sub(r"[^a-z0-9_-]+", "-", name.strip().lower()).strip("-_")[:64]
  297. return candidate if _PROFILE_ID_RE.match(candidate) else "my-work"
  298. def _invalid_profile_name_error(name: str) -> ValueError:
  299. suggestion = _suggest_profile_name(name)
  300. return ValueError(
  301. f"{name!r} is not a valid profile name. {_PROFILE_NAME_RULE} (for example: {suggestion}). "
  302. f"Then run `hermes profile create {suggestion}`."
  303. )
  304. # Validation
  305. def normalize_profile_name(name: str) -> str:
  306. """Canonical profile id used on disk and in ``-p`` argv: lowercase, ``default`` matched
  307. case-insensitively. Dashboards/tools may pass title-cased labels — normalize before
  308. validation, assignment, and subprocess spawn.
  309. Named profiles are stored lowercase under ``profiles/<id>/``. The special
  310. alias ``default`` is matched case-insensitively (``Default`` → ``default``).
  311. Dashboards and tools may pass title-cased display labels; normalize before
  312. validation, assignment, and subprocess spawn (see issue #18498).
  313. Raises ``ValueError`` for non-string input: a numeric profile id (e.g. a
  314. DB row id or a falsy sentinel) silently coerced via ``str()`` becomes a
  315. real on-disk profile directory (``profiles/0/``, #88842). Callers that
  316. hold a numeric id must resolve it to an actual profile name first.
  317. """
  318. if not isinstance(name, str):
  319. raise ValueError(
  320. "profile name must be a string, got "
  321. f"{type(name).__name__}: {name!r}"
  322. )
  323. stripped = name.strip()
  324. if not stripped:
  325. raise ValueError("profile name cannot be empty")
  326. if stripped.casefold() == "default":
  327. return "default"
  328. return stripped.lower()
  329. def validate_profile_name(name: str) -> None:
  330. """Raise ``ValueError`` unless *name* is a valid profile id (strict as-given lowercase —
  331. normalize mixed-case input first) and not in ``_RESERVED_NAMES``; ``default`` passes.
  332. Callers that accept mixed-case or title-cased input from users (dashboard UI, CLI args) should call
  333. :func:`normalize_profile_name` first. This separation keeps validate honest about what the on-disk
  334. directory name must look like, while ingress-point normalization handles UX flexibility (see #18498).
  335. """
  336. if name == "default":
  337. return # special alias for ~/.hermes
  338. if not _PROFILE_ID_RE.match(name):
  339. raise _invalid_profile_name_error(name)
  340. if name in _RESERVED_NAMES:
  341. raise ValueError(
  342. f"Profile name {name!r} is reserved — it collides with either "
  343. f"the Hermes installation itself or a common system binary. "
  344. f"Pick a different name."
  345. )
  346. def validate_alias_name(name: str) -> None:
  347. """Raise ``ValueError`` unless *name* is a safe wrapper filename: it is used verbatim
  348. under ``~/.local/bin``, so ``../../.bashrc`` must never escape the wrapper dir."""
  349. if not _PROFILE_ID_RE.match(name):
  350. raise ValueError(f"Invalid alias name {name!r}. {_PROFILE_NAME_RULE}.")
  351. def _canon_valid(name: str) -> str:
  352. """normalize + validate in one step; returns the canonical id."""
  353. canon = normalize_profile_name(name)
  354. validate_profile_name(canon)
  355. return canon
  356. def _existing_profile_dir(name: str) -> tuple[str, Path]:
  357. """``(canon, profile_dir)`` for an existing profile; FileNotFoundError otherwise."""
  358. canon = _canon_valid(name)
  359. profile_dir = get_profile_dir(canon)
  360. if not profile_dir.is_dir():
  361. raise _unknown_profile_error(canon)
  362. return canon, profile_dir
  363. def get_profile_dir(name: str) -> Path:
  364. """Resolve a profile name to its HERMES_HOME directory."""
  365. canon = normalize_profile_name(name)
  366. if canon == "default":
  367. return _get_default_hermes_home()
  368. # The name becomes a path component under profiles/; refuse anything that
  369. # is not a valid profile id so every caller (WS params, /p/<profile>/
  370. # prefixes, tool args) fails closed instead of escaping the root. The
  371. # regex only, not _RESERVED_NAMES: a pre-reserved-list dir like
  372. # profiles/hermes may still exist and must keep resolving.
  373. if not _PROFILE_ID_RE.match(canon):
  374. raise _invalid_profile_name_error(canon)
  375. return _get_profiles_root() / canon
  376. def profile_exists(name: str) -> bool:
  377. """Check whether a live (non-tombstoned) profile directory exists."""
  378. try:
  379. canon = normalize_profile_name(name)
  380. profile_dir = get_profile_dir(canon)
  381. except ValueError:
  382. return False
  383. if canon == "default":
  384. return True
  385. return named_profile_is_live(profile_dir)
  386. def profile_matches_home(name: str, home: Path | None = None) -> bool:
  387. """True when *name* refers to the profile served from *home* (default: current home).
  388. Lets single-profile gateways decide whether a ``/p/<profile>/`` URL prefix is
  389. self-referential (safe on the bare route) or names a different profile, which must fail
  390. closed rather than silently resolve the owner's config. Invalid names return False."""
  391. try:
  392. target = get_profile_dir(name)
  393. if home is None:
  394. from hermes_constants import get_hermes_home
  395. home = get_hermes_home()
  396. return Path(target).expanduser().resolve(strict=False) == Path(home).expanduser().resolve(strict=False)
  397. except Exception:
  398. return False
  399. def _iter_named_profile_dirs(*, live_only: bool = True) -> list[Path]:
  400. """Sorted named-profile dirs (valid ids, never ``default``); ``live_only`` skips tombstones.
  401. A dir is a profile only when it carries an identity marker (``named_profile_has_identity``):
  402. cron/logging side-effects and pre-tombstone ghost shells leave marker-less dirs that must
  403. not be listed, served, ticked, or ``.env``-seeded — that seeding is what turned a ghost
  404. shell into a "real" profile on the next ``hermes update`` (#95188, #94823, #99392)."""
  405. profiles_root = _get_profiles_root()
  406. if not profiles_root.is_dir():
  407. return []
  408. return [
  409. entry for entry in sorted(profiles_root.iterdir())
  410. if entry.is_dir()
  411. and entry.name != "default"
  412. and _PROFILE_ID_RE.match(entry.name)
  413. and named_profile_has_identity(entry)
  414. and not (live_only and named_profile_is_deleted(entry))
  415. ]
  416. def list_profile_names() -> list[str]:
  417. """Cheap name-only listing (``default`` + LIVE profile dirs). Unlike :func:`list_profiles` this
  418. reads NO per-profile config — safe for hot paths (cron target listings, create validation).
  419. Tombstoned shells are skipped like everywhere else: a stale process that re-mkdirs a deleted
  420. profile's directory must not resurface it as a ``bot-chat:<name>`` cron target."""
  421. names = ["default"]
  422. with contextlib.suppress(OSError):
  423. names.extend(entry.name for entry in _iter_named_profile_dirs())
  424. return names
  425. # Alias / wrapper script management
  426. def check_alias_collision(name: str) -> Optional[str]:
  427. """Return a human-readable collision message, or None if the name is safe."""
  428. canon = normalize_profile_name(name)
  429. try:
  430. validate_alias_name(canon)
  431. except ValueError as exc:
  432. return str(exc)
  433. if canon in _RESERVED_NAMES:
  434. return f"'{canon}' is a reserved name"
  435. if canon in _HERMES_SUBCOMMANDS:
  436. return f"'{canon}' conflicts with a hermes subcommand"
  437. try:
  438. result = subprocess.run(
  439. ["where" if sys.platform == "win32" else "which", canon],
  440. capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5,
  441. check=False,
  442. )
  443. if result.returncode == 0:
  444. existing_path = result.stdout.strip().splitlines()[0]
  445. expected = _wrapper_path(canon)
  446. if existing_path == str(expected) and _is_our_wrapper(expected):
  447. return None # our own wrapper, safe to overwrite
  448. return f"'{canon}' conflicts with an existing command ({existing_path})"
  449. except (FileNotFoundError, subprocess.TimeoutExpired):
  450. pass
  451. return None # safe
  452. def _is_wrapper_dir_in_path() -> bool:
  453. return str(_get_wrapper_dir()) in os.environ.get("PATH", "").split(os.pathsep)
  454. def create_wrapper_script(name: str, target: Optional[str] = None) -> Optional[Path]:
  455. """Create ``~/.local/bin/<name>`` activating profile *target* (default: *name*), so a
  456. custom alias can point at a differently-named profile without a post-hoc rewrite."""
  457. canon = normalize_profile_name(name)
  458. profile = normalize_profile_name(target) if target else canon
  459. validate_alias_name(canon) # alias is a verbatim filename: no traversal
  460. wrapper_dir = _get_wrapper_dir()
  461. try:
  462. wrapper_dir.mkdir(parents=True, exist_ok=True)
  463. except OSError as e:
  464. print(f"⚠ Could not create {wrapper_dir}: {e}")
  465. return None
  466. wrapper_path = _wrapper_path(canon)
  467. try:
  468. if sys.platform == "win32":
  469. wrapper_path.write_text(f"@echo off\r\nhermes -p {profile} %*\r\n", encoding="utf-8")
  470. else:
  471. hermes_exe = shutil.which("hermes") or "hermes"
  472. wrapper_path.write_text(f'#!/bin/sh\nexec {shlex.quote(hermes_exe)} -p {profile} "$@"\n', encoding="utf-8")
  473. wrapper_path.chmod(wrapper_path.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
  474. return wrapper_path
  475. except OSError as e:
  476. print(f"⚠ Could not create wrapper at {wrapper_path}: {e}")
  477. return None
  478. def remove_wrapper_script(name: str) -> bool:
  479. """Remove the wrapper script for a profile. Returns True if removed."""
  480. canon = normalize_profile_name(name)
  481. # A traversal-shaped name could point unlink() outside the wrapper dir; refuse it.
  482. try:
  483. validate_alias_name(canon)
  484. except ValueError:
  485. return False
  486. wrapper_path = _find_our_wrapper(canon)
  487. if wrapper_path is None:
  488. return False
  489. with contextlib.suppress(Exception):
  490. wrapper_path.unlink()
  491. return True
  492. return False
  493. def find_alias_for_profile(profile_name: str) -> Optional[str]:
  494. """Alias name of the wrapper activating *profile_name*, or None. For listing ALL profiles
  495. prefer :func:`build_alias_map`: per-profile calls re-read every wrapper N times (O(N*M)),
  496. which on a ``~/.local/bin`` full of large binaries meant multi-second ``list_profiles``."""
  497. return build_alias_map().get(normalize_profile_name(profile_name))
  498. # Cap on how much of a wrapper file is read when reverse-looking-up its profile. Real
  499. # wrappers are a few hundred bytes with the ``hermes -p X`` needle near the top; the wrapper
  500. # dir commonly also holds large binaries (ffmpeg, node, …) whose whole-file reads, N times,
  501. # dominated ``list_profiles`` (~4.5s).
  502. _WRAPPER_READ_LIMIT = 8192
  503. def build_alias_map() -> dict[str, str]:
  504. """Single-pass reverse map ``{canonical_profile -> alias_name}``.
  505. Scans the wrapper dir ONCE, reading only a head slice of each candidate and skipping
  506. binaries. A custom alias (file name != profile) wins over the profile-named wrapper;
  507. deterministic via sorted iteration."""
  508. wrapper_dir = _get_wrapper_dir()
  509. result: dict[str, str] = {}
  510. if not wrapper_dir.is_dir():
  511. return result
  512. is_windows = sys.platform == "win32"
  513. prefix = "hermes -p "
  514. for entry in sorted(wrapper_dir.iterdir()):
  515. if not entry.is_file():
  516. continue
  517. # Our wrappers are named after the alias; Windows ones carry .bat (none before #34796).
  518. if entry.suffix and not (is_windows and entry.suffix == ".bat"):
  519. continue
  520. try:
  521. with open(entry, "r", encoding="utf-8-sig", errors="strict") as f:
  522. content = f.read(_WRAPPER_READ_LIMIT)
  523. except (OSError, UnicodeDecodeError):
  524. continue # UnicodeDecodeError = a binary on PATH, not a wrapper
  525. idx = content.find(prefix)
  526. if idx == -1:
  527. continue
  528. rest = content[idx + len(prefix):]
  529. # Profile id is the first whitespace-delimited token after the flag.
  530. canon = rest.split(None, 1)[0].strip() if rest.strip() else ""
  531. if not canon:
  532. continue
  533. canon = normalize_profile_name(canon)
  534. alias = entry.stem if is_windows else entry.name
  535. if alias == canon:
  536. result.setdefault(canon, alias) # never overwrite a custom alias already found
  537. else:
  538. result[canon] = alias
  539. return result
  540. # ProfileInfo
  541. @dataclass
  542. class ProfileInfo:
  543. """Summary information about a profile."""
  544. name: str
  545. path: Path
  546. is_default: bool
  547. gateway_running: bool
  548. model: Optional[str] = None
  549. provider: Optional[str] = None
  550. has_env: bool = False
  551. skill_count: int = 0
  552. alias_path: Optional[Path] = None
  553. # Custom alias (wrapper file name) when it differs from ``name``; ``name`` when a
  554. # profile-named wrapper exists; None if no wrapper points here.
  555. alias_name: Optional[str] = None
  556. # Distribution metadata (None if the profile wasn't installed from a distribution).
  557. distribution_name: Optional[str] = None
  558. distribution_version: Optional[str] = None
  559. distribution_source: Optional[str] = None
  560. # 1-2 sentence role description from ``profile.yaml``; empty when never described.
  561. # Surfaced to the kanban decomposer so it routes work by role rather than name.
  562. description: str = ""
  563. # True when ``description`` was LLM-generated and not yet user-confirmed (dashboard
  564. # shows a "review" badge).
  565. description_auto: bool = False
  566. # Presentation-only display name; resolution/comparison/spawn always use ``name``.
  567. display_name: str = ""
  568. # Bot Mode title (``profile.yaml`` ``ui_meta['hermes-bots'].title``) — the name
  569. # the Bots roster shows. Presentation-only, like ``display_name``.
  570. bot_title: str = ""
  571. # Canonical ids this profile was previously known by (``hermes profile rename``
  572. # appends here). Lets Bot Mode group chats re-link persisted member
  573. # descriptors to the renamed live profile (#110200).
  574. previous_names: list[str] = field(default_factory=list)
  575. def _load_yaml_dict(path: Path) -> Optional[dict]:
  576. """Return the mapping in a YAML file, or None when missing/unreadable/not a mapping."""
  577. if not path.is_file():
  578. return None
  579. try:
  580. import hermes_yaml as yaml
  581. data = yaml.safe_load(path.read_text(encoding="utf-8-sig")) or {}
  582. except Exception:
  583. return None
  584. return data if isinstance(data, dict) else None
  585. def _read_distribution_meta(profile_dir: Path) -> tuple:
  586. """``(name, version, source)`` from ``distribution.yaml``; ``(None, None, None)`` if absent."""
  587. def _read() -> tuple:
  588. data = _load_yaml_dict(profile_dir / "distribution.yaml")
  589. if data is None:
  590. return None, None, None
  591. return data.get("name"), data.get("version"), data.get("source")
  592. return _cached_profile_read(profile_dir / "distribution.yaml", "distribution", _read)
  593. def _read_config_model(profile_dir: Path) -> tuple:
  594. """Read model/provider from a profile's config.yaml. Returns (model, provider)."""
  595. config_path = profile_dir / "config.yaml"
  596. if not config_exists(config_path):
  597. return None, None
  598. def _read() -> tuple:
  599. try:
  600. # load_config() targets the ACTIVE profile's home; read THIS profile's file raw.
  601. from hermes_cli.config import read_user_config_raw
  602. model_cfg = read_user_config_raw(config_path).get("model", {})
  603. if isinstance(model_cfg, str):
  604. return model_cfg, None
  605. if isinstance(model_cfg, dict):
  606. return model_cfg.get("default") or model_cfg.get("model"), model_cfg.get("provider")
  607. except Exception:
  608. pass
  609. return None, None
  610. # The user layer changes through the config backend, not necessarily on local disk.
  611. return _cached_profile_read(config_path, "config-model", _read, config_cache_version_or_none)
  612. def _seed_model_config(profile_dir: Path) -> None:
  613. """Copy (not link) the active profile's model block into a fresh profile so it is usable;
  614. profiles stay independent islands afterwards."""
  615. config_path = profile_dir / "config.yaml"
  616. if config_exists(config_path):
  617. return
  618. with contextlib.suppress(Exception): # creation must not fail over this; `hermes model` sets it later
  619. from hermes_constants import get_hermes_home
  620. from hermes_cli.config import atomic_config_write, read_user_config_raw
  621. from hermes_cli.profile_model_seed import launch_model_seed
  622. source = get_hermes_home() / "config.yaml"
  623. seed = launch_model_seed(read_user_config_raw(source)) if config_exists(source) else {}
  624. if seed:
  625. atomic_config_write(config_path, seed)
  626. def _check_gateway_running(profile_dir: Path) -> bool:
  627. """Gateway liveness for a profile dir, never mutating HERMES_HOME.
  628. Primary signal is ``gateway.pid`` verified against the runtime lock (fails closed when
  629. the lock isn't held by *this* reader: dashboard as a separate s6 service, launch-service
  630. gateways with no live PID file); fallback validates the PID in ``gateway_state.json``
  631. against the process table, matching ``/api/status``."""
  632. from gateway.status import get_running_pid, resolve_gateway_liveness
  633. # cleanup_stale=False: a status probe for ANOTHER profile must never unlink its PID file.
  634. return resolve_gateway_liveness(
  635. profile_dir=profile_dir, use_cache=False,
  636. pid_probe=lambda path: get_running_pid(path, cleanup_stale=False)).running
  637. def _served_by_running_multiplexer(profile_name: str) -> bool:
  638. """True when the live default gateway multiplexes ``profile_name`` (such a profile has no
  639. gateway.pid of its own, so ``_check_gateway_running`` alone reports it stopped).
  640. Single shared lookup with the named-profile start guard and cron liveness (#97120).
  641. """
  642. try:
  643. from hermes_cli.gateway import named_profile_served_by_running_multiplexer
  644. return named_profile_served_by_running_multiplexer(profile_name)
  645. except Exception:
  646. return False
  647. # In-process skill-count cache. Counting walks every skill's sub-tree (~4 fs calls per
  648. # skill); ``list_profiles`` counts EVERY profile, and its two remaining Desktop callers
  649. # (``GET /api/profiles``, ``profiles.list``) are POLLED every few seconds. Keyed by skills
  650. # dir; a walk is repeated only when the tree signature changes (skill add/remove) or after
  651. # the TTL (deep edits). Polled callers never walk: ``lazy_skill_count`` serves the last known
  652. # value and refreshes stale entries on a background thread, at most once per recheck window
  653. # per profile — the TTL is decoupled from the poll rate (#114041).
  654. _SKILL_COUNT_CACHE: dict[str, tuple[float, float, int]] = {}
  655. _SKILL_COUNT_TTL_SECONDS = 600.0
  656. _SKILL_COUNT_RECHECK_SECONDS = 60.0
  657. _SKILL_COUNT_NEXT_CHECK: dict[str, float] = {}
  658. _SKILL_COUNT_LOCK = threading.Lock()
  659. # One scan lock per skills dir so concurrent cold scans of the SAME profile share one walk
  660. # while different profiles' scans still run in parallel.
  661. _SKILL_COUNT_SCAN_LOCKS: dict[str, threading.Lock] = {}
  662. def _skills_dir_signature(skills_dir: Path) -> float:
  663. """Max mtime of ``skills_dir`` and its immediate children (adding/removing a category
  664. bumps the root, a skill bumps its category). One scandir: O(#categories), not O(#files)."""
  665. try:
  666. sig = skills_dir.stat().st_mtime
  667. except OSError:
  668. return 0.0
  669. try:
  670. with os.scandir(skills_dir) as it:
  671. for entry in it:
  672. try:
  673. if entry.is_dir(follow_symlinks=False):
  674. sig = max(sig, entry.stat(follow_symlinks=False).st_mtime)
  675. except OSError:
  676. continue
  677. except OSError:
  678. pass
  679. return sig
  680. def _walk_skill_count(skills_dir: Path) -> int:
  681. """One ``os.walk`` over the skills tree (prunes ``.git``/``node_modules``/support dirs
  682. instead of statting them). Best-effort: a subtree that vanishes mid-walk (a concurrent
  683. skill install/update) is skipped, never raised — ``os.walk`` (``onerror=None``) swallows
  684. scandir errors itself, so one profile's churn cannot abort the whole enumeration."""
  685. from agent.skill_utils import iter_skill_index_files
  686. return sum(1 for _ in iter_skill_index_files(skills_dir, "SKILL.md"))
  687. def _count_skills(profile_dir: Path) -> int:
  688. """Count installed skills in a profile (cached by skills-dir signature + TTL). Walks
  689. synchronously when stale — detail surfaces (``hermes profile info``, ``profiles.describe``)
  690. want the fresh number; polled lists go through :func:`_cached_skill_count`."""
  691. skills_dir = profile_dir / "skills"
  692. if not skills_dir.is_dir():
  693. return 0
  694. key = str(skills_dir)
  695. signature = _skills_dir_signature(skills_dir)
  696. cached = _SKILL_COUNT_CACHE.get(key)
  697. if cached is not None and cached[0] == signature and (time.time() - cached[1]) < _SKILL_COUNT_TTL_SECONDS:
  698. return cached[2]
  699. with _SKILL_COUNT_LOCK:
  700. scan_lock = _SKILL_COUNT_SCAN_LOCKS.setdefault(key, threading.Lock())
  701. with scan_lock:
  702. # Re-check under the lock: a concurrent caller may have just finished this walk.
  703. signature = _skills_dir_signature(skills_dir)
  704. cached = _SKILL_COUNT_CACHE.get(key)
  705. if cached is not None and cached[0] == signature and (time.time() - cached[1]) < _SKILL_COUNT_TTL_SECONDS:
  706. return cached[2]
  707. count = _walk_skill_count(skills_dir)
  708. # Stamp AFTER the walk: a scan longer than the TTL must not publish an already-expired entry.
  709. _SKILL_COUNT_CACHE[key] = (signature, time.time(), count)
  710. return count
  711. def _cached_skill_count(profile_dir: Path) -> int:
  712. """Last known skill count with ZERO skill-tree I/O on the calling thread. A never-counted
  713. or aged entry schedules one background :func:`_count_skills` per profile per recheck
  714. window (which itself re-walks only on signature change / TTL); the next poll picks the
  715. result up. ``0`` until the first refresh lands."""
  716. key = str(profile_dir / "skills")
  717. now = time.time()
  718. with _SKILL_COUNT_LOCK:
  719. due = _SKILL_COUNT_NEXT_CHECK.get(key, 0.0) <= now
  720. if due:
  721. _SKILL_COUNT_NEXT_CHECK[key] = now + _SKILL_COUNT_RECHECK_SECONDS
  722. if due:
  723. threading.Thread(target=_count_skills, args=(profile_dir,),
  724. name="hermes-skill-count", daemon=True).start()
  725. cached = _SKILL_COUNT_CACHE.get(key)
  726. return cached[2] if cached is not None else 0
  727. # profile.yaml — per-profile metadata (description, etc.)
  728. # Deliberately tiny and separate from ``config.yaml`` (user-facing Hermes config, ~5000
  729. # lines of defaults): this is metadata ABOUT the profile. Missing file -> empty defaults,
  730. # never an error; the kanban decomposer falls back to the profile name.
  731. def read_profile_meta(profile_dir: Path) -> dict:
  732. """Read ``profile.yaml`` -> ``{description, description_auto, display_name,
  733. previous_names}`` (empty defaults when missing/unreadable). Never raises — a
  734. corrupt file on one profile must not break ``hermes profile list``."""
  735. def _read() -> dict:
  736. data = _load_yaml_dict(profile_dir / "profile.yaml") or {}
  737. ui_meta = data.get("ui_meta")
  738. bot_title = ""
  739. if isinstance(ui_meta, dict):
  740. hermes_bots = ui_meta.get("hermes-bots")
  741. if isinstance(hermes_bots, dict):
  742. bot_title = str(hermes_bots.get("title") or "").strip()
  743. return {
  744. "description": str(data.get("description") or "").strip(),
  745. "description_auto": bool(data.get("description_auto", False)),
  746. "display_name": str(data.get("display_name") or "").strip(),
  747. "bot_title": bot_title,
  748. "previous_names": _clean_previous_names(data.get("previous_names")),
  749. }
  750. # A copy per caller (list included): the cached value is shared, and a caller that mutates
  751. # its result must not poison the next reader.
  752. meta = dict(_cached_profile_read(profile_dir / "profile.yaml", "profile-meta", _read))
  753. meta["previous_names"] = list(meta["previous_names"])
  754. return meta
  755. def _clean_previous_names(raw) -> list[str]:
  756. """Normalize the ``previous_names`` list from ``profile.yaml``: strings only,
  757. stripped, de-duplicated preserving order. Never raises."""
  758. if not isinstance(raw, list):
  759. return []
  760. cleaned: list[str] = []
  761. seen = set()
  762. for item in raw:
  763. name = str(item or "").strip()
  764. if name and name not in seen:
  765. seen.add(name)
  766. cleaned.append(name)
  767. return cleaned
  768. def write_profile_meta(
  769. profile_dir: Path, *, description: Optional[str] = None, description_auto: Optional[bool] = None,
  770. display_name: Optional[str] = None, previous_names: Optional[list[str]] = None,
  771. ) -> None:
  772. """Update ``profile.yaml`` in place: only passed fields are overwritten; the file is
  773. created if missing. The profile directory itself must exist."""
  774. if not profile_dir.is_dir():
  775. raise FileNotFoundError(f"profile directory does not exist: {profile_dir}")
  776. path = profile_dir / "profile.yaml"
  777. existing: dict = _load_yaml_dict(path) or {}
  778. if description is not None:
  779. existing["description"] = description.strip()
  780. if description_auto is not None:
  781. existing["description_auto"] = bool(description_auto)
  782. if display_name is not None:
  783. # Empty string clears the key (falls back to the canonical id).
  784. if display_name.strip():
  785. existing["display_name"] = display_name.strip()
  786. else:
  787. existing.pop("display_name", None)
  788. if previous_names is not None:
  789. # Rename history for group-chat member sync (#110200): consumers match
  790. # stale persisted handles against the live roster via these names.
  791. cleaned = _clean_previous_names(previous_names)
  792. if cleaned:
  793. existing["previous_names"] = cleaned
  794. else:
  795. existing.pop("previous_names", None)
  796. # Atomic write: bare open("w") truncates before the dump, and the read path swallows
  797. # parse errors as {}, so a crashed write would silently drop unspecified fields.
  798. # See #51356.
  799. from utils import atomic_yaml_write
  800. atomic_yaml_write(path, existing, sort_keys=False)
  801. def format_profile_label(name: str, display_name: Optional[str]) -> str:
  802. """``display_name (canonical_id)``, or the bare id when no display name is set (or it
  803. equals the id) — byte-for-byte the pre-feature rendering."""
  804. dn = (display_name or "").strip()
  805. return f"{dn} ({name})" if dn and dn != name else name
  806. def set_profile_display_name(profile_name: str, display_name: str) -> str:
  807. """Set (or clear, with ``""``) a presentation-only display name. Returns the stored value;
  808. raises ``ValueError`` over 64 chars."""
  809. _canon, profile_dir = _existing_profile_dir(profile_name)
  810. cleaned = (display_name or "").strip()
  811. if len(cleaned) > 64:
  812. raise ValueError(f"Display name too long ({len(cleaned)} chars, max 64).")
  813. write_profile_meta(profile_dir, display_name=cleaned)
  814. return cleaned
  815. # CRUD operations
  816. def _profile_info(name: str, path: Path, *, is_default: bool, alias_name: Optional[str] = None,
  817. lazy_skill_count: bool = False) -> ProfileInfo:
  818. """Build one :class:`ProfileInfo` from a profile directory."""
  819. model, provider = _read_config_model(path)
  820. dist_name, dist_version, dist_source = _read_distribution_meta(path)
  821. meta = read_profile_meta(path)
  822. alias_path = _find_our_wrapper(alias_name) if alias_name else None
  823. gateway_running = _check_gateway_running(path)
  824. if not is_default:
  825. gateway_running = gateway_running or _served_by_running_multiplexer(name)
  826. skill_count = _cached_skill_count(path) if lazy_skill_count else _count_skills(path)
  827. return ProfileInfo(
  828. name=name, path=path, is_default=is_default, gateway_running=gateway_running, model=model,
  829. provider=provider, has_env=(path / ".env").exists(), skill_count=skill_count,
  830. alias_path=alias_path, alias_name=alias_name, distribution_name=dist_name,
  831. distribution_version=dist_version, distribution_source=dist_source,
  832. **meta,
  833. )
  834. def list_profiles(*, lazy_skill_count: bool = False) -> list[ProfileInfo]:
  835. """Return info for all profiles, including the default.
  836. ``lazy_skill_count=True`` is for POLLED callers (``GET /api/profiles``, ``profiles.list``):
  837. ``skill_count`` is the last known value, refreshed off-request, so the request never walks
  838. a skill tree (#114041). Default ``False`` counts synchronously (CLI, detail views)."""
  839. profiles = []
  840. default_home = _get_default_hermes_home()
  841. if default_home.is_dir():
  842. profiles.append(_profile_info("default", default_home, is_default=True,
  843. lazy_skill_count=lazy_skill_count))
  844. named = _iter_named_profile_dirs()
  845. if named:
  846. alias_map = build_alias_map() # ONCE, not per profile (was the dominant cost)
  847. for entry in named:
  848. alias_name = alias_map.get(normalize_profile_name(entry.name))
  849. profiles.append(_profile_info(entry.name, entry, is_default=False, alias_name=alias_name,
  850. lazy_skill_count=lazy_skill_count))
  851. return profiles
  852. #: One signature/result per home: the webhook and
  853. #: api-server callers run :func:`profiles_to_serve` per inbound request, so the reader
  854. #: must not re-parse a profile's config.yaml every time.
  855. _STANDALONE_MEMO: dict[str, tuple[Optional[tuple], Optional[bool]]] = {}
  856. _STANDALONE_WARNED = False
  857. _STANDALONE_DEFAULT_WARNING = (
  858. "gateway.standalone is ignored on the default profile: it is the host gateway")
  859. def profile_is_standalone(home: Path) -> bool:
  860. """Does ``home``'s own config.yaml opt this profile out of the host multiplexer
  861. (``gateway.standalone: true``)? Memoised by file signature. The DEFAULT profile is
  862. never standalone — it IS the host — and warns once per process if the key is set there."""
  863. global _STANDALONE_WARNED
  864. from hermes_yaml import YAMLError
  865. home = Path(home)
  866. cfg_path = home / "config.yaml"
  867. key = str(home)
  868. try:
  869. signature = config_cache_version(cfg_path)
  870. except FileNotFoundError:
  871. signature = None
  872. except OSError as exc:
  873. signature = ("stat-error", exc.errno)
  874. if _STANDALONE_MEMO.get(key) != (signature, False):
  875. logger.warning("Cannot read gateway.standalone from %s (%s); treating as not standalone",
  876. cfg_path, type(exc).__name__)
  877. _STANDALONE_MEMO[key] = (signature, False)
  878. return False
  879. cached = _STANDALONE_MEMO.get(key)
  880. if cached is not None and cached[0] == signature and cached[1] is not None:
  881. return cached[1]
  882. value = None
  883. if signature is not None:
  884. from hermes_cli.config import read_user_config_raw
  885. try:
  886. cfg = read_user_config_raw(cfg_path) or {}
  887. except (YAMLError, OSError, UnicodeError) as exc:
  888. if cached is None or cached[0] != signature:
  889. logger.warning("Cannot read gateway.standalone from %s (%s); treating as not standalone",
  890. cfg_path, type(exc).__name__)
  891. # Access can recover without changing the signature. None retains the
  892. # warning receipt without caching a transient failure as config.
  893. _STANDALONE_MEMO[key] = (signature, False if isinstance(exc, YAMLError) else None)
  894. return False
  895. if isinstance(cfg.get("gateway"), dict):
  896. value = cfg["gateway"].get("standalone")
  897. result = _standalone_truthy(value)
  898. if home == _get_default_hermes_home():
  899. if result and not _STANDALONE_WARNED:
  900. logger.warning(_STANDALONE_DEFAULT_WARNING)
  901. _STANDALONE_WARNED = True
  902. result = False
  903. _STANDALONE_MEMO[key] = (signature, result)
  904. return result
  905. def _standalone_truthy(value: object) -> bool:
  906. """``gateway.standalone`` truthiness via the shared bool parser; only the
  907. ``gateway:`` section's ``standalone`` key is read (no top-level alias)."""
  908. from gateway.config import _bool_token
  909. if isinstance(value, str):
  910. return _bool_token(value) is True
  911. return bool(value)
  912. def parked_marker_path(home: Path) -> Path:
  913. return Path(home) / "gateway.parked"
  914. def profile_is_parked(home: Path) -> bool:
  915. """Marker contents are deliberately irrelevant, including for provisioning."""
  916. return parked_marker_path(home).exists()
  917. _parked_default_warned: set[Path] = set()
  918. def profiles_to_serve(multiplex: bool, *, include_standalone: bool = False,
  919. include_parked: bool = False) -> list[tuple[str, Path]]:
  920. """``(profile_name, hermes_home)`` pairs a gateway should serve — the single chokepoint
  921. for "which profiles does the inbound gateway handle".
  922. ``multiplex=False``: exactly one entry for the *active* profile (byte-for-byte the
  923. historical single-profile behavior; name is ``"default"`` or the named profile's id).
  924. ``multiplex=True``: default plus every live named profile under ``profiles/`` (tombstoned
  925. and parked profiles skipped). Pure directory read: never creates a profile dir (#94590).
  926. Named profiles that authored ``gateway.standalone: true`` are skipped because they opted
  927. out of the host multiplexer; a ``gateway.parked`` marker (``hermes -p X gateway stop``) skips
  928. a profile the host would otherwise serve. Callers enumerating INSTALLED profiles pass
  929. ``include_standalone=True, include_parked=True``; serving/ticking callers pass neither."""
  930. active = get_active_profile_name() or "default"
  931. default = _get_default_hermes_home()
  932. if profile_is_parked(default) and default not in _parked_default_warned:
  933. logger.warning("Ignoring gateway.parked for the default profile; stop the host gateway instead")
  934. _parked_default_warned.add(default)
  935. if not multiplex:
  936. return [(active, get_profile_dir(active))]
  937. serve: list[tuple[str, Path]] = [("default", default)]
  938. serve.extend((entry.name, entry) for entry in _iter_named_profile_dirs()
  939. if (include_standalone or not profile_is_standalone(entry))
  940. and (include_parked or not profile_is_parked(entry)))
  941. return serve
  942. def _resolve_clone_source(clone_from: Optional[str]) -> Path:
  943. """Directory to clone from: the named profile, or the active profile when ``None``."""
  944. require_file_tooling("Profile clone")
  945. if clone_from is None:
  946. from hermes_constants import get_hermes_home
  947. source_dir = get_hermes_home()
  948. else:
  949. clone_from = _canon_valid(clone_from)
  950. source_dir = get_profile_dir(clone_from)
  951. if not source_dir.is_dir():
  952. raise FileNotFoundError(f"Source profile '{clone_from or 'active'}' does not exist at {source_dir}")
  953. return source_dir
  954. def _seed_file_if_missing(path: Path, text: str, mode: Optional[int] = None) -> None:
  955. """Best-effort: write *text* to *path* unless it already exists; never raises."""
  956. if path.exists():
  957. return
  958. with contextlib.suppress(OSError):
  959. path.write_text(text, encoding="utf-8")
  960. if mode is not None:
  961. os.chmod(str(path), mode)
  962. def _clone_file(source_dir: Path, profile_dir: Path, relpath: str) -> None:
  963. """Copy one profile-relative file if it exists. ``.env`` is tightened to owner-only:
  964. ``copy2`` preserves source mode bits, so a loose source (umask 0o644) would leak."""
  965. src = source_dir / relpath
  966. if not src.exists():
  967. return
  968. dst = profile_dir / relpath
  969. dst.parent.mkdir(parents=True, exist_ok=True)
  970. shutil.copy2(src, dst)
  971. if relpath == ".env":
  972. with contextlib.suppress(OSError):
  973. os.chmod(str(dst), 0o600)
  974. # Files a clone edits in place after copying. A ``--clone-all`` copy preserves symlinks
  975. # (``symlinks=True``), so a symlinked source ``.env`` would otherwise be edited THROUGH the link and
  976. # the channel stripping would mutate the SOURCE profile. These are materialized as real files first.
  977. _CLONE_MATERIALIZE = (".env", "config.yaml", "auth.json", "SOUL.md")
  978. def _materialize_symlinked_files(profile_dir: Path) -> list[str]:
  979. """Replace symlinked root files the clone will edit with private copies of their targets (a
  980. dangling link is dropped). Returns the relative names materialized."""
  981. done: list[str] = []
  982. for name in _CLONE_MATERIALIZE:
  983. path = profile_dir / name
  984. if not path.is_symlink():
  985. continue
  986. target = Path(os.path.realpath(path))
  987. path.unlink()
  988. if target.is_file():
  989. shutil.copy2(target, path)
  990. done.append(name)
  991. return done
  992. def _junction_target(path: str) -> Optional[str]:
  993. """Target of an NTFS directory junction, else ``None``. A junction is a reparse point, not a
  994. symlink: ``os.path.islink()`` is False and ``shutil.copytree(symlinks=True)`` descends into it."""
  995. if os.name != "nt":
  996. return None
  997. try:
  998. if os.lstat(path).st_reparse_tag != stat.IO_REPARSE_TAG_MOUNT_POINT:
  999. return None
  1000. target = os.readlink(path)
  1001. except OSError:
  1002. return None
  1003. # readlink hands back the substitute name; CreateJunction rejects the ``\\?\`` spelling.
  1004. if target.startswith("\\\\?\\UNC\\"):
  1005. return "\\" + target[7:]
  1006. return target.removeprefix("\\\\?\\")
  1007. def _copytree_keep_junctions(src: Path, dst: Path, ignore, dirs_exist_ok: bool = False) -> None:
  1008. """``shutil.copytree(symlinks=True)`` that re-creates NTFS junctions as junctions instead of
  1009. traversing them. A ``skills/foo`` junction into a ``skills.external_dirs`` root copied as a
  1010. physical tree is a second same-named candidate and ``locate_skill`` refuses to guess (#113471).
  1011. A junction whose target is gone is skipped with a warning, never a crash."""
  1012. junctions: dict[str, str] = {}
  1013. def _ignore(directory: str, names: list[str]) -> set:
  1014. ignored = set(ignore(directory, names))
  1015. for name in names:
  1016. target = _junction_target(os.path.join(directory, name))
  1017. if target is not None:
  1018. junctions[os.path.join(directory, name)] = target
  1019. ignored.add(name)
  1020. return ignored
  1021. shutil.copytree(src, dst, symlinks=True, dirs_exist_ok=dirs_exist_ok, ignore=_ignore)
  1022. if junctions:
  1023. import _winapi # Windows-only stdlib module; only reachable once a junction was seen
  1024. for link, target in junctions.items():
  1025. try:
  1026. _winapi.CreateJunction(target, os.path.join(dst, os.path.relpath(link, src)))
  1027. except OSError as exc:
  1028. logger.warning("clone: skipped junction %s -> %s (%s)", link, target, exc)
  1029. def _clone_all_into(source_dir: Path, profile_dir: Path, canon: str) -> Optional[dict]:
  1030. """--clone-all: full copytree minus infrastructure/history, then strip runtime files
  1031. and cloned single-use OAuth grants."""
  1032. _copytree_keep_junctions(source_dir, profile_dir, _clone_all_copytree_ignore(source_dir))
  1033. materialized = _materialize_symlinked_files(profile_dir)
  1034. if materialized:
  1035. logger.info("profile %s: materialized symlinked %s so the clone never writes through to %s",
  1036. canon, materialized, source_dir)
  1037. # Excluded history dirs (sessions/, cron/) must still exist as empty dirs so the clone runs.
  1038. for subdir in _PROFILE_DIRS:
  1039. (profile_dir / subdir).mkdir(parents=True, exist_ok=True)
  1040. for stale in _CLONE_ALL_STRIP:
  1041. (profile_dir / stale).unlink(missing_ok=True)
  1042. # auth.json / .anthropic_oauth.json copied verbatim fork single-use OAuth grants
  1043. # (Anthropic / Codex / xAI): one credential with two owners, and the first profile to
  1044. # refresh revokes the pair for every sibling. Drop the copies; the clone reads the root
  1045. # grant through the credential-pool fallback.
  1046. from hermes_cli.auth import strip_cloned_single_use_oauth_grants
  1047. stripped = strip_cloned_single_use_oauth_grants(profile_dir)
  1048. if any(stripped.values()):
  1049. logger.info(
  1050. "profile %s: dropped cloned single-use OAuth grants %s "
  1051. "(inherits the root grant instead)", canon, stripped,
  1052. )
  1053. from agent.vault_store import VaultError, VaultStore
  1054. try: # a keychain-mode vault's copied pointer names the source's entry: the clone gets its own
  1055. return VaultStore(profile_dir / "vault").own_copied_key(get_profile_dir(canon) / "vault")
  1056. except VaultError as exc:
  1057. raise ValueError(f"Cannot copy the vault from {source_dir}: {exc}") from exc
  1058. def _strip_multiplex_flag(config_path: Path) -> None:
  1059. """Multiplexing belongs to the default profile; a clone that keeps the flag would start its
  1060. own multiplexer (or be refused at boot) the first time it runs a gateway."""
  1061. if not config_exists(config_path):
  1062. return
  1063. with contextlib.suppress(Exception): # creation must not fail over an unreadable copy
  1064. from hermes_cli.config import atomic_config_replace, read_user_config_raw
  1065. cfg = read_user_config_raw(config_path)
  1066. gateway = cfg.get("gateway") if isinstance(cfg.get("gateway"), dict) else {}
  1067. if "multiplex_profiles" not in cfg and "multiplex_profiles" not in gateway:
  1068. return
  1069. cfg.pop("multiplex_profiles", None)
  1070. gateway.pop("multiplex_profiles", None)
  1071. if not gateway and "gateway" in cfg:
  1072. cfg.pop("gateway")
  1073. # Deleting the flag is deliberate, so use the replace writer (the plain writer refuses
  1074. # omissions); the clone's comments still survive the round-trip.
  1075. atomic_config_replace(config_path, cfg)
  1076. def _clone_plugins_ignore(plugins_root: Path):
  1077. """copytree ignore for a cloned ``plugins/``: :func:`_non_exportable_entries` everywhere, plus
  1078. the installer's in-flight ``.install-*`` / ``.update-*`` staging dirs at the root."""
  1079. root = str(plugins_root)
  1080. def _ignore(directory: str, names: list[str]) -> set:
  1081. ignored = _non_exportable_entries(directory, names)
  1082. if directory == root:
  1083. # Directories only: ``.install-metadata.json`` shares the prefix and must travel.
  1084. ignored.update(n for n in names if n.startswith((".install-", ".update-"))
  1085. and os.path.isdir(os.path.join(directory, n)))
  1086. return ignored
  1087. return _ignore
  1088. def _clone_plugins(source_dir: Path, profile_dir: Path) -> None:
  1089. """Copy the source's user-installed plugins (``plugins/`` with ``.install-metadata.json``).
  1090. ``config.yaml`` already carries ``plugins.enabled`` and ``memory.provider``; without the code a
  1091. catalog-installed memory provider resolves nowhere in the clone, so the clone silently runs
  1092. without its memory (or, with lazy installs on, re-fetches the latest catalog pin instead of the
  1093. revision the source runs). The copy keeps each plugin's tree, revision and catalog provenance
  1094. (the install record). Python dependencies live in the shared venv, where the source's
  1095. selection of the same plugin already put them."""
  1096. source_plugins = source_dir / "plugins"
  1097. if source_plugins.is_dir():
  1098. _copytree_keep_junctions(source_plugins, profile_dir / "plugins",
  1099. _clone_plugins_ignore(source_plugins), dirs_exist_ok=True)
  1100. def cloned_plugin_names(profile_dir: Path) -> list[str]:
  1101. """Plugins a clone now carries in ``plugins/``, for the CLI notice."""
  1102. try:
  1103. return sorted(p.name for p in (profile_dir / "plugins").iterdir()
  1104. if not p.name.startswith(".") and (p.is_dir() or p.is_symlink()))
  1105. except OSError:
  1106. return []
  1107. def _bootstrap_profile_dir(profile_dir: Path, source_dir: Optional[Path],
  1108. sync_imports: bool = False) -> None:
  1109. """Fresh layout: bootstrap dirs, then either seed a model block (no source) or clone
  1110. config files, installed skills (the dashboard's "clone from default" must keep bundled
  1111. AND user-installed skills), and memory/identity files from *source_dir*.
  1112. ``sync_imports`` also copies the source's ``import-sync.json`` (the manifest the agent-importers
  1113. plugin's ``hermes import-agent`` writes) so the clone stays registered against the same external trees
  1114. and ``hermes -p <clone> import-agent --sync`` keeps pulling from them. The link is to the
  1115. external tree, never to the source profile: both profiles stay independent islands."""
  1116. profile_dir.mkdir(parents=True, exist_ok=True)
  1117. for subdir in _PROFILE_DIRS:
  1118. (profile_dir / subdir).mkdir(parents=True, exist_ok=True)
  1119. if source_dir is None:
  1120. _seed_model_config(profile_dir)
  1121. return
  1122. for relpath in _CLONE_CONFIG_FILES:
  1123. _clone_file(source_dir, profile_dir, relpath)
  1124. _strip_multiplex_flag(profile_dir / "config.yaml")
  1125. source_skills = source_dir / "skills"
  1126. if source_skills.is_dir():
  1127. _copytree_keep_junctions(source_skills, profile_dir / "skills", _non_exportable_entries, dirs_exist_ok=True)
  1128. for relpath in _CLONE_SUBDIR_FILES:
  1129. _clone_file(source_dir, profile_dir, relpath)
  1130. _clone_plugins(source_dir, profile_dir)
  1131. from hermes_cli.profile_memory_config import _load_config_dict, active_memory_provider, clone_memory_provider_config
  1132. clone_memory_provider_config(source_dir, profile_dir, active_memory_provider(_load_config_dict(source_dir)))
  1133. if sync_imports: # a plain file at the profile root, written by the agent-importers plugin
  1134. _clone_file(source_dir, profile_dir, "import-sync.json")
  1135. def create_profile(
  1136. name: str, clone_from: Optional[str] = None, clone_all: bool = False, clone_config: bool = False,
  1137. no_alias: bool = False, no_skills: bool = False, description: Optional[str] = None,
  1138. clone_channels: bool = False, sync_imports: bool = False, soul: Optional[str] = None,
  1139. ) -> Path:
  1140. """Create a new profile directory and return its path.
  1141. ``clone_from`` defaults to the active profile when cloning. ``clone_all`` copies all state;
  1142. ``clone_config`` copies config.yaml/.env/SOUL.md, installed skills, and identity files.
  1143. Either clone strips the source's messaging channels — bot tokens, allowlists, platform
  1144. sections, pairing/session state — unless ``clone_channels`` opts in: a copied bot credential
  1145. makes two gateways fight over one bot (``hermes_cli.profile_channels``; callers list what
  1146. was left behind with ``channel_platforms_configured(source_dir)``).
  1147. ``no_skills`` creates an empty profile and writes a marker so ``hermes update`` skips
  1148. re-seeding its skills; it is mutually exclusive with the clone options, which copy skills.
  1149. ``sync_imports`` (``--clone`` only; ``--clone-all`` copies the file anyway) also copies the
  1150. ``import-agent`` sync manifest so the clone can keep pulling the same external agent trees."""
  1151. if no_skills and (clone_from is not None or clone_config or clone_all):
  1152. raise ValueError(
  1153. "--no-skills is mutually exclusive with --clone / --clone-from / --clone-all "
  1154. "(cloning explicitly copies skills from the source profile)."
  1155. )
  1156. if sync_imports and not (clone_config or clone_all):
  1157. raise ValueError("--sync-imports requires --clone or --clone-from (there is no import "
  1158. "manifest to carry over without a source profile).")
  1159. cloning = clone_from is not None or clone_all or clone_config
  1160. if clone_channels and not cloning:
  1161. raise ValueError("--clone-channels only applies to a clone (--clone, --clone-from or --clone-all).")
  1162. canon = _canon_valid(name)
  1163. if canon == "default":
  1164. raise ValueError("Cannot create a profile named 'default' — it is the built-in profile (~/.hermes).")
  1165. profile_dir = get_profile_dir(canon)
  1166. if profile_dir.exists() and not named_profile_has_identity(profile_dir):
  1167. if named_profile_is_deleted(profile_dir):
  1168. # Empty shell left by a post-delete mkdir: invisible to ``profile list``, safe to replace
  1169. # unless a gateway still tearing the deleted profile down holds its gateway.lock in it.
  1170. if not wait_profile_unowned(profile_dir, timeout=0):
  1171. raise FileExistsError(f"Cannot create profile '{canon}': a running gateway still owns {profile_dir}")
  1172. shutil.rmtree(profile_dir)
  1173. else:
  1174. # A live marker-less dir is invisible to ``profile list`` but may still hold user
  1175. # files (skills/, memories/, cron/jobs.json): fail closed and name it, never rmtree.
  1176. raise FileExistsError(
  1177. f"Cannot create profile '{canon}': {profile_dir} exists but carries no profile identity "
  1178. "file, so it is not listed as a profile. Move or remove that directory first."
  1179. )
  1180. if profile_dir.exists():
  1181. raise _profile_exists_error(canon)
  1182. source_dir = _resolve_clone_source(clone_from) if cloning else None
  1183. if source_dir is not None and clone_channels:
  1184. from hermes_cli.profile_channels import clone_channels_refusal
  1185. refusal = clone_channels_refusal(source_dir, clone_from or get_active_profile_name() or "default")
  1186. if refusal:
  1187. raise ValueError(refusal)
  1188. clear_named_profile_deleted(profile_dir)
  1189. # Build in a hidden sibling and publish with one rename: a running multiplexer rescans profiles/
  1190. # on every create and every 30 s, and ``_iter_named_profile_dirs`` only lists valid ids (no leading
  1191. # dot), so it can never adopt the half-copied tree and start adapters on credentials the strip
  1192. # below has not removed yet.
  1193. from hermes_cli.profiles_initialization import clone_staging_dir, discard_unpublished_vault_key, finish_profile_layout
  1194. staging = clone_staging_dir(profile_dir)
  1195. clone_key = None # the keychain entry made for this clone's vault, if any
  1196. try:
  1197. if clone_all and source_dir:
  1198. clone_key = _clone_all_into(source_dir, staging, canon)
  1199. else:
  1200. _bootstrap_profile_dir(staging, source_dir, sync_imports=sync_imports)
  1201. if source_dir is not None and not clone_channels:
  1202. from hermes_cli.profile_channels import strip_channel_settings
  1203. stripped = strip_channel_settings(staging, include_state=clone_all, source_dir=source_dir)
  1204. if stripped:
  1205. logger.info("profile %s: cloned without messaging channels %s", canon, stripped)
  1206. finish_profile_layout(staging, no_skills=no_skills, clone_all=clone_all, description=description, soul=soul)
  1207. os.rename(staging, profile_dir)
  1208. except BaseException:
  1209. discard_unpublished_vault_key(clone_key)
  1210. shutil.rmtree(staging, ignore_errors=True)
  1211. raise
  1212. from hermes_cli.profile_memory_config import notify_memory_provider
  1213. notify_memory_provider(profile_dir, lambda p: p.on_profile_created(canon, str(profile_dir)))
  1214. # Inside a container under s6, register the gateway as a runtime s6 service so
  1215. # `hermes -p <profile> gateway start` supervises via `s6-svc -u` instead of a bare
  1216. # process. No-op on host (systemd/launchd/windows unit generation handles lifecycle).
  1217. _maybe_register_gateway_service(canon)
  1218. # A running multiplexer enumerates profiles/ at boot: ask it to serve this one now (it also
  1219. # rescans periodically, so a missed signal only delays serving).
  1220. _notify_multiplexer(canon)
  1221. return profile_dir
  1222. def _notify_multiplexer(canon: str) -> None:
  1223. from hermes_cli.gateway_multiplex_served import notify_multiplexer_profiles_changed
  1224. notify_multiplexer_profiles_changed(canon)
  1225. def _purge_identity(canon: str) -> bool:
  1226. """Settle a deleted profile's durable identity (``profile_identity.purge_profile_identity``).
  1227. False means the filesystem delete happened but the identity settlement did not — the caller
  1228. reports that as a pending settlement rather than a clean success."""
  1229. from hermes_cli.profile_identity import purge_profile_identity
  1230. return purge_profile_identity(canon)
  1231. def _live_default_multiplexer() -> bool:
  1232. """True when a live default gateway has recorded a served-profile set: every dir under
  1233. profiles/ is then served by it, so a profile-identity change must be unrouted first."""
  1234. try:
  1235. from hermes_cli.gateway_multiplex_served import recorded_served_profiles
  1236. return recorded_served_profiles() is not None
  1237. except Exception:
  1238. return False
  1239. def seed_profile_skills(profile_dir: Path, quiet: bool = False) -> Optional[dict]:
  1240. """Seed bundled skills into a profile via subprocess (sync_skills() caches HERMES_HOME at
  1241. module level). Returns the sync result dict, or None on failure. ``--no-skills`` profiles
  1242. still run the sync: ``sync_skills()`` detects the marker and seeds only essentials."""
  1243. project_root = Path(__file__).parent.parent.resolve()
  1244. try:
  1245. result = subprocess.run(
  1246. [sys.executable, "-c",
  1247. "import json; from tools.skills_sync import sync_skills; "
  1248. "r = sync_skills(quiet=True); print(json.dumps(r))"],
  1249. env={**os.environ, "HERMES_HOME": str(profile_dir)},
  1250. cwd=str(project_root),
  1251. capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=60,
  1252. check=False,
  1253. )
  1254. if result.returncode == 0 and result.stdout.strip():
  1255. return json.loads(result.stdout.strip())
  1256. if not quiet:
  1257. print(f"⚠ Skill seeding returned exit code {result.returncode}")
  1258. if result.stderr.strip():
  1259. print(f" {result.stderr.strip()[:200]}")
  1260. return None
  1261. except subprocess.TimeoutExpired:
  1262. if not quiet:
  1263. print("⚠ Skill seeding timed out (60s)")
  1264. return None
  1265. except Exception as e:
  1266. if not quiet:
  1267. print(f"⚠ Skill seeding failed: {e}")
  1268. return None
  1269. def backfill_profile_envs(quiet: bool = False) -> list[str]:
  1270. """Seed the placeholder ``.env`` header into every named profile lacking one; never
  1271. overwrites an existing file. It never copies the default's ``.env``: secrets are
  1272. profile-scoped, and a copied bot token makes two adapters fight over one bot.
  1273. """
  1274. backfilled: list[str] = []
  1275. for entry in _iter_named_profile_dirs():
  1276. env_path = entry / ".env"
  1277. if env_path.exists():
  1278. continue
  1279. try:
  1280. env_path.write_text(_PLACEHOLDER_ENV, encoding="utf-8")
  1281. os.chmod(str(env_path), 0o600)
  1282. backfilled.append(entry.name)
  1283. except OSError as e:
  1284. if not quiet:
  1285. print(f"⚠ Could not seed .env for profile '{entry.name}': {e}")
  1286. return backfilled
  1287. _BACKEND_TOKENS = frozenset({"serve", "dashboard", "gateway"})
  1288. _HERMES_ARGV_MARKERS = ("hermes_cli.main", "hermes-gateway", "tui_gateway")
  1289. # python / python3 / python3.12 / pythonw(.exe): the interpreter basenames a
  1290. # `#!/…/python3` console-script shim is exec'd through when something (e.g. Electron's
  1291. # `findOnPath('hermes')`) spawns the shim by handing the interpreter its path — then the
  1292. # OS-reported argv[0] is the interpreter, not "hermes".
  1293. _PYTHON_INTERPRETER_RE = re.compile(r"^python[\d.]*w?(\.exe)?$")
  1294. # Console-script entry points this project ships (pyproject.toml [project.scripts]).
  1295. # argv[1] is matched against exact names, not ``startswith("hermes")``: with a bare
  1296. # interpreter argv[0], argv[1] can be ANY user script ("hermes-notes.py").
  1297. _HERMES_CONSOLE_SCRIPT_NAMES = frozenset({"hermes", "hermes-agent", "hermes-acp"})
  1298. def _is_hermes_argv(argv: list) -> bool:
  1299. """True for a Hermes process: entrypoint marker in argv, executable named ``hermes*``,
  1300. or a python interpreter directly exec'ing a known ``hermes`` console-script shim."""
  1301. joined = " ".join(argv)
  1302. exe_name = os.path.basename(argv[0]).lower()
  1303. if any(marker in joined for marker in _HERMES_ARGV_MARKERS) or exe_name.startswith("hermes"):
  1304. return True
  1305. if len(argv) >= 2 and _PYTHON_INTERPRETER_RE.match(exe_name):
  1306. script_name = os.path.basename(str(argv[1])).lower()
  1307. return script_name.rsplit(".", 1)[0] in _HERMES_CONSOLE_SCRIPT_NAMES
  1308. return False
  1309. def _argv_profile_selectors(argv: list):
  1310. """Yield every profile name selected via ``-p X`` / ``--profile X`` / ``--profile=X``."""
  1311. for i, tok in enumerate(argv):
  1312. if tok in {"--profile", "-p"} and i + 1 < len(argv):
  1313. yield argv[i + 1]
  1314. elif tok.startswith("--profile="):
  1315. yield tok.split("=", 1)[1]
  1316. def _profile_bound_backend_pids(canon: str, profile_dir: Path) -> list[int]:
  1317. """PIDs of running Hermes *backends* bound to this profile (``gateway.pid`` only tracks
  1318. the messaging gateway). Tightly scoped: current-user processes, backend subcommands only
  1319. (never an interactive ``chat``/``tui``), never this process or its ancestors. Empty when
  1320. ``psutil`` can't inspect anything."""
  1321. try:
  1322. import psutil # type: ignore
  1323. except Exception:
  1324. return []
  1325. try:
  1326. resolved_dir = profile_dir.resolve()
  1327. except OSError:
  1328. resolved_dir = profile_dir
  1329. # Never terminate ourselves or a parent (`hermes -p <canon> profile delete` runs under
  1330. # the very profile it's deleting).
  1331. skip: set[int] = {os.getpid()}
  1332. with contextlib.suppress(Exception):
  1333. parent = psutil.Process(os.getpid()).parent()
  1334. while parent is not None:
  1335. skip.add(parent.pid)
  1336. parent = parent.parent()
  1337. try:
  1338. current_user = psutil.Process(os.getpid()).username()
  1339. except Exception:
  1340. current_user = None
  1341. pids: list[int] = []
  1342. for proc in psutil.process_iter(["pid", "name", "username", "cmdline"]):
  1343. try:
  1344. info = proc.info
  1345. pid = info.get("pid")
  1346. if pid is None or pid in skip:
  1347. continue
  1348. if current_user is not None and info.get("username") != current_user:
  1349. continue
  1350. argv = info.get("cmdline") or []
  1351. if not argv or not _is_hermes_argv(argv):
  1352. continue
  1353. if not ({tok.lower() for tok in argv} & _BACKEND_TOKENS):
  1354. continue
  1355. # Bound to THIS profile by selector flag, or by HERMES_HOME pointing at its dir.
  1356. bound = any(normalize_profile_name(sel) == canon for sel in _argv_profile_selectors(argv))
  1357. if not bound:
  1358. with contextlib.suppress(Exception): # environ() can raise AccessDenied even same-user
  1359. env_home = (proc.environ() or {}).get("HERMES_HOME", "")
  1360. bound = bool(env_home) and Path(env_home).resolve() == resolved_dir
  1361. if bound:
  1362. pids.append(pid)
  1363. except Exception:
  1364. continue # NoSuchProcess / AccessDenied / ZombieProcess and anything else
  1365. return pids
  1366. def _wait_then_force_kill(pids: list[int], start_times: dict, *, wait: float = 10.0) -> bool:
  1367. """After a graceful ``terminate_pid``, wait up to *wait* seconds (0.5s polls) for *pids*
  1368. to exit, then force-kill stragglers. True when every pid exited gracefully.
  1369. ``start_times`` pins each force kill to the same process incarnation (PID reuse guard)."""
  1370. from gateway.status import _pid_exists, get_process_start_time, terminate_pid
  1371. for _ in range(int(wait / 0.5)):
  1372. time.sleep(0.5)
  1373. if not any(_pid_exists(pid) for pid in pids):
  1374. return True
  1375. for pid in pids:
  1376. if _pid_exists(pid):
  1377. with contextlib.suppress(ProcessLookupError, PermissionError, OSError):
  1378. terminate_pid(pid, force=True, expected_start_time=start_times.get(pid, get_process_start_time(pid)))
  1379. return False
  1380. def _stop_profile_backends(canon: str, profile_dir: Path) -> None:
  1381. """Terminate Desktop-spawned / stray backends bound to this profile. Complements
  1382. ``_stop_gateway_process`` (which only knows ``gateway.pid``): a live ``serve``/``dashboard``
  1383. keeps creating files while ``rmtree`` walks, so the final rmdir fails ENOTEMPTY."""
  1384. pids = _profile_bound_backend_pids(canon, profile_dir)
  1385. if not pids:
  1386. return
  1387. try:
  1388. from gateway.status import terminate_pid
  1389. except Exception:
  1390. return
  1391. for pid in pids:
  1392. try:
  1393. terminate_pid(pid) # graceful first
  1394. except (ProcessLookupError, PermissionError, OSError):
  1395. continue
  1396. _wait_then_force_kill(pids, {})
  1397. print(f"✓ Stopped {len(pids)} profile backend process(es)")
  1398. def _stop_bot_desktop(profile_dir: Path) -> None:
  1399. """Stop the profile's Bot Desktop (Xvnc + Xfce launcher) before its directory is removed or renamed;
  1400. gateway shutdown does not reach it (its own session, its own pid file). Scoped through the hermes-home
  1401. override so the runtime reads THIS profile's bot-desktop/ state, whichever profile invoked the op.
  1402. A failure here is logged, never fatal: the profile op is what the user asked for."""
  1403. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  1404. from tools.bot_desktop import runtime
  1405. if not runtime.is_supported_host():
  1406. return
  1407. token = set_hermes_home_override(profile_dir)
  1408. try:
  1409. if runtime.stop():
  1410. print("✓ Bot Desktop stopped")
  1411. # The screen a human's exclusion protected is gone; on rename the directory (lease.json
  1412. # included) moves with the profile, and a human lease for a dead viewer would fence the
  1413. # agent out of the renamed profile's next screen until someone force-released it.
  1414. from tools.bot_desktop import lease
  1415. lease.release()
  1416. except Exception as e:
  1417. logger.warning("Could not stop the Bot Desktop of %s: %s", profile_dir, e)
  1418. finally:
  1419. reset_hermes_home_override(token)
  1420. def _print_delete_summary(canon: str, profile_dir: Path, gw_running: bool, wrapper_path: Optional[Path]) -> None:
  1421. """Show what ``delete_profile`` is about to remove."""
  1422. model, provider = _read_config_model(profile_dir)
  1423. skill_count = _count_skills(profile_dir)
  1424. dist_name, dist_version, dist_source = _read_distribution_meta(profile_dir)
  1425. print(f"\nProfile: {canon}")
  1426. print(f"Path: {profile_dir}")
  1427. if model:
  1428. print(f"Model: {model}" + (f" ({provider})" if provider else ""))
  1429. if skill_count:
  1430. print(f"Skills: {skill_count}")
  1431. if dist_name:
  1432. print(f"Distribution: {dist_name}@{dist_version or '?'}")
  1433. if dist_source:
  1434. print(f"Installed from: {dist_source}")
  1435. print("\nThis will permanently delete:")
  1436. print(" • All config, API keys, memories, sessions, skills, cron jobs")
  1437. if wrapper_path is not None:
  1438. print(f" • Command alias ({wrapper_path})")
  1439. if gw_running:
  1440. print(" ⚠ Gateway is running — it will be stopped.")
  1441. class ProfileIdentitySettlementPending(RuntimeError):
  1442. """The profile's directory was deleted, but its durable session/routing identity was not
  1443. settled (``hermes_cli.profile_identity.purge_profile_identity`` returned False).
  1444. Subclasses ``RuntimeError`` so delete-failure handling that treats the error as fatal (the
  1445. CLI's ``hermes profile delete``) keeps working unchanged; surfaces that can report a partial
  1446. success (the dashboard's ``DELETE /api/profiles/{name}``) catch this type — it carries the
  1447. profile, its now-removed path, and the retry command — instead of matching on the message.
  1448. """
  1449. def __init__(self, profile: str, path: Path):
  1450. self.profile = profile
  1451. self.path = path
  1452. self.retry_command = f"hermes profile purge-identity {profile}"
  1453. super().__init__(
  1454. f"Profile '{profile}' was deleted, but its session/routing identity settlement is "
  1455. f"still pending — run: {self.retry_command}")
  1456. def delete_profile(name: str, yes: bool = False) -> Path:
  1457. """Delete a profile, its wrapper script, and its gateway service (service disabled first
  1458. to prevent auto-restart, gateway stopped if running)."""
  1459. canon = normalize_profile_name(name)
  1460. if canon == "default":
  1461. raise ValueError("Cannot delete the default profile (~/.hermes).\nTo remove everything, use: hermes uninstall")
  1462. canon, profile_dir = _existing_profile_dir(canon)
  1463. gw_running = _check_gateway_running(profile_dir)
  1464. wrapper_path = _find_our_wrapper(canon)
  1465. _print_delete_summary(canon, profile_dir, gw_running, wrapper_path)
  1466. if not yes:
  1467. print()
  1468. try:
  1469. confirm = input(f"Type '{canon}' to confirm: ").strip()
  1470. except (KeyboardInterrupt, EOFError):
  1471. confirm = None
  1472. print()
  1473. if confirm != canon:
  1474. print("Cancelled.")
  1475. return profile_dir
  1476. # 1. Disable service (prevents auto-restart); drop the s6 slot on container (host no-op).
  1477. _cleanup_gateway_service(canon, profile_dir)
  1478. _maybe_unregister_gateway_service(canon)
  1479. # 2. Stop the gateway, then other backends bound to this profile (Desktop-spawned
  1480. # serve/dashboard the pid file never names): they hold the SQLite connection open and
  1481. # keep writing, which made rmtree fail ENOTEMPTY and resurrected the deleted tree.
  1482. if gw_running:
  1483. _stop_gateway_process(profile_dir)
  1484. _stop_profile_backends(canon, profile_dir)
  1485. _stop_bot_desktop(profile_dir)
  1486. # Tombstone before rmtree so a stale serve/logging mkdir cannot relist this name live.
  1487. mark_named_profile_deleted(profile_dir)
  1488. # The multiplexer sees the tombstone, stops this profile's adapters and releases its handles
  1489. # into the directory before we remove it. Identity settlement is a separate delete-only
  1490. # operation below: an ordinary unserve must preserve identity, because a rename's old name
  1491. # leaves the served set exactly like a deleted one does (#111926, delete side).
  1492. _notify_multiplexer(canon)
  1493. identity_settled = _purge_identity(canon)
  1494. # The main serve process survives this deletion. Stop only this profile's MCP
  1495. # transports and release cached stderr handles, including completed probes.
  1496. from hermes_constants import hermes_home_key
  1497. from tools.mcp_tool_lifecycle import shutdown_mcp_servers
  1498. shutdown_mcp_servers(scope=hermes_home_key(profile_dir))
  1499. # Release this process's holographic memory-store connections into the profile. The
  1500. # Desktop's main serve process opens memory_store.db for every profile and is
  1501. # deliberately not stopped above; on Windows its handles fail rmtree with WinError 32.
  1502. # Inside serve (DELETE /api/profiles/<name>) the handles live here; from the CLI no-op.
  1503. with contextlib.suppress(Exception): # best-effort: never block the delete on the release path
  1504. # 2c. See #88347.
  1505. from plugins.memory import import_provider_module
  1506. _released = import_provider_module("holographic", "store").MemoryStore.release_all_under(profile_dir)
  1507. if _released:
  1508. print(f"✓ Released {_released} memory-store connection(s) held by this process")
  1509. with contextlib.suppress(Exception):
  1510. from hermes_state_registry import close_all_under as _close_session_dbs_under
  1511. _closed = _close_session_dbs_under(profile_dir)
  1512. if _closed:
  1513. print(f"✓ Released {_closed} session database connection(s) held by this process")
  1514. # The Desktop serve process routes its agent/errors logs for every profile through one
  1515. # QueueListener. On Windows those ConcurrentRotatingFileHandler instances retain their
  1516. # ``.__*.lock`` files until explicitly closed, so rmtree otherwise fails with WinError 32.
  1517. with contextlib.suppress(Exception):
  1518. from hermes_logging import release_profile_log_handlers
  1519. _released_logs = release_profile_log_handlers(profile_dir)
  1520. if _released_logs:
  1521. print(f"✓ Released {_released_logs} profile log handler(s) held by this process")
  1522. # 3. Remove wrapper script
  1523. if wrapper_path and remove_wrapper_script(canon):
  1524. print(f"✓ Removed {wrapper_path}")
  1525. # 4. Remove profile directory
  1526. remove_error: Exception | None = None
  1527. try:
  1528. # A multiplexer still tearing the profile down holds its gateway.lock: never remove a home
  1529. # a live runtime owns (its writers would recreate the tree under the tombstone).
  1530. if not wait_profile_unowned(profile_dir):
  1531. raise RuntimeError("a running gateway still owns this profile; retry the delete once it settles")
  1532. _rmtree_with_retry(profile_dir, _rmtree_make_writable)
  1533. print(f"✓ Removed {profile_dir}")
  1534. except Exception as e:
  1535. print(f"⚠ Could not remove {profile_dir}: {e}")
  1536. remove_error = e
  1537. # 5. Clear active_profile if it pointed to this profile
  1538. _retarget_active_profile(canon, "default", "✓ Active profile reset to default")
  1539. if remove_error is not None:
  1540. raise RuntimeError(f"Could not remove profile directory {profile_dir}: {remove_error}") from remove_error
  1541. print(f"\nProfile '{canon}' deleted.")
  1542. if not identity_settled:
  1543. # Filesystem work and runtime teardown are done; the durable identity is not. Report the
  1544. # partial settlement as a typed failure (still a RuntimeError for the CLI's handler)
  1545. # instead of a clean success; the type carries the path and the retry for surfaces that
  1546. # can report a partial success.
  1547. raise ProfileIdentitySettlementPending(canon, profile_dir)
  1548. return profile_dir
  1549. def _s6_runtime_manager():
  1550. """The s6 service manager inside the container, else None. Silent on host: a failing/
  1551. absent detector must never print a confusing s6 warning to non-container users."""
  1552. try:
  1553. from hermes_cli.service_manager import detect_service_manager, get_service_manager
  1554. if detect_service_manager() != "s6":
  1555. return None
  1556. mgr = get_service_manager()
  1557. except Exception:
  1558. return None
  1559. return mgr if mgr.supports_runtime_registration() else None
  1560. def _maybe_register_gateway_service(profile_name: str) -> None:
  1561. """Register a profile's gateway with s6 inside the container. Best-effort: profile
  1562. creation must not fail over a supervision-tree hiccup; `gateway start` re-registers.
  1563. Port selection: each supervised profile gateway loads its own ``HERMES_HOME`` and binds the port
  1564. resolved by ``gateway/config.py`` from that profile's environment — ``API_SERVER_PORT`` (or
  1565. ``platforms.api_server.extra.port`` in the profile's ``config.yaml``), defaulting to 8642. There is no
  1566. ``[gateway] port`` key and no Python-side allocator (PR #30136 review item I5 retired the
  1567. SHA-256-derived range [9200, 9800) as dead code), so two profiles that both leave the port at its
  1568. default will both try to bind 8642 — give each profile a distinct ``API_SERVER_PORT`` in its ``.env``.
  1569. """
  1570. mgr = _s6_runtime_manager()
  1571. if mgr is None:
  1572. return
  1573. try:
  1574. mgr.register_profile_gateway(profile_name, start_now=False)
  1575. except ValueError:
  1576. pass # already registered (e.g. the container-boot reconciler brought up a stale slot)
  1577. except Exception as exc:
  1578. print(f"⚠ Could not register s6 gateway service: {exc}")
  1579. def _maybe_unregister_gateway_service(profile_name: str) -> None:
  1580. """Tear down a profile's s6 gateway service inside the container; host no-op, idempotent."""
  1581. mgr = _s6_runtime_manager()
  1582. if mgr is None:
  1583. return
  1584. try:
  1585. mgr.unregister_profile_gateway(profile_name)
  1586. except Exception as exc:
  1587. print(f"⚠ Could not unregister s6 gateway service: {exc}")
  1588. def _cleanup_gateway_service(name: str, profile_dir: Path) -> bool:
  1589. """Disable and remove systemd/launchd service for a profile; True when a unit was removed."""
  1590. import platform as _platform
  1591. # The service name follows get_hermes_home(): bind the override (the seam a multiplexed
  1592. # dashboard/tui-gateway process reads) and mirror the env for identity-file readers, so a
  1593. # DELETE from a multi-profile dashboard names THIS profile's unit, never the host's bare one.
  1594. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  1595. old_home = os.environ.get("HERMES_HOME")
  1596. home_token = set_hermes_home_override(str(profile_dir))
  1597. try:
  1598. os.environ["HERMES_HOME"] = str(profile_dir)
  1599. from hermes_cli.gateway import get_service_name, get_launchd_plist_path, user_systemd_unit_dir
  1600. def _run(*cmd: str) -> None:
  1601. subprocess.run(list(cmd), capture_output=True, check=False, timeout=10)
  1602. from hermes_cli.profiles_service_cleanup import owned_by_profile, remove_system_systemd_unit, remove_windows_task
  1603. system = _platform.system()
  1604. removed = False
  1605. if system == "Linux":
  1606. svc_name = get_service_name()
  1607. svc_file = user_systemd_unit_dir() / f"{svc_name}.service"
  1608. if svc_file.exists() and owned_by_profile(svc_file, profile_dir):
  1609. _run("systemctl", "--user", "disable", svc_name)
  1610. _run("systemctl", "--user", "stop", svc_name)
  1611. svc_file.unlink(missing_ok=True)
  1612. _run("systemctl", "--user", "daemon-reload")
  1613. print(f"✓ Service {svc_name} removed")
  1614. removed = True
  1615. # `gateway install --system` writes the same name under /etc; a survivor there
  1616. # restarts the removed profile at boot exactly like the user unit at login.
  1617. removed = remove_system_systemd_unit(profile_dir) or removed
  1618. elif system == "Darwin":
  1619. plist_path = get_launchd_plist_path()
  1620. if plist_path.exists() and owned_by_profile(plist_path, profile_dir):
  1621. _run("launchctl", "unload", str(plist_path))
  1622. plist_path.unlink(missing_ok=True)
  1623. print("✓ Launchd service removed")
  1624. removed = True
  1625. elif system == "Windows":
  1626. removed = remove_windows_task()
  1627. return removed
  1628. except Exception as e:
  1629. print(f"⚠ Service cleanup: {e}")
  1630. finally:
  1631. reset_hermes_home_override(home_token)
  1632. os.environ.pop("HERMES_HOME", None)
  1633. if old_home is not None:
  1634. os.environ["HERMES_HOME"] = old_home
  1635. return False
  1636. def _stop_gateway_process(profile_dir: Path) -> None:
  1637. """Stop a running gateway process via its PID file."""
  1638. pid_file = profile_dir / "gateway.pid"
  1639. if not pid_file.exists():
  1640. return
  1641. try:
  1642. raw = pid_file.read_text(encoding="utf-8-sig").strip()
  1643. data = json.loads(raw) if raw.startswith("{") else {"pid": int(raw)}
  1644. pid = int(data["pid"])
  1645. # Cross-profile kill refusal: the record's hermes_home stamp names the gateway's TRUE
  1646. # owner. A poisoned gateway.pid in this dir can point at another profile's live
  1647. # gateway — killing it starts a mutual SIGTERM restart loop.
  1648. from gateway.status import get_process_start_time, recorded_gateway_home_conflicts, terminate_pid
  1649. if recorded_gateway_home_conflicts(data, expected_home=profile_dir):
  1650. print(
  1651. f"✗ Refusing to stop PID {pid}: its recorded HERMES_HOME "
  1652. f"belongs to a different profile than {profile_dir} "
  1653. "(stale/poisoned PID record, #89315)."
  1654. )
  1655. return
  1656. # terminate_pid picks the Windows primitive (taskkill /T cascades to children; raw
  1657. # os.kill with SIGKILL fails at import on Windows).
  1658. expected_start_time = data.get("start_time")
  1659. if expected_start_time is None:
  1660. expected_start_time = get_process_start_time(pid)
  1661. terminate_pid(pid) # graceful first
  1662. if _wait_then_force_kill([pid], {pid: expected_start_time}):
  1663. print(f"✓ Gateway stopped (PID {pid})")
  1664. else:
  1665. print(f"✓ Gateway force-stopped (PID {pid})")
  1666. except (ProcessLookupError, PermissionError):
  1667. print("✓ Gateway already stopped")
  1668. except Exception as e:
  1669. print(f"⚠ Could not stop gateway: {e}")
  1670. # Active profile (sticky default)
  1671. def get_active_profile(root: Path | None = None) -> str:
  1672. """Read the sticky active profile name (of *root*, default: this process's Hermes root)."""
  1673. path = root / "active_profile" if root is not None else _get_active_profile_path()
  1674. try:
  1675. name = path.read_text(encoding="utf-8-sig").strip()
  1676. if not name:
  1677. return "default"
  1678. return name
  1679. except (FileNotFoundError, UnicodeDecodeError, OSError):
  1680. return "default"
  1681. def set_active_profile(name: str) -> None:
  1682. """Set the sticky active profile (``default`` = remove the file)."""
  1683. canon = _canon_valid(name)
  1684. if canon != "default" and not profile_exists(canon):
  1685. raise _missing_profile_error(canon)
  1686. path = _get_active_profile_path()
  1687. path.parent.mkdir(parents=True, exist_ok=True)
  1688. if canon == "default":
  1689. path.unlink(missing_ok=True)
  1690. else:
  1691. tmp = path.with_suffix(".tmp") # atomic write
  1692. tmp.write_text(canon + "\n", encoding="utf-8")
  1693. tmp.replace(path)
  1694. def _retarget_active_profile(old: str, new: str, message: str) -> None:
  1695. """If the sticky active profile is *old*, point it at *new* and print *message*. Never raises."""
  1696. with contextlib.suppress(Exception):
  1697. if get_active_profile() == old:
  1698. set_active_profile(new)
  1699. print(message)
  1700. def get_active_profile_name() -> str:
  1701. """Profile name inferred from HERMES_HOME: ``"default"`` when unset or ``~/.hermes``, the
  1702. name under ``~/.hermes/profiles/<name>``, ``"custom"`` for any other path."""
  1703. from hermes_constants import get_hermes_home
  1704. resolved = get_hermes_home().resolve()
  1705. if resolved == _get_default_hermes_home().resolve():
  1706. return "default"
  1707. profiles_root = _get_profiles_root().resolve()
  1708. try:
  1709. parts = resolved.relative_to(profiles_root).parts
  1710. if len(parts) == 1 and _PROFILE_ID_RE.match(parts[0]):
  1711. return parts[0]
  1712. except ValueError:
  1713. pass
  1714. return "custom"
  1715. def current_profile_name(default: str | None = None) -> str | None:
  1716. """Identity of the profile the current task runs FOR: the ``HERMES_HOME`` override when one is
  1717. bound (a multiplexed cron tick, a routed gateway turn), else a launcher-pinned
  1718. ``HERMES_PROFILE_NAME``/``HERMES_PROFILE`` (the kanban dispatcher pins it on its workers), else
  1719. the name derived from the process's ``HERMES_HOME``; *default* when nothing names a profile.
  1720. The env pin is read only outside an override: ``os.environ`` is the LAUNCH profile's, so under
  1721. an override it would re-label a served profile's board writes with the host's identity.
  1722. """
  1723. from hermes_constants import get_hermes_home_override
  1724. if get_hermes_home_override() is None:
  1725. for env_name in ("HERMES_PROFILE_NAME", "HERMES_PROFILE"):
  1726. value = (os.environ.get(env_name) or "").strip()
  1727. if value:
  1728. return value
  1729. try:
  1730. return get_active_profile_name() or default
  1731. except Exception:
  1732. return default
  1733. # Export / Import
  1734. def _inside_git_checkout(path: Path) -> bool:
  1735. """True when *path* lies inside a Git checkout. Walks the path's OWN resolved ancestry
  1736. (not cwd) so the check holds when HERMES_HOME sits in a checkout but the process runs
  1737. elsewhere (cron, service manager). Resolution failure reports True (fail closed)."""
  1738. try:
  1739. resolved = path.resolve()
  1740. except (OSError, RuntimeError): # RuntimeError: symlink loops on Python <= 3.12
  1741. return True
  1742. return any((candidate / ".git").exists() for candidate in (resolved, *resolved.parents))
  1743. def _profile_export_directory() -> Path:
  1744. """Choose an export directory that cannot become source-tree input."""
  1745. import tempfile
  1746. export_dir = _get_default_hermes_home() / "profile-exports"
  1747. if not _inside_git_checkout(export_dir):
  1748. return export_dir
  1749. # A custom deployment may point HERMES_HOME at its source checkout: use a sibling store,
  1750. # falling back to the OS temp dir only when the user's home itself is a checkout (dotfiles
  1751. # repo). Per-uid temp name: a fixed /tmp/hermes-profile-exports is a predictable shared
  1752. # path another local user could pre-create (or symlink) first.
  1753. uid_suffix = f"-{os.getuid()}" if hasattr(os, "getuid") else ""
  1754. candidates = (
  1755. Path.home() / ".hermes-profile-exports", Path(tempfile.gettempdir()) / f"hermes-profile-exports{uid_suffix}"
  1756. )
  1757. for candidate in candidates:
  1758. if not _inside_git_checkout(candidate):
  1759. return candidate
  1760. # Fail closed: writing a secret-bearing archive into a source tree is the incident this
  1761. # helper prevents; a stderr warning would not stop a scripted export.
  1762. raise ValueError(
  1763. # See #92457.
  1764. "No safe automatic export destination: every candidate directory is "
  1765. "inside a Git checkout. Provide an explicit output path outside the "
  1766. "checkout (CLI: -o /path/outside/repo/profile.tar.gz)."
  1767. )
  1768. def get_profile_export_path(name: str, *, timestamp: Optional[str] = None) -> Path:
  1769. """Managed destination for an export with no explicit output — outside the cwd and every
  1770. profile, since a ``<name>.tar.gz`` default in a source checkout got committed by accident."""
  1771. canon = _canon_valid(name)
  1772. export_dir = _profile_export_directory()
  1773. export_dir.mkdir(parents=True, exist_ok=True)
  1774. # exist_ok=True silently accepts a directory (or symlink) another local user pre-created
  1775. # at a predictable path; refuse to write a secret-bearing archive anywhere we don't own.
  1776. if export_dir.is_symlink():
  1777. raise ValueError(
  1778. f"Export directory {export_dir} is a symlink; refusing to write "
  1779. "a profile archive through it. Provide an explicit output path."
  1780. )
  1781. if hasattr(os, "getuid") and export_dir.stat().st_uid != os.getuid():
  1782. raise ValueError(
  1783. f"Export directory {export_dir} is owned by another user; "
  1784. "refusing to write a profile archive there. Provide an explicit output path."
  1785. )
  1786. stamp = timestamp or time.strftime("%Y%m%d-%H%M%S")
  1787. return export_dir / f"{canon}-{stamp}.tar.gz"
  1788. def _default_export_ignore(root_dir: Path):
  1789. """copytree ignore for the default-profile export: root-level allow-list
  1790. (``_DEFAULT_EXPORT_INCLUDE_ROOT``) plus universal exclusions. Surviving text files are
  1791. then force-redacted by :func:`_scrub_export_secrets`.
  1792. * **Root-level allow-list** — only entries whose name appears in ``_DEFAULT_EXPORT_INCLUDE_ROOT``
  1793. survive. Everything else (such as an unrelated ``x11-dev/`` directory in a Docker deployment where
  1794. HERMES_HOME equals the cwd) is excluded. Blacklisting was tried first and proved unable to anticipate
  1795. every non-Hermes file the user may have lying alongside HERMES_HOME (#58394). * **Universal exclusions
  1796. at any depth** — ``__pycache__``, sockets and other special files, temp files
  1797. (:func:`_non_exportable_entries`); plus npm lockfiles, which may appear at the root.
  1798. """
  1799. def _ignore(directory: str, contents: list) -> set:
  1800. # Universal exclusions and credential names (any depth) plus npm lockfiles that can appear at root.
  1801. ignored = _non_exportable_entries(directory, contents)
  1802. ignored.update({"package.json", "package-lock.json"} & set(contents))
  1803. ignored.update(_export_credential_entries(directory, contents))
  1804. if Path(directory) == root_dir:
  1805. ignored.update(entry for entry in contents if entry not in _DEFAULT_EXPORT_INCLUDE_ROOT)
  1806. return ignored
  1807. return _ignore
  1808. # Credential names dropped at ANY depth of every profile export, on top of the root-relative
  1809. # PROFILE_CREDENTIAL_PATHS. ``bot-desktop`` is the screen's runtime state:
  1810. # its persistent Chromium profile (Cookies, Login Data — the bot's live web sessions), Xauthority, sockets.
  1811. # The OS stores are dropped wherever they sit (a skill dir copied from a home carries its ``.ssh``).
  1812. _EXPORT_CREDENTIAL_FILES = frozenset({"auth.json", ".env", "bot-desktop", *_OS_CREDENTIAL_STORES})
  1813. _EXPORT_CREDENTIAL_PARTS = tuple(tuple(p.split("/")) for p in _EXPORT_CREDENTIAL_FILES)
  1814. def _export_credential_entries(directory: str, contents: list) -> set:
  1815. """Entries of *directory* that are an _EXPORT_CREDENTIAL_FILES store: matched on trailing path
  1816. components, so ``.config/gh`` drops at any depth while the rest of ``.config`` ships."""
  1817. parts = Path(directory).parts
  1818. return {entry for entry in contents for store in _EXPORT_CREDENTIAL_PARTS
  1819. if entry == store[-1] and parts[len(parts) + 1 - len(store):] == store[:-1]}
  1820. # Text/config suffixes secret-scrubbed on export; binary DBs, images etc. are left alone.
  1821. _EXPORT_REDACT_SUFFIXES = frozenset({
  1822. ".md", ".txt", ".yaml", ".yml", ".json", ".jsonl", ".toml", ".ini", ".cfg", ".conf", ".py", ".sh",
  1823. ".bash", ".zsh", ".js", ".ts", ".tsx", ".jsx", ".css", ".html", ".xml", ".csv",
  1824. })
  1825. # ``Path(".cursorrules").suffix`` is "" — name-match; ``*.env.example`` uses endswith; a hand-named
  1826. # config copy (``config.yaml.bak-my-note``) holds config.yaml's secrets under a suffix of its own.
  1827. _EXPORT_REDACT_NAMES = frozenset({".cursorrules"})
  1828. def _should_redact_export_file(path: Path) -> bool:
  1829. name = path.name
  1830. return (
  1831. name in _EXPORT_REDACT_NAMES
  1832. or name.lower().endswith(".env.example")
  1833. or name.lower().startswith("config.yaml.")
  1834. or path.suffix.lower() in _EXPORT_REDACT_SUFFIXES
  1835. )
  1836. def _scrub_export_secrets(staged: Path) -> None:
  1837. """Force-redact secret-shaped strings in a staged export tree (same pass as ``hermes
  1838. sessions export --redact``). Runs on the staged copy only; symlinks to text files are
  1839. materialized when content changes so redaction never follows a link back into the source."""
  1840. from agent.redact import redact_sensitive_text
  1841. for path in staged.rglob("*"):
  1842. try:
  1843. is_link = path.is_symlink()
  1844. if not path.is_file(): # broken links, symlinked dirs, non-files
  1845. continue
  1846. except OSError:
  1847. continue
  1848. if not _should_redact_export_file(path):
  1849. continue
  1850. try:
  1851. text = path.read_text(encoding="utf-8-sig")
  1852. except (UnicodeDecodeError, OSError):
  1853. continue
  1854. redacted = redact_sensitive_text(text, force=True)
  1855. if redacted == text:
  1856. continue
  1857. if is_link:
  1858. path.unlink()
  1859. path.write_text(redacted, encoding="utf-8")
  1860. def export_profile(name: str, output_path: str, extra_files: Optional[dict[str, str]] = None) -> Path:
  1861. """Export a profile to a tar.gz archive; credential files are excluded and staged text is
  1862. force-redacted first. Returns the output file path."""
  1863. import tempfile
  1864. canon, profile_dir = _existing_profile_dir(name)
  1865. # Archive base name without extension (.tar.gz appended by the writer).
  1866. base = str(Path(output_path)).removesuffix(".tar.gz").removesuffix(".tgz")
  1867. # The default profile IS ~/.hermes (dir name ".hermes"), so both paths stage a filtered
  1868. # copy under a temp dir named after the canonical id: root allow-list for default,
  1869. # credential exclusion for named profiles.
  1870. def _ignore_credentials(directory: str, contents: list) -> set:
  1871. ignored = _non_exportable_entries(directory, contents)
  1872. ignored.update(_export_credential_entries(directory, contents))
  1873. rel = Path(directory).relative_to(profile_dir).parts
  1874. ignored.update(e for e in contents if profile_path_is_private((*rel, e)))
  1875. if Path(directory) == profile_dir:
  1876. ignored |= PM_RUNTIME_ROOT_DIRS & set(contents)
  1877. return ignored
  1878. ignore = _default_export_ignore(profile_dir) if canon == "default" else _ignore_credentials
  1879. with tempfile.TemporaryDirectory() as tmpdir:
  1880. staged = Path(tmpdir) / canon
  1881. shutil.copytree(profile_dir, staged, symlinks=True, ignore=ignore)
  1882. for rel, content in (extra_files or {}).items():
  1883. target = staged.joinpath(*normalize_archive_parts(rel))
  1884. target.parent.mkdir(parents=True, exist_ok=True)
  1885. target.write_text(content, encoding="utf-8")
  1886. _scrub_export_secrets(staged)
  1887. return Path(make_targz(base, tmpdir, canon))
  1888. def import_profile(archive_path: str, name: Optional[str] = None) -> Path:
  1889. """Import a profile from a tar.gz archive."""
  1890. import tempfile
  1891. archive = Path(archive_path)
  1892. if not archive.exists():
  1893. raise FileNotFoundError(f"Archive not found: {archive}")
  1894. top_dirs = archive_root_dirs(archive)
  1895. archive_root = top_dirs.pop() if len(top_dirs) == 1 else None
  1896. inferred_name = name or archive_root
  1897. if not inferred_name:
  1898. raise ValueError(
  1899. "Cannot determine profile name from archive. "
  1900. "Specify it explicitly: hermes profile import <archive> --name <name>"
  1901. )
  1902. if archive_root is None:
  1903. raise ValueError("Profile archive must contain exactly one top-level directory.")
  1904. # Default-profile archives have "default/" at top level; importing as "default" would
  1905. # target ~/.hermes itself.
  1906. canon = _canon_valid(inferred_name)
  1907. if canon == "default":
  1908. raise ValueError(
  1909. "Cannot import as 'default' — that is the built-in root profile (~/.hermes). "
  1910. "Specify a different name: hermes profile import <archive> --name <name>"
  1911. )
  1912. profile_dir = get_profile_dir(canon)
  1913. if profile_dir.exists():
  1914. raise _profile_exists_error(canon)
  1915. _get_profiles_root().mkdir(parents=True, exist_ok=True)
  1916. with tempfile.TemporaryDirectory(prefix="hermes_profile_import_") as tmpdir:
  1917. staging_root = Path(tmpdir)
  1918. safe_extract_targz(archive, staging_root)
  1919. extracted = staging_root / archive_root
  1920. if not extracted.is_dir():
  1921. raise ValueError(f"Profile archive root is missing or invalid: {archive_root}")
  1922. final_source = extracted
  1923. if archive_root != canon:
  1924. final_source = staging_root / canon
  1925. extracted.rename(final_source)
  1926. # Remove foreign runtime state before publishing, including file-shaped roots.
  1927. # A failed removal must abort import rather than install a stale PM selection.
  1928. for child in final_source.iterdir():
  1929. if child.name in PM_RUNTIME_ROOT_DIRS:
  1930. if child.is_dir():
  1931. shutil.rmtree(child)
  1932. else:
  1933. child.unlink()
  1934. shutil.move(str(final_source), str(profile_dir))
  1935. return profile_dir
  1936. # Rename
  1937. def _refuse_rename_without_file_tooling(old_canon: str) -> None:
  1938. """A remote config backend keys each profile's settings by its canonical name, and the plane
  1939. has no rename: renaming the local home would leave the settings under the old name and read
  1940. another (possibly populated) level under the new one. Refused before any side effect."""
  1941. backend = _config_backend.get_config_backend()
  1942. if not backend.supports_file_tooling():
  1943. raise ValueError(
  1944. f"Cannot rename profile '{old_canon}': its config lives in the {backend.name!r} config "
  1945. "backend under that name, and renaming it there is not supported. Nothing was changed.")
  1946. def rename_profile(old_name: str, new_name: str) -> Path:
  1947. """Rename a profile: directory, wrapper script, service, active_profile. The default
  1948. profile's home IS the installation root, so "renaming" it sets a presentation-only
  1949. ``display_name`` instead — the canonical id stays ``default``."""
  1950. old_canon = _canon_valid(old_name)
  1951. if old_canon == "default":
  1952. if not (new_name or "").strip():
  1953. raise ValueError("Display name cannot be empty.")
  1954. cleaned = set_profile_display_name("default", new_name)
  1955. print(f"✓ Display name set: {cleaned} (canonical id remains 'default')")
  1956. return _get_default_hermes_home()
  1957. new_canon = _canon_valid(new_name)
  1958. if new_canon == "default":
  1959. raise ValueError("Cannot rename to 'default' — it is reserved.")
  1960. _refuse_rename_without_file_tooling(old_canon)
  1961. old_dir = get_profile_dir(old_canon)
  1962. new_dir = get_profile_dir(new_canon)
  1963. if not old_dir.is_dir():
  1964. raise _unknown_profile_error(old_canon)
  1965. if new_dir.exists():
  1966. raise _profile_exists_error(new_canon)
  1967. # 1. Remove the old name's service even when its gateway is stopped: the unit is named after
  1968. # the old profile and runs ``--profile <old>``, so the service manager would crash-loop it on
  1969. # the next login or container boot. Then stop the gateway and the screen whose launcher
  1970. # holds paths under the old name.
  1971. gw_running = _check_gateway_running(old_dir)
  1972. service_removed = _cleanup_gateway_service(old_canon, old_dir)
  1973. _maybe_unregister_gateway_service(old_canon)
  1974. if gw_running:
  1975. _stop_gateway_process(old_dir)
  1976. _stop_bot_desktop(old_dir)
  1977. # 1b. Unroute the old name from a live multiplexer BEFORE the rename (same protocol as
  1978. # delete_profile). A multiplexed secondary has no gateway.pid of its own, so the check above
  1979. # reports it stopped while the default gateway still holds its adapters, cron ticker, logging
  1980. # and SQLite handles; those re-``mkdir`` the old home the moment it moves (no tombstone →
  1981. # ``mkdir_under_hermes_home`` does not refuse it) and the periodic reconcile re-adopts the
  1982. # resurrected dir as a ghost served profile (#109267).
  1983. live_mux = _live_default_multiplexer()
  1984. if live_mux:
  1985. mark_named_profile_deleted(old_dir)
  1986. _notify_multiplexer(old_canon)
  1987. # 1c. Release this process's cached MCP stderr handle into the old home (same as
  1988. # delete_profile): Windows refuses to rename a directory holding an open file, and the
  1989. # handle would otherwise stay cached under the old key after the move.
  1990. from hermes_constants import hermes_home_key
  1991. from tools.mcp_tool_lifecycle import shutdown_mcp_servers
  1992. shutdown_mcp_servers(scope=hermes_home_key(old_dir))
  1993. # 2. Rename directory. If the move fails (cross-device EXDEV, permissions, a racing writer),
  1994. # undo the unroute so the profile is never stranded tombstoned-but-present.
  1995. try:
  1996. if live_mux and not wait_profile_unowned(old_dir): # same owner wait as delete_profile
  1997. raise RuntimeError("a running gateway still owns this profile; retry the rename once it settles")
  1998. old_dir.rename(new_dir)
  1999. except Exception:
  2000. if live_mux:
  2001. clear_named_profile_deleted(old_dir)
  2002. _notify_multiplexer(old_canon)
  2003. _maybe_register_gateway_service(old_canon)
  2004. if service_removed:
  2005. print(f"⚠ The gateway service was removed. Reinstall it with: hermes -p {old_canon} gateway install")
  2006. raise
  2007. print(f"✓ Renamed {old_dir.name} → {new_dir.name}")
  2008. # The tombstone lives at profiles/.deleted/<old_name>; old_dir is gone so nothing can
  2009. # resurrect it, and a future profile reusing the old name must not read as deleted.
  2010. if live_mux:
  2011. clear_named_profile_deleted(old_dir)
  2012. # 2b. Record the rename so Bot Mode group chats can re-link persisted
  2013. # member descriptors to the new slug (#110200). Best-effort: a metadata
  2014. # write failure must never fail the rename itself.
  2015. from hermes_cli.profile_identity import _record_profile_rename
  2016. _record_profile_rename(new_dir, old_canon)
  2017. # 3. Update profile-scoped Honcho host blocks, preserving aiPeer identity
  2018. from hermes_cli.profiles_honcho import migrate_honcho_profile_host
  2019. migrate_honcho_profile_host(old_canon, new_canon, new_dir)
  2020. # 3b. Let the profile's memory provider re-key what it stores under the old name.
  2021. from hermes_cli.profile_memory_config import notify_memory_provider
  2022. notify_memory_provider(new_dir, lambda p: p.on_profile_renamed(old_canon, new_canon, str(new_dir)))
  2023. # 4. Update wrapper script
  2024. remove_wrapper_script(old_canon)
  2025. collision = check_alias_collision(new_canon)
  2026. if not collision:
  2027. create_wrapper_script(new_canon)
  2028. print(f"✓ Alias updated: {new_canon}")
  2029. else:
  2030. print(f"⚠ Cannot create alias '{new_canon}' — {collision}")
  2031. # 5. Update active_profile if it pointed to old name
  2032. _retarget_active_profile(old_canon, new_canon, f"✓ Active profile updated: {new_canon}")
  2033. # 6. Migrate profile-name-keyed session/routing state (session keys, profile_name, heartbeats,
  2034. # delivery + routing index) from the old name to the new one. A stale ``agent:<old>:*`` routing
  2035. # key otherwise resolves to a profile that no longer exists on every inbound event.
  2036. from hermes_cli.profile_identity import _migrate_profile_identity
  2037. _migrate_profile_identity(old_canon, new_canon, live_mux)
  2038. # 7. Hot-serve the renamed profile now (mirrors create; a missed signal only delays it).
  2039. if live_mux:
  2040. _notify_multiplexer(new_canon)
  2041. _maybe_register_gateway_service(new_canon)
  2042. if service_removed:
  2043. print(f"⚠ The gateway service was removed. Reinstall it with: hermes -p {new_canon} gateway install")
  2044. return new_dir
  2045. # Profile env resolution (called from _apply_profile_override)
  2046. def profile_root_for_env_home(env_home: str, default_root: Path) -> Path:
  2047. """Hermes root named by an exported ``HERMES_HOME``: the grandparent of a profile-shaped value
  2048. (``<root>/profiles/<name>``, mirrors ``get_default_hermes_root()``), the value itself otherwise,
  2049. *default_root* when unset. Pure: callers pass any process's env, not only ``os.environ``."""
  2050. env_home = env_home.strip()
  2051. if not env_home:
  2052. return default_root
  2053. env_path = Path(env_home)
  2054. return env_path.parent.parent if env_path.parent.name == "profiles" else env_path
  2055. def resolve_profile_env(profile_name: str) -> str:
  2056. """Resolve a profile name to a HERMES_HOME path string. Called early in the CLI entry
  2057. point, before hermes modules are imported, to set HERMES_HOME.
  2058. When HERMES_HOME is already set, the configured spelling IS the launch root (it may be a
  2059. junction/symlink alias of the platform default). Keep that spelling so profile re-home does not destroy
  2060. the launcher's lexical provenance -- the subprocess sanitizer needs it to match Hermes-owned PYTHONPATH
  2061. entries written in the same spelling (#82581 junction follow-up). Physically the paths are identical
  2062. (junction-transparent); only the spelling is preserved.
  2063. """
  2064. canon = _canon_valid(profile_name)
  2065. root = profile_root_for_env_home(os.environ.get("HERMES_HOME", ""), _get_default_hermes_home())
  2066. if canon == "default":
  2067. return str(root)
  2068. profile_dir = root / "profiles" / canon
  2069. if not named_profile_is_live(profile_dir):
  2070. raise _missing_profile_error(canon)
  2071. return str(profile_dir)