The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: setup agent can search the catalog and install plugins and skills through the approval card
alt-glitch31e59b9441f6
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 5fb2dee9d66..aada8bc92e6 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -82,7 +82,8 @@ def _ra():AGENT_RUNTIME_POST_HOOK_TOOL_NAMES = frozenset({"todo_list", "session_search", "memory", "clarify", "read_terminal", "desktop_preview",- "drive_preview", "annotate_preview", "read_window_below", "manage_connections", "setup_mcp", "gui_tour",+ "drive_preview", "annotate_preview", "read_window_below", "manage_connections", "manage_catalog", "setup_mcp",+ "gui_tour","delegate_task",})diff --git a/agent/inline_tool_executors.py b/agent/inline_tool_executors.pyindex 76a675e8f50..43d855635e8 100644--- a/agent/inline_tool_executors.py+++ b/agent/inline_tool_executors.py@@ -211,6 +211,17 @@ def _scope_in_connected_mcp_servers(agent, result: Any) -> None:agent.enabled_toolsets = [*enabled, *added]+def _manage_catalog(agent, args: dict, ctx: InlineToolContext) -> Any:+ # The card callback lives on the agent; only a desktop chat draws catalog rows.+ from tools.connectors.catalog_tool import manage_catalog++ return manage_catalog(+ args, session_id=getattr(agent, "session_id", None), tool_call_id=ctx.tool_call_id,+ connection_callback=getattr(agent, "connection_callback", None),+ card_surface=getattr(agent, "platform", None) == "desktop",+ )++def _setup_mcp_shim(agent, args: dict, ctx: InlineToolContext) -> Any:# Replay shim for conversations whose cached prompt still names setup_mcp.# Not in _LEGACY_TOOL_ALIASES: inline tools bypass handle_function_call.@@ -263,6 +274,7 @@ INLINE_TOOL_EXECUTORS: Dict[str, InlineToolExecutor] = {("text", "text"), ("side", "side"), ("steps", "steps"), ("step_index", "step_index"),),"manage_connections": _manage_connections,+ "manage_catalog": _manage_catalog,"setup_mcp": _setup_mcp_shim,"delegate_task": lambda agent, args, ctx: agent._dispatch_delegate_task(args),}diff --git a/agent/tool_dispatch_helpers.py b/agent/tool_dispatch_helpers.pyindex 2ec46728d28..beb5842d62c 100644--- a/agent/tool_dispatch_helpers.py+++ b/agent/tool_dispatch_helpers.py@@ -25,7 +25,7 @@ from tools.threat_patterns import scan_for_threatslogger = logging.getLogger(__name__)# Interactive / user-facing tools never run concurrently: any of these in a batch is a barrier.-_NEVER_PARALLEL_TOOLS = frozenset({"clarify", "manage_connections"})+_NEVER_PARALLEL_TOOLS = frozenset({"clarify", "manage_connections", "manage_catalog"})# Read-only tools with no shared mutable session state._PARALLEL_SAFE_TOOLS = frozenset({diff --git a/tests/tools/test_connectors_catalog.py b/tests/tools/test_connectors_catalog.pynew file mode 100644index 00000000000..079a255a29d--- /dev/null+++ b/tests/tools/test_connectors_catalog.py@@ -0,0 +1,229 @@+"""``manage_catalog`` (the setup profile's catalog install through the connection card).++Contracts:+- the tool reaches only a session of the ``role: setup`` profile, and only a desktop chat draws it+- the model sends catalog ids and an action; every other key is refused before anything runs+- an id the catalog does not know, or a plugin this OS cannot run, is drawn failed and never installed+- an approved row installs into ``default`` (or the profile the Advanced modal named) and reports+ what went live; the card never witnesses the outcome+"""++import json+import threading+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++import pytest++from tools.connectors import live+from tools.connectors.catalog_tool import NOT_HERE, manage_catalog+from tools.connectors.contract import TargetState+from tools.connectors.run import apply_answer++[email protected](autouse=True)+def _clean_live():+ live.reset_for_tests()+ yield+ live.reset_for_tests()+++def _entry(name, *, platforms=(), requires_env=()):+ return SimpleNamespace(+ name=name, repo=f"https://github.com/example/{name}", sha="a" * 40, subdir="", tier="official",+ description=f"Drives {name}. More text.", requires_hermes="", platforms=list(platforms),+ capabilities=SimpleNamespace(requires_env=list(requires_env)),+ )+++class FakeInstaller:+ """The host side of a row: the catalog, the platform refusal and the installer."""++ def __init__(self, entries=(), *, refuse=None, install_error=""):+ self.entries = {e.name: e for e in entries}+ self.refusal = refuse or {}+ self.install_error = install_error+ self.installs = []++ def plugin_entry(self, name):+ return self.entries.get(name)++ def refuse(self, entry):+ if entry.name in self.refusal:+ raise RuntimeError(self.refusal[entry.name])++ def install_plugin(self, name, *, force, enable, ref):+ from hermes_constants import get_hermes_home++ self.installs.append({"name": name, "force": force, "enable": enable, "ref": ref,+ "home": Path(get_hermes_home())})+ if self.install_error:+ return {"ok": False, "error": self.install_error}+ tools = [f"mcp__{name}__status", f"mcp__{name}__launch"]+ return {"ok": True, "plugin_name": name, "missing_env": [], "activation": {+ "live_now": {"mcp_servers": [{"name": name, "connected": True, "tools": tools}], "skills": []}}}++ def skill_meta(self, identifier):+ return None++ def install_skill(self, identifier, *, force):+ raise AssertionError("no skill in these tests")+++def _card(answer, *, session_id="s1", profile_home=None):+ """A desktop card that answers the live operation a moment after it is drawn. ``profile_home`` is+ the session's profile, which ``connection.respond`` looks the operation up under."""+ seen = []++ def callback(payload):+ seen.append(payload)++ def respond():+ operation = live.get(session_id, payload["op_id"], profile_home=profile_home)+ if operation is not None:+ apply_answer(operation, json.dumps(answer(payload)))++ threading.Timer(0.01, respond).start()++ callback.seen = seen+ return callback+++def _install(items, installer, card):+ with patch("tools.connectors.run.WATCH_INTERVAL_SECONDS", 0.01):+ return json.loads(manage_catalog({"action": "install", "items": items}, session_id="s1",+ connection_callback=card, card_surface=True, installer=installer))+++def _approve(env=None):+ return lambda payload: {"targets": [{"name": t["name"], "status": "approved", "env": env}+ for t in payload["targets"] if t["state"] == "pending"]}+++def test_only_a_setup_profile_session_selects_the_tool(tmp_path, monkeypatch):+ import model_tools+ from hermes_cli.profiles import write_profile_meta+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ homes = {}+ for name, role in (("default", None), ("hermes-setup", "setup")):+ homes[name] = tmp_path / name+ homes[name].mkdir()+ if role:+ write_profile_meta(homes[name], role=role)+ for name, expected in (("default", False), ("hermes-setup", True)):+ token = set_hermes_home_override(str(homes[name]))+ try:+ # Even an explicit request for the toolset does not reach a profile without the role.+ names = model_tools._select_tool_names(["setup", "web"], None, quiet_mode=True)+ finally:+ reset_hermes_home_override(token)+ assert ("manage_catalog" in names) is expected, name+ # The setup guide's one tool is sent directly, never hidden behind tool_search.+ from tools.tool_search import is_deferrable_tool_name+ assert not is_deferrable_tool_name("manage_catalog")++[email protected]("args", [+ {"action": "install", "items": [{"kind": "plugin", "id": "x"}], "profile": "work"},+ {"action": "install", "items": [{"kind": "plugin", "id": "x", "sha": "b" * 40}]},+ {"action": "install", "items": [{"kind": "plugin", "id": "x", "url": "https://evil.example/x"}]},+])+def test_a_source_version_or_profile_from_the_model_is_refused_before_anything_runs(args):+ installer, card = FakeInstaller([_entry("x")]), _card(_approve())+ out = json.loads(manage_catalog(args, session_id="s1", connection_callback=card, card_surface=True,+ installer=installer))+ assert "error" in out and not card.seen and not installer.installs+++def test_off_the_desktop_the_result_points_at_the_cli_and_opens_no_card():+ installer, card = FakeInstaller([_entry("x")]), _card(_approve())+ for callback, surface in ((None, True), (card, False)):+ out = json.loads(manage_catalog({"action": "install", "items": [{"kind": "plugin", "id": "x"}]},+ session_id="s1", connection_callback=callback, card_surface=surface,+ installer=installer))+ assert out["error"] == NOT_HERE+ assert not card.seen and not installer.installs and live.current("s1") is None+++def test_unknown_and_unsupported_ids_are_drawn_failed_and_never_installed():+ installer = FakeInstaller([_entry("nvidia-app", platforms=["windows"])],+ refuse={"nvidia-app": "Plugin 'nvidia-app' is unavailable on darwin; "+ "supported platforms: windows."})+ card = _card(lambda payload: {"settled_by": "continue"})+ out = _install([{"kind": "plugin", "id": "nope"}, {"kind": "plugin", "id": "nvidia-app"}], installer, card)+ drawn = {t["name"]: t for t in card.seen[0]["targets"]}+ assert {t["state"] for t in drawn.values()} == {TargetState.failed.value} # drawn with the reason+ rows = {t["name"]: t for t in out["targets"]}+ assert "catalog" in rows["nope"]["detail"]+ assert "unavailable on darwin" in rows["nvidia-app"]["detail"]+ assert rows["nvidia-app"]["display"] == "Nvidia App" and rows["nvidia-app"]["platforms"] == ["windows"]+ assert not installer.installs+++def test_an_approved_row_installs_into_default_and_lists_the_live_tools(tmp_path):+ from hermes_cli.profiles import get_profile_dir, write_profile_meta+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ setup_home = tmp_path / "hermes-setup"+ setup_home.mkdir()+ write_profile_meta(setup_home, role="setup")+ installer = FakeInstaller([_entry("blender")])+ card = _card(_approve(), profile_home=str(setup_home))+ token = set_hermes_home_override(str(setup_home)) # the call comes from the setup chat+ try:+ out = _install([{"kind": "plugin", "id": "blender"}], installer, card)+ finally:+ reset_hermes_home_override(token)+ (row,) = out["targets"]+ assert card.seen[0]["targets"][0]["state"] == TargetState.pending.value # nothing ran before the card+ assert row["state"] == TargetState.connected.value and row["target_profile"] == "default"+ assert row["tools"] == ["mcp__blender__status", "mcp__blender__launch"]+ (call,) = installer.installs+ assert (call["force"], call["enable"], call["ref"]) == (False, True, None)+ assert call["home"].resolve() == Path(get_profile_dir("default")).resolve() != setup_home.resolve()+++def test_advanced_values_pick_the_profile_force_and_pin(tmp_path):+ from hermes_cli.profiles import create_profile++ work = create_profile("work", no_alias=True)+ installer = FakeInstaller([_entry("blender")])+ pin = "c" * 40+ out = _install([{"kind": "plugin", "id": "blender"}], installer,+ _card(_approve({"target_profile": "work", "force": "1", "enable": "0", "ref": pin})))+ (row,) = out["targets"]+ (call,) = installer.installs+ assert (call["force"], call["enable"], call["ref"]) == (True, False, pin)+ assert call["home"].resolve() == Path(work).resolve() and row["target_profile"] == "work"+ assert "not enabled" in row["detail"]+++def test_a_failed_install_stays_failed_until_the_user_tries_again():+ installer = FakeInstaller([_entry("blender")], install_error="clone failed: network down")+ attempts = []++ def answer(payload):+ (target,) = payload["targets"]+ attempts.append(target["state"])+ return {"targets": [{"name": "blender", "status": "approved", "env": None}]}++ card = _card(answer)+ with patch("tools.connectors.run.WATCH_INTERVAL_SECONDS", 0.01):+ result = {}+ thread = threading.Thread(target=lambda: result.setdefault("out", json.loads(manage_catalog(+ {"action": "install", "items": [{"kind": "plugin", "id": "blender"}]}, session_id="s1",+ connection_callback=card, card_surface=True, installer=installer))))+ thread.start()+ for _ in range(200):+ operation = live.current("s1")+ if operation is not None and operation.targets[0].state == TargetState.failed:+ break+ threading.Event().wait(0.01)+ assert operation.targets[0].detail == "clone failed: network down"+ installer.install_error = ""+ apply_answer(operation, json.dumps({"targets": [{"name": "blender", "status": "approved"}]}))+ thread.join(5)+ assert result["out"]["targets"][0]["state"] == TargetState.connected.value+ assert len(installer.installs) == 2diff --git a/tools/connectors/catalog.py b/tools/connectors/catalog.pynew file mode 100644index 00000000000..fb769f89172--- /dev/null+++ b/tools/connectors/catalog.py@@ -0,0 +1,359 @@+"""``manage_catalog`` install targets: catalog plugins and hub skills, installed through the card.++``prepare`` resolves every id against the plugin catalog (the Plugins tab's resolver) or the skills+hub and fills the row the card draws; an id that does not resolve, or a plugin this OS cannot run,+is drawn failed with the reason. Nothing installs until the user approves a row. The install runs on+a worker under the TARGET profile's runtime scope (``default`` unless the Advanced modal named+another), through the same host install the Plugins tab uses, so the catalog pin, the kill list, the+security scan and the live activation of the plugin's MCP servers and skills are the host's.+"""++from __future__ import annotations++import contextlib+import contextvars+import io+import json+import logging+import re+import threading+from dataclasses import dataclass, field+from typing import Any, Callable, Dict, List, Optional++from tools.connectors.contract import Actor, SettleReason, TargetState+from tools.connectors.mcp import _fail, _move+from tools.connectors.operation import ConnectionOperation, IllegalTransition, Target++logger = logging.getLogger(__name__)++DEFAULT_PROFILE = "default"+# The Advanced modal's own keys (CATALOG-ROW-CONTRACT.md); every other answer key is a credential.+_OPTION_KEYS = frozenset({"target_profile", "agent_half", "desktop_half", "enable", "force", "ref"})+_COMMIT_SHA = re.compile(r"^[0-9a-fA-F]{40}$")+_TIERS = frozenset({"official", "community"})+++def _flag(value: Optional[str], default: bool) -> bool:+ return default if value in (None, "") else value == "1"+++def _first_sentence(text: str) -> str:+ text = " ".join(str(text or "").split())+ head, dot, _rest = text.partition(". ")+ return f"{head}." if dot else text+++def _display(identifier: str) -> str:+ leaf = identifier.rstrip("/").rsplit("/", 1)[-1]+ return " ".join(part.capitalize() for part in re.split(r"[-_]+", leaf) if part) or identifier+++def target_scope(profile: str):+ """Bind the named profile's home, secrets and terminal policy, the way an RPC for that profile+ does. The install writes its tree, config and ``.env`` there, never into the setup profile. The+ home override is bound for the launch profile too: the calling thread carries the setup+ profile's override, and an unbound launch scope would leave it in place."""+ from tui_gateway import server+ from tui_gateway.launch_profile_policy import launch_profile_runtime_scope++ home = server._profile_home(profile) # None = the launch profile; raises for a missing one+ scope = (launch_profile_runtime_scope(server._hermes_home) if home is None+ else server._session_profile_runtime_scope({"profile_home": str(home)}))+ with scope:+ yield+++class HostInstaller:+ """The host side of a catalog row. Tests replace it; production reads the real catalog, hub and+ installer."""++ def plugin_entry(self, name: str) -> Any:+ from hermes_cli.plugin_catalog import get_live_catalog_entry++ return get_live_catalog_entry(name)++ def refuse(self, entry: Any) -> None:+ """Raise with the installer's own text when the catalog would refuse this entry here."""+ from hermes_cli.plugins_cmd_catalog import _refuse_unsupported_catalog_platform, raise_if_removed++ raise_if_removed(entry.name, entry.repo)+ _refuse_unsupported_catalog_platform(entry)++ def install_plugin(self, name: str, *, force: bool, enable: bool, ref: Optional[str]) -> Dict[str, Any]:+ from hermes_cli.plugins_cmd import dashboard_install_plugin++ return dashboard_install_plugin("", force=force, enable=enable, catalog_name=name, ref=ref)++ def skill_meta(self, identifier: str) -> Optional[Dict[str, Any]]:+ from hermes_cli.skills_hub import inspect_skill++ return inspect_skill(identifier)++ def install_skill(self, identifier: str, *, force: bool) -> str:+ """Install headless and return the installed skill's name. ``do_install`` reports only by+ printing, so success is read from the hub lock file and failure from its last line."""+ from rich.console import Console++ from hermes_cli.skills_hub import do_install+ from tools.skills_hub import HubLockFile++ out = io.StringIO()+ do_install(identifier, force=force, skip_confirm=True,+ console=Console(file=out, width=200, no_color=True, highlight=False))+ entry = next((e for e in HubLockFile().list_installed() if e.get("identifier") == identifier), None)+ if entry is None:+ lines = [line.strip() for line in out.getvalue().splitlines() if line.strip()]+ raise RuntimeError(lines[-1] if lines else "the skill was not installed")+ return str(entry["name"])+++@dataclass+class _Work:+ done: threading.Event = field(default_factory=threading.Event)+ outcome: Dict[str, Any] = field(default_factory=dict)+ error: str = ""+++class _Runner:+ """Resolved catalog facts and install work for one operation's rows."""++ def __init__(self, installer: HostInstaller):+ self.installer = installer+ self.op_id: Optional[str] = None+ self.facts: Dict[str, Any] = {} # row name -> PluginCatalogEntry | skill meta; never on the wire+ self.work: Dict[str, _Work] = {}+ # The Advanced values the user approved per row; Try again (env null) reuses them. Values+ # are credentials in part, so they stay here, off the target.+ self.approved_env: Dict[str, Dict[str, str]] = {}++ # -- prepare: resolve each id and draw its row ------------------------------------------------++ def prepare(self, operation: ConnectionOperation) -> None:+ _RUNNERS[operation.op_id] = self+ self.op_id = operation.op_id+ for target in operation.targets:+ target.extra = {"display": _display(target.name), "target_profile": DEFAULT_PROFILE}+ try:+ self._resolve(target)+ except Exception as exc:+ _fail(operation, target, self._detail(exc, target))++ def _resolve(self, target: Target) -> None:+ if target.kind == "plugin":+ entry = self.installer.plugin_entry(target.name)+ if entry is None:+ raise LookupError(f"'{target.name}' is not in the Hermes plugin catalog")+ self.facts[target.name] = entry+ target.extra = _plugin_row(entry)+ target.required_env = [{"name": name, "required": False, "secret": True, "default": ""}+ for name in entry.capabilities.requires_env]+ self.installer.refuse(entry)+ return+ meta = self.installer.skill_meta(target.name)+ if not meta:+ raise LookupError(f"'{target.name}' was not found in the skills hub")+ self.facts[target.name] = meta+ target.extra = {+ "display": str(meta.get("name") or _display(target.name)),+ "description": _first_sentence(meta.get("description") or ""),+ "tier": "official" if meta.get("source") == "official" else "community",+ "target_profile": DEFAULT_PROFILE,+ }++ # -- the card's answer ------------------------------------------------------------------------++ def approve(self, operation: ConnectionOperation, target: Target, env: Optional[Dict[str, str]]) -> None:+ approved = {**self.approved_env.get(target.name, {}), **(env or {})}+ actor = Actor.user if target.state == TargetState.failed else Actor.backend_watcher+ if target.name not in self.facts: # failed at prepare: Try again resolves once more+ try:+ self._resolve(target)+ except Exception as exc:+ _fail(operation, target, self._detail(exc, target))+ return+ error = self._check_answer(target, approved)+ if error:+ _fail(operation, target, error)+ return+ self.approved_env[target.name] = approved+ if not _move(operation, target, TargetState.initiated, actor, detail=""):+ return+ self._spawn(operation, target, approved)++ def _check_answer(self, target: Target, env: Dict[str, str]) -> str:+ if target.kind == "plugin" and env.get("agent_half") == "0":+ return "only the desktop half was selected; install it from Settings, Plugins"+ ref = env.get("ref")+ if ref and not _COMMIT_SHA.match(ref):+ return "the pin must be a full 40-character commit SHA"+ declared = set(target_declared_env(self.facts.get(target.name)))+ undeclared = sorted(k for k in env if k not in _OPTION_KEYS and k not in declared)+ if undeclared:+ return f"'{target.name}' does not declare {', '.join(undeclared)}"+ return ""++ def _spawn(self, operation: ConnectionOperation, target: Target, env: Dict[str, str]) -> None:+ work = _Work()+ self.work[target.name] = work++ def body() -> None:+ try:+ work.outcome = self._install(target, env)+ except Exception as exc:+ work.error = self._detail(exc, target)+ work.done.set()+ operation.wake.set()++ # A copy of the answering thread's context; the install binds the target profile itself.+ threading.Thread(target=contextvars.copy_context().run, args=(body,), daemon=True,+ name=f"catalog-install-{target.name}").start()++ def _install(self, target: Target, env: Dict[str, str]) -> Dict[str, Any]:+ profile = (env.get("target_profile") or DEFAULT_PROFILE).strip()+ force = _flag(env.get("force"), False)+ with target_scope(profile):+ _save_credentials({k: v for k, v in env.items() if k not in _OPTION_KEYS and v})+ if target.kind == "skill":+ identifier = str(self.facts[target.name].get("identifier") or target.name)+ return {"profile": profile, "skill": self.installer.install_skill(identifier, force=force)}+ enable = _flag(env.get("enable"), True)+ result = self.installer.install_plugin(target.name, force=force, enable=enable, ref=env.get("ref") or None)+ if not result.get("ok"):+ raise RuntimeError(result.get("error") or "the install failed")+ return {"profile": profile, "enabled": enable, **result}++ # -- the watcher --------------------------------------------------------------------------------++ def observe(self, operation: ConnectionOperation) -> None:+ for target in operation.targets:+ work = self.work.get(target.name)+ if operation.settled or target.state != TargetState.initiated or work is None or not work.done.is_set():+ continue+ self.work.pop(target.name, None)+ if work.error:+ _fail(operation, target, work.error)+ continue+ extra, detail = _installed_row(target, work.outcome)+ _move(operation, target, TargetState.connected, Actor.backend_watcher, detail=detail, **extra)++ def close(self) -> None:+ if self.op_id is not None:+ _RUNNERS.pop(self.op_id, None)++ def _detail(self, exc: Any, target: Target) -> str:+ from agent.redact import redact_sensitive_text++ text = str(exc) or exc.__class__.__name__+ for value in self.approved_env.get(target.name, {}).values():+ if value and len(value) > 3:+ text = text.replace(value, "[REDACTED]")+ return redact_sensitive_text(text, force=True) or "error"+++def target_declared_env(fact: Any) -> List[str]:+ caps = getattr(fact, "capabilities", None)+ return list(getattr(caps, "requires_env", None) or ())+++def _plugin_row(entry: Any) -> Dict[str, Any]:+ requirements = [f"Hermes {entry.requires_hermes}"] if entry.requires_hermes else []+ requirements += [f"{name} environment variable" for name in entry.capabilities.requires_env]+ row: Dict[str, Any] = {+ "display": _display(entry.name),+ "description": _first_sentence(entry.description),+ "tier": entry.tier if entry.tier in _TIERS else "community",+ "repo": entry.repo,+ "sha": entry.sha,+ "requirements": requirements,+ "has_desktop_half": False,+ "target_profile": DEFAULT_PROFILE,+ }+ if entry.platforms:+ row["platforms"] = list(entry.platforms)+ if entry.subdir:+ row["subdir"] = entry.subdir+ return row+++def _installed_row(target: Target, outcome: Dict[str, Any]) -> tuple:+ """The connected row's fields (the drawn row plus what went live) and its one-line detail."""+ extra = {**target.extra, "target_profile": outcome["profile"]}+ if target.kind == "skill":+ return {**extra, "skill": outcome["skill"], "tools": []}, ""+ live = (outcome.get("activation") or {}).get("live_now") or {}+ servers = live.get("mcp_servers") or []+ tools = [name for server in servers if server.get("connected") for name in server.get("tools") or ()]+ notes = [f"MCP server {s['name']} not connected: {s.get('error') or 'unknown error'}"+ for s in servers if not s.get("connected")]+ if not outcome.get("enabled", True):+ notes.append("installed but not enabled")+ if outcome.get("missing_env"):+ notes.append(f"set {', '.join(outcome['missing_env'])} to finish setup")+ skills = [s["name"] for s in live.get("skills") or () if s.get("name")]+ if skills:+ extra["skill"] = skills[0]+ return {**extra, "tools": tools}, "; ".join(notes)+++def _save_credentials(env: Dict[str, str]) -> None:+ from hermes_cli.config import save_env_value, validate_env_var_name_for_write++ for key, value in env.items():+ validate_env_var_name_for_write(key)+ save_env_value(key, value)+++# op_id -> the runner driving it, so the card's answer (RPC thread) finds the work.+_RUNNERS: Dict[str, _Runner] = {}+++def owns(op_id: str) -> bool:+ return op_id in _RUNNERS+++def apply_answer(operation: ConnectionOperation, raw: str) -> None:+ """The card's ``connection.respond`` for a catalog operation: skip, approve (with the Advanced+ values or null for defaults), approve again on a failed row (Try again), and Continue."""+ try:+ answer = json.loads(raw)+ except (TypeError, ValueError):+ answer = {}+ answer = answer if isinstance(answer, dict) else {}+ runner = _RUNNERS.get(operation.op_id)+ for entry in answer.get("targets") or ():+ if not isinstance(entry, dict):+ continue+ target = operation.target(str(entry.get("name") or "").strip())+ if target is None:+ continue+ status = str(entry.get("status") or "").lower()+ if status == "skipped":+ try:+ operation.transition(target.name, TargetState.skipped, Actor.user)+ except IllegalTransition:+ if not target.resolved and not operation.settled:+ raise+ elif status == "approved" and runner is not None and target.state in (TargetState.pending, TargetState.failed):+ env = entry.get("env")+ runner.approve(operation, target, {str(k): str(v) for k, v in env.items()} if isinstance(env, dict) else None)+ if answer.get("settled_by") == SettleReason.continue_.value and not operation.all_resolved:+ operation.settle(SettleReason.continue_)+++def retry(operation: ConnectionOperation, names: List[str]) -> Optional[str]:+ runner = _RUNNERS.get(operation.op_id)+ if runner is None or operation.settled:+ return "this operation has settled; its result is frozen"+ for name in names:+ target = operation.target(name)+ if target is not None and target.state == TargetState.failed:+ runner.approve(operation, target, None)+ return None+++def open_runner(installer: Optional[HostInstaller] = None) -> _Runner:+ return _Runner(installer or HostInstaller())+++Callback = Callable[[Dict[str, Any]], Optional[str]]diff --git a/tools/connectors/catalog_tool.py b/tools/connectors/catalog_tool.pynew file mode 100644index 00000000000..0cedf41b266--- /dev/null+++ b/tools/connectors/catalog_tool.py@@ -0,0 +1,183 @@+"""``manage_catalog``: the setup agent's catalog search and install-through-the-card.++``search`` reads the plugin catalog (the Plugins tab's resolver) and the skills hub and says what is+already installed in ``default``. ``install`` opens the same connection operation+``manage_connections`` opens, with rows of kind ``plugin`` / ``skill``; the host installs each row+the user approves (``tools/connectors/catalog.py``). The model sends catalog ids and an action,+nothing else: the pin, scan, target profile and activation are the host's.+"""++from __future__ import annotations++import json+from typing import Any, Callable, Dict, List, Optional++from tools.registry import tool_error++ACTIONS = ("search", "install")+ITEM_KINDS = ("plugin", "skill")+_TOP_KEYS = frozenset({"action", "kind", "query", "items", "reason"})+_ITEM_KEYS = frozenset({"kind", "id"})+SEARCH_LIMIT = 10++NOT_HERE = (+ "manage_catalog is available only in the Hermes desktop app, where the approval card can be drawn. "+ "Tell the user to install from a terminal instead: `hermes plugins install <id>` for a plugin, "+ "`hermes skills install <id>` for a skill."+)++NOTE = (+ "Settled once; do not re-offer a row the user skipped. Each installed row names target_profile: "+ "its tools and skills are live now in that profile's open chats and in every new chat of it; "+ "they are callable in this chat only when this chat runs in that profile. A failed row carries "+ "the reason in detail."+)++MANAGE_CATALOG_SCHEMA = {+ "name": "manage_catalog",+ "description": (+ "Find and install Hermes catalog plugins and hub skills for the user. 'search' lists matches "+ "(id, kind, display, tier, platforms, installed) and changes nothing. 'install' shows the user "+ "one approval card with a row per item and blocks until every row is installed, skipped, or "+ "the card is closed; the host installs each approved row into the user's default profile at "+ "the catalog's reviewed version. Pass only catalog ids exactly as 'search' returns them; the "+ "host decides the source, version, profile and settings, and the user can change them on the "+ "card. Offer an install only for something the user asked for or agreed to."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "action": {"type": "string", "enum": list(ACTIONS)},+ "kind": {"type": "string", "enum": list(ITEM_KINDS),+ "description": "search only: limit results to plugins or skills."},+ "query": {"type": "string", "description": "search only: words to match; empty lists plugins."},+ "items": {+ "type": "array",+ "description": "install only: the catalog items to offer, one card row each.",+ "items": {+ "type": "object",+ "properties": {+ "kind": {"type": "string", "enum": list(ITEM_KINDS)},+ "id": {"type": "string", "description": "Catalog id as 'search' returns it."},+ },+ "required": ["kind", "id"],+ "additionalProperties": False,+ },+ },+ "reason": {"type": "string", "description": "install only: one line on why these are offered."},+ },+ "required": ["action"],+ "additionalProperties": False,+ },+}+++def _check_args(args: Dict[str, Any]) -> Optional[str]:+ unknown = sorted(set(args) - _TOP_KEYS)+ if unknown:+ return (f"unknown parameter(s) {', '.join(unknown)}: manage_catalog takes action, kind, query, "+ "items and reason. The host decides source, version, profile and settings.")+ if args.get("action") not in ACTIONS:+ return f"action must be one of {', '.join(ACTIONS)}."+ if args.get("kind") not in (None, *ITEM_KINDS):+ return f"kind must be one of {', '.join(ITEM_KINDS)}."+ if args["action"] == "search":+ return None+ items = args.get("items")+ if not isinstance(items, list) or not items:+ return "install needs 'items': [{\"kind\": \"plugin\", \"id\": \"<catalog id>\"}, ...]."+ for item in items:+ if not isinstance(item, dict):+ return "every item is an object {kind, id}."+ extra = sorted(set(item) - _ITEM_KEYS)+ if extra:+ return (f"unknown item field(s) {', '.join(extra)}: an item is {{kind, id}}. The host decides "+ "source, version, profile and settings.")+ if item.get("kind") not in ITEM_KINDS or not str(item.get("id") or "").strip():+ return "every item needs kind (plugin or skill) and a non-empty id."+ return None+++def manage_catalog(+ args: Dict[str, Any],+ *,+ session_id: Optional[str] = None,+ tool_call_id: Optional[str] = None,+ connection_callback: Optional[Callable[[Dict[str, Any]], Optional[str]]] = None,+ card_surface: bool = False,+ installer: Any = None,+) -> str:+ """``card_surface``: the session is a desktop chat, the one surface that draws catalog rows."""+ error = _check_args(args)+ if error:+ return tool_error(error)+ if connection_callback is None or not card_surface:+ return tool_error(NOT_HERE)+ if args["action"] == "search":+ return json.dumps(search(str(args.get("query") or ""), args.get("kind"), installer=installer),+ ensure_ascii=False)+ return install(args["items"], session_id=session_id, tool_call_id=tool_call_id,+ connection_callback=connection_callback, installer=installer)+++def install(items: List[Dict[str, str]], *, session_id: Optional[str], tool_call_id: Optional[str],+ connection_callback: Callable[[Dict[str, Any]], Optional[str]], installer: Any = None) -> str:+ from tools.connectors.catalog import open_runner+ from tools.connectors.gateway.config import operation_session_key+ from tools.connectors.operation import Target+ from tools.connectors.run import Kind, run_operation++ seen, targets = set(), []+ for item in items:+ key = (item["kind"], str(item["id"]).strip())+ if key not in seen:+ seen.add(key)+ targets.append(Target(name=key[1], kind=key[0], action="install"))+ runner = open_runner(installer)+ try:+ return run_operation(+ targets, Kind(prepare=runner.prepare, observe=runner.observe, note=NOTE),+ session_key=operation_session_key(session_id), tool_call_id=tool_call_id,+ connection_callback=connection_callback, with_urls_in_result=False,+ )+ finally:+ runner.close()+++def search(query: str, kind: Optional[str], *, installer: Any = None) -> Dict[str, Any]:+ from tools.connectors.catalog import DEFAULT_PROFILE, target_scope++ rows: List[Dict[str, Any]] = []+ with target_scope(DEFAULT_PROFILE):+ if kind in (None, "plugin"):+ rows += _plugin_rows(query)+ if kind in (None, "skill") and query.strip():+ rows += _skill_rows(query)+ return {"results": rows, "installed_in": DEFAULT_PROFILE}+++def _plugin_rows(query: str) -> List[Dict[str, Any]]:+ from hermes_cli.plugin_catalog import filter_entries, load_catalog_live+ from hermes_cli.plugins_cmd import PluginOperationError, _read_install_metadata+ from tools.connectors.catalog import _display++ try:+ installed = {str(rec["catalog"]["name"]) for rec in _read_install_metadata().values()+ if isinstance(rec, dict) and isinstance(rec.get("catalog"), dict) and rec["catalog"].get("name")}+ except PluginOperationError:+ installed = set()+ return [{"id": e.name, "kind": "plugin", "display": _display(e.name), "tier": e.tier,+ "platforms": list(e.platforms), "installed": e.name in installed}+ for e in filter_entries(load_catalog_live(), query)[:SEARCH_LIMIT]]+++def _skill_rows(query: str) -> List[Dict[str, Any]]:+ from tools.skills_hub import HubLockFile+ from tools.skills_hub_github import GitHubAuth+ from tools.skills_hub_search import create_source_router, unified_search++ installed = {str(e.get("identifier")) for e in HubLockFile().list_installed()}+ return [{"id": r.identifier, "kind": "skill", "display": r.name,+ "tier": "official" if r.source == "official" else "community", "platforms": [],+ "installed": r.identifier in installed}+ for r in unified_search(query, create_source_router(GitHubAuth()), limit=SEARCH_LIMIT)]diff --git a/tools/connectors/contract.py b/tools/connectors/contract.pyindex 696f38f2dea..cc45e12ece0 100644--- a/tools/connectors/contract.py+++ b/tools/connectors/contract.py@@ -33,7 +33,7 @@ class SettleReason(str, Enum):interrupt = "interrupt"-KINDS: Tuple[str, ...] = ("connector", "mcp")+KINDS: Tuple[str, ...] = ("connector", "mcp", "plugin", "skill")RESOLVED_STATES = frozenset({TargetState.connected, TargetState.skipped})@@ -53,6 +53,12 @@ TRANSITIONS: Dict[Tuple[str, TargetState], Dict[TargetState, Actor]] = {("mcp", _S.initiated): {_S.connected: _A.backend_watcher, _S.failed: _A.backend_watcher, _S.skipped: _A.user},("mcp", _S.failed): {_S.initiated: _A.user, _S.skipped: _A.user},}+# ``manage_catalog`` rows install like an MCP entry: approve starts the host's install, the install+# worker witnesses ``connected``, Try again re-runs a failed row.+for _kind in ("plugin", "skill"):+ for (_k, _from), _edges in list(TRANSITIONS.items()):+ if _k == "mcp":+ TRANSITIONS[(_kind, _from)] = dict(_edges)def allowed(kind: str, current: TargetState, to: TargetState) -> Optional[Actor]:diff --git a/tools/connectors/run.py b/tools/connectors/run.pyindex cce49af2d18..4c92c31c3ea 100644--- a/tools/connectors/run.py+++ b/tools/connectors/run.py@@ -61,9 +61,19 @@ def reissue(operation: ConnectionOperation, names: Sequence[str]) -> Optional[stmint(managed_client(), operation, stale, reinitiate=True, actor=Actor.user)return None+ from tools.connectors import catalogfrom tools.connectors.mcp import retry- return REFUSED if retry(operation, stale) else None+ rerun = catalog.retry if catalog.owns(operation.op_id) else retry+ return REFUSED if rerun(operation, stale) else None+++def apply_answer(operation: ConnectionOperation, raw: str) -> None:+ """Hand the card's answer to the module running this operation (a catalog install or an MCP+ one); a managed operation's card only skips and continues, which the MCP fold also covers."""+ from tools.connectors import catalog, mcp++ (catalog.apply_answer if catalog.owns(operation.op_id) else mcp.apply_answer)(operation, raw)def run_operation(diff --git a/tools/connectors/tool.py b/tools/connectors/tool.pyindex efb62ee673a..dce527280c5 100644--- a/tools/connectors/tool.py+++ b/tools/connectors/tool.py@@ -6,6 +6,7 @@ Disconnecting accounts remains a portal-only user decision.from typing import Any, Callable, Dict, Optional+from tools.connectors.catalog_tool import MANAGE_CATALOG_SCHEMA, manage_catalogfrom tools.connectors.gateway import config as gateway_configfrom tools.connectors.managed import run_managed_actionfrom tools.connectors.mcp import run_mcp_operation@@ -143,3 +144,13 @@ registry.register(check_fn=lambda: gateway_config.connectors_available(),emoji="π",)++# The setup profile's catalog install. Reachable only through the ``setup`` toolset, which the+# profile's role grants; registry dispatch has no card callback, so it answers with the CLI pointer.+registry.register(+ name="manage_catalog",+ toolset="setup",+ schema=MANAGE_CATALOG_SCHEMA,+ handler=lambda args, **kw: manage_catalog(args, session_id=kw.get("session_id")),+ emoji="π§©",+)diff --git a/tools/tool_search.py b/tools/tool_search.pyindex 16e0d7188d3..5c5a6ec7fd4 100644--- a/tools/tool_search.py+++ b/tools/tool_search.py@@ -134,8 +134,10 @@ def _core_tool_names() -> frozenset[str]:# Session-gated GUI toolsets: off ``_HERMES_CORE_TOOLS`` so non-GUI clients never pay-# their schema; once enabled they stay direct unless the deferral list names them.-_DIRECT_SURFACE_TOOLSETS = frozenset({"desktop_ui", "project"})+# their schema; once enabled they stay direct unless the deferral list names them. ``setup``+# is the setup profile's whole job: a guide that has to search for its one tool first+# answers the user's install request with a tool_search round trip.+_DIRECT_SURFACE_TOOLSETS = frozenset({"desktop_ui", "project", "setup"})# Event-triggered tools deferred BY DEFAULT (a catalog stub suffices). Keep the curated# list in DEFAULT_CONFIG so config discovery and runtime behavior cannot drift. An explicitdiff --git a/toolsets.py b/toolsets.pyindex 5d031fe418f..289003182ca 100644--- a/toolsets.py+++ b/toolsets.py@@ -149,7 +149,7 @@ TOOLSETS = {"setup": _ts("Onboarding-only surface for the setup profile: catalog plugin/skill install ""requests through the approval card",- [],+ ["manage_catalog"],role="setup",),"clarify": _ts("Ask the user clarifying questions (multiple-choice or open-ended)", ["clarify"]),diff --git a/tui_gateway/methods_connectors.py b/tui_gateway/methods_connectors.pyindex 7d062530951..ab583a251d6 100644--- a/tui_gateway/methods_connectors.py+++ b/tui_gateway/methods_connectors.py@@ -372,8 +372,8 @@ def _(rid, params):def _apply_connection_answer(rid, answer, operation):from tools.connectors import livefrom tools.connectors.contract import SettleReason- from tools.connectors.mcp import apply_answerfrom tools.connectors.operation import IllegalTransition+ from tools.connectors.run import apply_answerfrom tui_gateway.contracts.connectors import ConnectorErrorReasontry:diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.mdindex b1e2b6ddd5a..e15adfb6582 100644--- a/website/docs/reference/tools-reference.md+++ b/website/docs/reference/tools-reference.md@@ -64,6 +64,7 @@ One tool for both kinds of external app. A target is a managed connector (`"gmai| Tool | Description | Requires environment ||------|-------------|----------------------|+| `manage_catalog` | Setup profile only (the `setup` toolset), desktop chat only. `search` lists catalog plugins and hub skills matching `query` (optionally one `kind`) with `id`, `kind`, `display`, `tier`, `platforms` and `installed` (present in the `default` profile); it changes nothing. `install` takes `items: [{kind, id}]` and shows one approval card with a row per item (Install, Advanced, Skip); an id the catalog does not know, or a plugin this OS cannot run, is drawn failed with the reason. An approved row installs into `default` (or the profile chosen under Advanced) at the catalog's reviewed commit, with the same kill list, security scan and live activation as the Plugins tab, so the plugin's MCP tools and skills are usable in that profile's open chats at once. The result lists each row as `connected` (with `tools` and `skill`), `skipped`, `failed` (with `detail`) or `not_connected`. The model cannot pass a source, commit, profile or setting. Anywhere else the call returns the `hermes plugins install` / `hermes skills install` command to run instead. | β || `manage_connections` | Managed actions: `status`, `connect`, `reconnect` (repairs only what is not connected; `force: true` restarts a working one). MCP actions, for `mcp: true` targets only: `install` a catalog entry, `enable` a disabled configured server, `authorize` (OAuth). In the desktop app, the terminal UI and the classic CLI every action shows a card and blocks until each target is connected, skipped, or the 300-second deadline passes; the result lists targets as `connected`, `skipped` or `not_connected` and carries no link. An MCP `install` collects the entry's setup values in the card, runs the entry's OAuth from the card when it has one (the user opens the link; nothing opens by itself), and saves configuration, tokens and values together when the server accepts the token. A connected MCP target carries `tools` (the registered names) and `tools_listing`, and those tools are callable through `tool_describe`/`tool_call` in the same turn. A target with `discovery_error` is authorized but its tools could not be listed; call `install` or `authorize` for it again to retry discovery without new consent. On surfaces with no card (messaging, scripted dispatch) managed targets return a `connect_url` per app for the user to open, and an MCP target runs at once: `authorize` and an OAuth `install` return the authorization URL, other installs and `enable` report the outcome, and a missing credential comes back as `failed` naming the variable to set. Cannot disconnect or revoke an account. | β |The deadline for one call is five minutes, fixed by the backend when the call starts;diff --git a/website/docs/reference/toolsets-reference.md b/website/docs/reference/toolsets-reference.mdindex 03b34044a83..889b7a4d7dd 100644--- a/website/docs/reference/toolsets-reference.md+++ b/website/docs/reference/toolsets-reference.md@@ -77,7 +77,7 @@ Or in-session:| `safe` | `image_generate`, `vision_analyze`, `web_extract`, `web_search` (via `includes`) | Read-only research + media generation. No file writes, no terminal, no code execution. || `search` | `web_search` | Web search only (without extract). || `session_search` | `session_search` | Search past conversation sessions. |-| `setup` | (none yet) | Onboarding-only surface of the desktop setup profile (catalog install requests through the approval card). Granted by the backend to sessions whose profile carries `role: setup` in its `profile.yaml`; stripped from every other profile even when a config list, `HERMES_TUI_TOOLSETS`, or `all` names it. Not configurable and not listed by `hermes tools`. |+| `setup` | `manage_catalog` | Onboarding-only surface of the desktop setup profile: search the plugin catalog and skills hub, and install items through the approval card. Granted by the backend to sessions whose profile carries `role: setup` in its `profile.yaml`; stripped from every other profile even when a config list, `HERMES_TUI_TOOLSETS`, or `all` names it. Not configurable and not listed by `hermes tools`. || `skills` | `skill_manage`, `skill_view`, `skills_list` | Skill CRUD and browsing. || `spotify` | `spotify_albums`, `spotify_devices`, `spotify_library`, `spotify_playback`, `spotify_playlists`, `spotify_queue`, `spotify_search` | Native Spotify control (playback, queue, search, playlists, albums, library). Registered by the bundled `spotify` plugin. || `terminal` | `process_manage`, `terminal` | Shell command execution and background process management. |diff --git a/website/docs/user-guide/features/plugin-catalog.md b/website/docs/user-guide/features/plugin-catalog.mdindex 7734c442692..928e599b763 100644--- a/website/docs/user-guide/features/plugin-catalog.md+++ b/website/docs/user-guide/features/plugin-catalog.md@@ -32,6 +32,10 @@ The catalog complements β it does not replace β the existingnormal plugin under the hood; the catalog just adds discovery and a reviewlayer on top.+During desktop onboarding, the setup guide can also offer catalog plugins and skills through an+approval card. Each row installs into your `default` profile only when you click Install, at the+same reviewed commit this page describes.+## What's in an entryEach catalog entry is a small YAML file in the