onboarding.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. """Contextual first-touch onboarding hints, and the entry points of desktop first-run onboarding.
  2. Each hint is shown once per install the *first* time a user hits a behavior
  3. fork, tracked in ``config.yaml`` under ``onboarding.seen.<flag>``. Kept tiny and
  4. dependency-free so both the CLI and gateway can import it.
  5. First-run onboarding (one chat in the default profile, driven by ``setup_beat``) lives in the
  6. siblings: ``onboarding_flow`` (beats and the run record, pure), ``onboarding_text`` (the words),
  7. ``onboarding_facts`` (the safe facts) and ``onboarding_record`` (where the run is stored).
  8. """
  9. from __future__ import annotations
  10. import logging
  11. from pathlib import Path
  12. from typing import Any, Mapping, Optional
  13. from agent.onboarding_record import observe_tool_result
  14. logger = logging.getLogger(__name__)
  15. # Flag names (stable — used as config.yaml keys under onboarding.seen)
  16. BUSY_INPUT_FLAG = "busy_input_prompt"
  17. TOOL_PROGRESS_FLAG = "tool_progress_prompt"
  18. OPENCLAW_RESIDUE_FLAG = "openclaw_residue_cleanup"
  19. PROFILE_BUILD_FLAG = "profile_build_offered"
  20. # Busy-input hints are keyed by the effective busy_input_mode that was just
  21. # applied so the message matches reality; "interrupt" is the default branch.
  22. _BUSY_INPUT_HINTS_GATEWAY = {
  23. "queue": (
  24. "💡 First-time tip — I queued your message instead of interrupting. Send `/busy interrupt` to make new messages "
  25. "stop the current task immediately, or `/busy status` to check. This notice won't appear again."
  26. ),
  27. "steer": (
  28. "💡 First-time tip — I steered your message into the current run; it will arrive after the next tool "
  29. "call instead of interrupting. Send `/busy interrupt` or `/busy queue` to change this, or `/busy "
  30. "status` to check. This notice won't appear again."
  31. ),
  32. "redirect": (
  33. "💡 First-time tip — I redirected the current run using your message. Completed work stays in "
  34. "context, and `/stop` still cancels the task. Send `/busy queue` to wait for a separate turn, or "
  35. "`/busy status` to check. This notice won't appear again."
  36. ),
  37. }
  38. _BUSY_INPUT_HINT_GATEWAY_DEFAULT = (
  39. "💡 First-time tip — I just interrupted my current task to answer you. Send `/busy queue` to queue "
  40. "follow-ups for after the current task instead, `/busy steer` to inject them mid-run without "
  41. "interrupting, or `/busy status` to check. This notice won't appear again."
  42. )
  43. _BUSY_INPUT_HINTS_CLI = {
  44. "queue": (
  45. "(tip) Your message was queued for the next turn. Use /busy interrupt to make Enter stop the current "
  46. "run instead, or /busy steer to inject mid-run. This tip only shows once."
  47. ),
  48. "steer": (
  49. "(tip) Your message was steered into the current run; it arrives after the next tool call. Use /busy "
  50. "interrupt or /busy queue to change this. This tip only shows once."
  51. ),
  52. "redirect": (
  53. "(tip) Your correction redirected the current run without discarding completed work. Use /stop to "
  54. "cancel or /busy queue to wait for a separate turn. This tip only shows once."
  55. ),
  56. }
  57. _BUSY_INPUT_HINT_CLI_DEFAULT = (
  58. "(tip) Your message interrupted the current run. Use /busy queue to queue messages for the next turn "
  59. "instead, or /busy steer to inject mid-run. This tip only shows once."
  60. )
  61. def busy_input_hint_gateway(mode: str) -> str:
  62. """Hint shown the first time a user messages while the agent is busy (markdown)."""
  63. return _BUSY_INPUT_HINTS_GATEWAY.get(mode, _BUSY_INPUT_HINT_GATEWAY_DEFAULT)
  64. def busy_input_hint_cli(mode: str) -> str:
  65. """CLI version of the busy-input hint (plain text, no markdown)."""
  66. return _BUSY_INPUT_HINTS_CLI.get(mode, _BUSY_INPUT_HINT_CLI_DEFAULT)
  67. def tool_progress_hint_gateway() -> str:
  68. return ("💡 First-time tip — that tool took a while and I'm streaming every step. If the progress messages "
  69. "feel noisy, send `/verbose` to cycle modes (all → new → off). This notice won't appear again.")
  70. def tool_progress_hint_cli() -> str:
  71. return ("(tip) That tool ran for a while. Use /verbose to cycle tool-progress "
  72. "display modes (all -> new -> off -> verbose). This tip only shows once.")
  73. def openclaw_residue_hint_cli() -> str:
  74. """Banner shown the first time Hermes finds ``~/.openclaw/``: migrate first, cleanup (which breaks OpenClaw) after."""
  75. return (
  76. "A legacy OpenClaw directory was detected at ~/.openclaw/.\n"
  77. "To port your config, memory, and skills over to Hermes, run `hermes import-agent openclaw` "
  78. "(from the agent-importers plugin: `hermes plugins install agent-importers`).\n"
  79. "If you've already migrated and want to archive the old directory, run `hermes claw cleanup` "
  80. "(renames it to ~/.openclaw.pre-migration — OpenClaw will stop working after this).\n"
  81. "This tip only shows once."
  82. )
  83. def detect_openclaw_residue(home: Optional[Path] = None) -> bool:
  84. """True if ``$HOME/.openclaw`` is a directory (``home`` override for tests)."""
  85. try:
  86. return ((home or Path.home()) / ".openclaw").is_dir()
  87. except OSError:
  88. return False
  89. def _onboarding_section(config: Mapping[str, Any]) -> Mapping[str, Any]:
  90. onboarding = config.get("onboarding") if isinstance(config, Mapping) else None
  91. return onboarding if isinstance(onboarding, Mapping) else {}
  92. def profile_build_mode(config: Mapping[str, Any]) -> str:
  93. """``config.onboarding.profile_build``: ``"off"`` never offers; anything else -> ``"ask"``.
  94. Only governs whether the offer is made; lookups inside the flow are
  95. consented to separately in conversation.
  96. """
  97. mode = _onboarding_section(config).get("profile_build")
  98. return "off" if isinstance(mode, str) and mode.strip().lower() == "off" else "ask"
  99. # Shared by both first-contact notes so a real first-message task is never
  100. # replaced by the intro (plain or profile-build offer).
  101. TASK_FIRST_CLAUSE = (
  102. "If this message is itself a real request or task, DO THE TASK FIRST -- call "
  103. "whatever tools it needs -- and only then, in the closing sentences of that same "
  104. "reply, do what this note asks. Never let this note replace or skip work the user "
  105. "actually asked for. "
  106. )
  107. PLAIN_INTRO_NOTE = (
  108. "[System note: This is the user's very first message ever. "
  109. + TASK_FIRST_CLAUSE
  110. + "What this note asks: briefly introduce yourself and mention that /help shows "
  111. "available commands, in one or two sentences.]"
  112. )
  113. def first_contact_turn_note(
  114. config: Mapping[str, Any],
  115. config_path: Path,
  116. *,
  117. session_history_empty: bool,
  118. install_has_prior_sessions: bool,
  119. onboarding_run_active: bool = False,
  120. ) -> Optional[str]:
  121. """Return a one-shot sidecar note for the install's first-ever message.
  122. Matches the gateway first-contact path: when ``profile_build`` is ``ask``
  123. and the offer has not been latched yet, return the opt-in profile-build
  124. directive and persist ``onboarding.seen.profile_build_offered``. Otherwise
  125. return the plain intro note. Returns ``None`` when this is not the first
  126. contact (non-empty session history or prior sessions exist on the install).
  127. ``onboarding_run_active``: the chat is running first-run onboarding, whose opening replaces this note.
  128. """
  129. if not session_history_empty or install_has_prior_sessions or onboarding_run_active:
  130. return None
  131. try:
  132. if (
  133. profile_build_mode(config) == "ask"
  134. and not is_seen(config, PROFILE_BUILD_FLAG)
  135. ):
  136. mark_seen(config_path, PROFILE_BUILD_FLAG)
  137. return profile_build_directive().strip()
  138. return PLAIN_INTRO_NOTE
  139. except Exception as e:
  140. logger.debug("first_contact_turn_note failed, using plain intro: %s", e)
  141. return PLAIN_INTRO_NOTE
  142. def profile_build_directive() -> str:
  143. """System-note directive appended to the very first message ever.
  144. Short opt-in profile-build flow persisting to the user-profile memory store;
  145. phrased so the agent ASKS before any lookup and never silently reads
  146. connected accounts.
  147. """
  148. return (
  149. "\n\n"
  150. "[System note: This is the user's very first message ever. " + TASK_FIRST_CLAUSE
  151. + "What this note asks: after a one-sentence introduction (mention /help "
  152. "shows commands), OFFER — do not assume — to build a short profile of them so you can be more useful, and "
  153. "explain they can decline or do it later. If and ONLY IF they accept:\n"
  154. " 1. Ask for whatever they're comfortable sharing (name, what they do, how they like you to work). "
  155. "Volunteered facts come first.\n"
  156. " 2. Before ANY external lookup, say what you intend to look up and get explicit consent for that step. Never "
  157. "read their connected accounts (email, calendar, etc.) silently — ask each time.\n"
  158. " 3. With consent, you may use web_search to confirm public details (e.g. employer, public profiles) from the "
  159. "data points they gave.\n"
  160. " 4. Save each confirmed, durable fact with the memory tool using target=\"user\" — keep entries compact and "
  161. "high-signal.\n"
  162. "If they decline at any point, stop immediately and continue normally. Keep the whole exchange light and "
  163. "conversational, not an interrogation.]"
  164. )
  165. def is_seen(config: Mapping[str, Any], flag: str) -> bool:
  166. """True if the user has already been shown this first-touch hint."""
  167. seen = _onboarding_section(config).get("seen")
  168. return bool(seen.get(flag)) if isinstance(seen, Mapping) else False
  169. def mark_seen(config_path: Path, flag: str) -> bool:
  170. """Persist ``onboarding.seen.<flag> = True`` atomically; False on any error (best-effort)."""
  171. try:
  172. from hermes_cli.config import atomic_config_write, read_user_config_raw
  173. except Exception as e: # pragma: no cover — dependency issue
  174. logger.debug("onboarding: failed to import config helpers: %s", e)
  175. return False
  176. try:
  177. cfg: dict = read_user_config_raw(config_path)
  178. if not isinstance(cfg.get("onboarding"), dict):
  179. cfg["onboarding"] = {}
  180. seen = cfg["onboarding"].get("seen")
  181. if not isinstance(seen, dict):
  182. seen = cfg["onboarding"]["seen"] = {}
  183. if seen.get(flag) is not True:
  184. seen[flag] = True
  185. atomic_config_write(config_path, cfg)
  186. return True
  187. except Exception as e:
  188. logger.debug("onboarding: failed to mark flag %s: %s", flag, e)
  189. return False
  190. __all__ = [
  191. "BUSY_INPUT_FLAG",
  192. "OPENCLAW_RESIDUE_FLAG",
  193. "PLAIN_INTRO_NOTE",
  194. "PROFILE_BUILD_FLAG",
  195. "TOOL_PROGRESS_FLAG",
  196. "busy_input_hint_cli",
  197. "busy_input_hint_gateway",
  198. "detect_openclaw_residue",
  199. "first_contact_turn_note",
  200. "is_seen",
  201. "mark_seen",
  202. "observe_tool_result",
  203. "openclaw_residue_hint_cli",
  204. "profile_build_directive",
  205. "profile_build_mode",
  206. "tool_progress_hint_cli",
  207. "tool_progress_hint_gateway",
  208. ]