setup_agent_import.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. """First-time ``hermes setup``'s "Coming from another agent?" step (it replaces core's old OpenClaw
  2. migration offer).
  3. Detection is a few ``is_dir`` checks and needs nothing installed. Importing lives in the
  4. ``agent-importers`` catalog plugin (``hermes import-agent <source>``): only after the user says yes
  5. does this step install it through the normal catalog install and run its import in a child process,
  6. which owns the preview, the confirmation and what gets imported. Setup helpers are imported lazily
  7. from hermes_cli.setup so test patches there apply.
  8. """
  9. from __future__ import annotations
  10. import os
  11. import subprocess
  12. import sys
  13. import textwrap
  14. from pathlib import Path
  15. from typing import NamedTuple, Optional
  16. PLUGIN = "agent-importers"
  17. class ImportSource(NamedTuple):
  18. name: str # ``hermes import-agent <name>``
  19. label: str
  20. dirs: tuple[str, ...] # paths under ``~`` (or absolute) that show the agent is here; first found wins
  21. extra_args: tuple[str, ...] = ()
  22. exports: tuple[str, ...] = () # globs under ``~`` for export files the plugin reads
  23. # The plugin's importers, with the dirs its own auto-detection checks.
  24. IMPORT_SOURCES: tuple[ImportSource, ...] = (
  25. # Core's setup step migrated OpenClaw's allowlisted API keys and bot tokens after the preview, so
  26. # the provider and messaging sections that follow find them already set; kept.
  27. ImportSource("openclaw", "OpenClaw", (".openclaw", ".clawdbot", ".moltbot"), ("--migrate-secrets",)),
  28. ImportSource("claude-code", "Claude Code", (".claude",)),
  29. ImportSource("codex", "Codex CLI", (".codex",)),
  30. ImportSource("cursor", "Cursor", (".cursor",)),
  31. # Grok Bot lives in its cloud account: the desktop app's dirs only show it is used here, and the
  32. # plugin walks the user through having each Bot export itself (or reads an export already saved).
  33. ImportSource("grok-bot", "Grok Bot", ("Library/Application Support/Grok Bot", "/Applications/Grok Bot.app",
  34. "Applications/Grok Bot.app", ".config/Grok Bot",
  35. "AppData/Roaming/Grok Bot", "AppData/Local/Programs/Grok Bot"),
  36. exports=("Downloads/grok-bot-export*",)),
  37. # OpenBot (nightly-labs/openbot): Electron user data with openbot.db, per OS, or its agent workspaces.
  38. ImportSource("openbot", "OpenBot", ("Library/Application Support/OpenBot", ".config/OpenBot",
  39. "AppData/Roaming/OpenBot", "OpenBot/Agents")),
  40. )
  41. def detect_import_sources() -> list[tuple[ImportSource, Path]]:
  42. """The sources with a setup on this computer, each with the dir found."""
  43. found = []
  44. for source in IMPORT_SOURCES:
  45. home = next((p for p in (Path.home() / d for d in source.dirs) if p.is_dir()), None)
  46. home = home or next((p for g in source.exports for p in sorted(Path.home().glob(g))), None)
  47. if home is not None:
  48. found.append((source, home))
  49. return found
  50. def offer_agent_import(hermes_home: Path, from_setup: bool = True) -> str:
  51. """When another agent's setup is on this computer, offer to import it: pick which (when several),
  52. install the plugin if it is missing and run its import for each pick. Returns the labels whose
  53. import changed this home's config.yaml or .env (``""`` when none did). Asks nothing, and so never
  54. installs anything, when nothing is found or no one can answer the prompts."""
  55. from hermes_cli.setup import _info, is_noninteractive, print_header, print_info, prompt_yes_no
  56. found = [] if is_noninteractive() else detect_import_sources()
  57. if not found:
  58. return ""
  59. user_home = str(Path.home())
  60. print_header("Coming from another agent?", gap=True)
  61. context = ("Found on this computer: " + ", ".join(
  62. f"{s.label} ({str(p).replace(user_home, '~', 1)})" for s, p in found) + ".",
  63. "Hermes can bring over its settings, memories, skills and MCP servers.",
  64. "You'll see a preview and confirm before anything changes.")
  65. _info(*context)
  66. names = " or ".join(s.label for s, _ in found) if len(found) <= 2 else "any of them"
  67. # The menu clears the screen, so the question carries what it refers to ("any of them").
  68. if not prompt_yes_no(f"Import your setup from {names}?", default=True,
  69. description="\n".join(f" {w}" for line in context for w in textwrap.wrap(line, 76))):
  70. print_info(f"Skipped. Import later with: hermes plugins install {PLUGIN}, then hermes import-agent")
  71. return ""
  72. picked = _pick_sources(found)
  73. if not picked or not _ensure_plugin(hermes_home):
  74. return ""
  75. return ", ".join(s.label for s in picked if _run_import(s, hermes_home, from_setup))
  76. def _pick_sources(found: list[tuple[ImportSource, Path]]) -> list[ImportSource]:
  77. """Only one found: that one (the question named it). Several: a checklist, all checked."""
  78. from hermes_cli.setup import print_info, prompt_checklist
  79. if len(found) == 1:
  80. return [found[0][0]]
  81. picked = prompt_checklist("Which agents should Hermes import from?", [s.label for s, _ in found],
  82. list(range(len(found))))
  83. if not picked:
  84. print_info("Nothing selected, so nothing was imported.")
  85. return [found[i][0] for i in picked]
  86. def _ensure_plugin(hermes_home: Path) -> bool:
  87. """The plugin installed and enabled in *hermes_home*: the catalog install (reviewed pin, the
  88. usual install checks) when it is missing, else just an enable."""
  89. from hermes_cli.left_core_migration import plugin_present
  90. from hermes_cli.plugins_admission import AdmissionRefused
  91. from hermes_cli.plugins_cmd import cmd_enable
  92. from hermes_cli.plugins_cmd_install import cmd_install
  93. from hermes_cli.setup import _info, print_warning
  94. present = plugin_present(PLUGIN, hermes_home)
  95. if not present:
  96. _info(None, f"Importing is done by the '{PLUGIN}' plugin from the Hermes plugin catalog. "
  97. "Installing it now...")
  98. try:
  99. if present:
  100. cmd_enable(PLUGIN)
  101. else:
  102. cmd_install(PLUGIN, enable=True, brief=True) # the line above already said what and why
  103. # Both print their own error first: a refusal exits, an enable whose dependencies PM cannot
  104. # admit raises. Either way the import is skipped and the rest of setup goes on.
  105. except (SystemExit, AdmissionRefused):
  106. pass
  107. else:
  108. if plugin_present(PLUGIN, hermes_home):
  109. return True
  110. verb = "enabled" if present else "installed"
  111. print_warning(f"The '{PLUGIN}' plugin could not be {verb}, so nothing was imported. "
  112. f"Try again later with: hermes plugins {'enable' if present else 'install'} {PLUGIN}")
  113. return False
  114. def _snapshot(hermes_home: Path) -> tuple[Optional[bytes], ...]:
  115. return tuple(p.read_bytes() if p.is_file() else None # config-reader: ok — child-run change snapshot
  116. for p in (hermes_home / "config.yaml", hermes_home / ".env"))
  117. def _run_import(source: ImportSource, hermes_home: Path, from_setup: bool = True) -> bool:
  118. """The offer's import: :func:`_import_child` for *source*; True when the run changed config.yaml
  119. or .env, which the setup sections after it read. Bare ``hermes migrate`` runs it as its own
  120. command (``from_setup`` False: no setup-only flags such as OpenClaw's ``--migrate-secrets``)."""
  121. before = _snapshot(hermes_home)
  122. _import_child(source, hermes_home, from_setup=from_setup)
  123. return _snapshot(hermes_home) != before
  124. def _import_child(source: ImportSource, hermes_home: Path, extra_args: tuple[str, ...] = (),
  125. from_setup: bool = True) -> int:
  126. """``hermes import-agent <source>`` in a child process, so the freshly installed plugin's command
  127. is wired; it previews and asks before changing anything (and exits 0 on a no too). Returns its
  128. exit code. ``hermes migrate`` passes the user's flags as ``extra_args`` and runs it as a command
  129. of its own (``from_setup`` False)."""
  130. from hermes_cli.setup import print_header, print_warning
  131. from tools.environments.local import served_profile_child_env
  132. print_header(f"Importing from {source.label}", gap=True)
  133. # A home that is not <root>/profiles/<name> is the root: without a selector the child's
  134. # _apply_profile_override would follow the sticky active_profile into another profile.
  135. selector = [] if hermes_home.resolve().parent.name == "profiles" else ["--profile", "default"]
  136. # --from-setup: the plugin's import speaks as a step of this setup (no "run hermes setup" pointers,
  137. # OpenClaw's skipped items folded into one line).
  138. # source.extra_args are setup's own choices (OpenClaw's --migrate-secrets, what core's old setup
  139. # step did); `hermes migrate` passes only what the user typed.
  140. argv = [sys.executable, "-P", "-m", "hermes_cli.main", *selector, "import-agent", source.name,
  141. *(source.extra_args if from_setup else ()), *extra_args, *(["--from-setup"] if from_setup else [])]
  142. env = served_profile_child_env(target_home=hermes_home)
  143. if os.environ.get("PYTHONPATH"): # this same interpreter running Hermes: keep the source tree
  144. env["PYTHONPATH"] = os.environ["PYTHONPATH"] # a checkout launched by path, which it strips
  145. # health: allow HX006 -- interactive child: the user reads its preview and answers its prompts
  146. returncode = subprocess.run(argv, env=env, check=False).returncode
  147. # An install from before the plugin gained this importer (or --from-setup) refuses it in argparse
  148. # (exit 2) before asking anything: update the plugin once and try again.
  149. if returncode == 2 and _update_plugin(source):
  150. returncode = subprocess.run(argv, env=env, check=False).returncode # health: allow HX006 -- same child
  151. if returncode == 2:
  152. print_warning(f"The {source.label} import did not run. If the error names an invalid choice or "
  153. f"unrecognized arguments, update the plugin first: hermes plugins update {PLUGIN}")
  154. elif returncode:
  155. print_warning(f"The {source.label} import stopped with errors; see the report above.")
  156. return returncode
  157. def _update_plugin(source: ImportSource) -> bool:
  158. """Bring the installed plugin to the catalog's current pin; False when that update failed."""
  159. from hermes_cli.plugins_cmd_update import cmd_update
  160. from hermes_cli.setup import _info
  161. _info(None, f"Your '{PLUGIN}' plugin predates the {source.label} importer. Updating it...")
  162. try:
  163. cmd_update(PLUGIN, interactive=False)
  164. except SystemExit: # it printed why
  165. return False
  166. return True
  167. def migrate_from_agents(hermes_home: Path, source_name: str = "", extra_args: tuple[str, ...] = ()) -> int:
  168. """``hermes migrate [<agent>]``: the same import as setup's step, on demand. Named: install the
  169. plugin when missing and run that agent's import with ``extra_args``. Bare: offer the agents found
  170. on this computer, as setup does."""
  171. from hermes_cli.setup import is_noninteractive, print_info
  172. if not source_name:
  173. found = detect_import_sources()
  174. if found and not is_noninteractive():
  175. offer_agent_import(hermes_home, from_setup=False)
  176. return 0
  177. print_info(("Found: " + ", ".join(s.label for s, _ in found) + ". " if found else
  178. "No other agent setup found on this computer. ")
  179. + "Import one with: " + ", ".join(f"hermes migrate {s.name}" for s in IMPORT_SOURCES))
  180. return 0
  181. source = next(s for s in IMPORT_SOURCES if s.name == source_name)
  182. if not _ensure_plugin(hermes_home):
  183. return 1
  184. return 1 if _import_child(source, hermes_home, extra_args, from_setup=False) else 0