setup_beat_tool.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. """``setup_beat``: the one onboarding-only tool. It shows a beat's card through the desktop, waits
  2. for the user (``CARD_TIMEOUT_S``), and returns their answer with a short reminder of the next beat.
  3. The ``onboarding`` toolset carrying it is folded in only for the onboarding chat, at agent build
  4. (``tui_gateway/methods_onboarding.py``). The run record is the session's ``onboarding_run``
  5. (``agent/onboarding_record.py``); the order and the options are ``agent/onboarding_flow.py``.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import logging
  10. from collections.abc import Callable, Mapping
  11. from typing import Any
  12. from agent import onboarding_flow as flow
  13. from agent.onboarding_text import finish_reminder, reminder
  14. from agent.onboarding_text import question as beat_question
  15. from tools.registry import registry, tool_error
  16. logger = logging.getLogger(__name__)
  17. BEATS = ("next", *flow.BEAT_IDS, "done")
  18. def _connected() -> dict:
  19. from tools.connectors.display import connected_slugs
  20. from tools.connectors.gateway.client import ConnectorClient
  21. return {"connected": sorted(connected_slugs(ConnectorClient()))}
  22. def _installed() -> dict:
  23. from hermes_cli.plugin_catalog_presence import onboarding_names
  24. from hermes_cli.plugins_cmd import _catalog_installed_dir
  25. return {"installed": [name for name in onboarding_names() if _catalog_installed_dir(name) is not None]}
  26. # A card closed without its own answer (words, a value, a skip, the deadline) still reports these.
  27. _PRESENT = {"connectors": _connected, "plugins": _installed}
  28. def _present(beat: str) -> dict | None:
  29. if (read := _PRESENT.get(beat)) is None:
  30. return None
  31. try:
  32. return read()
  33. except Exception:
  34. logger.warning("onboarding: could not read what the %s beat has on this machine", beat, exc_info=True)
  35. return None
  36. def _direct_event(beat: str, args: Mapping[str, Any]) -> flow.Event | None:
  37. """An event the call carries in itself (no card): done, a value given in words, or a skip. Only the
  38. Skip setup button (onboarding.skip) ends onboarding early; the model never decides the user quit."""
  39. if beat == "done":
  40. return flow.Done()
  41. if args.get("skip"):
  42. return flow.Skipped(beat, _present(beat))
  43. value = args.get("value")
  44. return flow.Recorded(beat, value.strip(), _present(beat)) if isinstance(value, str) and value.strip() else None
  45. def _reply_event(beat: str, reply: Mapping[str, Any] | None) -> flow.Event:
  46. reply = reply or {}
  47. said = reply.get("said")
  48. if beat == "name" and isinstance(said, str) and said.strip():
  49. # Words typed while the name card waits are the name, like its own text box.
  50. return flow.Answered(beat, {"name": said.strip()}, said.strip())
  51. if reply.get("wrote_instead"):
  52. # A message sent instead of answering: the desktop sends it as the user's next turn.
  53. return flow.Wrote(beat, _present(beat))
  54. answer = reply.get("answer")
  55. return flow.Answered(beat, answer) if isinstance(answer, dict) and answer else flow.TimedOut(beat, _present(beat))
  56. def _skill_resolver() -> Callable[[str], str | None]:
  57. """A written first-task skill name -> the name skill_view loads it with here, or None. A plugin skill
  58. (``blender:blender``) resolves through the installed catalog plugin to its registered name."""
  59. from hermes_cli.plugins_activation_live import catalog_plugin_skill
  60. from tools.skills_tool import find_all_skills
  61. bundled = {skill["name"] for skill in find_all_skills()}
  62. return lambda name: catalog_plugin_skill(name) if ":" in name else (name if name in bundled else None)
  63. def _result(step: flow.Step, beat: str | None = None, extra: str = "") -> str:
  64. facts = flow.Facts.from_stored(step.record["facts"])
  65. # Only a first task's reminder names skills; the skills scan is skipped for every other result.
  66. resolve_skill = _skill_resolver() if step.reminder.startswith("build_") else (lambda name: name)
  67. text = reminder(step.reminder, step.record, facts, beat, resolve_skill) + extra
  68. return json.dumps({**step.result, **({"reminder": text} if text else {})}, ensure_ascii=False)
  69. def _connector_slugs() -> set[str] | None:
  70. """The connectors this account can connect, as the card lists them; None when the list is unreachable."""
  71. from tools.connectors.targets import hosted_names
  72. return hosted_names()
  73. def _suggest_from(slugs: set[str] | None) -> str:
  74. # The model guesses an app's connector from what is installed (GitHub from the gh CLI); the card shows
  75. # only listed ones, so it names its suggestions from this list.
  76. return f" Suggest only connectors from this list, by these slugs: {', '.join(sorted(slugs))}." if slugs else ""
  77. def _unlisted_suggestions(args: Mapping[str, Any]) -> str | None:
  78. """The refusal for connector suggestions the card cannot show, or None when every one is listed."""
  79. wanted = [str(slug).strip().lower() for slug in args.get("suggest") or () if str(slug).strip()]
  80. slugs = _connector_slugs() if wanted else None
  81. unlisted = [slug for slug in wanted if slugs is not None and slug not in slugs]
  82. if not unlisted:
  83. return None
  84. return json.dumps({"error": "not connectors here", "reminder": (
  85. f"No card shown: {', '.join(unlisted)} cannot be connected here. Do not mention them as connections."
  86. f"{_suggest_from(slugs)} Then call setup_beat(beat=\"connectors\", suggest=[...]) again, or without "
  87. "suggest when none fits.")}, ensure_ascii=False)
  88. def _card(beat: str, step: flow.Step, args: Mapping[str, Any]) -> dict:
  89. facts = flow.Facts.from_stored(step.record["facts"])
  90. card = flow.BEAT_BY_ID[beat].card(facts, step.record["picks"])
  91. if beat == "name":
  92. from agent.onboarding_facts import suggested_name
  93. # The account name goes to the card only; the model reads it if the user picks it.
  94. card = {"suggested": name} if (name := suggested_name()) else {}
  95. if beat == "connectors":
  96. card = {"suggested": [str(slug) for slug in args.get("suggest") or () if str(slug).strip()]}
  97. return card
  98. def setup_beat_tool(args: Mapping[str, Any], *, db=None, session_id: str = "", tool_call_id: str = "",
  99. callback: Callable[[dict], dict | None] | None = None,
  100. end_turn: Callable[[], object] | None = None) -> str:
  101. """``callback(payload) -> {answer?} | {said} | {wrote_instead: true} | None`` asks the desktop to show
  102. ``{beat, question, card}`` and blocks until the user answers or the card closes. ``end_turn`` ends the
  103. agent's turn once this result is in: a card the user wrote past, whose message is the next turn."""
  104. from agent import onboarding_record as records
  105. beat = args.get("beat")
  106. if beat not in BEATS:
  107. return tool_error(f"beat must be one of: {', '.join(BEATS)}.")
  108. record = records.load(db, session_id)
  109. if record is None:
  110. return tool_error("Onboarding is not running in this chat.")
  111. if beat != "next" and (event := _direct_event(beat, args)) is not None:
  112. return _result(records.advance(db, session_id, event))
  113. if beat == "next":
  114. beat = flow.next_beat(record) if flow.is_active(record) else None
  115. if beat is None:
  116. return json.dumps({"next": "done", "reminder": finish_reminder(record)} if flow.is_active(record)
  117. else {"error": "Onboarding is over in this chat; it is a normal chat now."})
  118. if callback is None:
  119. return tool_error("setup_beat cards show only in the Hermes desktop app.")
  120. if beat == "connectors" and (refused := _unlisted_suggestions(args)):
  121. return refused
  122. shown = records.advance(db, session_id, flow.Shown(beat, tool_call_id, args.get("options"), args.get("suggest")))
  123. if shown.result: # refused, or a beat this machine skips
  124. extra = _suggest_from(_connector_slugs()) if shown.reminder == "offer_first" else ""
  125. return _result(shown, extra=extra)
  126. question = str(args.get("question") or "").strip() or beat_question(beat, (record.get("facts") or {}).get("locale"))
  127. reply = callback({"beat": beat, "question": question, "card": _card(beat, shown, args),
  128. "tool_call_id": tool_call_id or None})
  129. after = records.load(db, session_id)
  130. if after is not None and after["phase"] == flow.PHASE_SKIPPED:
  131. # Skip setup closed the card (onboarding.skip already wrote the record).
  132. return _result(flow.Step(after, {"skipped_all": True}, "skip_all"))
  133. event = _reply_event(beat, reply)
  134. result = _result(records.advance(db, session_id, event), beat)
  135. if isinstance(event, flow.Wrote) and end_turn is not None:
  136. # Otherwise the model answers a card the user moved past while their message waits for the turn to end.
  137. end_turn()
  138. return result
  139. SETUP_BEAT_SCHEMA = {
  140. "name": "setup_beat",
  141. "description": (
  142. "Run the first-run onboarding in this chat. Shows the card for a beat and waits for the user, then "
  143. "returns their answer and what to do next. beat=next shows the next beat. Pass value to record an answer "
  144. "they gave in words, skip to record that they skipped a beat. The build card needs options: your picks "
  145. "from the list its reminder gives. beat=done ends onboarding after the first "
  146. "build is shown and its close card is answered. Nothing here ends it early: a user who wants to stop "
  147. "presses Skip setup."
  148. ),
  149. "parameters": {
  150. "type": "object",
  151. "required": ["beat"],
  152. "properties": {
  153. "beat": {"type": "string", "enum": list(BEATS)},
  154. "question": {"type": "string", "description": "Your line above the card."},
  155. "value": {"type": "string", "description": "Record an answer given in words (a name, or an option id). No card."},
  156. "skip": {"type": "boolean", "description": "They skipped this beat in words. No card."},
  157. "suggest": {"type": "array", "items": {"type": "string"},
  158. "description": "connectors only: slugs pinned as Suggested."},
  159. "options": {"type": "array", "maxItems": 4, "description": "build only: up to four picks, ids from the list.",
  160. "items": {"type": "object", "required": ["id", "label"],
  161. "properties": {"id": {"type": "string"},
  162. "label": {"type": "string", "maxLength": 32}}}},
  163. },
  164. },
  165. }
  166. registry.register(
  167. name="setup_beat", toolset="onboarding", schema=SETUP_BEAT_SCHEMA,
  168. # The agent loop runs it inline with the session's record and card callback
  169. # (agent/inline_tool_executors.py); a bare registry dispatch has neither.
  170. handler=lambda args, **kw: setup_beat_tool(args),
  171. emoji="🎛",
  172. )