profile_cmd.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. """``hermes profile`` command — one handler per action, dispatched by ``PROFILE_ACTIONS``.
  2. Imports from ``hermes_cli.profiles`` stay lazy (inside each handler) so tests can monkeypatch
  3. the module attributes.
  4. """
  5. from __future__ import annotations
  6. from pathlib import Path
  7. import os
  8. import sys
  9. from typing import NoReturn, Optional
  10. def _die(msg: str, code: int = 1, *, err: bool = False) -> NoReturn:
  11. print(msg, file=sys.stderr if err else sys.stdout)
  12. sys.exit(code)
  13. def _confirm(prompt: str) -> bool:
  14. """y/N prompt; EOF / Ctrl-C count as "no"."""
  15. try:
  16. answer = input(prompt).strip().lower()
  17. except (EOFError, KeyboardInterrupt):
  18. answer = ""
  19. return answer in {"y", "yes"}
  20. def _is_active(p, active: str) -> bool:
  21. return p.name == active or (active == "default" and p.is_default)
  22. def _env_file_has_key(env_path: Path, key: str) -> bool:
  23. """True when *key* is assigned in *env_path* (unreadable/mis-encoded file → False, never aborts)."""
  24. from agent.secret_scope import load_env_file
  25. return key in load_env_file(env_path)
  26. def _render_distribution_plan(plan) -> None:
  27. """Print a human-readable summary of a pending distribution install."""
  28. from hermes_cli.profile_distribution import MANIFEST_FILENAME
  29. mf = plan.manifest
  30. print(f"\nDistribution: {mf.name} v{mf.version}")
  31. if mf.description:
  32. print(f" {mf.description}")
  33. if mf.author:
  34. print(f" Author: {mf.author}")
  35. if mf.hermes_requires:
  36. print(f" Requires: Hermes {mf.hermes_requires}")
  37. print(f" Source: {plan.provenance}")
  38. print(f" Target: {plan.target_dir}")
  39. if plan.existing:
  40. # Updating an existing distribution (dist-owned overwritten, config preserved, user
  41. # data untouched) vs overwriting a hand-built plain profile (same mechanics, but the
  42. # user didn't sign up for it).
  43. if (plan.target_dir / MANIFEST_FILENAME).is_file():
  44. print(" (profile exists — will overwrite distribution-owned files only)")
  45. else:
  46. print(
  47. " ⚠ Profile exists but is NOT a distribution. Installing here will\n"
  48. " overwrite its SOUL.md and mcp.json and replace any skill or cron job\n"
  49. " of the same name the distribution ships.\n"
  50. " Your memories, sessions, auth.json, and .env will be preserved,\n"
  51. " but any hand-edits to distribution-owned files will be lost."
  52. )
  53. if mf.env_requires:
  54. print("\n Env vars:")
  55. for er in mf.env_requires:
  56. tag = "required" if er.required else "optional"
  57. # Shell environment OR the target profile's .env — don't nag about set keys.
  58. already = os.environ.get(er.name) is not None or (
  59. plan.target_dir.is_dir() and _env_file_has_key(plan.target_dir / ".env", er.name)
  60. )
  61. status = "✓ set" if already else ("needs setting" if er.required else "—")
  62. line = f" • {er.name} ({tag}, {status})"
  63. if er.description:
  64. line += f" — {er.description}"
  65. print(line)
  66. if plan.has_cron:
  67. print(
  68. "\n ⚠ This distribution ships cron jobs. They will NOT run "
  69. "automatically — review and enable manually."
  70. )
  71. def _profile_status(args):
  72. """Bare ``hermes profile`` — show current profile status."""
  73. from hermes_constants import display_hermes_home
  74. from hermes_cli.profiles import format_profile_label, get_active_profile_name, list_profiles
  75. profile_name = get_active_profile_name()
  76. dhh = display_hermes_home()
  77. current = next((p for p in list_profiles() if _is_active(p, profile_name)), None)
  78. label = format_profile_label(profile_name, current.display_name if current else "")
  79. print(f"\nActive profile: {label}")
  80. print(f"Path: {dhh}")
  81. if current is not None:
  82. p = current
  83. if p.model:
  84. print(f"Model: {p.model}" + (f" ({p.provider})" if p.provider else ""))
  85. print(f"Gateway: {'running' if p.gateway_running else 'stopped'}")
  86. print(f"Skills: {p.skill_count} installed")
  87. if p.alias_path:
  88. print(f"Alias: {p.alias_name or p.name} → hermes -p {p.name}")
  89. print()
  90. def _profile_list(args):
  91. from hermes_cli.profiles import format_profile_label, get_active_profile_name, list_profiles
  92. profiles = list_profiles()
  93. active = get_active_profile_name()
  94. if not profiles:
  95. print("No profiles found.")
  96. return
  97. print(f"\n {'Profile':<16} {'Model':<28} {'Gateway':<12} {'Alias':<12} {'Distribution'}")
  98. print(f" {'─' * 15} {'─' * 27} {'─' * 11} {'─' * 11} {'─' * 20}")
  99. for p in profiles:
  100. marker = " ◆" if _is_active(p, active) else " "
  101. name = format_profile_label(p.name, p.display_name)
  102. model = (p.model or "—")[:26]
  103. gw = "running" if p.gateway_running else "stopped"
  104. alias = (p.alias_name or p.name) if p.alias_path and not p.is_default else "—"
  105. dist = f"{p.distribution_name}@{p.distribution_version or '?'}"[:30] if p.distribution_name else "—"
  106. print(f"{marker}{name:<15} {model:<28} {gw:<12} {alias:<12} {dist}")
  107. print()
  108. for line in _shared_credential_warnings(profiles):
  109. print(line)
  110. def _shared_credential_warnings(profiles) -> list:
  111. """One warning per named profile whose bot credential is byte-identical to the default's
  112. (typically an old ``--clone`` that copied .env): the collision that parks a multiplexed
  113. adapter or makes two standalone gateways fight over one bot."""
  114. from hermes_cli.profile_channels import shared_channel_credentials, shared_credential_warning
  115. default = next((p for p in profiles if p.is_default), None)
  116. if default is None:
  117. return []
  118. lines = []
  119. for p in profiles:
  120. if p.is_default:
  121. continue
  122. try:
  123. shared = shared_channel_credentials(p.path, default.path)
  124. except Exception:
  125. continue
  126. if shared:
  127. lines.append(shared_credential_warning(p.name, shared))
  128. return lines + ([""] if lines else [])
  129. def _profile_use(args):
  130. from hermes_cli.profiles import set_active_profile
  131. name = args.profile_name
  132. try:
  133. set_active_profile(name)
  134. print("Switched to: default (~/.hermes)" if name == "default" else f"Switched to: {name}")
  135. except (ValueError, FileNotFoundError) as e:
  136. _die(f"Error: {e}")
  137. def _source_profile_dir(source_label: str) -> Path:
  138. from hermes_cli.profiles import get_profile_dir
  139. source_dir = get_profile_dir(source_label)
  140. if not source_dir.is_dir():
  141. raise FileNotFoundError(source_dir)
  142. return source_dir
  143. def _print_channel_clone_notice(name: str, source_label: str, clone_channels: bool, clone_flag: str) -> None:
  144. from hermes_cli.profile_channels import (
  145. channel_platforms_configured, format_stripped_notice, shared_channel_credentials,
  146. shared_credential_warning,
  147. )
  148. from hermes_cli.profiles import get_profile_dir
  149. try:
  150. source_dir = _source_profile_dir(source_label)
  151. except FileNotFoundError:
  152. return
  153. if not clone_channels:
  154. for line in format_stripped_notice(name, channel_platforms_configured(source_dir), clone_flag):
  155. print(line)
  156. return
  157. shared = shared_channel_credentials(get_profile_dir(name), source_dir)
  158. if shared:
  159. print(shared_credential_warning(name, shared, source_label))
  160. def _profile_create(args):
  161. from hermes_cli.profiles import (
  162. _get_wrapper_dir, _is_wrapper_dir_in_path, check_alias_collision, create_profile,
  163. create_wrapper_script, get_active_profile_name, seed_profile_skills,
  164. )
  165. name = args.profile_name
  166. clone = getattr(args, "clone", False)
  167. clone_all = getattr(args, "clone_all", False)
  168. no_alias = getattr(args, "no_alias", False)
  169. no_skills = getattr(args, "no_skills", False)
  170. clone_from = getattr(args, "clone_from", None)
  171. clone_channels = getattr(args, "clone_channels", False)
  172. sync_imports = getattr(args, "sync_imports", False)
  173. clone_config = clone or clone_from is not None
  174. cloned = clone_config or clone_all
  175. source_label = clone_from or get_active_profile_name()
  176. try:
  177. profile_dir = create_profile(
  178. name=name, clone_from=clone_from, clone_all=clone_all, clone_config=clone_config,
  179. no_alias=no_alias, no_skills=no_skills, description=getattr(args, "description", None),
  180. clone_channels=clone_channels, sync_imports=sync_imports,
  181. )
  182. except (ValueError, FileExistsError, FileNotFoundError) as e:
  183. _die(f"Error: {e}")
  184. print(f"\nProfile '{name}' created at {profile_dir}")
  185. if cloned:
  186. if clone_all:
  187. print(f"Full copy from {source_label} (excluding session history, cron jobs, backups, and snapshots).")
  188. else:
  189. print(f"Cloned config, .env, SOUL.md, and skills from {source_label}.")
  190. from hermes_cli.profiles import cloned_plugin_names
  191. plugin_names = cloned_plugin_names(profile_dir)
  192. if plugin_names:
  193. print(f"Cloned installed plugins too: {', '.join(plugin_names)}.")
  194. from hermes_cli.profile_memory_config import cloned_memory_provider
  195. memory_provider = cloned_memory_provider(profile_dir)
  196. if memory_provider:
  197. print(f"Cloned memory provider config ({memory_provider}) too.")
  198. if sync_imports:
  199. print(f"Import sources carried over — `hermes -p {name} import-agent --sync` "
  200. "keeps pulling the same Claude Code / Codex trees.")
  201. _print_channel_clone_notice(name, source_label, clone_channels, "--clone-all" if clone_all else "--clone")
  202. # Auto-clone Honcho config for the new profile (only with clone operations)
  203. try:
  204. from plugins.memory import import_provider_module
  205. honcho_cli = import_provider_module("honcho", "cli")
  206. except Exception:
  207. honcho_cli = None # Honcho plugin not installed
  208. if honcho_cli is not None:
  209. try:
  210. if honcho_cli.clone_honcho_for_profile(name):
  211. print(f"Honcho config cloned (peer: {name})")
  212. except honcho_cli.ConfigWriteRefused as e:
  213. print(f"Honcho config not cloned: {e}")
  214. except Exception:
  215. pass # Honcho not configured
  216. else:
  217. # Fresh profiles only: clones already carry the source's (user-curated) skills.
  218. result = seed_profile_skills(profile_dir)
  219. if result and result.get("skipped_opt_out"):
  220. print("No bundled skills seeded (--no-skills). Delete .no-bundled-skills in the profile to opt back in.")
  221. elif result:
  222. print(f"{len(result.get('copied', []))} bundled skills synced.")
  223. else:
  224. print(f"⚠ Skills could not be seeded. Run `{name} update` to retry.")
  225. if not no_alias:
  226. collision = check_alias_collision(name)
  227. if collision:
  228. print(f"\n⚠ Cannot create alias '{name}' — {collision}")
  229. print(f" Choose a custom alias: hermes profile alias {name} --name <custom>")
  230. print(f" Or access via flag: hermes -p {name} chat")
  231. else:
  232. wrapper_path = create_wrapper_script(name)
  233. if wrapper_path:
  234. print(f"Wrapper created: {wrapper_path}")
  235. if not _is_wrapper_dir_in_path():
  236. print(f"\n⚠ {_get_wrapper_dir()} is not in your PATH.")
  237. print(" Add to your shell config (~/.bashrc or ~/.zshrc):")
  238. print(' export PATH="$HOME/.local/bin:$PATH"')
  239. try:
  240. profile_dir_display = "~/" + profile_dir.relative_to(Path.home()).as_posix()
  241. except ValueError:
  242. profile_dir_display = str(profile_dir)
  243. print("\nNext steps:")
  244. print(f" {name} setup Configure API keys and model")
  245. print(f" {name} chat Start chatting")
  246. from hermes_cli.gateway_multiplex_served import live_default_gateway_pid, recorded_served_profiles
  247. from hermes_cli.profiles import normalize_profile_name
  248. served = recorded_served_profiles() if live_default_gateway_pid() is not None else None
  249. if served is not None and normalize_profile_name(name) in {normalize_profile_name(p) for p in served}:
  250. print(" (served now by the running multiplexed gateway — add its bot token and it connects)")
  251. elif served is not None:
  252. # The multiplexer did not pick the profile up (older gateway or the signal failed): a restart serves it.
  253. print(" hermes gateway restart Serve this profile from the running multiplexed gateway")
  254. else:
  255. print(f" {name} gateway start Start the messaging gateway")
  256. if clone or clone_all:
  257. print(f"\n Edit {profile_dir_display}/.env for different API keys")
  258. print(f" Edit {profile_dir_display}/SOUL.md for different personality")
  259. else:
  260. print(f"\n ⚠ This profile has no API keys yet. Run '{name} setup' first,")
  261. print(" or it will inherit keys from your shell environment.")
  262. print(f" Edit {profile_dir_display}/SOUL.md to customize personality")
  263. print()
  264. def _profile_delete(args):
  265. from hermes_cli.profiles import delete_profile
  266. try:
  267. delete_profile(args.profile_name, yes=getattr(args, "yes", False))
  268. except (ValueError, FileNotFoundError, RuntimeError) as e:
  269. _die(f"Error: {e}")
  270. def _describe_target_dir(name: str) -> Path:
  271. """Profile dir for ``describe``: ``default`` maps to the CURRENT home (get_hermes_home),
  272. everything else to its named directory."""
  273. from hermes_cli import profiles as _profiles_mod
  274. if _profiles_mod.normalize_profile_name(name) == "default":
  275. from hermes_constants import get_hermes_home as _hh
  276. return Path(_hh())
  277. return _profiles_mod.get_profile_dir(name)
  278. def _profile_describe(args):
  279. from hermes_cli import profiles as _profiles_mod
  280. all_flag = bool(getattr(args, "all_missing", False))
  281. auto_flag = bool(getattr(args, "auto", False))
  282. overwrite_flag = bool(getattr(args, "overwrite", False))
  283. text_value = getattr(args, "text", None)
  284. name = getattr(args, "profile_name", None)
  285. if all_flag and not auto_flag:
  286. _die("profile describe: --all requires --auto", 2, err=True)
  287. if all_flag and (text_value or name):
  288. _die("profile describe: --all is mutually exclusive with a profile name / --text", 2, err=True)
  289. if not all_flag and not name:
  290. _die("profile describe: profile name is required (or --all --auto)", 2, err=True)
  291. if text_value and auto_flag:
  292. _die("profile describe: --text is mutually exclusive with --auto", 2, err=True)
  293. # Show current description if no operation requested.
  294. if name and not text_value and not auto_flag:
  295. try:
  296. profile_dir = _describe_target_dir(name)
  297. except Exception as exc:
  298. _die(f"Error: {exc}", err=True)
  299. if not profile_dir.is_dir():
  300. _die(f"Error: profile '{name}' not found", err=True)
  301. meta = _profiles_mod.read_profile_meta(profile_dir)
  302. desc = meta.get("description") or ""
  303. if not desc:
  304. print(f"(no description set for '{name}')")
  305. else:
  306. tag = "[auto] " if meta.get("description_auto") else ""
  307. print(f"{tag}{desc}")
  308. sys.exit(0)
  309. # --text path: just write the user-authored description.
  310. if text_value:
  311. try:
  312. _profiles_mod.write_profile_meta(_describe_target_dir(name), description=text_value, description_auto=False)
  313. print(f"Description updated for '{name}'.")
  314. except Exception as exc:
  315. _die(f"Error: {exc}", err=True)
  316. sys.exit(0)
  317. # --auto path: invoke the LLM describer.
  318. from hermes_cli import profile_describer as _pd
  319. if all_flag:
  320. targets = _pd.list_describable_profiles(missing_only=True)
  321. if not targets:
  322. _die("All profiles already have descriptions.", 0)
  323. else:
  324. targets = [name]
  325. ok_count = 0
  326. for tgt in targets:
  327. outcome = _pd.describe_profile(tgt, overwrite=overwrite_flag)
  328. if outcome.ok:
  329. ok_count += 1
  330. print(f"Described '{outcome.profile_name}': {outcome.description}")
  331. else:
  332. print(f"profile describe {outcome.profile_name}: {outcome.reason}", file=sys.stderr)
  333. sys.exit(0 if (ok_count > 0 if all_flag else ok_count == 1) else 1)
  334. def _profile_show(args):
  335. name = args.profile_name
  336. from hermes_cli.profiles import (
  337. get_profile_dir, profile_exists, _read_config_model, _check_gateway_running,
  338. _served_by_running_multiplexer, _count_skills, _read_distribution_meta, _wrapper_path,
  339. find_alias_for_profile, format_profile_label, read_profile_meta,
  340. )
  341. if not profile_exists(name):
  342. _die(f"Error: Profile '{name}' does not exist.")
  343. profile_dir = get_profile_dir(name)
  344. model, provider = _read_config_model(profile_dir)
  345. gw = _check_gateway_running(profile_dir) or _served_by_running_multiplexer(name)
  346. dist_name, dist_version, dist_source = _read_distribution_meta(profile_dir)
  347. alias_name = find_alias_for_profile(name)
  348. display = read_profile_meta(profile_dir).get("display_name", "")
  349. print(f"\nProfile: {format_profile_label(name, display)}")
  350. print(f"Path: {profile_dir}")
  351. if model:
  352. print(f"Model: {model}" + (f" ({provider})" if provider else ""))
  353. print(f"Gateway: {'running' if gw else 'stopped'}")
  354. print(f"Skills: {_count_skills(profile_dir)}")
  355. print(f".env: {'exists' if (profile_dir / '.env').exists() else 'not configured'}")
  356. print(f"SOUL.md: {'exists' if (profile_dir / 'SOUL.md').exists() else 'not configured'}")
  357. if dist_name:
  358. print(f"Distribution: {dist_name}@{dist_version or '?'}")
  359. if dist_source:
  360. print(f"Installed from: {dist_source}")
  361. print(f" (run `hermes profile info {name}` for full manifest)")
  362. if alias_name:
  363. print(f"Alias: {alias_name} → hermes -p {name} ({_wrapper_path(alias_name)})")
  364. print()
  365. def _profile_alias(args):
  366. from hermes_cli.profiles import (
  367. _get_wrapper_dir, _is_wrapper_dir_in_path, check_alias_collision, create_wrapper_script,
  368. profile_exists, remove_wrapper_script, validate_alias_name,
  369. )
  370. name = args.profile_name
  371. remove = getattr(args, "remove", False)
  372. custom_name = getattr(args, "alias_name", None)
  373. alias_name = custom_name or name
  374. try:
  375. validate_alias_name(alias_name)
  376. except ValueError as exc:
  377. _die(f"Error: {exc}")
  378. if remove: # runs without the profile: an orphan alias outlives it
  379. exists = profile_exists(name)
  380. if custom_name and not exists: # orphan cleanup is `alias <alias> --remove`
  381. _die(f"Error: Profile '{name}' does not exist.")
  382. if remove_wrapper_script(alias_name):
  383. print(f"✓ Removed alias '{alias_name}'")
  384. elif not exists:
  385. _die(f"Error: No alias '{alias_name}' and no profile '{name}'. `hermes doctor` lists orphan aliases.")
  386. else:
  387. print(f"No alias '{alias_name}' found to remove.")
  388. return
  389. if not profile_exists(name):
  390. _die(f"Error: Profile '{name}' does not exist.")
  391. collision = check_alias_collision(alias_name)
  392. if collision:
  393. _die(f"Error: {collision}")
  394. wrapper_path = create_wrapper_script(alias_name, target=name if custom_name else None)
  395. if wrapper_path:
  396. print(f"✓ Alias created: {wrapper_path}")
  397. if not _is_wrapper_dir_in_path():
  398. print(f"⚠ {_get_wrapper_dir()} is not in your PATH.")
  399. def _profile_rename(args):
  400. from hermes_cli.profiles import normalize_profile_name, rename_profile
  401. try:
  402. new_dir = rename_profile(args.old_name, args.new_name)
  403. if normalize_profile_name(args.old_name) != "default":
  404. print(f"\nProfile renamed: {args.old_name} → {args.new_name}")
  405. print(f"Path: {new_dir}\n")
  406. except (ValueError, FileExistsError, FileNotFoundError) as e:
  407. _die(f"Error: {e}")
  408. def _profile_migrate_identity(args):
  409. """Retry the identity migration of a rename that already completed. Exits non-zero when a
  410. live gateway would not migrate (it still owns the routing index in memory), or when a
  411. database rejected the rewrite (collision, lock, partial failure)."""
  412. from hermes_cli.profile_identity import migrate_profile_identity
  413. try:
  414. migrated = migrate_profile_identity(args.old_name, args.new_name)
  415. except (ValueError, FileNotFoundError) as e:
  416. _die(f"Error: {e}")
  417. if not migrated:
  418. _die(f"Error: session identity was not migrated. Restart or stop the gateway, then run:\n"
  419. f" hermes profile migrate-identity {args.old_name} {args.new_name}", err=True)
  420. print(f"✓ Session/routing identity migrated: {args.old_name} → {args.new_name}")
  421. def _profile_purge_identity(args):
  422. """Retry the identity purge of a delete that already completed. Exits non-zero when a live
  423. gateway would not purge (it still owns the routing index in memory), or when a database rejected
  424. the delete (lock, partial failure)."""
  425. from hermes_cli.profile_identity import purge_profile_identity
  426. try:
  427. purged = purge_profile_identity(args.profile_name)
  428. except ValueError as e:
  429. _die(f"Error: {e}")
  430. if not purged:
  431. _die(f"Error: session identity was not purged. Restart or stop the gateway, then run:\n"
  432. f" hermes profile purge-identity {args.profile_name}", err=True)
  433. print(f"✓ Session/routing identity purged: {args.profile_name}")
  434. def _profile_export(args):
  435. from hermes_cli.profiles import export_profile, get_profile_export_path
  436. name = args.profile_name
  437. try:
  438. output = args.output or str(get_profile_export_path(name))
  439. result_path = export_profile(name, output)
  440. print(f"✓ Exported '{name}' to {result_path}")
  441. except (ValueError, FileNotFoundError, OSError) as e:
  442. _die(f"Error: {e}")
  443. def _profile_import(args):
  444. from hermes_cli.profiles import check_alias_collision, create_wrapper_script, import_profile
  445. try:
  446. profile_dir = import_profile(args.archive, name=getattr(args, "import_name", None))
  447. name = profile_dir.name
  448. print(f"✓ Imported profile '{name}' at {profile_dir}")
  449. if not check_alias_collision(name):
  450. wrapper_path = create_wrapper_script(name)
  451. if wrapper_path:
  452. print(f" Wrapper created: {wrapper_path}")
  453. print()
  454. except (ValueError, FileExistsError, FileNotFoundError) as e:
  455. _die(f"Error: {e}")
  456. def _profile_install(args):
  457. import tempfile
  458. from hermes_cli.profile_distribution import DistributionError, install_distribution, plan_install
  459. try:
  460. # Preview: stage into a scratch dir, show the manifest, then do the real install.
  461. # The double-stage avoids any side-effects if the user declines.
  462. with tempfile.TemporaryDirectory(prefix="hermes_dist_preview_") as tmp:
  463. plan = plan_install(args.source, Path(tmp), override_name=getattr(args, "install_name", None))
  464. _render_distribution_plan(plan)
  465. if not getattr(args, "yes", False) and not _confirm("\nProceed with install? [y/N] "):
  466. print("Install cancelled.")
  467. return
  468. plan = install_distribution(
  469. args.source, name=getattr(args, "install_name", None), force=getattr(args, "force", False),
  470. create_alias=getattr(args, "alias", False),
  471. )
  472. print(f"\n✓ Installed '{plan.manifest.name}' v{plan.manifest.version}")
  473. print(f" Profile path: {plan.target_dir}")
  474. if plan.manifest.env_requires:
  475. print(
  476. f" Next: copy .env.EXAMPLE to .env and fill in required keys:\n"
  477. f" {plan.target_dir}/.env.EXAMPLE"
  478. )
  479. if plan.has_cron:
  480. print(
  481. " Cron jobs were included but are NOT scheduled automatically.\n"
  482. f" Review them with: hermes -p {plan.manifest.name} cron list"
  483. )
  484. print(f"\n Use with: hermes -p {plan.manifest.name} chat")
  485. except (DistributionError, ValueError) as e:
  486. _die(f"Error: {e}")
  487. def _profile_update(args):
  488. from hermes_cli.profile_distribution import DistributionError, read_manifest, update_distribution
  489. from hermes_cli.profiles import get_profile_dir, normalize_profile_name
  490. try:
  491. canon = normalize_profile_name(args.profile_name)
  492. current = read_manifest(get_profile_dir(canon))
  493. if current is None:
  494. _die(
  495. f"Error: Profile '{canon}' is not a distribution (no distribution.yaml). "
  496. "Only profiles installed via `hermes profile install` can be updated."
  497. )
  498. force_config = getattr(args, "force_config", False)
  499. if not getattr(args, "yes", False):
  500. print(f"\nUpdate '{canon}' from: {current.source or '(no source)'}")
  501. print(f" Currently at version {current.version}")
  502. if force_config:
  503. print(" --force-config set: config.yaml WILL be overwritten.")
  504. else:
  505. print(" config.yaml will be preserved (pass --force-config to overwrite).")
  506. print(" User data (memories, sessions, auth, .env) will NOT be touched.")
  507. if not _confirm("\nProceed? [y/N] "):
  508. print("Update cancelled.")
  509. return
  510. plan = update_distribution(canon, force_config=force_config)
  511. print(f"\n✓ Updated '{plan.manifest.name}' → v{plan.manifest.version}")
  512. if plan.has_cron:
  513. print(f" Cron files were refreshed. Review with: hermes -p {plan.manifest.name} cron list")
  514. except (DistributionError, ValueError) as e:
  515. _die(f"Error: {e}")
  516. _INFO_FIELDS = (
  517. ("description", "Description: "),
  518. ("author", "Author: "),
  519. ("license", "License: "),
  520. ("hermes_requires", "Requires: Hermes "),
  521. ("source", "Source: "),
  522. ("installed_at", "Installed: "),
  523. )
  524. def _profile_info(args):
  525. from hermes_cli.profile_distribution import describe_distribution, DistributionError
  526. try:
  527. data = describe_distribution(args.profile_name)
  528. except (DistributionError, ValueError) as e:
  529. _die(f"Error: {e}")
  530. if not data:
  531. print(f"Profile '{args.profile_name}' is not a distribution (no distribution.yaml).")
  532. return
  533. print(f"\nDistribution: {data.get('name')}")
  534. print(f"Version: {data.get('version', '?')}")
  535. for key, label in _INFO_FIELDS:
  536. if data.get(key):
  537. print(f"{label}{data[key]}")
  538. env_reqs = data.get("env_requires") or []
  539. if env_reqs:
  540. print("\nEnvironment variables:")
  541. for er in env_reqs:
  542. tag = "required" if er.get("required", True) else "optional"
  543. line = f" {er['name']} ({tag})"
  544. if er.get("description"):
  545. line += f" — {er['description']}"
  546. print(line)
  547. if er.get("default") is not None:
  548. print(f" default: {er['default']}")
  549. print()
  550. # Order mirrors the original if/elif chain; None = bare ``hermes profile``.
  551. PROFILE_ACTIONS = {
  552. None: _profile_status,
  553. 'list': _profile_list,
  554. 'use': _profile_use,
  555. 'create': _profile_create,
  556. 'delete': _profile_delete,
  557. 'describe': _profile_describe,
  558. 'show': _profile_show,
  559. 'alias': _profile_alias,
  560. 'rename': _profile_rename,
  561. 'purge-identity': _profile_purge_identity,
  562. 'migrate-identity': _profile_migrate_identity,
  563. 'export': _profile_export,
  564. 'import': _profile_import,
  565. 'install': _profile_install,
  566. 'update': _profile_update,
  567. 'info': _profile_info,
  568. }
  569. def cmd_profile(args):
  570. """Profile management — create, delete, list, switch, alias."""
  571. handler = PROFILE_ACTIONS.get(getattr(args, "profile_action", None))
  572. if handler is not None:
  573. return handler(args)