The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): inspect plugin repositories through the gateway
unsupportedpastels3f945df636d1
diff --git a/apps/desktop/src/app/settings/plugin-install-details.tsx b/apps/desktop/src/app/settings/plugin-install-details.tsxindex d26d2c69ac2..18df5d52f0b 100644--- a/apps/desktop/src/app/settings/plugin-install-details.tsx+++ b/apps/desktop/src/app/settings/plugin-install-details.tsx@@ -14,7 +14,8 @@ import {desktopHalfFromPackage,installComponents,type InstallModalCopy,- type ProbeResult+ type ProbeResult,+ skipsDesktopHalf} from './plugin-install-run'const CAPTION = 'text-[length:var(--conversation-caption-font-size)]'@@ -130,6 +131,10 @@ function ContentsRow({components.desktop && {title: [copy.desktopLabel, fromPackage ? null : probe.desktopName].filter(Boolean).join(' · '),hint: fromPackage ? copy.desktopTargetFromPackage : copy.desktopTarget+ },+ skipsDesktopHalf(request, probe) && {+ title: [copy.desktopLabel, probe.desktopName].filter(Boolean).join(' · '),+ hint: copy.desktopUnavailable}].filter(line => line !== false)diff --git a/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsx b/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsxnew file mode 100644index 00000000000..8838531eca0--- /dev/null+++ b/apps/desktop/src/app/settings/plugin-install-modal.browser.test.tsx@@ -0,0 +1,181 @@+import { JsonRpcGatewayError } from '@hermes/shared'+import { QueryClientProvider } from '@tanstack/react-query'+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import { MemoryRouter } from 'react-router'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// The browser-hosted app: no Electron preload, so no `window.hermesDesktop.probePluginRepo` and no+// `installDesktopPlugin`. Inspection and install both ride the gateway.+const { requestGateway } = vi.hoisted(() => ({+ requestGateway: vi.fn(async (_method: string, _params?: Record<string, unknown>): Promise<unknown> => ({+ plugins: []+ }))+}))++vi.mock('@/app/gateway/hooks/use-gateway-request', () => ({+ useGatewayRequest: () => ({ requestGateway })+}))+vi.mock('@/hermes', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getProfiles: async () => ({ profiles: [] })+}))++import { queryClient } from '@/lib/query-client'+import { $notifications } from '@/store/notifications'+import { $pluginInstallRequest, closePluginInstallRequest, openPluginInstallRequest } from '@/store/plugin-install-request'+import { $activeGatewayProfile } from '@/store/profile'+import { $connection, $gatewayState } from '@/store/session'++import { PluginInstallModal } from './plugin-install-modal'++const DELEGATION = {+ catalogName: 'advanced-delegation',+ repo: 'https://github.com/NousResearch/hermes-official-plugins#advanced-delegation',+ sha: 'e404b6816b20237a82f6fbe2749b5a576cf75dba',+ summary: 'Two extra delegation modes for delegate_task.',+ title: 'Advanced Delegation',+ tier: 'official'+}++const UNAVAILABLE = 'Plugin inspection is unavailable in this environment.'+const DESKTOP_UNAVAILABLE = 'Desktop plugin install is unavailable in this environment.'++const callsFor = (action: string) =>+ requestGateway.mock.calls.filter(([method, params]) => method === 'plugins.manage' && params?.action === action)++const installButton = () => screen.queryByRole('button', { name: /^Install/ }) as HTMLButtonElement | null++/** Answer `inspect` with *inspection* (or throw it), `install` with *install*, everything else an empty list. */+const backend = (inspection: unknown, install: unknown = { ok: true, plugin_name: 'advanced-delegation' }) =>+ requestGateway.mockImplementation(async (method, params) => {+ if (method !== 'plugins.manage') {+ return { plugins: [] }+ }++ if (params?.action === 'inspect') {+ if (inspection instanceof Error) {+ throw inspection+ }++ return inspection+ }++ return params?.action === 'install' ? install : { plugins: [] }+ })++const AGENT_ONLY = { ok: true, agent: true, agent_name: 'advanced-delegation', desktop: false, warnings: [] }++const renderModal = () =>+ render(+ <MemoryRouter initialEntries={['/']}>+ <QueryClientProvider client={queryClient}>+ <PluginInstallModal />+ </QueryClientProvider>+ </MemoryRouter>+ )++beforeEach(() => {+ vi.clearAllMocks()+ queryClient.clear()+ closePluginInstallRequest()+ $notifications.set([])+ $gatewayState.set('idle')+ // The browser bridge's connection is always `remote` (browser-connection.ts).+ $connection.set({ mode: 'remote' } as NonNullable<ReturnType<typeof $connection.get>>)+ $activeGatewayProfile.set('default')+ expect(window.hermesDesktop).toBeUndefined()+})+afterEach(() => {+ cleanup()+ closePluginInstallRequest()+})++describe('Plugin install in the browser-hosted app (no window.hermesDesktop)', () => {+ it('inspects the catalog pick through the gateway and installs the agent plugin', async () => {+ backend(AGENT_ONLY)+ renderModal()+ act(() => openPluginInstallRequest(DELEGATION))++ const dialog = await screen.findByRole('dialog', { name: 'Advanced Delegation' })+ await waitFor(() => expect(installButton()?.disabled).toBe(false))+ expect(within(dialog).queryByText(UNAVAILABLE)).toBeNull()+ expect(callsFor('inspect')[0]?.[1]).toMatchObject({+ action: 'inspect',+ identifier: DELEGATION.repo,+ catalog_name: 'advanced-delegation',+ profile: 'default'+ })++ fireEvent.click(installButton()!)++ await waitFor(() => expect($pluginInstallRequest.get()).toBeNull())+ expect(callsFor('install')).toHaveLength(1)+ expect(callsFor('install')[0]?.[1]).toMatchObject({ catalog_name: 'advanced-delegation', enable: true })+ expect($notifications.get().some(n => n.kind === 'warning' && n.message === DESKTOP_UNAVAILABLE)).toBe(false)+ })++ it('says inspection is unavailable, with no Retry, when the backend predates the inspect action', async () => {+ backend(new JsonRpcGatewayError('unknown plugins action: inspect', { code: 4017 }))+ renderModal()+ act(() => openPluginInstallRequest(DELEGATION))++ expect((await screen.findByRole('alert')).textContent).toBe(UNAVAILABLE)+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()+ expect(installButton()).toBeNull()+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeTruthy()+ expect(callsFor('install')).toHaveLength(0)+ })++ it('shows a failed read and retries the inspection', async () => {+ backend({ ok: false, agent: false, desktop: false, warnings: [], error: 'Git clone failed: network down' })+ renderModal()+ act(() => openPluginInstallRequest({ repo: 'https://github.com/example/plugin' }))++ expect((await screen.findByRole('alert')).textContent).toBe('Git clone failed: network down')+ backend({ ok: true, agent: true, agent_name: 'plugin', desktop: false, warnings: [] })+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))++ await waitFor(() => expect(installButton()?.disabled).toBe(false))+ expect(callsFor('inspect')).toHaveLength(2)+ expect(callsFor('install')).toHaveLength(0)+ })++ it('offers Retry after a transient transport failure', async () => {+ backend(new Error('request timed out after 120s: plugins.manage'))+ renderModal()+ act(() => openPluginInstallRequest({ repo: 'https://github.com/example/plugin' }))++ expect((await screen.findByRole('alert')).textContent).toBe('request timed out after 120s: plugins.manage')+ expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()+ })++ it('installs the agent half of a mixed package and reports the desktop half as skipped, not installed', async () => {+ backend(+ { ok: true, agent: true, agent_name: 'pkg', desktop: true, desktop_name: 'pkg', warnings: [] },+ { ok: true, plugin_name: 'pkg', enabled: true }+ )+ renderModal()+ act(() => openPluginInstallRequest({ repo: 'https://github.com/example/pkg' }))++ expect(await screen.findByText(DESKTOP_UNAVAILABLE)).toBeTruthy()+ await waitFor(() => expect(installButton()?.disabled).toBe(false))+ fireEvent.click(installButton()!)++ await waitFor(() => expect($pluginInstallRequest.get()).toBeNull())+ expect(callsFor('install')).toHaveLength(1)+ const notes = $notifications.get()+ expect(notes.some(n => n.kind === 'warning' && n.message === DESKTOP_UNAVAILABLE)).toBe(true)+ expect(notes.some(n => n.kind === 'success' && /desktop/i.test(n.message))).toBe(false)+ })++ it('refuses a desktop-only package without a Retry loop', async () => {+ backend({ ok: true, agent: false, desktop: true, desktop_name: 'ui', warnings: [] })+ renderModal()+ act(() => openPluginInstallRequest({ repo: 'https://github.com/example/ui' }))++ expect((await screen.findByRole('alert')).textContent).toBe('This package has nothing to install here.')+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()+ expect(installButton()).toBeNull()+ expect(callsFor('install')).toHaveLength(0)+ })+})diff --git a/apps/desktop/src/app/settings/plugin-install-modal.tsx b/apps/desktop/src/app/settings/plugin-install-modal.tsxindex 94c07352f20..d996706458d 100644--- a/apps/desktop/src/app/settings/plugin-install-modal.tsx+++ b/apps/desktop/src/app/settings/plugin-install-modal.tsx@@ -21,7 +21,7 @@ import { Input } from '@/components/ui/input'import { useI18n } from '@/i18n'import { AlertTriangle, Loader2 } from '@/lib/icons'import { cn } from '@/lib/utils'-import { COMMIT_SHA_RE } from '@/store/agent-plugins'+import { COMMIT_SHA_RE, inspectAgentPlugin } from '@/store/agent-plugins'import {$pluginInstallRequest,closePluginInstallRequest,@@ -32,7 +32,7 @@ import { $activeGatewayProfile, $profiles, $profileScope, normalizeProfileKey, pimport { $connection } from '@/store/session'import { PluginInstallDetails } from './plugin-install-details'-import { type InstallModalCopy, type ProbeResult, runPluginInstall } from './plugin-install-run'+import { installComponents, type InstallModalCopy, type ProbeResult, runPluginInstall } from './plugin-install-run'import { usePluginProbe } from './use-plugin-probe'const CAPTION = 'text-[length:var(--conversation-caption-font-size)]'@@ -63,9 +63,22 @@ function pluginTitle(request: PluginInstallRequest, probe: null | ProbeResult):return request.title || request.catalogName || probe?.agentName || probe?.desktopName || repoName(request.repo)}-/** The inspection's one-line reason, when it could not read the repository. */+/** The inspection's one-line reason, when it could not read the repository. An environment that cannot+ * inspect at all reads `fallback`, not the transport's wording. */function probeFailure(probe: null | ProbeResult, fallback: string): null | string {- return probe && !probe.ok ? probe.error || fallback : null+ return probe && !probe.ok ? (!probe.unavailable && probe.error) || fallback : null+}++/** A repository read fine but nothing in it can be installed from here (a desktop-only plugin in the+ * browser-hosted app): no retry changes that. */+function nothingInstallable(request: PluginInstallRequest, probe: null | ProbeResult): boolean {+ if (!probe?.ok) {+ return false+ }++ const components = installComponents(request, probe)++ return !components.agent && !components.desktop}function ProbeWarnings({ copy, probe }: { copy: InstallModalCopy; probe: null | ProbeResult }) {@@ -259,10 +272,11 @@ interface InstallFooterProps {installing: booleanonInstall: () => voidonRetry: () => void+ retryable: boolean}-/** Cancel, then Install (one loader while it runs) or, after a failure, Retry. */-function InstallFooter({ canInstall, failed, installing, onInstall, onRetry }: InstallFooterProps) {+/** Cancel, then Install (one loader while it runs) or, after a failure, Retry — unless retrying cannot help. */+function InstallFooter({ canInstall, failed, installing, onInstall, onRetry, retryable }: InstallFooterProps) {const { t } = useI18n()const m = t.settings.plugins.installModal@@ -272,7 +286,7 @@ function InstallFooter({ canInstall, failed, installing, onInstall, onRetry }: I{t.common.cancel}</Button>{failed ? (- <Button onClick={onRetry}>{t.common.retry}</Button>+ retryable && <Button onClick={onRetry}>{t.common.retry}</Button>) : (<Button disabled={!canInstall} onClick={onInstall}>{installing && <Loader2 className="animate-spin" />}@@ -300,12 +314,16 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewProconst profileScope = useStore($profileScope)const verified = Boolean(request.catalogName)const enable = request.enable ?? true- const { probe, start, cancel, settled } = usePluginProbe(m.probeUnavailable)const [targetProfile, setTargetProfile] = useState(() =>normalizeProfileKey(request.profile || activeProfile || profileScope))+ // Without Electron's inspection (the browser-hosted app) the backend clones and reads the repository.+ const { probe, start, cancel, settled } = usePluginProbe(m.probeUnavailable, repo =>+ inspectAgentPlugin(requestGateway, { identifier: repo, catalogName: request.catalogName, profile: targetProfile })+ )+const [advancedOpen, setAdvancedOpen] = useState(!verified)const [force, setForce] = useState(request.force ?? false)const [pinRef, setPinRef] = useState('')@@ -322,8 +340,15 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewProconst targetLabel = profileLabel(targetInfo ?? { name: targetProfile })const pin = pinRef.trim().toLowerCase()const pinInvalid = pin !== '' && !COMMIT_SHA_RE.test(pin)+ const nothing = nothingInstallable(request, probe)+// Hidden while a retry runs, so the loader is the only thing on screen.- const failure = installing ? null : (installError ?? probeFailure(probe, m.probeUnavailable))+ const failure = installing+ ? null+ : (installError ?? probeFailure(probe, m.probeUnavailable) ?? (nothing ? m.nothingToInstall : null))++ // Retrying reruns an install or a read that failed; it cannot add a capability this environment lacks.+ const retryable = Boolean(installError) || !(probe?.unavailable || nothing)const line = `${verified ? m.reviewedByNous : m.securityIntro} ${(enable ? m.installsAndEnables : m.installsOnly)(targetLabel)}`const install = async () => {@@ -410,6 +435,7 @@ function InstallView({ request, installing, onInstallingChange }: InstallViewProinstalling={installing}onInstall={() => void install()}onRetry={retry}+ retryable={retryable}/></>)diff --git a/apps/desktop/src/app/settings/plugin-install-run.ts b/apps/desktop/src/app/settings/plugin-install-run.tsindex 538592bc92a..dce723694ca 100644--- a/apps/desktop/src/app/settings/plugin-install-run.ts+++ b/apps/desktop/src/app/settings/plugin-install-run.ts@@ -26,10 +26,28 @@ const HINT_COMPONENTS = {desktop: probe => ({ agent: false, desktop: probe.desktop })} satisfies Record<'agent' | 'both' | 'desktop', (probe: ProbeResult) => InstallComponents>+/** Whether this app can put a desktop half down. Native Desktop clones or copies one; the browser-hosted+ * app has no disk of its own and its server materialises none, so there a package installs its agent+ * half alone. */+export function desktopInstallSupported(): boolean {+ return Boolean(window.hermesDesktop?.installDesktopPlugin)+}+/** What an install puts down: every half the repository has, narrowed by a legacy deep link or by- * "install the agent half here" (whose desktop half is already loaded). */-export function installComponents(request: PluginInstallRequest, probe: ProbeResult): InstallComponents {- return HINT_COMPONENTS[request.legacyHint ?? 'both'](probe)+ * "install the agent half here" (whose desktop half is already loaded), and by what this app can install. */+export function installComponents(+ request: PluginInstallRequest,+ probe: ProbeResult,+ desktopSupported = desktopInstallSupported()+): InstallComponents {+ const wanted = HINT_COMPONENTS[request.legacyHint ?? 'both'](probe)++ return { agent: wanted.agent, desktop: wanted.desktop && desktopSupported }+}++/** A desktop half the request wants that this app cannot install: skipped and said so, never reported done. */+export function skipsDesktopHalf(request: PluginInstallRequest, probe: ProbeResult): boolean {+ return installComponents(request, probe, true).desktop && !installComponents(request, probe).desktop}/** A unified package installed into a local backend carries its own desktop half; the app copies that half@@ -201,6 +219,10 @@ export async function runPluginInstall(plan: InstallPlan, deps: InstallDeps): Prnotify({ kind: 'success', message })}+ if (agentResult?.ok && skipsDesktopHalf(plan.request, plan.probe)) {+ notify({ kind: 'warning', message: deps.copy.desktopUnavailable })+ }+if (report.errors.length > 0) {return { status: 'failed', error: report.errors.join(' ') }}diff --git a/apps/desktop/src/app/settings/use-plugin-probe.test.ts b/apps/desktop/src/app/settings/use-plugin-probe.test.tsnew file mode 100644index 00000000000..d181e3d3803--- /dev/null+++ b/apps/desktop/src/app/settings/use-plugin-probe.test.ts@@ -0,0 +1,82 @@+import { act, renderHook, waitFor } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import type { ProbeResult } from './plugin-install-run'+import { usePluginProbe } from './use-plugin-probe'++const found = (agentName: string): ProbeResult => ({ ok: true, agent: true, agentName, desktop: false, warnings: [] })++const deferred = <T>() => {+ let resolve!: (value: T) => void+ const promise = new Promise<T>(done => (resolve = done))++ return { promise, resolve }+}++afterEach(() => vi.unstubAllGlobals())++describe('usePluginProbe', () => {+ it('answers unavailable when neither Electron nor the gateway can inspect', async () => {+ const { result } = renderHook(() => usePluginProbe('unavailable here'))++ act(() => result.current.start('owner/repo'))++ await waitFor(() =>+ expect(result.current.probe).toMatchObject({ ok: false, unavailable: true, error: 'unavailable here' })+ )+ })++ it('keeps the newest inspection when an older gateway answer lands late', async () => {+ const first = deferred<ProbeResult>()+ const second = deferred<ProbeResult>()+ const gateway = vi.fn((repo: string) => (repo === 'a' ? first.promise : second.promise))+ const { result } = renderHook(() => usePluginProbe('unavailable', gateway))++ act(() => result.current.start('a'))+ act(() => result.current.start('b'))+ const settled = result.current.settled()+ await act(async () => second.resolve(found('b')))+ await act(async () => first.resolve(found('a')))++ expect(result.current.probe?.agentName).toBe('b')+ expect((await settled)?.agentName).toBe('b')+ })++ it('drops an answer that lands after cancel', async () => {+ const late = deferred<ProbeResult>()+ const { result } = renderHook(() => usePluginProbe('unavailable', () => late.promise))++ act(() => result.current.start('a'))+ act(() => result.current.cancel())+ await act(async () => late.resolve(found('a')))++ expect(result.current.probe).toBeNull()+ expect(await result.current.settled()).toBeNull()+ })++ it('prefers Electron inspection when the preload provides it', async () => {+ const probePluginRepo = vi.fn(async () => found('native'))+ const gateway = vi.fn(async () => found('gateway'))+ vi.stubGlobal('hermesDesktop', { probePluginRepo })+ const { result } = renderHook(() => usePluginProbe('unavailable', gateway))++ act(() => result.current.start('owner/repo'))++ await waitFor(() => expect(result.current.probe?.agentName).toBe('native'))+ expect(probePluginRepo).toHaveBeenCalledWith({ identifier: 'owner/repo' })+ expect(gateway).not.toHaveBeenCalled()+ })++ it('does not restart an inspection when the caller passes a fresh gateway closure each render', async () => {+ const gateway = vi.fn(async (_repo: string) => found('one'))+ const { result, rerender } = renderHook(() => usePluginProbe('unavailable', repo => gateway(repo)))++ act(() => result.current.start('owner/repo'))+ await waitFor(() => expect(result.current.probe?.agentName).toBe('one'))+ const start = result.current.start+ rerender()++ expect(result.current.start).toBe(start)+ expect(gateway).toHaveBeenCalledTimes(1)+ })+})diff --git a/apps/desktop/src/app/settings/use-plugin-probe.ts b/apps/desktop/src/app/settings/use-plugin-probe.tsindex 0923d06708e..ed4852ad1a8 100644--- a/apps/desktop/src/app/settings/use-plugin-probe.ts+++ b/apps/desktop/src/app/settings/use-plugin-probe.ts@@ -1,24 +1,45 @@-import { useCallback, useRef, useState } from 'react'+import { useCallback, useEffect, useRef, useState } from 'react'import type { ProbeResult } from './plugin-install-run'const NO_PROBE: Promise<null> = Promise.resolve(null)+export type GatewayProbe = (repo: string) => Promise<ProbeResult>+/** Inspect a repository once per request. `settled()` lets Install wait on an inspection still running, and a- * newer start (or `cancel`) turns every older answer stale, so a late result never paints over newer intent. */-export function usePluginProbe(unavailableMessage: string) {+ * newer start (or `cancel`) turns every older answer stale, so a late result never paints over newer intent.+ * Native Desktop inspects in Electron; a renderer without that door (the browser-hosted app) asks the+ * backend through `gatewayProbe`. With neither, inspection is `unavailable`. */+export function usePluginProbe(unavailableMessage: string, gatewayProbe?: GatewayProbe) {const [probe, setProbe] = useState<null | ProbeResult>(null)const token = useRef(0)const pending = useRef<Promise<null | ProbeResult>>(NO_PROBE)+ // The newest door, read when an inspection starts: a fresh closure each render must not restart one.+ const gateway = useRef(gatewayProbe)++ // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)+ useEffect(() => {+ gateway.current = gatewayProbe+ }, [gatewayProbe])const start = useCallback((repo: string) => {const mine = ++token.currentconst probeFn = window.hermesDesktop?.probePluginRepo+ const viaGateway = gateway.currentconst run: Promise<ProbeResult> = probeFn? probeFn({ identifier: repo })- : Promise.resolve({ ok: false, agent: false, desktop: false, warnings: [], error: unavailableMessage })+ : viaGateway+ ? viaGateway(repo)+ : Promise.resolve({+ ok: false,+ agent: false,+ desktop: false,+ warnings: [],+ unavailable: true,+ error: unavailableMessage+ })setProbe(null)pending.current = run.then(result => {diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 3313f280a9c..2080d78ab69 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -656,6 +656,8 @@ declare global {desktopName?: string | nullwarnings?: string[]insecure?: boolean+ /** Inspection itself is missing here (not a failed read): Retry cannot help. */+ unavailable?: booleanerror?: string}>installDesktopPlugin?: (payload: {diff --git a/apps/desktop/src/store/agent-plugins.ts b/apps/desktop/src/store/agent-plugins.tsindex ff5aef67dd1..eb5db5cbd7b 100644--- a/apps/desktop/src/store/agent-plugins.ts+++ b/apps/desktop/src/store/agent-plugins.ts@@ -1,4 +1,4 @@-import type { PluginsManageParams } from '@hermes/shared'+import { JsonRpcGatewayError, type PluginsManageParams } from '@hermes/shared'import { atom } from 'nanostores'import { notifyError } from '@/store/notifications'@@ -365,6 +365,78 @@ export async function installAgentPlugin(}}+/** What a repository holds, the shape native Desktop's `probePluginRepo` answers. `unavailable`: the+ * backend cannot inspect at all (it predates `plugins.manage inspect`), which no retry changes. */+export interface AgentPluginInspection {+ ok: boolean+ agent: boolean+ desktop: boolean+ agentName?: string | null+ desktopName?: string | null+ warnings: string[]+ insecure?: boolean+ unavailable?: boolean+ error?: string+}++// `_run_action`'s unknown action, and JSON-RPC's unknown method.+const INSPECT_UNSUPPORTED_CODES = new Set([4017, -32601])++/** Inspect a source through the backend (`plugins.manage inspect`): it clones into a temp folder and+ * reports which halves ship, installing and running nothing. For a renderer with no Git of its own+ * (the browser-hosted app); native Desktop inspects in Electron. Never rejects. */+export async function inspectAgentPlugin(+ request: GatewayRequest,+ opts: { identifier: string; catalogName?: string; profile?: string | null }+): Promise<AgentPluginInspection> {+ try {+ const result = await request<{+ ok?: boolean+ agent?: boolean+ desktop?: boolean+ agent_name?: string | null+ desktop_name?: string | null+ warnings?: string[]+ insecure?: boolean+ error?: string+ }>(+ 'plugins.manage',+ withProfile(+ {+ action: 'inspect',+ identifier: opts.identifier,+ ...(opts.catalogName ? { catalog_name: opts.catalogName } : {})+ },+ opts.profile+ ),+ // A clone runs on the backend, as an install's does.+ PLUGIN_INSTALL_REQUEST_TIMEOUT_MS+ )++ const ok = Boolean(result?.ok)++ return {+ ok,+ agent: ok && Boolean(result.agent),+ desktop: ok && Boolean(result.desktop),+ agentName: result?.agent_name ?? null,+ desktopName: result?.desktop_name ?? null,+ warnings: result?.warnings ?? [],+ insecure: Boolean(result?.insecure),+ ...(ok ? {} : { error: result?.error || 'Inspection failed' })+ }+ } catch (e) {+ return {+ ok: false,+ agent: false,+ desktop: false,+ warnings: [],+ unavailable: e instanceof JsonRpcGatewayError && INSPECT_UNSUPPORTED_CODES.has(e.code ?? 0),+ error: e instanceof Error ? e.message : String(e)+ }+ }+}+/** One security-scan finding on an update the scan blocked. */export interface AgentPluginScanFinding {severity: stringdiff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex b3e9c783b53..8707810d3ff 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4387,7 +4387,7 @@ export interface PluginToolsetRow {label: stringdescription: string}-/** ``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin that widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose security scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only); ``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only); ``presence``: ``names`` (catalog names, answered in that order). */+/** ``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``; ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin that widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose security scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only); ``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only); ``presence``: ``names`` (catalog names, answered in that order). */export interface PluginsManageParams {profile?: string | nullaction?: PluginsAction@@ -4403,8 +4403,8 @@ export interface PluginsManageParams {values?: Record<string, unknown> | nullnames?: string[] | null}-export type PluginsAction = 'list' | 'toggle' | 'install' | 'update' | 'remove' | 'settings' | 'onboarding' | 'presence'-/** ``list`` → ``plugins`` + counts; ``toggle`` → ``ok``/``unchanged``/``restart_required``/``name`` (the canonical key written)/``plugin``; ``install`` → ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s ok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the running gateway picked it up and re-wired its handlers) and ``activation`` — the honest split of what is live now vs deferred, so ``restart_required`` is True only when no gateway answered or the running gateway/backend cannot import the plugin's Python dependencies (``activation.missing_dependencies``); ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the ``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds — nothing changed until the client retries with ``accept_capabilities`` — or ``ok=false`` + ``scan_blocked`` with ``scan_verdict`` / ``scan_findings`` (retry a caution verdict with ``force``); ``remove`` → ``ok``/``name`` plus ``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``. */+export type PluginsAction = 'list' | 'toggle' | 'install' | 'inspect' | 'update' | 'remove' | 'settings' | 'onboarding' | 'presence'+/** ``list`` → ``plugins`` + counts; ``toggle`` → ``ok``/``unchanged``/``restart_required``/``name`` (the canonical key written)/``plugin``; ``install`` → ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s ok payload; ``inspect`` → ``ok``/``agent``/``desktop``/``agent_name``/``desktop_name``/``warnings``/``insecure`` or ``ok=false`` + ``error``; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the running gateway picked it up and re-wired its handlers) and ``activation`` — the honest split of what is live now vs deferred, so ``restart_required`` is True only when no gateway answered or the running gateway/backend cannot import the plugin's Python dependencies (``activation.missing_dependencies``); ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the ``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds — nothing changed until the client retries with ``accept_capabilities`` — or ``ok=false`` + ``scan_blocked`` with ``scan_verdict`` / ``scan_findings`` (retry a caution verdict with ``force``); ``remove`` → ``ok``/``name`` plus ``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``. */export interface PluginsManageResult {plugins?: AgentPluginRow[] | nulluser_count?: number | null@@ -4435,6 +4435,11 @@ export interface PluginsManageResult {written?: string[] | nullonboarding?: OnboardingCatalogPlugin[] | nullpresence?: CatalogPluginPresence[] | null+ agent?: boolean | null+ desktop?: boolean | null+ agent_name?: string | null+ desktop_name?: string | null+ insecure?: boolean | null}/** ``methods_tools._plugin_rows`` + ``plugins_cmd_catalog.catalog_row_fields`` provenance. */export interface AgentPluginRow {diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex b4cb62a49c9..f2ad3c83ac0 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -27654,6 +27654,7 @@"list","toggle","install",+ "inspect","update","remove","settings",@@ -27718,7 +27719,7 @@},"PluginsManageParams": {"additionalProperties": false,- "description": "``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``\n(+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin\nthat widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose\nsecurity scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only);\n``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only);\n``presence``: ``names`` (catalog names, answered in that order).",+ "description": "``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``\n(+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``; ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin\nthat widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whose\nsecurity scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only);\n``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only);\n``presence``: ``names`` (catalog names, answered in that order).","properties": {"profile": {"anyOf": [@@ -27878,7 +27879,7 @@},"PluginsManageResult": {"additionalProperties": false,- "description": "``list`` \u2192 ``plugins`` + counts; ``toggle`` \u2192 ``ok``/``unchanged``/``restart_required``/``name``\n(the canonical key written)/``plugin``; ``install`` \u2192 ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s\nok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the\nrunning gateway picked it up and re-wired its handlers) and ``activation`` \u2014 the honest split of what is\nlive now vs deferred, so ``restart_required`` is True only when no gateway answered or the running\ngateway/backend cannot import the plugin's Python dependencies (``activation.missing_dependencies``); ``update`` \u2192 ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the\n``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds \u2014 nothing changed until the\nclient retries with ``accept_capabilities`` \u2014 or ``ok=false`` + ``scan_blocked`` with ``scan_verdict`` /\n``scan_findings`` (retry a caution verdict with ``force``); ``remove`` \u2192 ``ok``/``name`` plus\n``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``.",+ "description": "``list`` \u2192 ``plugins`` + counts; ``toggle`` \u2192 ``ok``/``unchanged``/``restart_required``/``name``\n(the canonical key written)/``plugin``; ``install`` \u2192 ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s\nok payload; ``inspect`` \u2192 ``ok``/``agent``/``desktop``/``agent_name``/``desktop_name``/``warnings``/``insecure``\nor ``ok=false`` + ``error``; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the\nrunning gateway picked it up and re-wired its handlers) and ``activation`` \u2014 the honest split of what is\nlive now vs deferred, so ``restart_required`` is True only when no gateway answered or the running\ngateway/backend cannot import the plugin's Python dependencies (``activation.missing_dependencies``); ``update`` \u2192 ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the\n``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds \u2014 nothing changed until the\nclient retries with ``accept_capabilities`` \u2014 or ``ok=false`` + ``scan_blocked`` with ``scan_verdict`` /\n``scan_findings`` (retry a caution verdict with ``force``); ``remove`` \u2192 ``ok``/``name`` plus\n``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``.","properties": {"plugins": {"anyOf": [@@ -28261,6 +28262,66 @@],"default": null,"title": "Presence"+ },+ "agent": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Agent"+ },+ "desktop": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Desktop"+ },+ "agent_name": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Agent Name"+ },+ "desktop_name": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Desktop Name"+ },+ "insecure": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Insecure"}},"title": "PluginsManageResult",diff --git a/hermes_cli/plugins_cmd_inspect.py b/hermes_cli/plugins_cmd_inspect.pynew file mode 100644index 00000000000..006aaccbdfc--- /dev/null+++ b/hermes_cli/plugins_cmd_inspect.py@@ -0,0 +1,103 @@+"""Read-only inspection of a plugin source before install: which halves (agent, desktop) it ships.++The gateway's answer to the install dialog's repository check, for a client with no Git of its own+(the browser-hosted app). Native Desktop runs the same check in Electron+(``apps/desktop/electron/desktop-plugin-install.ts`` ``probePluginRepo``); the detection rules and the+result shape match it. The source goes through the installer's own resolution, kill list and+clone (non-interactive, credentials scrubbed, ``plugins.clone_timeout_seconds``) into a temporary+directory outside every profile's ``plugins/``. Nothing is installed, imported or run: only the+manifest files are read, as text.+"""++from __future__ import annotations++import json+import tempfile+from pathlib import Path+from typing import Any, Optional++import hermes_yaml as yaml++#: A manifest is a few hundred bytes; never read a hostile multi-megabyte one into memory.+_MANIFEST_MAX_BYTES = 256 * 1024+++def _pc():+ """The facade, read at call time: tests patch ``plugins_cmd.<name>`` and sibling calls must see it."""+ from hermes_cli import plugins_cmd+ return plugins_cmd+++def _manifest_name(path: Path, loads) -> Optional[str]:+ """The manifest's ``name`` when the file is a small regular file that parses, else None."""+ try:+ if path.is_symlink() or not path.is_file() or path.stat().st_size > _MANIFEST_MAX_BYTES:+ return None+ data = loads(path.read_text(encoding="utf-8"))+ except (OSError, UnicodeDecodeError, ValueError, yaml.YAMLError):+ return None+ name = data.get("name") if isinstance(data, dict) else None+ return name.strip() if isinstance(name, str) and name.strip() else None+++def detect_components(root: Path, fallback_name: str) -> dict[str, Any]:+ """Electron's ``detectPluginComponents``: an agent half is ``plugin.yaml``/``plugin.yml`` with+ ``__init__.py``, or a portable ``plugin.json``; a desktop half is ``plugin.js`` at the root or in+ ``desktop/``."""+ yaml_path = next((root / n for n in ("plugin.yaml", "plugin.yml") if (root / n).is_file()), None)+ portable = root / "plugin.json"+ agent = (yaml_path is not None and (root / "__init__.py").is_file()) or portable.is_file()+ desktop = (root / "plugin.js").is_file() or (root / "desktop" / "plugin.js").is_file()+ agent_name = None+ if agent:+ agent_name = (_manifest_name(yaml_path, yaml.safe_load) if yaml_path is not None else None) or (+ _manifest_name(portable, json.loads) if portable.is_file() else None) or fallback_name+ return {"agent": agent, "desktop": desktop, "agent_name": agent_name}+++def _desktop_folder_name(git_url: str, subdir: Optional[str]) -> str:+ """Electron's ``desktopPluginFolderName``: the subdirectory's last real segment, else the repo name."""+ parts = [p for p in (subdir or "").replace("\\", "/").split("/") if p and p not in (".", "desktop")]+ return parts[-1] if parts else _pc()._repo_name_from_url(git_url)+++def _failure(error: str, warnings: list[str], insecure: bool) -> dict[str, Any]:+ return {"ok": False, "agent": False, "desktop": False, "warnings": warnings, "insecure": insecure,+ "error": error}+++def inspect_plugin_source(identifier: str, *, catalog_name: Optional[str] = None) -> dict[str, Any]:+ """``{ok, agent, desktop, agent_name, desktop_name, warnings, insecure}``, or ``ok: False`` with+ ``error``. *catalog_name* inspects the curated entry at its reviewed pin (its repo replaces+ *identifier*), so the dialog shows exactly what the catalog install will put down."""+ pc = _pc()+ revision = None+ names: tuple[str, ...] = ()+ if catalog_name:+ from hermes_cli import plugins_cmd_catalog as catalog+ entry = catalog.get_live_catalog_entry(catalog_name)+ if entry is None:+ return _failure(f"'{catalog_name}' is not in the Hermes plugin catalog.", [], False)+ identifier, revision, names = entry.install_identifier, entry.sha or None, (entry.name,)+ try:+ git_url, subdir = pc._resolve_git_url(identifier)+ except ValueError as exc:+ return _failure(str(exc), [], False)+ insecure = git_url.startswith(("http://", "file://"))+ warnings = ["This URL uses an insecure or local scheme. Prefer https:// or git@ for production installs."] \+ if insecure else []+ try:+ from hermes_cli.plugins_cmd_catalog import raise_if_removed+ raise_if_removed(identifier, git_url, *names)+ with tempfile.TemporaryDirectory(prefix="hermes-plugin-inspect-") as tmp:+ clone = Path(tmp) / "plugin"+ pc._clone_plugin_repo(clone, git_url, revision, subdir)+ root = pc._resolve_subdir_within(clone, subdir) if subdir else clone+ fallback = subdir.rstrip("/").rsplit("/", 1)[-1] if subdir else pc._repo_name_from_url(git_url)+ found = detect_components(root, fallback)+ except pc.PluginOperationError as exc:+ return _failure(str(exc), warnings, insecure)+ if not found["agent"] and not found["desktop"]:+ return _failure("No agent or desktop plugin artifacts found in this repository.", warnings, insecure)+ return {"ok": True, **found, "desktop_name": _desktop_folder_name(git_url, subdir) if found["desktop"] else None,+ "warnings": warnings, "insecure": insecure}diff --git a/tests/hermes_cli/test_plugins_cmd_inspect.py b/tests/hermes_cli/test_plugins_cmd_inspect.pynew file mode 100644index 00000000000..9c5c495ee4c--- /dev/null+++ b/tests/hermes_cli/test_plugins_cmd_inspect.py@@ -0,0 +1,153 @@+"""``plugins_cmd_inspect.inspect_plugin_source``: the install dialog's read-only repository check.++Every case clones a real local Git repository through the installer's clone path; nothing is mocked+but the catalog lookup and the kill list.+"""++import subprocess+from pathlib import Path+from types import SimpleNamespace++import pytest++from hermes_cli import plugins_cmd_catalog+from hermes_cli.plugins_cmd import PluginOperationError+from hermes_cli.plugins_cmd_inspect import inspect_plugin_source+++def _git(repo: Path, *args: str) -> str:+ return subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True).stdout.strip()+++def _repo(tmp_path: Path, files: dict[str, str], name: str = "source") -> Path:+ repo = tmp_path / name+ repo.mkdir()+ _git(repo, "init", "-q", "-b", "main")+ _git(repo, "config", "user.email", "[email protected]")+ _git(repo, "config", "user.name", "t")+ _git(repo, "config", "uploadpack.allowAnySHA1InWant", "true")+ _commit(repo, files)+ return repo+++def _commit(repo: Path, files: dict[str, str]) -> str:+ for rel, text in files.items():+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ _git(repo, "add", "-A")+ _git(repo, "commit", "-q", "-m", "c")+ return _git(repo, "rev-parse", "HEAD")+++def sentinel(tmp_path):+ return tmp_path / "imported.flag"+++def _agent_files(sentinel: Path, name: str = "demo-agent") -> dict[str, str]:+ # Importing this package would leave the sentinel behind: inspection must never import it.+ return {"plugin.yaml": f"name: {name}\nversion: 1.0.0\n",+ "__init__.py": f"open({str(sentinel)!r}, 'w').write('ran')\n"}+++def test_agent_only_package_is_read_without_running_its_code(tmp_path, sentinel):+ repo = _repo(tmp_path, _agent_files(sentinel))++ result = inspect_plugin_source(repo.as_uri())++ assert result == {"ok": True, "agent": True, "desktop": False, "agent_name": "demo-agent", "desktop_name": None,+ "warnings": [result["warnings"][0]], "insecure": True}+ assert "insecure or local scheme" in result["warnings"][0]+ assert not sentinel.exists()+++def test_mixed_package_in_a_subdirectory_reports_both_halves(tmp_path, sentinel):+ files = {f"pkgs/demo/{k}": v for k, v in _agent_files(sentinel).items()}+ files["pkgs/demo/desktop/plugin.js"] = "export default {}\n"+ files["other/huge.txt"] = "x"+ repo = _repo(tmp_path, files)++ result = inspect_plugin_source(f"{repo.as_uri()}#pkgs/demo")++ assert result["ok"] is True+ assert (result["agent"], result["desktop"]) == (True, True)+ assert (result["agent_name"], result["desktop_name"]) == ("demo-agent", "demo")+ assert not sentinel.exists()+++def test_desktop_only_and_portable_packages(tmp_path):+ desktop = _repo(tmp_path, {"plugin.js": "export default {}\n"}, name="ui-plugin")+ portable = _repo(tmp_path, {"plugin.json": '{"name": "portable-one"}'}, name="portable")++ assert inspect_plugin_source(desktop.as_uri()) | {"warnings": []} == {+ "ok": True, "agent": False, "desktop": True, "agent_name": None, "desktop_name": "ui-plugin",+ "warnings": [], "insecure": True}+ assert inspect_plugin_source(portable.as_uri())["agent_name"] == "portable-one"+++def test_repository_without_plugin_artifacts_is_a_failed_read(tmp_path):+ repo = _repo(tmp_path, {"README.md": "nothing here\n"})++ result = inspect_plugin_source(repo.as_uri())++ assert result["ok"] is False+ assert result["error"] == "No agent or desktop plugin artifacts found in this repository."+++def test_unreachable_source_and_bad_identifier_fail_without_raising(tmp_path):+ missing = inspect_plugin_source((tmp_path / "nope").as_uri())+ bad = inspect_plugin_source("not-a-repo")++ assert missing["ok"] is False and missing["error"]+ assert bad["ok"] is False and bad["error"]+++def test_subdirectory_escape_is_refused(tmp_path, sentinel):+ repo = _repo(tmp_path, _agent_files(sentinel))++ result = inspect_plugin_source(f"{repo.as_uri()}#../..")++ assert result["ok"] is False+++def test_kill_listed_source_is_refused_before_cloning(tmp_path, sentinel, monkeypatch):+ repo = _repo(tmp_path, _agent_files(sentinel))+ seen = []++ def refuse(*candidates):+ seen.append(candidates)+ raise PluginOperationError("removed from the catalog")+ monkeypatch.setattr(plugins_cmd_catalog, "raise_if_removed", refuse)+ monkeypatch.setattr("hermes_cli.plugins_cmd._clone_plugin_repo", lambda *a, **k: pytest.fail("cloned"))++ result = inspect_plugin_source(repo.as_uri())++ assert result == {"ok": False, "agent": False, "desktop": False, "warnings": result["warnings"],+ "insecure": True, "error": "removed from the catalog"}+ assert seen+++def test_catalog_entry_is_inspected_at_its_reviewed_pin(tmp_path, sentinel, monkeypatch):+ repo = _repo(tmp_path, _agent_files(sentinel))+ pin = _git(repo, "rev-parse", "HEAD")+ _commit(repo, {"desktop/plugin.js": "export default {}\n"}) # newer than the pin+ entry = SimpleNamespace(name="demo", install_identifier=repo.as_uri(), sha=pin)+ monkeypatch.setattr(plugins_cmd_catalog, "get_live_catalog_entry", lambda name: entry if name == "demo" else None)++ pinned = inspect_plugin_source("ignored/identifier", catalog_name="demo")+ unknown = inspect_plugin_source("", catalog_name="missing")++ assert (pinned["ok"], pinned["agent"], pinned["desktop"]) == (True, True, False)+ assert unknown == {"ok": False, "agent": False, "desktop": False, "warnings": [], "insecure": False,+ "error": "'missing' is not in the Hermes plugin catalog."}+++def test_inspection_writes_nothing_into_the_profile(tmp_path, sentinel, monkeypatch):+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ repo = _repo(tmp_path, _agent_files(sentinel))++ assert inspect_plugin_source(repo.as_uri())["ok"] is True+ assert not (home / "plugins").exists() or not any((home / "plugins").iterdir())diff --git a/tests/tui_gateway/test_plugins_manage_inspect.py b/tests/tui_gateway/test_plugins_manage_inspect.pynew file mode 100644index 00000000000..8150df52c70--- /dev/null+++ b/tests/tui_gateway/test_plugins_manage_inspect.py@@ -0,0 +1,54 @@+"""Gateway ``plugins.manage inspect``: the browser-hosted app's repository check before install.++Drives the real RPC dispatch and a real local clone: the answer carries the probe contract's fields,+a failed read is ``ok: false`` (not an RPC error), and nothing lands in the profile's plugins folder.+"""++import subprocess++from tui_gateway import server+++def _manage(**params):+ return server.handle_request({"id": "1", "method": "plugins.manage", "params": params})+++def _repo(path, files):+ path.mkdir()+ for rel, text in files.items():+ (path / rel).parent.mkdir(parents=True, exist_ok=True)+ (path / rel).write_text(text, encoding="utf-8")+ for args in (("init", "-q", "-b", "main"), ("add", "-A"),+ ("-c", "[email protected]", "-c", "user.name=t", "commit", "-q", "-m", "c")):+ subprocess.run(["git", *args], cwd=path, check=True, capture_output=True)+ return path+++def test_inspect_reports_halves_and_installs_nothing(tmp_path, monkeypatch):+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ repo = _repo(tmp_path / "pkg", {"plugin.yaml": "name: pkg\nversion: 1.0.0\n", "__init__.py": "",+ "desktop/plugin.js": "export default {}\n"})++ result = _manage(action="inspect", identifier=repo.as_uri())["result"]++ assert {k: result[k] for k in ("ok", "agent", "desktop", "agent_name", "desktop_name", "insecure")} == {+ "ok": True, "agent": True, "desktop": True, "agent_name": "pkg", "desktop_name": "pkg", "insecure": True}+ assert not (home / "plugins" / "pkg").exists()+ listed = _manage(action="list")["result"]["plugins"]+ assert all(row["name"] != "pkg" for row in listed)+++def test_failed_read_is_an_answer_not_an_rpc_error(tmp_path):+ response = _manage(action="inspect", identifier=(tmp_path / "missing").as_uri())++ assert "error" not in response+ assert response["result"]["ok"] is False+ assert response["result"]["error"]+++def test_inspect_requires_a_source():+ response = _manage(action="inspect")++ assert response["error"]["code"] == 4019diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.pyindex 21d3fd7ca1c..2bbdef6601a 100644--- a/tui_gateway/contracts/tools_mcp_plugins.py+++ b/tui_gateway/contracts/tools_mcp_plugins.py@@ -616,6 +616,7 @@ class PluginsAction(WireEnum):list = "list"toggle = "toggle"install = "install"+ inspect = "inspect"update = "update"remove = "remove"settings = "settings"@@ -625,7 +626,7 @@ class PluginsAction(WireEnum):class PluginsManageParams(ProfileParams):"""``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``- (+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin+ (+ ``force``, ``enable``, ``ref``); ``inspect``: ``identifier``/``repo`` or ``catalog_name``; ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pinthat widened the plugin after the user confirmed the ``delta``, + ``force`` to apply an update whosesecurity scan returned caution after the user saw the findings); ``remove``: ``name`` (user installs only);``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only);@@ -805,7 +806,8 @@ class PluginScanFinding(Result):class PluginsManageResult(Result):"""``list`` → ``plugins`` + counts; ``toggle`` → ``ok``/``unchanged``/``restart_required``/``name``(the canonical key written)/``plugin``; ``install`` → ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s- ok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the+ ok payload; ``inspect`` → ``ok``/``agent``/``desktop``/``agent_name``/``desktop_name``/``warnings``/``insecure``+ or ``ok=false`` + ``error``; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (therunning gateway picked it up and re-wired its handlers) and ``activation`` — the honest split of what islive now vs deferred, so ``restart_required`` is True only when no gateway answered or the runninggateway/backend cannot import the plugin's Python dependencies (``activation.missing_dependencies``); ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the@@ -849,6 +851,13 @@ class PluginsManageResult(Result):onboarding: list[OnboardingCatalogPlugin] | None = None# ``presence`` → the named catalog plugins this OS runs, in the order asked; unknown names dropped.presence: list[CatalogPluginPresence] | None = None+ # ``inspect`` → which halves the source ships (``ok`` + ``warnings``, or ``ok=false`` + ``error``) and+ # whether its URL scheme is insecure; nothing was installed (``hermes_cli.plugins_cmd_inspect``).+ agent: bool | None = None+ desktop: bool | None = None+ agent_name: str | None = None+ desktop_name: str | None = None+ insecure: bool | None = Nonemethod("plugins.manage", params=PluginsManageParams, result=PluginsManageResult,diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex 5a781734627..94b3e25ab60 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -1770,6 +1770,17 @@ def _plugins_install(rid, params):return _ok(rid, _with_activation(result, str(result.get("plugin_name") or "")) if result.get("enabled") else result)+def _plugins_inspect(rid, params):+ """Read-only pre-install check of ``identifier``/``repo`` (or ``catalog_name`` at its pin): which halves it+ ships. Nothing is installed or run; a source that cannot be read answers ``ok: false`` + ``error``."""+ ident = (params.get("identifier") or params.get("repo") or "").strip()+ catalog_name = str(params.get("catalog_name") or "").strip()+ if not ident and not catalog_name:+ return _err(rid, 4019, "plugins.inspect requires 'identifier', 'repo', or 'catalog_name'")+ inspect = _tools_mod("hermes_cli.plugins_cmd_inspect").inspect_plugin_source+ return _ok(rid, inspect(ident, catalog_name=catalog_name or None))++def _plugins_update(rid, params):"""The same update as the dashboard and ``hermes plugins update``: a catalog install re-pins to thecurrent catalog SHA, a git install pulls. Every update is scanned. A refusal changes nothing and@@ -1858,7 +1869,7 @@ def _plugins_presence(rid, params):_PLUGINS_ACTIONS = {"list": _plugins_list, "onboarding": _plugins_onboarding, "presence": _plugins_presence,- "toggle": _plugins_toggle, "install": _plugins_install,+ "toggle": _plugins_toggle, "install": _plugins_install, "inspect": _plugins_inspect,"update": _plugins_update, "remove": _plugins_remove, "settings": _plugins_settings}@@ -1867,7 +1878,7 @@ def _(rid, params: dict) -> dict:"""TUI Plugins Hub backend (shares primitives with ``hermes plugins`` / the dashboard):``list`` → {plugins, user_count, bundled_count}; ``toggle`` flips ``key``/``name`` per ``enable``;``install`` git-clones ``identifier``/``repo`` or a curated ``catalog_name`` (``force``, ``enable``- default True); ``update`` re-pins a catalog install or pulls a git install (``force`` accepts a caution scan); ``remove`` deletes+ default True); ``inspect`` reports which halves that source ships, installing nothing; ``update`` re-pins a catalog install or pulls a git install (``force`` accepts a caution scan); ``remove`` deletesa user install by ``name``; ``settings`` writes manifest-declared ``values`` for ``key``."""return _run_action(rid, params, _PLUGINS_ACTIONS, "plugins")