Skip to content

feat(agent-hub): discover installed agent entry points - #1187

Merged
kovtcharov merged 9 commits into
amd:mainfrom
ZardLi1115:feat/agent-hub-entry-points
May 21, 2026
Merged

kovtcharov merged 9 commits into
amd:mainfrom
ZardLi1115:feat/agent-hub-entry-points

Conversation

@ZardLi1115

Copy link
Copy Markdown
Contributor

Summary

  • Adds gaia.agents entry point discovery so standalone Python agent wheels can register with AgentRegistry.
  • Keeps existing built-in, custom directory, and native manifest discovery behavior unchanged.

Root Cause

  • Agent Hub Phase 0 needs installed wheel discovery, but the registry only scanned built-ins, ~/.gaia/agents/, and native manifests.

Changes

  • Register AgentRegistration objects exposed through the gaia.agents entry point group.
  • Skip entry point IDs already claimed by earlier discovery stages.
  • Add unit coverage for successful entry point registration and duplicate-ID protection.

Validation

  • uv run --python .venv/bin/python pytest tests/unit/agents/test_registry.py -q
  • uv run --python .venv/bin/python python util/lint.py --imports
  • uv run --python .venv/bin/python python util/lint.py --black --isort

Notes

@github-actions github-actions Bot added tests Test changes agents labels May 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Clean, focused extension — the registry infrastructure for Agent Hub Phase 0 is solid. One medium cleanup worth doing before merge (the Python 3.8 compat shim), plus a few minor gaps.


Summary

The approach is correct: entry-point discovery is inserted at step 3 (after custom-dir, before native), duplicate-ID protection is ordered right (builtins/custom-dir win), and _load_entry_point_registration is cleanly extracted so it can be tested in isolation. The happy-path and override-guard tests cover the two most important scenarios.

The main thing to fix before merge: the hasattr(entry_points, "select") compatibility branch is Python 3.8 era code. GAIA requires Python 3.10+ (setup.py:264), where importlib.metadata.entry_points(group=...) has been the stable, one-liner API since 3.9. The branch adds two code paths for no gain — including a dead else path that isn't tested.


Issues Found

🟡 Unnecessary Python 3.8 compatibility shim (registry.py:851–855)

GAIA's python_requires=">=3.10" means the else: entry_points.get(...) branch can never execute in a supported environment. importlib.metadata.entry_points(group=...) is the standard form from Python 3.9+ and takes a keyword argument directly — no intermediate object needed.

        agent_entry_points = importlib.metadata.entry_points(
            group=AGENT_ENTRY_POINT_GROUP
        )

This also eliminates the untested legacy path, resolving the test-coverage gap below.


🟢 Missing type annotation on _load_entry_point_registration (registry.py:882)

Return type is annotated (-> AgentRegistration) but the parameter isn't. The correct stdlib type is importlib.metadata.EntryPoint.

    def _load_entry_point_registration(
        self, entry_point: importlib.metadata.EntryPoint
    ) -> AgentRegistration:

🟢 Warning drops the traceback (registry.py:862–866)

When a broken entry point fails to load, the warning logs the exception message but not the stack trace. Without exc_info=True the root cause is invisible in debug mode.

                logger.warning(
                    "registry: Failed to load agent entry point %s: %s",
                    entry_point.name,
                    exc,
                    exc_info=True,
                )

🟢 Test coverage gaps

Three missing cases in TestEntryPointDiscovery:

a) Bad entry-point type triggers warning and skips — verifies that when an entry point loads something that is not an AgentRegistration (or callable returning one), the outer loop catches the TypeError, logs a warning, and continues rather than crashing.

b) Entry point with namespaced_agent_id already set — verifies the preserve-existing-ID branch (if not registration.namespaced_agent_id) is actually taken when the registration already carries a namespace.

c) Legacy .get() path — currently untested. Becomes moot if the compat shim is removed (see 🟡 above).


Strengths

  • Resilience pattern is consistent. The try / except Exception → warning → continue loop mirrors exactly how _load_from_dir handles broken custom-dir agents (registry.py:282–287). Same contract, same style.
  • Clean extraction. _load_entry_point_registration separates the loading/validation logic from the loop, making it independently testable and readable.
  • Duplicate-ID ordering is correct. Entry-point agents are checked against self._agents after builtins and custom-dir have already populated it, so installed wheels can never silently shadow a built-in.
  • "installed:" namespace prefix is a thoughtful design: it makes the source of an entry-point agent unambiguous in logs and the UI without adding any fields to AgentRegistration.

Verdict

Approve with suggestions. The compat shim removal is the only change worth doing before merge; the rest are minor polish. No blocking issues.

@github-actions

Copy link
Copy Markdown
Contributor

Clean, focused prerequisite for Agent Hub Phase 0 — the logic is correct and the select/get compatibility shim properly handles both modern and legacy importlib.metadata APIs. Two gaps worth addressing before the next phase builds on this foundation.


Issues

🟡 Error-path tests missing (tests/unit/agents/test_registry.py)

The three new tests cover happy-path registration, legacy dict API, and ID collision protection, but the warning-and-continue branch in _discover_entry_point_agents (registry.py:861-869) is never exercised. Two scenarios are untested:

  1. entry_point.load() raises (e.g. ImportError from a broken wheel)
  2. _load_entry_point_registration raises TypeError because the loaded value isn't an AgentRegistration

The error path is trivially exercisable with the same SimpleNamespace-based approach used in the existing tests:

def test_bad_entry_point_is_skipped_with_warning(self, monkeypatch):
    bad_ep = SimpleNamespace(name="bad", load=lambda: object())  # not AgentRegistration
    entry_points = SimpleNamespace(select=lambda group: [bad_ep])
    monkeypatch.setattr(
        registry_module.importlib.metadata, "entry_points", lambda: entry_points
    )

    registry = AgentRegistry()
    registry._discover_entry_point_agents()  # must not raise

    assert registry.get("bad") is None

🟢 getattr(entry_points, "get") has no fallback (registry.py:856)

If entry_points() returns an object with neither select nor get, getattr(…, "get") raises AttributeError outside the per-entry-point try/except, aborting the whole discovery method. In practice this can't happen with importlib.metadata, but a stricter form costs nothing:

            agent_entry_points = getattr(entry_points, "get", lambda g, d: d)(
                AGENT_ENTRY_POINT_GROUP, []
            )

🟢 Missing type annotation on _load_entry_point_registration parameter (registry.py:884)

    def _load_entry_point_registration(
        self, entry_point: importlib.metadata.EntryPoint
    ) -> AgentRegistration:

Strengths

  • Precedence ordering is correct and commented: built-ins → custom dir → entry points → native. _discover_native_agents already had if agent_id in self._agents protection (registry.py:968), so the new stage slots in cleanly without any cross-stage ordering surprises.
  • dataclasses.replace() for namespace injection (registry.py:894-897): cleanly stamps installed:<id> onto the namespaced_agent_id without mutating the caller's AgentRegistration object.
  • AGENT_ENTRY_POINT_GROUP constant exported at module level (registry.py:17): wheel authors can import the canonical group name from gaia.agents.registry rather than hardcoding the string.

Verdict

Approve with suggestions — the core logic and compatibility shim are solid. The two green nits can be self-applied; the 🟡 gap (error-path tests) is worth addressing in this PR since the _discover_entry_point_agents error branch would be the first thing to trip in real-world use with a malformed wheel.

@github-actions

Copy link
Copy Markdown
Contributor

Clean, focused prerequisite for Agent Hub Phase 0. The discovery loop is fault-isolated correctly and the duplicate-ID guard preserves the right precedence order. One type-contract gap that will silently bite future callers needs fixing before merge.


Issues

🟡 Important — Missing "installed" source value forces reuse of "custom_python" (src/gaia/agents/registry.py:192)

AgentRegistration.source is typed Literal["builtin", "custom_python", "native"]. Entry-point agents produced by _load_entry_point_registration have no source value assigned, so callers must pass source="custom_python" — the test does exactly this (test_discovers_agent_registration_entry_point, line 126). That's semantically incorrect and creates invisible coupling: src/gaia/ui/routers/connectors.py:451 gates directory-based MCP scanning on source == "custom_python". Today the agent_dir is None half of that guard accidentally skips wheel agents, but any future guard that checks source == "custom_python" alone to distinguish directory agents from installed ones will silently include wheel agents.

    source: Literal["builtin", "custom_python", "native", "installed"]

Then in _load_entry_point_registration, validate that the incoming registration carries "installed" (or assign it as the default):

    def _load_entry_point_registration(
        self, entry_point: importlib.metadata.EntryPoint
    ) -> AgentRegistration:
        loaded = entry_point.load()
        registration = loaded() if callable(loaded) else loaded
        if not isinstance(registration, AgentRegistration):
            raise TypeError(
                f"{AGENT_ENTRY_POINT_GROUP} entry point {entry_point.name!r} "
                "must load an AgentRegistration or a zero-argument callable "
                "returning one"
            )
        if not registration.namespaced_agent_id:
            registration = dataclasses.replace(
                registration,
                namespaced_agent_id=f"installed:{registration.id}",
            )
        if registration.source not in ("installed", "custom_python"):
            registration = dataclasses.replace(registration, source="installed")
        return registration

Also update the four test fixtures that set source="custom_python" to use source="installed".


🟢 Minor — caplog test missing at_level context (tests/unit/agents/test_registry.py:489-492)

test_bad_entry_point_is_skipped_with_warning reads caplog.text without a caplog.at_level(...) guard, inconsistent with the existing pattern at line 371 in the same file. The test likely passes today (pytest default captures WARNING+), but it will silently stop capturing if the logger's default level is changed.

    def test_bad_entry_point_is_skipped_with_warning(self, monkeypatch, caplog):
        entry_point = self._entry_point("broken-agent", object())
        monkeypatch.setattr(
            registry_module.importlib.metadata,
            "entry_points",
            lambda group: [entry_point],
        )

        registry = AgentRegistry()
        with caplog.at_level("WARNING", logger="gaia.agents.registry"):
            registry._discover_entry_point_agents()

        assert registry.get("broken-agent") is None
        assert "Failed to load agent entry point broken-agent" in caplog.text

🟢 Nit — Entry point group name collides with Python package namespace (src/gaia/agents/registry.py:28)

AGENT_ENTRY_POINT_GROUP = "gaia.agents" is the same string as the Python package. Entry point groups are arbitrary strings so there's no runtime conflict, but third-party developers browsing setup.py could mistake this for a sub-package namespace. A name like "gaia.agent_plugins" or "gaia.installed_agents" makes the intent unambiguous. Low priority if the name is already settled in Agent Hub plans.


🟢 Nit — No setup.py example or doc pointer for the extension point (setup.py)

Third-party developers who want to publish an installable agent wheel have no guidance on the required entry point format. A comment near setup.py:255 showing the expected shape would close the loop:

# Third-party agent wheels register AgentRegistration instances here:
#   entry_points={"gaia.agents": ["my-agent = my_pkg.registration:get_registration"]}

A follow-on doc update to docs/plans/agent-hub.mdx can land later, but the comment should be in this PR so the code is self-describing.


Strengths

  • The continue-on-duplicate pattern in _discover_entry_point_agents (lines 861–873) correctly protects built-ins and earlier-registered agents without delegating to _register's overwrite path — the precedence ordering is right.
  • dataclasses.replace() for the default namespaced_agent_id assignment is clean; no mutation, no new subclass, preserves the dataclass invariant.
  • Four test scenarios (happy path, ID collision, load failure, existing namespace preserved) give solid behavioral coverage for a new extension surface.

Verdict

Request changes — the source Literal gap is the one thing that will silently wrong-foot future callers; the rest are nits. Easy fix: add "installed" to the Literal, assign it in _load_entry_point_registration, update the four test fixtures. The caplog and group-name nits can be addressed in the same pass.

@github-actions

Copy link
Copy Markdown
Contributor

Summary

Clean, well-scoped prerequisite for Agent Hub Phase 0. The new _discover_entry_point_agents / _load_entry_point_registration pair follows the same defensive pattern as the existing custom-dir and native-manifest stages: fail-open on bad entry points, log with full traceback, skip ID collisions. The source="installed" enforcement in _load_entry_point_registration is the right call — third-party wheels shouldn't be able to misrepresent their origin. Four test scenarios cover the critical paths. One test has unnecessary mocking indirection; one behavior branch (source coercion) has no test coverage.


Issues Found

🟢 Minor — Unnecessary select() indirection in first test (test_registry.py:427)

Three of the four new tests use the simpler direct lambda lambda group: [entry_point], but the happy-path test uses an extra SimpleNamespace.select() wrapper that serves no purpose. The mock ends up doing entry_points(group=x) → select(group=x) → [entry_point] instead of entry_points(group=x) → [entry_point]. Suggest aligning with the pattern used by the other three tests:

        monkeypatch.setattr(
            registry_module.importlib.metadata,
            "entry_points",
            lambda group: [entry_point],
        )

This also makes entry_points = SimpleNamespace(...) on line 427 dead, so that line should be removed too.


🟢 Minor — source coercion path is untested (registry.py:99-100)

_load_entry_point_registration silently rewrites source to "installed" if a third-party registration declares something else (e.g. "builtin" or "custom_python"). This is a meaningful trust-boundary enforcement, but there's no test that exercises it. The happy-path test pre-sets source="installed", so the branch at line 99 is never reached by the test suite. A one-case test would suffice:

def test_source_is_always_coerced_to_installed(self, monkeypatch):
    registration = AgentRegistration(
        id="hub-chat",
        name="Hub Chat",
        description="...",
        source="builtin",   # wrong — should be corrected
        conversation_starters=[],
        factory=lambda **kw: None,
        agent_dir=None,
        models=[],
    )
    entry_point = self._entry_point("hub-chat", lambda: registration)
    monkeypatch.setattr(
        registry_module.importlib.metadata,
        "entry_points",
        lambda group: [entry_point],
    )
    registry = AgentRegistry()
    registry._discover_entry_point_agents()
    assert registry.get("hub-chat").source == "installed"

🟢 Minor — Duplicate-ID check is outside the lock (registry.py:868-875)

if registration.id in self._agents:   # read outside self._lock
    ...
    continue
self._register(registration)           # acquires self._lock internally

_register itself re-checks inside the lock and would overwrite with a warning if the race triggered. In practice this code runs single-threaded at startup, so it's not a real bug, but it's worth a comment or moving the check inside _register's lock as an explicit "skip if already present" variant. Not a blocker.


Strengths

  • _load_entry_point_registration unconditionally forces source="installed" — wheels cannot masquerade as builtins. This is the right security posture for a plugin extension point.
  • exc_info=True on the failure-handler gives full tracebacks for entry-point load failures, which will be essential when debugging third-party wheels.
  • dataclasses.replace() for both mutations keeps AgentRegistration effectively immutable and avoids aliasing bugs.

Verdict

Approve with suggestions. No blocking issues. Apply the mock simplification in the first test and add a one-case source-coercion test; both are straightforward. The core implementation is solid.

@github-actions

Copy link
Copy Markdown
Contributor

Clean, well-scoped registry extension — the entry-point plumbing is solid and the duplicate-ID guard is exactly right. One functional bug is present that will silently break the grant-ledger for installed agents; everything else is minor or nit-level.


Issues

🟡 Factory not stamped with _gaia_namespaced_agent_id (registry.py:884–899)

Every other discovery path wraps its factory with _wrap_factory_with_namespaced_id so that Agent.process_query picks up the correct namespaced key for the grant-ledger:

  • builtins: factory=_wrap_factory_with_namespaced_id(chat_factory, "builtin:chat") (line 332)
  • custom Python: factory=_wrap_factory_with_namespaced_id(python_factory, namespaced_id) (line 1197)

_load_entry_point_registration coerces both namespaced_agent_id and source but never wraps the factory. The agent instance returned by create_agent will therefore fall back to AGENT_ID in process_query instead of the installed:… key — the scope grant stored under namespaced_agent_id won't be consulted. Add the wrap as the final step, after namespaced_agent_id is finalised:

        if not registration.namespaced_agent_id:
            registration = dataclasses.replace(
                registration,
                namespaced_agent_id=f"installed:{registration.id}",
            )
        if registration.source != "installed":
            registration = dataclasses.replace(registration, source="installed")
        registration = dataclasses.replace(
            registration,
            factory=_wrap_factory_with_namespaced_id(
                registration.factory, registration.namespaced_agent_id
            ),
        )
        return registration

The existing unit test (test_discovers_agent_registration_entry_point) still passes because _wrap_factory_with_namespaced_id silently skips AttributeError on non-Agent return values — no test changes needed.


🟢 Non-callable direct-AgentRegistration path not tested (test_registry.py:141)

All five new tests use a lambda: registration wrapper, so the else branch of loaded() if callable(loaded) else loaded in _load_entry_point_registration is never exercised. A one-liner entry point like entry_point = "hub-chat = mypkg:MY_REGISTRATION" (where MY_REGISTRATION is the AgentRegistration instance at module level, not a factory) would take this path silently. Worth adding a single test case.


🟢 except Exception in discovery loop (registry.py:861–867)

The catch is not silent (it logs with exc_info=True), but CLAUDE.md's "no silent fallbacks" guidance asks for specific exception types or re-raising with context. For a plugin-loading loop a broad catch is defensible; even so, naming the concrete failure categories in the comment would clarify intent for future readers:

            except Exception as exc:  # entry point may be from any third-party wheel
                logger.warning(

Strengths

  • AGENT_ENTRY_POINT_GROUP is defined as a module-level constant — a single source of truth if the group name changes, and importable by external wheel authors.
  • The duplicate-ID guard is correct: builtins, custom-dir, and entry-point agents are discovered in a fixed order and later stages cannot clobber earlier ones.
  • source coercion in _load_entry_point_registration is a good defensive measure — entry point authors cannot accidentally misrepresent the agent's origin.
  • Test coverage is proportionate: five cases hit the success path, the no-override guard, the warning path, and the two normalisation coercions.

Verdict

Request changes — the factory-wrapping gap is a functional bug in the grant-ledger path that all installed agents will hit in production. The fix is three lines and mechanical. The two nits are non-blocking.

@github-actions

Copy link
Copy Markdown
Contributor

The PR lands a clean, well-scoped registry extension. The _discover_entry_point_agents method follows the exact same defensive shape as native agent discovery, source coercion is consistent across both registry and UI models, and the five test cases cover the paths that matter. One grant-ledger namespace gap deserves a fix before merge; the rest are nits.


Issues

🟡 namespaced_agent_id is not constrained to the installed: prefix (registry.py:893-898)

source is always coerced to "installed" unconditionally (line 897-898). namespaced_agent_id is only defaulted when empty (lines 893-896). A wheel that provides namespaced_agent_id="builtin:chat" bypasses the coercion and lands in the grant-ledger under the same key as the built-in chat agent — the exact attack vector that _RESERVED_BUILTIN_IDS was added (T-X2/#915) to prevent for ~/.gaia/agents/. The defense-in-depth argument ("wheels require pip install") is weaker than it sounds for security-conscious users who install third-party agent packages.

The test_preserves_existing_namespaced_agent_id test with "wheel:hub-chat" shows custom prefixes are intentionally supported — but that test doesn't cover the "builtin:*" case. Two options:

Option A — enforce installed: prefix always (simpler, safer):

# Always coerce: source coercion already signals this is an installed agent.
registration = dataclasses.replace(
    registration,
    namespaced_agent_id=f"installed:{registration.id}",
    source="installed",
)

Option B — keep custom prefixes but reject builtin: namespace claims explicitly, matching the custom-agent guard (registry.py:1098-1106):

if not registration.namespaced_agent_id:
    registration = dataclasses.replace(
        registration,
        namespaced_agent_id=f"installed:{registration.id}",
    )
elif registration.namespaced_agent_id.startswith("builtin:"):
    raise TypeError(
        f"{AGENT_ENTRY_POINT_GROUP} entry point {entry_point.name!r} "
        "must not use the reserved 'builtin:' namespace in namespaced_agent_id"
    )
if registration.source != "installed":
    registration = dataclasses.replace(registration, source="installed")

The docstring comment on AgentRegistration.namespaced_agent_id (line 210-214) also needs to be updated to document the installed:<id> scheme — it currently only mentions builtin: and custom:.


🟢 No test for the direct AgentRegistration load path (registry.py:87)

_load_entry_point_registration branches on callable(loaded) — if False, it uses loaded directly as the registration. Every test uses self._entry_point("name", lambda: registration) (the callable path). The non-callable path (self._entry_point("name", registration)) has no coverage. A one-liner test would close the gap:

def test_discovers_direct_agent_registration_entry_point(self, monkeypatch):
    registration = AgentRegistration(
        id="direct-agent",
        name="Direct",
        description="Loaded directly, not via callable",
        source="installed",
        conversation_starters=[],
        factory=lambda **kw: SimpleNamespace(kind="direct"),
        agent_dir=None,
        models=[],
    )
    # entry point .load() returns the registration directly (not a factory)
    entry_point = self._entry_point("direct-agent", registration)
    monkeypatch.setattr(
        registry_module.importlib.metadata,
        "entry_points",
        lambda group: [entry_point],
    )
    registry = AgentRegistry()
    registry._discover_entry_point_agents()
    assert registry.get("direct-agent") is not None

🟢 Unnecessary SimpleNamespace indirection in one test (test_registry.py:207-213)

Four of the five tests mock entry_points as lambda group: [entry_point]. test_entry_point_does_not_override_existing_agent wraps it in a SimpleNamespace with a select method that adds no logic. The inconsistency makes the test harder to read at a glance.

        monkeypatch.setattr(
            registry_module.importlib.metadata,
            "entry_points",
            lambda group: [entry_point],
        )

Strengths

  • source is always coerced to "installed" regardless of what the wheel declares — the right call; mirrors the approach the registry takes with all other trust boundaries.
  • _wrap_factory_with_namespaced_id is reused correctly, so the _gaia_namespaced_agent_id attribute is set on instantiated agents without duplicating that logic.
  • The skip-on-collision path logs a warning rather than raising, which is the right fail-loud-but-non-fatal posture for a discovery step where other agents should still load.

Verdict

Request changes — the namespaced_agent_id enforcement gap is a genuine grant-ledger security concern that should be addressed before merge. The fix is small (a few lines). The two nits can be addressed in the same commit or a follow-up, but the namespace issue should not ship as-is given the explicit effort put into T-X2/#915.

@github-actions

Copy link
Copy Markdown
Contributor

The registry backend is solid — the security invariant (namespace coercion to installed: on every code path) is correctly enforced, test coverage is thorough, and the discovery ordering (installed < builtin/custom) is intentional and correct. Three gaps need attention before this ships to users.


Issues

🟡 Frontend badge display broken for installed agents

AgentHubCard.tsx (sourceBadge) falls through to the "Custom" label for any unknown source value. AgentDetailModal.tsx shows no badge at all when source is installed because only builtin, native, and custom_python are checked. Users seeing an installed wheel agent will either get a misleading "Custom" label or no label.

src/gaia/apps/webui/src/components/AgentHubCard.tsx:8-11

function sourceBadge(source: string) {
    if (source === 'builtin') return <span className="agent-badge agent-badge-builtin">Built-in</span>;
    if (source === 'native') return <span className="agent-badge agent-badge-native">Native</span>;
    if (source === 'installed') return <span className="agent-badge agent-badge-installed">Installed</span>;
    return <span className="agent-badge agent-badge-custom">Custom</span>;

src/gaia/apps/webui/src/components/AgentDetailModal.tsx:54-56

                            {agent.source === 'builtin' && <span className="agent-badge agent-badge-builtin">Built-in</span>}
                            {agent.source === 'native' && <span className="agent-badge agent-badge-native">Native</span>}
                            {agent.source === 'custom_python' && <span className="agent-badge agent-badge-custom">Custom</span>}
                            {agent.source === 'installed' && <span className="agent-badge agent-badge-installed">Installed</span>}

(A matching CSS rule for .agent-badge-installed will also be needed — copy the pattern from .agent-badge-native or .agent-badge-custom.)


🟡 Sort order for installed agents is implicit

AgentHubGrid.tsx:24 maps { builtin: 0, custom_python: 1, native: 2 }. Installed agents fall through to ?? 1, co-mingling with custom Python agents. The intent should be stated explicitly.

src/gaia/apps/webui/src/components/AgentHubGrid.tsx:24

    const order: Record<string, number> = { builtin: 0, custom_python: 1, installed: 2, native: 3 };

(Adjust the slot number to match whatever product decision is made for ordering.)


🟢 Grant-ledger docstring doesn't mention installed: namespace

src/gaia/connectors/grants.py:14-15 lists builtin: and custom: namespaces; installed: and native: are absent. Since the security model depends on consumers knowing the full namespace taxonomy, this should be updated.

Where ``namespaced_agent_id`` is ``builtin:<id>`` for built-in agents,
``custom:<sha256-prefix>:<id>`` for custom agents under ``~/.gaia/agents/``
(per plan amendment A9), ``installed:<id>`` for wheel-installed agents, and
``native:<id>`` for C++/binary agents.

Same gap in src/gaia/apps/webui/src/types/index.ts:37-38:

    /**
     * Opaque grant-ledger key. Built-ins are `builtin:<id>`, custom agents
     * are `custom:<sha256-prefix>:<id>`, installed wheel agents are
     * `installed:<id>`. Pass this to the grants endpoint.
     */

Strengths

  • Security namespace coercion is unconditional. Whether the author supplies the right namespaced_agent_id/source or not, _load_entry_point_registration always forces installed:{id} before the factory is wrapped — an installed wheel can never impersonate a builtin: scope in the grant ledger.
  • Discovery ordering is correct. Running installed-agent discovery before native agents (step 3 vs 4) means installed Python wheels shadow native manifests for the same ID, and the pre-existing built-in/custom stages (steps 1–2) are still protected by the duplicate ID guard at the head of _discover_entry_point_agents.
  • Test coverage is comprehensive. Six distinct scenarios (callable vs direct registration, source coercion, namespace coercion, duplicate-ID protection, bad entry point warning) cover both the happy path and every edge case introduced by this PR.

Verdict

Request changes. The two frontend display bugs (🟡) will be visible to the first user who installs a wheel agent — installed agents will carry the wrong badge or no badge. These are a direct consequence of this PR introducing the installed source value and are straightforward to fix in the same PR. The grants doc nit (🟢) is a minor follow-up but worth fixing here since it describes the security model.

@github-actions

Copy link
Copy Markdown
Contributor

Clean, well-scoped prerequisite for Agent Hub Phase 0. Seven new test cases cover the happy path, duplicate-ID protection, and source/namespace coercion — the invariants that matter most here.


Summary

The entry point group constant, skip-if-already-registered guard, and installed: namespace coercion all follow the exact patterns already in use for builtin and custom-directory agents. The exc_info=True in the warning logger is actually an improvement over the existing custom-directory _load_from_dir pattern, which logs without it. UI model sync (AgentInfo.source) is a one-liner and correct.

Two minor nits below — neither blocks a merge.


Issues Found

🟢 Minor — _load_entry_point_registration: two dataclasses.replace calls can be one (registry.py:893–908)

The conditional coerce and the unconditional factory-wrap are always both applied. Collapsing them eliminates the branch and makes it obvious that every installed registration exits with enforced namespace, source, and wrapped factory.

    def _load_entry_point_registration(
        self, entry_point: importlib.metadata.EntryPoint
    ) -> AgentRegistration:
        loaded = entry_point.load()
        registration = loaded() if callable(loaded) else loaded
        if not isinstance(registration, AgentRegistration):
            raise TypeError(
                f"{AGENT_ENTRY_POINT_GROUP} entry point {entry_point.name!r} "
                "must load an AgentRegistration or a zero-argument callable "
                "returning one"
            )
        namespaced_id = f"installed:{registration.id}"
        return dataclasses.replace(
            registration,
            namespaced_agent_id=namespaced_id,
            source="installed",
            factory=_wrap_factory_with_namespaced_id(registration.factory, namespaced_id),
        )

🟢 Minor — tests don't assert the group kwarg passed to entry_points (test_registry.py:185, 225, 243, …)

Every test monkeypatches with lambda group: [entry_point], which accepts but ignores the group value. If AGENT_ENTRY_POINT_GROUP were accidentally changed, the tests would still pass. Asserting the constant makes the guard real.

        monkeypatch.setattr(
            registry_module.importlib.metadata,
            "entry_points",
            lambda group: [entry_point] if group == registry_module.AGENT_ENTRY_POINT_GROUP else [],
        )

Apply this pattern to all seven monkeypatch sites in TestEntryPointDiscovery.


Strengths

  • Security posture is solid: namespace coercion (installed:<id>) is enforced unconditionally in _load_entry_point_registration, and the skip-if-registered guard protects both builtin and custom-directory agents from being shadowed — mirrors the intent documented in namespaced_agent_id's comment block.
  • Discovery ordering is intentional and documented: builtin → custom → installed → native, with the step comment updated to reflect the new step 3 (registry.py:292–296).
  • Test coverage is proportional: coercion, duplicate protection, direct-registration, callable-factory, and bad-plugin-warning all have dedicated cases — nothing important is left implicit.

@github-actions github-actions Bot added the electron Electron app changes label May 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Clean, well-scoped prerequisite for Agent Hub Phase 0. The discovery logic is sound, the namespace coercion defends against privilege escalation, and the test suite covers the important edge cases. Two small items to clean up before merge.


Issues

🟢 Minor — Stale docstring in _wrap_factory_with_namespaced_id (registry.py:152)

The existing docstring still reads "custom-installed agent get its proper custom:<sha256>:<id> namespace" — it doesn't mention the new installed:<id> path. Not a code bug, but a future reader reasoning about why the wrapper exists for installed agents will be confused by the custom: reference.

    The base ``Agent.process_query`` reads ``_gaia_namespaced_agent_id`` (and
    falls back to ``AGENT_ID``) when wrapping the call in the agent context
    contextvar. Setting this attribute on the instance is what lets a
    custom or installed agent get its proper ``custom:<sha256>:<id>`` or
    ``installed:<id>`` namespace instead of the bare ``AGENT_ID``.

🟢 Minor — Unknown-source sort fallback is now misleading (AgentHubGrid.tsx:24)

const oa = order[a.source] ?? 1;

The fallback 1 (same ordinal as custom_python) predates this PR, but the PR updated the sort comment to list the order explicitly. Any future source value not in the order map silently groups with custom_python, which is surprising. Not blocking, but worth a comment so the next reader doesn't assume it's intentional parity.

    const order: Record<string, number> = { builtin: 0, custom_python: 1, installed: 2, native: 3 };
    // Unknown sources fall back to custom_python ordering (1).

Strengths

  • Namespace coercion is airtight. _load_entry_point_registration unconditionally rewrites namespaced_agent_id to installed:<id> and source to "installed", so a malicious wheel can't claim builtin:chat by shipping a pre-filled AgentRegistration. The test test_entry_point_namespaced_agent_id_is_coerced_to_installed explicitly pins this invariant.

  • Discovery-loop exception handling is appropriately scoped. Using except Exception as exc with logger.warning(..., exc_info=True) and continue is the right call here — one broken wheel should not abort the whole registry startup. The pattern also matches the existing custom-directory loop at registry.py:285. Adding exc_info=True is actually an improvement over the older pattern.

  • Test coverage is thorough. Six scenarios cover the happy path (callable and direct entry points), source/namespace coercion, duplicate-ID protection, and bad-entry-point logging. Each tests exactly one invariant, making failures easy to diagnose.


Verdict

Approve with suggestions. The two nits above are polish; neither is a correctness issue. The missing installable-agent docs (how to declare [project.entry-points."gaia.agents"] in a downstream wheel) is a known gap acknowledged in the PR notes as out of scope for this prerequisite PR — fine to follow in the next commit.

@kovtcharov
kovtcharov added this pull request to the merge queue May 21, 2026
Merged via the queue into amd:main with commit 6379e18 May 21, 2026
24 checks passed
@itomek itomek mentioned this pull request May 21, 2026
5 of 6 tasks
antmikinka pushed a commit to antmikinka/gaia that referenced this pull request May 21, 2026
# GAIA v0.19.0 Release Notes

GAIA v0.19.0 tightens the agent loop against silent-failure regressions
and continues the focused-agent split. A new `gaia eval agent`
reliability harness exercises tool selection end-to-end against the
local Agent UI MCP backend and surfaced four agent-loop bugs that
previously produced silently-wrong "Task completed" answers — all four
are fixed in this release. Dedicated `BrowserAgent` and `AnalystAgent`
replace the ChatAgent-backed web and data profiles. Agents can now
declare a `REQUIRED_HARDWARE` capability tier that is validated at
startup against the running Lemonade server. GAIA can connect to a
remote Lemonade Server protected by an API key. And a new CI job
auto-implements PRs for bulletproof bug issues in parallel with the
existing triage path.

**Why upgrade:**
- **MCP tool-calling reliability framework + four framework fixes** —
`gaia eval agent` runs a user-simulator + judge against the local MCP
backend; the harness uncovered and fixed silent loop-break lies, a
~85-token JSON-envelope leak in tool-calling-model prompts, a missed
native-path failure check, and an over-broad eval rubric.
- **Specialized agents** — `BrowserAgent` and `AnalystAgent` ship as
dedicated implementations behind the `gaia browse` and `gaia analyze`
CLIs, replacing the monolithic ChatAgent-backed profiles.
- **Hardware-requirement validation** — agents can declare
`REQUIRED_HARDWARE` and fail fast at startup when the host's device tier
(CPU/iGPU/dGPU/NPU/hybrid) does not satisfy it, instead of silently
degrading.
- **Remote Lemonade auth** — setting `LEMONADE_API_KEY` threads
`Authorization: Bearer <key>` through every Lemonade-bound HTTP path;
wrong/missing key surfaces an actionable error naming the variable.
- **CI auto-fix for bulletproof bug issues** — bug-labelled issues that
meet the "1-2 files, < 50 lines, 100% confidence" bar now get an
auto-implemented PR in parallel with the standard triage comment.


## What's New

### MCP Tool-Calling Reliability Framework

A new end-to-end eval harness lands at `src/gaia/eval/runner.py` (PR
[amd#718](amd#718)) and is invoked via `gaia
eval agent`. The runner spawns a subprocess that acts as user-simulator
+ LLM judge against the live Agent UI MCP backend, exercises 10 generic
scenarios (no-param, single-param, multi-step, conditional,
error-handling, "no tool needed"), and produces per-tool failure rollups
via `analyze_failures.py`. The judge rubric in `judge_turn.md` grades on
tool selection alone for `verbatim`-tagged scenarios — it explicitly
does not penalize the agent for underlying-service failures, which had
been conflating pipeline correctness with hardware availability.

Running the harness against the agent loop immediately exposed four
framework regressions, all fixed in this release:

- **Silent loop-break lie.** When small local models emitted just the
server prefix (`mcp_foo_mcp`) instead of the full registered tool name,
the agent retried four times and then hard-coded `"Task completed with
mcp_foo_mcp. No further action needed"` as the final answer despite zero
successful tool calls. Server-name sanitisation now strips redundant
`mcp` tokens before namespacing, and a new
`Agent._build_loop_break_summary` helper branches on whether the last
result was an error so the user sees the actual error wording. A new AST
guard in `tests/unit/agents/test_agent_source_invariants.py` prevents
the lie-on-loop literal from reappearing.
- **JSON envelope leak in tool-calling-model prompts.** The `{"tool":
..., "tool_args": ...}` template was supposed to be suppressed for
models that support native `tools=[]` calling, but `self.model_id` was
assigned *after* `_register_tools()` ran, so the suppression check
always returned False and ~85 redundant tokens shipped in every prompt.
Moving the `model_id = model_id` assignment ahead of registration closes
the gap; a regression test asserts the `==== RESPONSE FORMAT ====` block
does not appear in a tool-calling agent's system prompt.
- **Loop-break helper missed the native path.** The shared helper looked
at `step_results[-1]` to detect a failure streak, but the
native-tool-call path appends to `previous_outputs` instead (wrapper
dicts). On native callers the helper saw an empty list, missed every
failure, and returned `"Task completed"`. The fix unwraps
`previous_outputs` at the call site; the regression test exercises the
helper with a sequence of error results.
- **Eval rubric conflated pipeline and hardware.** Some MCP services
wrap real operation failures in a `status: success` envelope with the
failure buried in `data.content[*].text`. On dev hardware where
vendor-side features don't all work, the judge graded the agent as
failing even when it picked the right tool. The new STEP 0 in
`judge_turn.md` overrides the rubric for `verbatim`-tagged scenarios —
`correctness = 10` if the right tool was invoked, `0` if the wrong tool
was, regardless of underlying op success.

Eight new unit-test files cover the sanitiser matrix, loop-break helper,
candidate-list invariant, scenario validation, and `--iterations` flag.


### Dedicated Browser and Analyst Agents

The Agent UI's web and data entries previously routed to `ChatAgent`
profiles, which meant they carried the full monolithic agent surface
instead of the focused tool sets the use cases actually need. PR
[amd#1070](amd#1070) adds dedicated
`BrowserAgent` and `AnalystAgent` implementations and wires the built-in
web/data registrations (plus their `lite` variants) to them. Two new CLI
subcommands ship alongside: `gaia browse` for the browser flow and `gaia
analyze` for the analyst flow. Both compose the relevant tool mixins
explicitly rather than inheriting everything from the ChatAgent shim.


### Hardware-Requirement Validation for Agents

Agents can now declare a hardware capability tier via `REQUIRED_HARDWARE
= HardwareRequirement(min_device=...)` (PR
[amd#1057](amd#1057)). At agent startup,
`LemonadeManager.ensure_ready(required_min_device=...)` queries the
running Lemonade server through `LemonadeClient.get_system_info()` and
raises `HardwareRequirementError` if the host's reported device tier
does not satisfy the declaration. NPU-only or dGPU-only agents fail fast
at construction time instead of silently degrading at first inference.

This is Phase 1 — validation only. The resolved `recipe` is computed and
logged for debugging but is *not* applied to the Lemonade server startup
path; a follow-up will wire the resolved recipe through if the project
chooses to.


### `LEMONADE_API_KEY` for Authenticated Remote Lemonade

Before this release, GAIA could not connect to a remote Lemonade Server
protected by an API key — every request returned `401` regardless of the
user's configuration. PR [amd#1149](amd#1149)
(closes [amd#1139](amd#1139)) threads
`LEMONADE_API_KEY` (from `.env` or the shell environment) as
`Authorization: Bearer <key>` through every Lemonade-bound HTTP path in
GAIA: the central `LemonadeClient._send_request`, the four
`requests`-bypass sites, both OpenAI-SDK constructor sites,
`LemonadeProvider`, `VLMClient`, the Agent UI router (`system.py`),
Agent UI chat helpers, the server startup probes, and the base `Agent`
health probe.

Behaviour is fully additive — when the env var is unset, every call path
behaves identically to v0.18.1. A wrong or missing key produces a
fixed-string error naming `LEMONADE_API_KEY` (the response body is
intentionally not echoed back, to avoid leaking reflected
`Authorization` headers from misconfigured proxies).


### CI Auto-Fix for Bulletproof Bug Issues

PR [amd#1159](amd#1159) adds a Claude-powered
auto-fix job to `.github/workflows/claude.yml` that runs in parallel
with the existing `issue-handler` triage. When a new issue lands with
the `bug` label, Claude reads the report, and if the fix passes a strict
"bulletproof" bar — 1–2 files touched, fewer than 50 lines changed, 100%
confidence, no hardware-dependent verification needed — it implements
the change, validates with `python util/lint.py` and the relevant unit
tests, opens a PR, and posts the PR link plus step-by-step verification
instructions back on the originating issue. Bug reports that don't meet
the bar still get the standard triage comment from `issue-handler`; the
auto-fixer exits silently for the rest.


## Bug Fixes

- **BrowserAgent and AnalystAgent crashed instantly in the Agent UI**
(PR [amd#1202](amd#1202)) — Selecting either
of the new split agents and sending any message raised `AttributeError:
'<Agent>' object has no attribute '_mcp_manager'`. The MCP client
mixin's optional attribute was never initialised on the split agents,
and `get_mcp_status_report()` — invoked on every `/api/chat/send` — hit
the undefined dereference. The two-layer fix adds a class-level
`_mcp_manager: Optional[MCPClientManager] = None` on `MCPClientMixin`
(covering every future agent that inherits it) plus explicit per-agent
initialisation in the five affected agents (documenting intent at the
point of use). CLI paths were unaffected — only the Agent UI's
`/api/chat/send` triggered the bug.
- **`LEMONADE_BASE_URL` env var normalisation** (PR
[amd#1160](amd#1160)) — Setting
`LEMONADE_BASE_URL` to a value without the trailing `/api/v1` suffix
produced 404s deep in the request pipeline. The variable is now
normalised on load so both `http://host:8000` and
`http://host:8000/api/v1` resolve to the same canonical form.
- **Custom agents on disk now visible to the Agent UI** (PR
[amd#1138](amd#1138)) — `~/.gaia/agents/`
registrations were not surfacing to the Agent UI's agent list because
the registry discovery pass skipped the disk source on cold start. The
fix lists custom-directory agents alongside the built-ins on every
request.
- **`pr-review` CI re-enabled and credit-resilient** (PR
[amd#1163](amd#1163)) — The Claude-based
`pr-review` job had been disabled after an Anthropic credit window; all
Claude-backed jobs now treat 429 quota errors as non-fatal warnings so
CI keeps moving when the project hits its quota.
- **Silent skips in `test_sdk.py` removed** (PR
[amd#1190](amd#1190)) — Tests that depended on
an environment fixture were silently `pytest.skip()`-ing instead of
being explicitly conditional. The skips are now gated on the actual
fixture and surface as `XFAIL` when intentionally inapplicable. Closes
the first slice of [amd#877](amd#877).
- **`refresh-context7` fails loudly on unexpected status** (PR
[amd#1073](amd#1073)) — The terminal job of
the publish workflow previously masked non-cooldown HTTP responses as
"OK". It now distinguishes the known HTTP 400 cooldown window from any
other status code, so a regression that breaks the Context7 refresh is
no longer indistinguishable from the documented cooldown.


## Tooling & Docs

- **CLI smoke-test for every subcommand and console script** (PR
[amd#1193](amd#1193)) — Every `gaia
<subcommand>` and every console script declared in `setup.py` is now
exercised with `--help` in CI, catching import-time regressions and
shadowed entry points before they ship.
- **Fail-path coverage for `GovernedAgentMixin` and `CheckpointBridge`**
(PR [amd#1161](amd#1161)) — Adds unit tests
for the error/abort branches of the governance layer that were
previously only exercised on the happy path.
- **Custom-agent MCP harness for installer testing** (PR
[amd#1069](amd#1069)) — A reproducible
installer-level MCP harness for custom agents, so installer-affecting
changes are tested against the real agent-registration path rather than
mocks.
- **Dependabot revived, agent-ui entry added, patch auto-merge shipped**
(PR [amd#1191](amd#1191)) — Dependabot PRs are
flowing again, the Agent UI npm workspace is now covered, and patch-bump
PRs that pass CI auto-merge.


## Full Changelog

**17 commits** since v0.18.1:

- `6c6e4c34` — fix(agents): unbreak BrowserAgent/AnalystAgent in Agent
UI (amd#1202)
- `6379e183` — feat(agent-hub): discover installed agent entry points
(amd#1187)
- `a79acc88` — test(cli): smoke-test every subcommand and console script
with --help (amd#1193)
- `f7a75902` — ci(dependabot): revive PRs, add agent-ui entry, ship
patch auto-merge (amd#1191)
- `70d75b70` — fix(tests): remove silent skips in test_sdk.py (amd#877 Part
A) (amd#1190)
- `f8b2c1ab` — feat: MCP tool calling reliability test framework (amd#718)
- `f4270687` — feat(agent-hub): Agent Hub UI + platform plan + hub
skeleton (amd#1103)
- `6ef1feee` — fix(llm): normalize LEMONADE_BASE_URL env var to include
/api/v1 suffix (amd#1160)
- `72b77167` — fix(ci): re-enable pr-review and make all Claude jobs
credit-resilient (amd#1163)
- `b46bf654` — fix(agent-ui): list custom agents from disk (amd#1138)
- `63aedb47` — test: add fail-path coverage for GovernedAgentMixin and
CheckpointBridge (amd#1161)
- `7b8f22c0` — feat(llm): support LEMONADE_API_KEY for authenticated
remote Lemonade (amd#1149)
- `b22fa73d` — feat(ci): auto-fix job for bulletproof bug issues (amd#1159)
- `6b7b9e7d` — fix(ci): make refresh-context7 fail loudly on unexpected
status (amd#1073)
- `e2d4e2d7` — feat(sdk): hardware requirement validation for agents
(amd#1057)
- `1a73dcc5` — feat(agents): add browser and analyst agents (amd#1070)
- `2554424b` — test(installer): add custom agent MCP harness (amd#1069)

Full Changelog:
[v0.18.1...v0.19.0](amd/gaia@v0.18.1...v0.19.0)

## Release checklist

- [x] `util/validate_release_notes.py docs/releases/v0.19.0.mdx` passes
- [x] `src/gaia/version.py` → `0.19.0`
- [x] `src/gaia/apps/webui/package.json` → `0.19.0`
- [x] Navbar label in `docs/docs.json` → `v0.19.0 · Lemonade 10.2.0`
- [x] All 17 commits in range (v0.18.1..HEAD) are represented in the
notes
- [ ] Review from @kovtcharov-amd addressed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents electron Electron app changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants