profile_channels.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. """Messaging-channel settings a profile clone must NOT inherit.
  2. A ``--clone``d profile that keeps the source's bot tokens, allowlists and platform state makes two
  3. gateways fight over one bot (standalone) or blocks ``hermes gateway migrate --multiplex`` with a
  4. duplicate-credential finding per platform.
  5. The inventory is OWNERSHIP-based and evaluated in the SOURCE profile's plugin scope: every adapter
  6. (built-in ``Platform`` member, a platform that left core — its ``LEFT_CORE`` row, plugin installed or
  7. not — or a plugin registered under the source's ``HERMES_HOME``) owns the env
  8. keys it declares outright (``required_env``, allowlist / allow-all / home-channel names, its
  9. ``env_overrides`` / ``env_enable_credentials``, core's ``config_env._ENV_ENABLE_CREDENTIALS``) plus every key
  10. under its canonical ``<PLATFORM>_`` prefix and its historical alias prefixes. Gateway-wide channel
  11. policy (``GATEWAY_ALLOW_ALL_USERS`` / ``GATEWAY_ALLOWED_USERS``) and relay enrollment identity
  12. (``GATEWAY_RELAY_*``) are channel settings too. A prefix an adapter SHARES with a non-channel
  13. capability (``TWILIO_*`` is also the telephony skill, ``EMAIL_*`` mail-sending scripts, and a plugin
  14. platform's ``shared_env_prefixes`` its own tools) is stripped only when the source actually runs that adapter — the credential is
  15. then the bot's identity; otherwise it is a tool key and survives. Model/provider keys, tool keys,
  16. memory and general config are never touched.
  17. """
  18. from __future__ import annotations
  19. import contextlib
  20. import logging
  21. import re
  22. from functools import partial
  23. from pathlib import Path
  24. from typing import Dict, Iterable, List, Optional, Set, Tuple
  25. logger = logging.getLogger(__name__)
  26. # Historical env prefixes that do not match a platform's config id. They SUPPLEMENT the canonical
  27. # ``<PLATFORM>_`` prefix (``WECOM_DM_POLICY`` and ``SMS_WEBHOOK_PORT`` are wecom / sms keys too).
  28. _PLATFORM_ENV_PREFIX_ALIASES: dict[str, tuple[str, ...]] = {
  29. "email": ("EMAIL_",),
  30. "qqbot": ("QQ_",),
  31. "relay": ("GATEWAY_RELAY_",),
  32. "sms": ("TWILIO_",),
  33. }
  34. # Pseudo-platform for gateway-wide channel policy: not an adapter, but a clone that inherits the
  35. # source's allow-all / allowlist boundary hands a freshly configured bot the source's authorization.
  36. GATEWAY_POLICY_ID = "gateway"
  37. _GATEWAY_POLICY_KEYS = ("GATEWAY_ALLOW_ALL_USERS", "GATEWAY_ALLOWED_USERS")
  38. # Prefixes a messaging adapter shares with a NON-channel capability. Their credentials belong to the
  39. # channel only while the source runs that adapter; the adapter's policy keys are channel-only always.
  40. _SHARED_WITH_TOOLS: dict[str, tuple[str, ...]] = {
  41. "sms": ("TWILIO_",), # telephony skill reads TWILIO_ACCOUNT_SID / TWILIO_AUTH_TOKEN
  42. "email": ("EMAIL_",), # mail-sending skills read EMAIL_ADDRESS / EMAIL_PASSWORD / EMAIL_SMTP_*
  43. }
  44. _POLICY_MARKERS = ("_ALLOWED_USERS", "_ALLOW_ALL_USERS", "_ALLOWED_CHATS", "_HOME_CHANNEL", "_HOME_ADDRESS")
  45. # Multiplexer-owner settings: a clone of the default that inherits them and is then started
  46. # standalone tries to be a second multiplexer for every profile on the host.
  47. _GATEWAY_OWNER_KEYS = ("multiplex_profiles", "profile_routes")
  48. _ENV_LINE_RE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=")
  49. @contextlib.contextmanager
  50. def _plugin_scope(source_dir: Optional[Path]):
  51. """Evaluate adapter discovery in ``source_dir``'s plugin scope (its private ``plugins/``), not the
  52. ambient profile's. ``None`` keeps the ambient scope."""
  53. if source_dir is None:
  54. yield
  55. return
  56. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  57. token = set_hermes_home_override(str(source_dir))
  58. try:
  59. yield
  60. finally:
  61. reset_hermes_home_override(token)
  62. def platform_env_prefixes(platform_id: str) -> tuple[str, ...]:
  63. """Env-var prefixes owned by one messaging platform: canonical ``<PLATFORM>_`` plus aliases."""
  64. canonical = platform_id.upper().replace("-", "_") + "_"
  65. return (canonical, *_PLATFORM_ENV_PREFIX_ALIASES.get(platform_id, ()))
  66. def _registry_entries() -> list:
  67. with contextlib.suppress(Exception):
  68. from hermes_cli.plugins import discover_plugins
  69. discover_plugins() # idempotent per profile scope
  70. from gateway.platform_registry import platform_registry
  71. return list(platform_registry.all_entries())
  72. return []
  73. def _left_core_platforms() -> list:
  74. """Rows of platforms that left core for a catalog plugin (``hermes_cli.left_core_migration``).
  75. Their channel ownership comes from the row, so it holds while the plugin is absent."""
  76. from hermes_cli.left_core_migration import LEFT_CORE
  77. return [feature for feature in LEFT_CORE if feature.platform]
  78. def _shared_with_tools(source_dir: Optional[Path] = None) -> dict[str, tuple[str, ...]]:
  79. """``_SHARED_WITH_TOOLS``, left-core platforms' prefixes, and every plugin platform's
  80. ``shared_env_prefixes`` in ``source_dir``'s scope."""
  81. shared = dict(_SHARED_WITH_TOOLS)
  82. shared.update({f.platform: f.channel_env_prefixes for f in _left_core_platforms() if f.channel_env_prefixes})
  83. with _plugin_scope(source_dir):
  84. for entry in _registry_entries():
  85. prefixes = tuple(getattr(entry, "shared_env_prefixes", ()) or ())
  86. if prefixes:
  87. shared[entry.name] = prefixes
  88. return shared
  89. def platform_ids(source_dir: Optional[Path] = None) -> list[str]:
  90. """Every messaging platform id: built-in ``Platform`` members, platforms that left core, plus the
  91. plugin adapters registered in ``source_dir``'s scope (ambient scope when ``None``)."""
  92. from gateway.config import Platform
  93. ids = {m.value for m in Platform.__members__.values() if m.value != "local"}
  94. ids.update(feature.platform for feature in _left_core_platforms())
  95. with _plugin_scope(source_dir):
  96. ids.update(entry.name for entry in _registry_entries())
  97. return sorted(ids)
  98. def _cred_row_envs(row) -> set[str]:
  99. """Every env name a ``gateway.platform_env.EnvCred`` row reads."""
  100. names: set[str] = set()
  101. def _flatten(spec) -> None:
  102. if isinstance(spec, str):
  103. names.add(spec)
  104. elif isinstance(spec, (tuple, list)):
  105. for item in spec:
  106. _flatten(item)
  107. _flatten(row.creds)
  108. if row.token:
  109. names.add(row.token)
  110. for key_env in (*row.fixed, *row.optional, *row.optional_stripped):
  111. _flatten(key_env[1])
  112. if row.warn_missing:
  113. names.add(row.warn_missing[0])
  114. if row.home:
  115. names.update({row.home, f"{row.home}_NAME", f"{row.home}_THREAD_ID"})
  116. return names
  117. def config_env_table_keys(entries: Iterable = ()) -> dict[str, str]:
  118. """``{ENV_KEY: platform_id}`` for the names the gateway env overrides read outright: core's
  119. enable-credential sets plus, for each given registry entry, its ``env_enable_credentials`` and
  120. every ``EnvCred`` row of its ``env_overrides``. With no *entries* it is registry-free (core rows
  121. only), so it stays cheap at import time; raises if the core table cannot be read."""
  122. from gateway import config_env
  123. from gateway.platform_env import EnvCred
  124. keys: dict[str, str] = {}
  125. for platform, names in config_env._ENV_ENABLE_CREDENTIALS.items():
  126. keys.update(dict.fromkeys(names, platform.value))
  127. for entry in entries:
  128. keys.update(dict.fromkeys(getattr(entry, "env_enable_credentials", ()) or (), entry.name))
  129. for step in getattr(entry, "env_overrides", ()) or ():
  130. if isinstance(step, EnvCred):
  131. keys.update(dict.fromkeys(_cred_row_envs(step), step.platform.value))
  132. return keys
  133. def _env_override_steps(entries: Iterable) -> list:
  134. """Every step a registry entry declares in ``env_overrides``."""
  135. return [step for entry in entries for step in getattr(entry, "env_overrides", ()) or ()]
  136. def declared_channel_env_keys(source_dir: Optional[Path] = None) -> dict[str, str]:
  137. """``{ENV_KEY: platform_id}`` for every env name an adapter declares outright (registry entry
  138. fields, the gateway env-override table) plus gateway-wide channel policy. Prefix matching covers
  139. the rest."""
  140. keys: dict[str, str] = dict.fromkeys(_GATEWAY_POLICY_KEYS, GATEWAY_POLICY_ID)
  141. for feature in _left_core_platforms():
  142. keys.update(dict.fromkeys(feature.enable_env, feature.platform))
  143. with _plugin_scope(source_dir):
  144. entries = _registry_entries()
  145. for entry in entries:
  146. for name in (*entry.required_env, entry.allowed_users_env, entry.allow_all_env, entry.cron_deliver_env_var):
  147. if name:
  148. keys[name] = entry.name
  149. with contextlib.suppress(Exception):
  150. keys.update(config_env_table_keys(entries))
  151. for step in _env_override_steps(entries):
  152. if isinstance(step, partial):
  153. platform = step.keywords.get("platform")
  154. for kw in ("env", "env_base"):
  155. if step.keywords.get(kw) and platform is not None:
  156. keys[step.keywords[kw]] = platform.value
  157. return keys
  158. def _policy_env_keys(source_dir: Optional[Path] = None) -> set[str]:
  159. """Allowlist / allow-all / home-channel names adapters declare — channel-only by nature."""
  160. names: set[str] = set(_GATEWAY_POLICY_KEYS)
  161. with _plugin_scope(source_dir):
  162. entries = _registry_entries()
  163. for entry in entries:
  164. names.update(n for n in (entry.allowed_users_env, entry.allow_all_env, entry.cron_deliver_env_var) if n)
  165. with contextlib.suppress(Exception):
  166. from gateway.platform_env import EnvCred
  167. for step in _env_override_steps(entries):
  168. if isinstance(step, EnvCred) and step.home:
  169. names.update({step.home, f"{step.home}_NAME", f"{step.home}_THREAD_ID"})
  170. elif isinstance(step, partial) and step.keywords.get("env_base"):
  171. base = step.keywords["env_base"]
  172. names.update({base, f"{base}_NAME", f"{base}_THREAD_ID"})
  173. return names
  174. _CREDENTIAL_SUFFIXES = (
  175. "_TOKEN", "_SECRET", "_KEY", "_PASSWORD", "_APP_ID", "_CLIENT_ID", "_BOT_ID", "_ACCOUNT_SID",
  176. "_SERVICE_ACCOUNT_JSON", "_PROJECT_ID",
  177. )
  178. def credential_env_keys() -> dict[str, str]:
  179. """``{ENV_KEY: platform_id}`` for the keys that make an adapter CONNECT AS a bot (token / app id /
  180. client id / secret — the shape ``GatewayRunner._adapter_credential_fingerprint`` hashes). Enable
  181. flags, URLs and hosts are excluded: two profiles pointing at one Mattermost server collide only
  182. when they also share the token."""
  183. keys: dict[str, str] = {}
  184. for feature in _left_core_platforms():
  185. keys.update(dict.fromkeys(feature.enable_env, feature.platform))
  186. entries = _registry_entries()
  187. for entry in entries:
  188. keys.update(dict.fromkeys(entry.required_env, entry.name))
  189. with contextlib.suppress(Exception):
  190. from gateway import config_env
  191. from gateway.platform_env import EnvCred
  192. for platform, names in config_env._ENV_ENABLE_CREDENTIALS.items():
  193. keys.update(dict.fromkeys(names, platform.value))
  194. for entry in entries:
  195. keys.update(dict.fromkeys(entry.env_enable_credentials, entry.name))
  196. for step in _env_override_steps(entries):
  197. if isinstance(step, EnvCred):
  198. creds: set[str] = set()
  199. for group in step.creds:
  200. creds.update((group,) if isinstance(group, str) else group)
  201. if step.token:
  202. creds.add(step.token)
  203. keys.update(dict.fromkeys(creds, step.platform.value))
  204. return {key: pid for key, pid in keys.items() if key.endswith(_CREDENTIAL_SUFFIXES)}
  205. def _env_values(env_path: Path, wanted: Optional[dict[str, str]] = None) -> dict[str, str]:
  206. """Non-blank assignments in ``env_path`` (restricted to ``wanted`` keys when given)."""
  207. values: dict[str, str] = {}
  208. if not env_path.is_file():
  209. return values
  210. from dotenv import dotenv_values
  211. with contextlib.suppress(Exception):
  212. for key, value in (dotenv_values(env_path, encoding="utf-8-sig") or {}).items():
  213. if (wanted is None or key in wanted) and value and value.strip():
  214. values[key] = value.strip()
  215. return values
  216. def _explicit_enabled(raw: dict, pid: str) -> Optional[bool]:
  217. """``platforms.<pid>.enabled`` (either nesting) when the source config states it, else None."""
  218. gateway = raw["gateway"] if isinstance(raw.get("gateway"), dict) else {}
  219. for section in (raw.get("platforms"), gateway.get("platforms")):
  220. block = section.get(pid) if isinstance(section, dict) else None
  221. if isinstance(block, dict) and "enabled" in block:
  222. return bool(block["enabled"])
  223. return None
  224. def _shared_adapters_active(source_dir: Optional[Path], shared: dict[str, tuple[str, ...]]) -> set[str]:
  225. """Shared-prefix platforms the SOURCE runs as a channel: explicitly enabled in its config.yaml, or
  226. auto-enabled by a complete credential set in its ``.env`` and not explicitly disabled — the same
  227. gate ``gateway.platform_env.EnvCred`` applies at gateway start."""
  228. from hermes_cli.config_backend import config_exists
  229. if source_dir is None:
  230. return set(shared) # no source to consult: the historical (strip) behaviour
  231. raw: dict = {}
  232. if config_exists(source_dir / "config.yaml"):
  233. from hermes_cli.config import read_user_config_raw
  234. with contextlib.suppress(Exception):
  235. raw = read_user_config_raw(source_dir / "config.yaml") or {}
  236. env = _env_values(source_dir / ".env")
  237. creds_by_platform: dict[str, set[str]] = {}
  238. with contextlib.suppress(Exception):
  239. from gateway import config_env
  240. for platform, names in config_env._ENV_ENABLE_CREDENTIALS.items():
  241. creds_by_platform[platform.value] = set(names)
  242. with _plugin_scope(source_dir):
  243. entries = _registry_entries()
  244. # A declared enable-credential set beats a left-core row and the manifest ``required_env``.
  245. for entry in entries:
  246. if entry.env_enable_credentials:
  247. creds_by_platform.setdefault(entry.name, set(entry.env_enable_credentials))
  248. for feature in _left_core_platforms():
  249. creds_by_platform.setdefault(feature.platform, set(feature.enable_env))
  250. for entry in entries:
  251. creds_by_platform.setdefault(entry.name, set(entry.required_env))
  252. active: set[str] = set()
  253. for pid in shared:
  254. explicit = _explicit_enabled(raw, pid)
  255. if explicit is not None:
  256. if explicit:
  257. active.add(pid)
  258. continue
  259. creds = creds_by_platform.get(pid) or set()
  260. if creds and all(env.get(name) for name in creds):
  261. active.add(pid)
  262. return active
  263. class ChannelKeyIndex:
  264. """Resolves an env key to the messaging platform that owns it (``None`` = not a channel key),
  265. evaluated in ``source_dir``'s plugin scope with the ownership rule for shared prefixes."""
  266. def __init__(self, source_dir: Optional[Path] = None) -> None:
  267. self.source_dir = source_dir
  268. self.platforms = platform_ids(source_dir)
  269. self.declared = declared_channel_env_keys(source_dir)
  270. self.policy = _policy_env_keys(source_dir)
  271. self.shared = _shared_with_tools(source_dir)
  272. self.shared_active = _shared_adapters_active(source_dir, self.shared)
  273. self._prefixes: list[tuple[str, str]] = sorted(
  274. ((prefix, pid) for pid in self.platforms
  275. for prefix in dict.fromkeys((*platform_env_prefixes(pid), *self.shared.get(pid, ())))),
  276. key=lambda item: -len(item[0]), # longest prefix wins: WECOM_CALLBACK_ before WECOM_
  277. )
  278. def platform_for(self, key: str) -> Optional[str]:
  279. pid = self.declared.get(key) or next((pid for prefix, pid in self._prefixes if key.startswith(prefix)), None)
  280. if pid is None:
  281. return None
  282. shared = self.shared.get(pid)
  283. if shared and key.startswith(shared) and pid not in self.shared_active and not self._is_policy(key):
  284. return None # a tool credential the source never used as a bot: keep it
  285. return pid
  286. def _is_policy(self, key: str) -> bool:
  287. return key in self.policy or any(marker in key for marker in _POLICY_MARKERS)
  288. def _env_key_of_line(line: str) -> Optional[str]:
  289. match = _ENV_LINE_RE.match(line)
  290. return match.group(1) if match else None
  291. def strip_channel_env_file(env_path: Path, index: Optional[ChannelKeyIndex] = None) -> dict[str, list[str]]:
  292. """Drop every messaging-channel assignment from ``env_path`` in place; comments, blank lines and
  293. every other key survive verbatim. Returns ``{platform: [keys removed]}``."""
  294. if not env_path.is_file():
  295. return {}
  296. index = index or ChannelKeyIndex()
  297. removed: dict[str, list[str]] = {}
  298. kept: list[str] = []
  299. text = env_path.read_text(encoding="utf-8-sig", errors="replace")
  300. for line in text.splitlines():
  301. key = _env_key_of_line(line)
  302. platform = index.platform_for(key) if key else None
  303. if key is None or platform is None:
  304. kept.append(line)
  305. else:
  306. removed.setdefault(platform, []).append(key)
  307. if removed:
  308. env_path.write_text("\n".join(kept) + ("\n" if text.endswith("\n") or kept else ""), encoding="utf-8")
  309. return removed
  310. def _channel_config_paths(raw: dict, platforms: Iterable[str]) -> list[tuple[str, ...]]:
  311. """Dotted paths in a raw config.yaml mapping that hold platform identity: ``platforms``, every
  312. top-level ``<platform>:`` block, ``gateway.platforms`` / ``gateway.<platform>``, and the
  313. multiplexer-owner keys (both spellings the gateway loader accepts)."""
  314. paths: list[tuple[str, ...]] = []
  315. gateway: dict = raw["gateway"] if isinstance(raw.get("gateway"), dict) else {}
  316. if "platforms" in raw:
  317. paths.append(("platforms",))
  318. if "platforms" in gateway:
  319. paths.append(("gateway", "platforms"))
  320. for key in _GATEWAY_OWNER_KEYS:
  321. if key in raw:
  322. paths.append((key,))
  323. if key in gateway:
  324. paths.append(("gateway", key))
  325. for pid in platforms:
  326. if pid in raw:
  327. paths.append((pid,))
  328. if pid in gateway:
  329. paths.append(("gateway", pid))
  330. return paths
  331. def strip_channel_config(config_path: Path, index: Optional[ChannelKeyIndex] = None) -> list[str]:
  332. """Remove platform sections from a raw ``config.yaml`` in place. Returns the dotted paths removed."""
  333. from hermes_cli.config_backend import config_exists
  334. if not config_exists(config_path):
  335. return []
  336. from hermes_cli.config import atomic_config_replace, read_user_config_raw
  337. index = index or ChannelKeyIndex()
  338. raw = read_user_config_raw(config_path)
  339. paths = _channel_config_paths(raw, index.platforms)
  340. if not paths:
  341. return []
  342. for path in paths:
  343. node = raw
  344. for seg in path[:-1]:
  345. node = node[seg]
  346. node.pop(path[-1], None)
  347. if isinstance(raw.get("gateway"), dict) and not raw["gateway"]:
  348. raw.pop("gateway")
  349. atomic_config_replace(config_path, raw)
  350. return [".".join(path) for path in paths]
  351. def channel_state_entries(root: Path, index: Optional[ChannelKeyIndex] = None) -> list[Path]:
  352. """Root entries of a profile that hold per-bot runtime identity: pairing approvals and the
  353. WhatsApp device session (``platforms/`` + legacy dirs), the gateway's per-platform ledgers,
  354. channel directories and every ``<platform>_*`` file OR directory an adapter writes beside
  355. config.yaml (Google Chat keeps user tokens in ``google_chat_user_tokens/``)."""
  356. if not root.is_dir():
  357. return []
  358. index = index or ChannelKeyIndex()
  359. fixed = {"platforms", "pairing", "whatsapp", "gateway", "channel_directory.json", "channel_aliases.json"}
  360. prefixes = tuple(f"{pid}_" for pid in index.platforms)
  361. return sorted(entry for entry in root.iterdir() if entry.name in fixed or entry.name.startswith(prefixes))
  362. def _remove_entry(entry: Path) -> None:
  363. """Remove a state entry without following symlinks (``rmtree`` refuses a symlinked dir and would
  364. otherwise leave the copied link in place; unlinking the link never touches the source)."""
  365. import shutil
  366. if entry.is_symlink() or not entry.is_dir():
  367. entry.unlink(missing_ok=True)
  368. else:
  369. shutil.rmtree(entry, ignore_errors=True)
  370. def strip_channel_settings(profile_dir: Path, *, include_state: bool, source_dir: Optional[Path] = None) -> dict[str, list[str]]:
  371. """Strip channel credentials/identity from a freshly cloned profile, judged in ``source_dir``'s
  372. plugin scope. ``include_state`` also drops the runtime state ``--clone-all`` copied. Returns
  373. ``{platform|"config"|"state": [what]}``."""
  374. index = ChannelKeyIndex(source_dir)
  375. stripped: dict[str, list[str]] = dict(strip_channel_env_file(profile_dir / ".env", index))
  376. config_paths = strip_channel_config(profile_dir / "config.yaml", index)
  377. if config_paths:
  378. stripped["config"] = config_paths
  379. if include_state:
  380. dropped = []
  381. for entry in channel_state_entries(profile_dir, index):
  382. _remove_entry(entry)
  383. dropped.append(entry.name)
  384. if dropped:
  385. stripped["state"] = dropped
  386. return stripped
  387. def channel_platforms_configured(profile_dir: Path) -> list[str]:
  388. """Platform ids with any channel setting in ``profile_dir`` (.env keys or config.yaml sections) —
  389. what a channel-less clone of it leaves behind. Pure read, in ``profile_dir``'s plugin scope."""
  390. from hermes_cli.config_backend import config_exists
  391. index = ChannelKeyIndex(profile_dir)
  392. found: set[str] = set()
  393. env_path = profile_dir / ".env"
  394. if env_path.is_file():
  395. for line in env_path.read_text(encoding="utf-8-sig", errors="replace").splitlines():
  396. key = _env_key_of_line(line)
  397. platform = index.platform_for(key) if key else None
  398. if platform and platform != GATEWAY_POLICY_ID:
  399. found.add(platform)
  400. config_path = profile_dir / "config.yaml"
  401. if config_exists(config_path):
  402. from hermes_cli.config import read_user_config_raw
  403. raw = read_user_config_raw(config_path)
  404. for path in _channel_config_paths(raw, index.platforms):
  405. node = raw
  406. for seg in path:
  407. node = node[seg]
  408. if path[-1] == "platforms" and isinstance(node, dict):
  409. found.update(str(k) for k in node)
  410. elif path[-1] in index.platforms:
  411. found.add(path[-1])
  412. return sorted(found)
  413. def clone_channels_refusal(source_dir: Path, source_label: str) -> Optional[str]:
  414. """Why ``--clone-channels`` must be refused for ``source_dir``: a live multiplexer already serves
  415. the source, so the copied bot would be parked as a duplicate credential at once (the same finding
  416. the migrate preflight reports). ``None`` when the copy is allowed. Shared by CLI, REST and TUI
  417. through :func:`hermes_cli.profiles.create_profile`."""
  418. from hermes_cli.gateway_multiplex_served import recorded_served_profiles
  419. from hermes_cli.profiles import normalize_profile_name
  420. served = recorded_served_profiles()
  421. if not served or len(served) < 2 or normalize_profile_name(source_label) not in {
  422. normalize_profile_name(p) for p in served
  423. }:
  424. return None
  425. platforms = channel_platforms_configured(source_dir)
  426. if not platforms:
  427. return None
  428. return (
  429. f"--clone-channels would copy {', '.join(platforms)} from '{source_label}', which the running "
  430. "multiplexed gateway already serves: the bot can only belong to one profile, so the copy would be "
  431. "parked as a duplicate credential. Clone without --clone-channels and give the new profile its own bot "
  432. "(hermes -p <name> setup), or route its chats with gateway.profile_routes instead."
  433. )
  434. def _config_platform_tokens(config_path: Path) -> dict[str, str]:
  435. """``{platform: token}`` from ``platforms.<p>.token|api_key`` (both nesting spellings)."""
  436. from hermes_cli.config_backend import config_exists
  437. tokens: dict[str, str] = {}
  438. if not config_exists(config_path):
  439. return tokens
  440. from hermes_cli.config import read_user_config_raw
  441. raw = read_user_config_raw(config_path)
  442. gateway: dict = raw["gateway"] if isinstance(raw.get("gateway"), dict) else {}
  443. for section in (raw.get("platforms"), gateway.get("platforms")):
  444. if not isinstance(section, dict):
  445. continue
  446. for pid, block in section.items():
  447. if isinstance(block, dict):
  448. token = block.get("token") or block.get("api_key")
  449. if isinstance(token, str) and token.strip():
  450. tokens[str(pid)] = token.strip()
  451. return tokens
  452. def shared_channel_credentials(profile_dir: Path, source_dir: Path) -> list[str]:
  453. """Platforms whose CONNECTING credential (bot token / app id / account) in ``profile_dir`` is
  454. byte-identical to ``source_dir``'s — the bots that will collide. Pure file reads: no secret
  455. manager, no gateway config load, so ``hermes profile list`` can afford it per profile."""
  456. wanted = credential_env_keys()
  457. mine = _env_values(profile_dir / ".env", wanted)
  458. theirs = _env_values(source_dir / ".env", wanted)
  459. shared = {wanted[key] for key in mine if theirs.get(key) == mine[key]}
  460. mine_cfg = _config_platform_tokens(profile_dir / "config.yaml")
  461. theirs_cfg = _config_platform_tokens(source_dir / "config.yaml")
  462. shared.update(pid for pid, token in mine_cfg.items() if theirs_cfg.get(pid) == token)
  463. return sorted(shared)
  464. def shared_credential_warning(profile: str, platforms: list[str], source: str = "default") -> str:
  465. return (
  466. f"⚠ Profile '{profile}' shares its {', '.join(platforms)} credential with {source}: the bot can "
  467. f"only belong to one profile. Give '{profile}' its own bot (hermes -p {profile} setup, or the "
  468. f"dashboard Messaging page) or remove the token from '{profile}'; a multiplexed gateway parks "
  469. f"the duplicate and `hermes gateway migrate --multiplex` refuses until it is gone."
  470. )
  471. def format_stripped_notice(profile: str, platforms: list[str], clone_flag: str = "--clone") -> list[str]:
  472. """Lines printed after a channel-less clone so the user knows what was left behind and how to
  473. configure the new profile's own bots."""
  474. if not platforms:
  475. return []
  476. return [
  477. f"Messaging channels were NOT cloned ({', '.join(platforms)}): a copied bot token or allowlist "
  478. "would make two gateways fight over one bot.",
  479. f" Configure this profile's own bots: hermes -p {profile} setup (or the dashboard Messaging page)",
  480. f" To copy the source's channels anyway: hermes profile create {profile} {clone_flag} --clone-channels",
  481. ]