catalog_tool.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. """``manage_catalog``: a desktop chat's catalog search and install-through-the-card.
  2. ``search`` reads the plugin catalog (the Plugins tab's resolver) and the skills hub and says what is
  3. already installed in this chat's profile. ``install`` opens the same connection operation
  4. ``manage_connections`` opens, with rows of kind ``plugin`` / ``skill``; the host installs each row
  5. the user approves (``tools/connectors/catalog.py``). The model sends catalog ids and an action,
  6. nothing else: the pin, scan, target profile and activation are the host's.
  7. """
  8. from __future__ import annotations
  9. import json
  10. from typing import Any, Callable, Dict, List, Optional
  11. from tools.registry import tool_error
  12. ACTIONS = ("search", "install")
  13. ITEM_KINDS = ("plugin", "skill")
  14. _TOP_KEYS = frozenset({"action", "kind", "query", "items", "reason"})
  15. _ITEM_KEYS = frozenset({"kind", "id"})
  16. SEARCH_LIMIT = 10
  17. NOT_HERE = (
  18. "manage_catalog is available only in the Hermes desktop app, where the approval card can be drawn. "
  19. "Tell the user to install from a terminal instead: `hermes plugins install <id>` for a plugin, "
  20. "`hermes skills install <id>` for a skill."
  21. )
  22. NOTE = (
  23. "Settled once; do not re-offer a row the user skipped. Each installed row names target_profile: "
  24. "its tools and skills are live now in that profile's open chats and in every new chat of it; "
  25. "they are callable in this chat only when this chat runs in that profile. A failed row carries "
  26. "the reason in detail."
  27. )
  28. MANAGE_CATALOG_SCHEMA = {
  29. "name": "manage_catalog",
  30. "description": (
  31. "Find and install Hermes catalog plugins and hub skills for the user. 'search' lists matches "
  32. "(id, kind, display, tier, platforms, installed) and changes nothing. 'install' shows the user "
  33. "one approval card with a row per item and blocks until every row is installed, skipped or "
  34. "failed, or the card is closed; the host installs each approved row into this chat's profile at "
  35. "the catalog's reviewed version, and turns on a catalog plugin that is installed but not "
  36. "enabled. Pass only catalog ids exactly as 'search' returns them; the "
  37. "host decides the source, version, profile and settings, and the user can change them on the "
  38. "card. Offer an install only for something the user asked for or agreed to."
  39. ),
  40. "parameters": {
  41. "type": "object",
  42. "properties": {
  43. "action": {"type": "string", "enum": list(ACTIONS)},
  44. "kind": {"type": "string", "enum": list(ITEM_KINDS),
  45. "description": "search only: limit results to plugins or skills."},
  46. "query": {"type": "string", "description": "search only: words to match; empty lists plugins."},
  47. "items": {
  48. "type": "array",
  49. "description": "install only: the catalog items to offer, one card row each.",
  50. "items": {
  51. "type": "object",
  52. "properties": {
  53. "kind": {"type": "string", "enum": list(ITEM_KINDS)},
  54. "id": {"type": "string", "description": "Catalog id as 'search' returns it."},
  55. },
  56. "required": ["kind", "id"],
  57. "additionalProperties": False,
  58. },
  59. },
  60. "reason": {"type": "string", "description": "install only: one line on why these are offered."},
  61. },
  62. "required": ["action"],
  63. "additionalProperties": False,
  64. },
  65. }
  66. def _check_args(args: dict[str, Any]) -> Optional[str]:
  67. unknown = sorted(set(args) - _TOP_KEYS)
  68. if unknown:
  69. return (f"unknown parameter(s) {', '.join(unknown)}: manage_catalog takes action, kind, query, "
  70. "items and reason. The host decides source, version, profile and settings.")
  71. if args.get("action") not in ACTIONS:
  72. return f"action must be one of {', '.join(ACTIONS)}."
  73. if args.get("kind") not in (None, *ITEM_KINDS):
  74. return f"kind must be one of {', '.join(ITEM_KINDS)}."
  75. if args["action"] == "search":
  76. return None
  77. items = args.get("items")
  78. if not isinstance(items, list) or not items:
  79. return "install needs 'items': [{\"kind\": \"plugin\", \"id\": \"<catalog id>\"}, ...]."
  80. for item in items:
  81. if not isinstance(item, dict):
  82. return "every item is an object {kind, id}."
  83. extra = sorted(set(item) - _ITEM_KEYS)
  84. if extra:
  85. return (f"unknown item field(s) {', '.join(extra)}: an item is {{kind, id}}. The host decides "
  86. "source, version, profile and settings.")
  87. if item.get("kind") not in ITEM_KINDS or not str(item.get("id") or "").strip():
  88. return "every item needs kind (plugin or skill) and a non-empty id."
  89. return None
  90. def manage_catalog(
  91. args: dict[str, Any],
  92. *,
  93. session_id: Optional[str] = None,
  94. tool_call_id: Optional[str] = None,
  95. connection_callback: Optional[Callable[[dict[str, Any]], Optional[str]]] = None,
  96. card_surface: bool = False,
  97. installer: Any = None,
  98. ) -> str:
  99. """``card_surface``: the session is a desktop chat, the one surface that draws catalog rows."""
  100. error = _check_args(args)
  101. if error:
  102. return tool_error(error)
  103. if connection_callback is None or not card_surface:
  104. return tool_error(NOT_HERE)
  105. if args["action"] == "search":
  106. return json.dumps(search(str(args.get("query") or ""), args.get("kind"), installer=installer),
  107. ensure_ascii=False)
  108. return install(args["items"], session_id=session_id, tool_call_id=tool_call_id,
  109. connection_callback=connection_callback, installer=installer)
  110. def install(items: list[dict[str, str]], *, session_id: Optional[str], tool_call_id: Optional[str],
  111. connection_callback: Callable[[dict[str, Any]], Optional[str]], installer: Any = None) -> str:
  112. from tools.connectors.catalog import open_runner
  113. from tools.connectors.gateway.config import operation_session_key
  114. from tools.connectors.operation import Target
  115. from tools.connectors.run import Kind, run_operation
  116. seen, targets = set(), []
  117. for item in items:
  118. key = (item["kind"], str(item["id"]).strip())
  119. if key not in seen:
  120. seen.add(key)
  121. targets.append(Target(name=key[1], kind=key[0], action="install"))
  122. runner = open_runner(installer)
  123. try:
  124. return run_operation(
  125. targets, Kind(prepare=runner.prepare, observe=runner.observe, note=NOTE),
  126. session_key=operation_session_key(session_id), tool_call_id=tool_call_id,
  127. connection_callback=connection_callback, with_urls_in_result=False,
  128. )
  129. finally:
  130. runner.close()
  131. def search(query: str, kind: Optional[str], *, installer: Any = None) -> dict[str, Any]:
  132. """Runs on the tool call's thread, in this chat's profile scope, so ``installed`` is this
  133. chat's profile's."""
  134. from hermes_constants import get_hermes_home, profile_name_for_home
  135. rows: list[dict[str, Any]] = []
  136. if kind in (None, "plugin"):
  137. rows += _plugin_rows(query)
  138. if kind in (None, "skill") and query.strip():
  139. rows += _skill_rows(query)
  140. return {"results": rows, "installed_in": profile_name_for_home(get_hermes_home())}
  141. def _plugin_rows(query: str) -> list[dict[str, Any]]:
  142. from hermes_cli.plugin_catalog import filter_entries, load_catalog_live
  143. from hermes_cli.plugins_cmd import PluginOperationError, _read_install_metadata
  144. from tools.connectors.catalog import _display
  145. try:
  146. installed = {str(rec["catalog"]["name"]) for rec in _read_install_metadata().values()
  147. if isinstance(rec, dict) and isinstance(rec.get("catalog"), dict) and rec["catalog"].get("name")}
  148. except PluginOperationError:
  149. installed = set()
  150. return [{"id": e.name, "kind": "plugin", "display": _display(e.name), "tier": e.tier,
  151. "platforms": list(e.platforms), "installed": e.name in installed}
  152. for e in filter_entries(load_catalog_live(), query)[:SEARCH_LIMIT]]
  153. def _skill_rows(query: str) -> list[dict[str, Any]]:
  154. from tools.skills_hub import HubLockFile, installed_entry
  155. from tools.skills_hub_github import GitHubAuth
  156. from tools.skills_hub_search import create_source_router, unified_search
  157. installed = HubLockFile().by_identifier()
  158. return [{"id": r.identifier, "kind": "skill", "display": r.name,
  159. "tier": "official" if r.source == "official" else "community", "platforms": [],
  160. "installed": installed_entry(installed, r.identifier, r.source) is not None}
  161. for r in unified_search(query, create_source_router(GitHubAuth()), limit=SEARCH_LIMIT)]