The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): catalog deep links ask the backend for the entry
Brooklyn Nicholsond8e94b5694c5
diff --git a/apps/desktop/src/lib/plugin-catalog.test.ts b/apps/desktop/src/lib/plugin-catalog.test.tsnew file mode 100644index 00000000000..88562c9f614--- /dev/null+++ b/apps/desktop/src/lib/plugin-catalog.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it, vi } from 'vitest'++import { type CatalogRequest, lookupPluginCatalogEntry } from './plugin-catalog'++const SHA = 'a'.repeat(40)++const replying =+ (reply: unknown): CatalogRequest =>+ async <T>() =>+ reply as T++const noFetch = vi.fn(async () => {+ throw new Error('the renderer must not fetch the docs host when the backend answers')+}) as unknown as typeof fetch++describe('lookupPluginCatalogEntry', () => {+ it('asks the backend, not the docs host (its 301 has no CORS header)', async () => {+ const calls: [string, Record<string, unknown>][] = []+ const found = { name: 'aihubmix', repo: 'https://github.com/AIhubmix/mono', sha: SHA, subdir: 'aihubmix' }++ const request: CatalogRequest = async <T>(method: string, params: Record<string, unknown>) => {+ calls.push([method, params])++ return { status: 'found', entry: found } as T+ }++ await expect(lookupPluginCatalogEntry(' aihubmix ', { fetchImpl: noFetch, request })).resolves.toEqual({+ ok: true,+ entry: { name: 'aihubmix', repo: 'https://github.com/AIhubmix/mono', sha: SHA, subdir: 'aihubmix' }+ })+ expect(calls).toEqual([['plugins.catalog.lookup', { name: 'aihubmix' }]])+ expect(noFetch).not.toHaveBeenCalled()+ })++ it.each([+ [{ status: 'unknown' }, 'unknown'],+ [{ status: 'invalid_name' }, 'invalid_name'],+ [{ status: 'unavailable' }, 'unavailable'],+ [{ status: 'found', entry: { name: 'x' } }, 'unavailable'],+ [{ status: 'something-new' }, 'unavailable']+ ] as const)('backend %j → %s, with no fetch', async (reply, error) => {+ await expect(+ lookupPluginCatalogEntry('weather', { fetchImpl: noFetch, request: replying(reply) })+ ).resolves.toEqual({+ ok: false,+ error+ })+ })++ it('refuses a non-catalog name before asking anyone', async () => {+ const asked: string[] = []++ const request: CatalogRequest = async <T>(method: string) => {+ asked.push(method)++ return { status: 'found' } as T+ }++ await expect(lookupPluginCatalogEntry('../etc', { fetchImpl: noFetch, request })).resolves.toEqual({+ ok: false,+ error: 'invalid_name'+ })+ expect(asked).toEqual([])+ })++ it('falls back to the direct feed only when the backend cannot answer', async () => {+ const feed = [{ name: 'weather', repo: 'https://github.com/x/weather', sha: SHA, subdir: '' }]+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify(feed))) as unknown as typeof fetch++ const request: CatalogRequest = async () => {+ throw new Error('method not found: plugins.catalog.lookup')+ }++ await expect(lookupPluginCatalogEntry('weather', { fetchImpl, request })).resolves.toMatchObject({+ ok: true,+ entry: { name: 'weather', repo: 'https://github.com/x/weather' }+ })+ expect(fetchImpl).toHaveBeenCalledTimes(1)+ })+})diff --git a/apps/desktop/src/lib/plugin-catalog.ts b/apps/desktop/src/lib/plugin-catalog.tsindex 5ebcbfcb7de..dfb786ebdc2 100644--- a/apps/desktop/src/lib/plugin-catalog.ts+++ b/apps/desktop/src/lib/plugin-catalog.ts@@ -8,10 +8,18 @@* deep link resolves against the SAME document so a link and an in-app pick* always agree on the repo, subdir and reviewed pin for a name.*+ * The lookup asks the backend (`plugins.catalog.lookup`), which reads the live+ * catalog with its cache, kill list and in-tree fallback. The renderer can't+ * fetch the JSON itself: the docs host answers with a cross-origin 301 that+ * carries no CORS header, so the browser rejects it (hermes-agent 136483). Only+ * a backend that predates the method falls back to the direct fetch.+ ** Everything here only classifies — nothing installs. Callers open the Install* Plugin dialog, which still requires the user's explicit confirmation.*/+import { activeGatewayProfileKey, requestGatewayForProfile } from '@/store/gateway'+export const CATALOG_ORIGIN = 'https://hermes-agent.nousresearch.com'export const CATALOG_PICKER_URL = `${CATALOG_ORIGIN}/docs/plugins?embed=picker`export const PLUGIN_CATALOG_URL = `${CATALOG_ORIGIN}/docs/api/plugins.json`@@ -20,6 +28,7 @@ export const PLUGIN_CATALOG_URL = `${CATALOG_ORIGIN}/docs/api/plugins.json`export const PLUGIN_CATALOG_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/const FETCH_TIMEOUT_MS = 15_000+const LOOKUP_TIMEOUT_MS = 20_000/** The fields an install needs — the same ones the embedded picker posts on a pick. */export interface PluginCatalogEntry {@@ -55,21 +64,18 @@ function asEntry(raw: unknown): null | PluginCatalogEntry {}}-/**- * Look one name up in the live catalog. Unknown names are a hard `unknown`,- * never a guess: the deep link must not turn an arbitrary string into a git- * identifier the dialog would then clone.- */-export async function lookupPluginCatalogEntry(- name: string,- fetchImpl: typeof fetch = (...args) => fetch(...args)-): Promise<PluginCatalogLookup> {- const trimmed = name.trim()+/** A gateway RPC, as `requestGatewayForProfile` sends it for the active profile. */+export type CatalogRequest = <T>(method: string, params: Record<string, unknown>) => Promise<T>- if (!PLUGIN_CATALOG_NAME_RE.test(trimmed)) {- return { ok: false, error: 'invalid_name' }- }+interface CatalogLookupReply {+ entry?: unknown+ status?: string+}++const activeProfileRequest: CatalogRequest = (method, params) =>+ requestGatewayForProfile(activeGatewayProfileKey(), method, params, LOOKUP_TIMEOUT_MS)+async function lookupFromFeed(name: string, fetchImpl: typeof fetch): Promise<PluginCatalogLookup> {let rows: unknowntry {@@ -92,7 +98,46 @@ export async function lookupPluginCatalogEntry(}// Catalog names are directory names and the CLI treats them case-sensitively.- const match = rows.map(asEntry).find(entry => entry?.name === trimmed)+ const match = rows.map(asEntry).find(entry => entry?.name === name)return match ? { ok: true, entry: match } : { ok: false, error: 'unknown' }}++/**+ * Look one name up in the live catalog. Unknown names are a hard `unknown`,+ * never a guess: the deep link must not turn an arbitrary string into a git+ * identifier the dialog would then clone. The backend answers; a backend that+ * can't (older than the method, or unreachable) falls back to the direct fetch.+ */+export async function lookupPluginCatalogEntry(+ name: string,+ {+ fetchImpl = (...args) => fetch(...args),+ request = activeProfileRequest+ }: { fetchImpl?: typeof fetch; request?: CatalogRequest } = {}+): Promise<PluginCatalogLookup> {+ const trimmed = name.trim()++ if (!PLUGIN_CATALOG_NAME_RE.test(trimmed)) {+ return { ok: false, error: 'invalid_name' }+ }++ let reply: CatalogLookupReply++ try {+ reply = await request<CatalogLookupReply>('plugins.catalog.lookup', { name: trimmed })+ } catch {+ return lookupFromFeed(trimmed, fetchImpl)+ }++ if (reply.status === 'found') {+ const entry = asEntry(reply.entry)++ return entry ? { ok: true, entry } : { ok: false, error: 'unavailable' }+ }++ return {+ ok: false,+ error: reply.status === 'unknown' || reply.status === 'invalid_name' ? reply.status : 'unavailable'+ }+}diff --git a/apps/desktop/src/store/plugin-catalog-install.test.ts b/apps/desktop/src/store/plugin-catalog-install.test.tsindex 1032e1bec37..7c93786b137 100644--- a/apps/desktop/src/store/plugin-catalog-install.test.ts+++ b/apps/desktop/src/store/plugin-catalog-install.test.ts@@ -1,7 +1,7 @@// @vitest-environment jsdomimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { PLUGIN_CATALOG_URL, type PluginCatalogLookup } from '@/lib/plugin-catalog'+import { lookupPluginCatalogEntry, PLUGIN_CATALOG_URL, type PluginCatalogLookup } from '@/lib/plugin-catalog'import { $agentPlugins } from './agent-plugins'import { $notifications } from './notifications'@@ -58,20 +58,27 @@ describe('requestPluginCatalogInstallFromDeepLink', () => {expect(toasts[0]?.message).toContain(fragment)})- it('resolves against the live catalog feed by default and rejects unknown names', async () => {+ it('falls back to the live catalog feed on a backend without the lookup, and rejects unknown names', async () => {const feed = JSON.stringify([{ name: 'weather', repo: 'https://github.com/x/weather', sha: 'a'.repeat(40), subdir: '' }])const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response(feed, { status: 200 }))- await requestPluginCatalogInstallFromDeepLink('weather-evil')+ const lookup = (name: string) =>+ lookupPluginCatalogEntry(name, {+ request: async () => {+ throw new Error('method not found')+ }+ })++ await requestPluginCatalogInstallFromDeepLink('weather-evil', lookup)expect(fetchSpy).toHaveBeenCalledWith(PLUGIN_CATALOG_URL, expect.anything())expect($pluginInstallRequest.get()).toBeNull()expect($notifications.get()[0]?.message).toContain('\u201Cweather-evil\u201D is not in the Hermes plugin catalog')- await requestPluginCatalogInstallFromDeepLink('weather')+ await requestPluginCatalogInstallFromDeepLink('weather', lookup)expect($pluginInstallRequest.get()).toMatchObject({ catalogName: 'weather', repo: 'https://github.com/x/weather' })})diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 7e852135f57..08f069789b1 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4441,6 +4441,23 @@ export interface OnboardingCatalogPlugin {app_state: CatalogAppStatesentence: string}+export interface PluginCatalogLookupParams {+ profile?: string | null+ name: string+}+/** ``found`` carries ``entry``. ``unknown`` covers a name the catalog doesn't list and one it removed; ``unavailable`` means neither the live catalog nor the in-tree fallback could be read. */+export interface PluginCatalogLookupResult {+ status: PluginCatalogLookupStatus+ entry?: PluginCatalogLookupEntry | null+}+export type PluginCatalogLookupStatus = 'found' | 'invalid_name' | 'unknown' | 'unavailable'+/** The fields an install needs: the same ones the embedded catalog picker posts on a pick. */+export interface PluginCatalogLookupEntry {+ name: string+ repo: string+ sha: string+ subdir: string+}/** ``answers`` rides only on a reconnect replay (locks the server already accepted; null = skipped). */export interface ClarifyRequestParams {session_id: string@@ -5281,6 +5298,8 @@ export interface RpcMethods {'pet.thumb': { params: PetThumbParams; result: PetThumbResult }/** Cheapest liveness probe; answered on the WS reader thread even while every agent is mid-turn. */ping: { params: PingParams; result: PingResult }+ /** One curated plugin-catalog entry by name, from the backend's live catalog (cached, with the in-tree fallback and kill list); backs hermes://plugin/install?catalog= deep links. */+ 'plugins.catalog.lookup': { params: PluginCatalogLookupParams; result: PluginCatalogLookupResult }/** Loaded plugin manager entries (legacy flat view); the Plugins Hub uses plugins.manage list. */'plugins.list': { params: PluginsListParams; result: PluginsListResult }/** Plugins Hub backend: list installed plugins, toggle, git-install, re-pin a catalog install, or remove a user install. */@@ -5665,6 +5684,7 @@ export const RPC_METHODS = ['pet.select','pet.thumb','ping',+ 'plugins.catalog.lookup','plugins.list','plugins.manage','preview.restart',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 8fa3884dd54..d408ccf3c0e 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -2436,6 +2436,24 @@}}},+ {+ "name": "plugins.catalog.lookup",+ "summary": "One curated plugin-catalog entry by name, from the backend's live catalog (cached, with the in-tree fallback and kill list); backs hermes://plugin/install?catalog= deep links.",+ "params": [+ {+ "name": "params",+ "schema": {+ "$ref": "#/components/schemas/PluginCatalogLookupParams"+ }+ }+ ],+ "result": {+ "name": "result",+ "schema": {+ "$ref": "#/components/schemas/PluginCatalogLookupResult"+ }+ }+ },{"name": "plugins.list","summary": "Loaded plugin manager entries (legacy flat view); the Plugins Hub uses plugins.manage list.",@@ -22392,6 +22410,97 @@"title": "PluginActivation","type": "object"},+ "PluginCatalogLookupEntry": {+ "additionalProperties": false,+ "description": "The fields an install needs: the same ones the embedded catalog picker posts on a pick.",+ "properties": {+ "name": {+ "title": "Name",+ "type": "string"+ },+ "repo": {+ "title": "Repo",+ "type": "string"+ },+ "sha": {+ "title": "Sha",+ "type": "string"+ },+ "subdir": {+ "title": "Subdir",+ "type": "string"+ }+ },+ "required": [+ "name",+ "repo",+ "sha",+ "subdir"+ ],+ "title": "PluginCatalogLookupEntry",+ "type": "object"+ },+ "PluginCatalogLookupParams": {+ "additionalProperties": false,+ "properties": {+ "profile": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Profile"+ },+ "name": {+ "title": "Name",+ "type": "string"+ }+ },+ "required": [+ "name"+ ],+ "title": "PluginCatalogLookupParams",+ "type": "object"+ },+ "PluginCatalogLookupResult": {+ "additionalProperties": false,+ "description": "``found`` carries ``entry``. ``unknown`` covers a name the catalog doesn't list and one it removed;\n``unavailable`` means neither the live catalog nor the in-tree fallback could be read.",+ "properties": {+ "status": {+ "$ref": "#/components/schemas/PluginCatalogLookupStatus"+ },+ "entry": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/PluginCatalogLookupEntry"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ }+ },+ "required": [+ "status"+ ],+ "title": "PluginCatalogLookupResult",+ "type": "object"+ },+ "PluginCatalogLookupStatus": {+ "enum": [+ "found",+ "invalid_name",+ "unknown",+ "unavailable"+ ],+ "title": "PluginCatalogLookupStatus",+ "type": "string"+ },"PluginLiveNow": {"additionalProperties": false,"properties": {diff --git a/tests/tui_gateway/test_plugins_catalog_lookup.py b/tests/tui_gateway/test_plugins_catalog_lookup.pynew file mode 100644index 00000000000..c84a50c6de3--- /dev/null+++ b/tests/tui_gateway/test_plugins_catalog_lookup.py@@ -0,0 +1,58 @@+"""``plugins.catalog.lookup``: the deep link's catalog lookup, resolved by the backend (hermes-agent 136483)."""++import pytest++from hermes_cli import plugin_catalog as pc+from tui_gateway import server++SHA = "a" * 40+++def _entry(name, repo=None, subdir=""):+ return pc.entry_from_mapping({"name": name, "repo": repo or f"https://github.com/fx/{name}", "sha": SHA,+ "description": "d.", "maintainer": "fx", "subdir": subdir}, name)+++def _lookup(name, **extra):+ resp = server.handle_request({"id": "1", "method": "plugins.catalog.lookup", "params": {"name": name, **extra}})+ assert "error" not in resp, resp+ return resp["result"]+++def catalog(monkeypatch):+ entries = [_entry("weather"), _entry("aihubmix", "https://github.com/AIhubmix/mono", subdir="aihubmix"),+ _entry("pulled")]+ monkeypatch.setattr(pc, "load_catalog_live", lambda: entries)+ monkeypatch.setattr(pc, "load_removed_list", lambda catalog_dir=None: [pc.RemovedEntry(name="pulled")])+ monkeypatch.setattr(pc, "live_removed_list", list)+ return entries+++def test_a_listed_name_returns_what_the_install_dialog_needs(catalog):+ assert _lookup("aihubmix") == {"status": "found", "entry": {+ "name": "aihubmix", "repo": "https://github.com/AIhubmix/mono", "sha": SHA, "subdir": "aihubmix"}}+ assert _lookup(" weather ")["entry"]["subdir"] == ""+++def test_an_unlisted_or_removed_name_is_unknown_never_a_guess(catalog):+ assert _lookup("weather-evil") == {"status": "unknown"}+ assert _lookup("pulled") == {"status": "unknown"} # listed but on the kill list++[email protected]("name", ["", "../etc", "https://github.com/x/y", "Weather", "a" * 65])+def test_anything_but_a_catalog_name_is_invalid(catalog, name):+ assert _lookup(name) == {"status": "invalid_name"}+++def test_an_unreadable_catalog_is_unavailable(monkeypatch):+ monkeypatch.setattr(pc, "load_catalog_live", list) # no live doc, no cache, no in-tree entries+ assert _lookup("weather") == {"status": "unavailable"}+++def test_the_lookup_reads_the_backend_catalog_not_the_docs_redirect(monkeypatch, tmp_path):+ """The live fetch follows the docs host's redirect server-side (httpx, follow_redirects), where CORS+ does not apply; with the network down the in-tree catalog still answers."""+ monkeypatch.setattr(pc, "fetch_live_catalog", lambda force=False: None)+ first = pc.load_catalog()[0]+ assert _lookup(first.name)["entry"]["sha"] == first.shadiff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.pyindex 9e0b8454ee4..a601c689a44 100644--- a/tui_gateway/contracts/tools_mcp_plugins.py+++ b/tui_gateway/contracts/tools_mcp_plugins.py@@ -772,3 +772,36 @@ class PluginsManageResult(Result):method("plugins.manage", params=PluginsManageParams, result=PluginsManageResult,doc="Plugins Hub backend: list installed plugins, toggle, git-install, re-pin a catalog install, ""or remove a user install.")+++class PluginCatalogLookupStatus(WireEnum):+ found = "found"+ invalid_name = "invalid_name"+ unknown = "unknown"+ unavailable = "unavailable"+++class PluginCatalogLookupParams(ProfileParams):+ name: str+++class PluginCatalogLookupEntry(Result):+ """The fields an install needs: the same ones the embedded catalog picker posts on a pick."""++ name: str+ repo: str+ sha: str+ subdir: str+++class PluginCatalogLookupResult(Result):+ """``found`` carries ``entry``. ``unknown`` covers a name the catalog doesn't list and one it removed;+ ``unavailable`` means neither the live catalog nor the in-tree fallback could be read."""++ status: PluginCatalogLookupStatus+ entry: PluginCatalogLookupEntry | None = None+++method("plugins.catalog.lookup", params=PluginCatalogLookupParams, result=PluginCatalogLookupResult,+ doc="One curated plugin-catalog entry by name, from the backend's live catalog (cached, with the "+ "in-tree fallback and kill list); backs hermes://plugin/install?catalog= deep links.")diff --git a/tui_gateway/methods_plugin_catalog.py b/tui_gateway/methods_plugin_catalog.pynew file mode 100644index 00000000000..0ce3530a4e2--- /dev/null+++ b/tui_gateway/methods_plugin_catalog.py@@ -0,0 +1,43 @@+"""``plugins.catalog.lookup``: one curated-catalog entry, resolved by the backend.++The Desktop's ``hermes://plugin/install?catalog=<name>`` deep link used to fetch the docs-site JSON+from the renderer. That URL answers with a cross-origin 301, so the browser's CORS check fails on the+redirect and every link reported the catalog as unreachable (hermes-agent 136483). The backend already+reads the live catalog (cache, failure window, in-tree fallback and kill list), and ``plugins.manage+install {catalog_name}`` resolves the pin from the same place, so the lookup lives here too.++Bodies are rebound onto server.py's globals (method_ctx.bind_module) and reference them bare.+"""++from __future__ import annotations++from .method_ctx import HandlerRegistry, bind_module++_registry = HandlerRegistry()+method = _registry.method+_profile_scoped = _registry.profile_scoped+++@method("plugins.catalog.lookup")+@_profile_scoped+def _(rid, params: dict) -> dict:+ from hermes_cli.plugin_catalog import _NAME_RE, find_removed, load_catalog_live++ name = str(params.get("name") or "").strip()+ if not _NAME_RE.match(name):+ return _ok(rid, {"status": "invalid_name"})+ # The loaders never raise: a dead host falls back to the cache, then to the in-tree catalog.+ # Nothing readable at all is "unavailable", never a guess.+ entries = load_catalog_live()+ if not entries:+ return _ok(rid, {"status": "unavailable"})+ entry = next((e for e in entries if e.name == name), None)+ # A removed name or repo is never offered: install would refuse it anyway.+ if entry is None or find_removed(entry.name) or find_removed(entry.repo):+ return _ok(rid, {"status": "unknown"})+ return _ok(rid, {"status": "found", "entry": {"name": entry.name, "repo": entry.repo, "sha": entry.sha,+ "subdir": entry.subdir}})+++def register(server) -> None:+ bind_module(globals(), server, skip=("_",))diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 5570ab0ba93..44316003ba4 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -184,7 +184,8 @@ _LONG_HANDLERS = frozenset({"subscription.resume", "subscription.upgrade", "usage.bars", "session.usage", "billing.step_up","browser.manage", "cli.exec", "complete.path", "complete.slash", "llm.oneshot", "model.options","pet.cells", "pet.gallery", "pet.generate", "pet.hatch", "pet.info", "pet.select", "pet.thumb",- "learning.frames", "plugins.manage", "reload.mcp", "mcp.servers.test", "mcp.servers.oauth.start",+ "learning.frames", "plugins.manage", "plugins.catalog.lookup", "reload.mcp", "mcp.servers.test",+ "mcp.servers.oauth.start","process.list", "profiles.configure", "profiles.create", "profiles.describe", "profiles.get_asset","profiles.list", "profiles.set_asset", "bot_relay.roster.sync", "bot_relay.outbox.drain","bot_relay.deliver", "bot_relay.reply", "image.generate", "projects.discover_repos",@@ -3676,7 +3677,8 @@ from . import (methods_connectors as _methods_connectors, methods_connectors_account as _methods_connectors_account,methods_display as _methods_display, methods_display_watch as _methods_display_watch,methods_onboarding as _methods_onboarding, methods_i18n as _methods_i18n,- methods_shared_metrics as _methods_shared_metrics, methods_start_chat as _methods_start_chat)+ methods_shared_metrics as _methods_shared_metrics, methods_start_chat as _methods_start_chat,+ methods_plugin_catalog as _methods_plugin_catalog)for _m in (_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,@@ -3688,6 +3690,6 @@ for _m in (_methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign,_methods_session_control, _methods_subagents, _methods_vault, _methods_free_tier, _methods_connectors,_methods_connectors_account, _methods_display, _methods_display_watch, _methods_onboarding,- _methods_i18n, _methods_shared_metrics, _methods_start_chat):+ _methods_i18n, _methods_shared_metrics, _methods_start_chat, _methods_plugin_catalog):_m.register(sys.modules[__name__])del _m