Skip to content

feat: agent registry with per-session agent selection - #720

Merged
itomek merged 24 commits into
mainfrom
feat/issue-612-agent-registry
Apr 9, 2026
Merged

itomek merged 24 commits into
mainfrom
feat/issue-612-agent-registry

Conversation

@itomek

@itomek itomek commented Apr 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • AgentRegistry discovers agents at boot from built-in Python agents, custom Python modules (~/.gaia/agents/*/agent.py), and YAML manifests (~/.gaia/agents/*/agent.yaml)
  • Per-session agent routing — sessions store agent_type; the correct agent is instantiated on cache miss
  • Agent selector in the chat footer and WelcomeScreen — switching agents mid-conversation creates a new session; switching on an empty session updates in place
  • Agent name in message header — shows "GAIA {Agent Name} | Thinking" during streaming and "GAIA {Agent Name} | 3m ago" after completion
  • YAML manifest agents support MCP servers, model preferences, and conversation starters — drop a folder in ~/.gaia/agents/ and it appears in the UI after a server restart
  • Builder Agent — "+" button opens a conversational agent creator that generates agent.py (with optional MCP scaffolding) and auto-refreshes the selector without a server restart
  • DispatchQueue boot orchestration — _check_lemonade and _import_modules run in parallel at startup; _load_model runs after _check_lemonade completes; all tasks report progress to the frontend
  • New guide: docs/guides/custom-agent.mdx

Closes #612, #713

Test plan

  • python -m pytest tests/unit/agents/ tests/unit/chat/ui/ — all tests pass
  • Agent selector visible in chat footer and WelcomeScreen; switching mid-conversation creates new session
  • Message header shows agent name during and after streaming
  • Builder creates a working agent at ~/.gaia/agents/<name>/agent.py; appears in selector immediately
  • YAML manifest in ~/.gaia/agents/<name>/agent.yaml appears after server restart
  • Boot progress banner shows task names; send button disabled until ready

itomek and others added 5 commits April 2, 2026 11:54
Preload LLM model and ML dependencies at application startup instead
of on the first user prompt, eliminating a 30-120s delay. A new
DispatchQueue tracks background task status and exposes it to the
frontend via /api/system/status and /api/system/tasks.

Backend:
- Add DispatchQueue (src/gaia/ui/dispatch.py) with job lifecycle,
  dependency support, visibility filter, and auto-pruning
- Replace fire-and-forget asyncio.create_task() in lifespan with
  three dispatched startup jobs: check Lemonade, import modules,
  load AI model
- Promote _model_load_lock to model_load_lock for cross-module use
- Extend SystemStatus with init_state and init_tasks fields
- Add GET /api/system/tasks endpoint

Frontend:
- Adaptive status polling (3s during init, 15s otherwise)
- ConnectionBanner Case 0: blue init banner with task name + spinner
- Disable chat input and WelcomeScreen during initialization

Tests:
- 8 unit tests for DispatchQueue (lifecycle, dependencies, visibility,
  concurrency, pruning)
- 8 integration tests for startup init (status endpoint, tasks
  endpoint, wiring, defaults)

Closes #713

Co-Authored-By: Tomasz Iniewicz <[email protected]>
- Let _load_model exceptions propagate so job fails properly (not
  silent DONE when Lemonade unreachable)
- Import _DEFAULT_MODEL_NAME constant instead of hardcoding
- Use InitTaskInfo model instead of Dict[str, Any] for init_tasks
- Use get_dispatch_queue DI helper in /api/system/tasks endpoint
- Remove unused patch import from test file

Co-Authored-By: Tomasz Iniewicz <[email protected]>
- Fix finally block overwriting completed_at set by early returns
- Fail loudly when dependency job ID is not found (instead of silent skip)
- Use defensive getattr in get_dispatch_queue DI helper
- Fix adaptive polling replacing 3s with 15s before first status response
- Add regression test for init_tasks error field absence

Co-Authored-By: Tomasz Iniewicz <[email protected]>
Add a 4th boot task "Preparing AI assistant" that sends a single-token
warmup inference after model load.  This populates Lemonade's LCP-based
prompt cache with the ~7,400-token system prompt so the first real user
message gets a cache hit — reducing TTFT from 249s to ~21s (91%).

- Add _warmup_prompt_cache() closure in server.py lifespan
- Increase _DEPENDENCY_TIMEOUT from 60s to 600s for model downloads
- Explicit MCP cleanup in finally block to prevent subprocess leaks
- Add tests for warmup task registration and dependency chain

Verified end-to-end: fresh Lemonade + GAIA restart, warmup completes,
first message TTFT = 21.7s (down from 249.4s), second message = 2.0s.

Co-Authored-By: Tomasz Iniewicz <[email protected]>
Adds an AgentRegistry that discovers and loads agents at boot from three
sources: built-in Python agents (ChatAgent, GaiaAgent), custom Python
modules (~/.gaia/agents/*/agent.py), and YAML manifests
(~/.gaia/agents/*/agent.yaml).

Key changes:
- AgentRegistry: discover(), get(), list(), create_agent(), resolve_model()
- GaiaAgent: new lightweight agent (~797 tokens vs ChatAgent's ~5,760),
  used for boot warmup to reduce first-message TTFT on AMD iGPU hardware
- YAML manifest agents support MCP server config, custom tools, model
  preferences, and conversation starters
- Sessions store agent_type; chat helpers route to the correct agent per session
- Non-streaming path strips JSON envelope from manifest/GaiaAgent responses
- Fix UnboundLocalError in streaming path (agent_type closure shadowing)
- Fix _response_format_template initialized before _register_tools() so
  MCP-loaded agents get the correct system prompt on first cache build
- Agent selector moved from sidebar into the chat input area (footer pill
  in ChatView, pills on WelcomeScreen) matching Claude Code / Perplexity UX
- GaiaAgent hidden from UI selector (internal warmup agent); only Chat Agent
  and custom agents appear
- /api/agents endpoint; 39 unit tests covering registry and router

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@github-actions github-actions Bot added dependencies Dependency updates agents tests Test changes electron Electron app changes labels Apr 6, 2026
@itomek
itomek marked this pull request as ready for review April 6, 2026 23:38
@itomek
itomek requested a review from kovtcharov-amd as a code owner April 6, 2026 23:38
@itomek itomek self-assigned this Apr 6, 2026
@itomek itomek closed this Apr 7, 2026
@itomek itomek reopened this Apr 7, 2026
Adds a built-in hidden BuilderAgent that scaffolds new custom GAIA agents
through conversation. Users trigger it via a "+" button in the ChatView
input footer or "Build a Custom Agent" on the WelcomeScreen. The agent
asks for a name, writes a zoo-themed YAML manifest to ~/.gaia/agents/<id>/
and hot-reloads it into the registry so it appears immediately without a
restart. Includes path traversal guards, YAML injection prevention, and a
round-trip AgentManifest validation step.

- src/gaia/agents/builder/: BuilderAgent, system prompt, YAML template
- setup.py: register gaia.agents.builder package
- AgentRegistry.register_from_dir(): hot-reload method for new agents
- _chat_helpers.get_agent_registry(): accessor for builder hot-reload
- Agent UI: "+" button in ChatView footer, "Build a Custom Agent" on WelcomeScreen
- docs/guides/custom-agent.mdx: full user guide
- tests: 62 unit tests covering normalization, YAML gen, registry integration
@github-actions github-actions Bot added the documentation Documentation changes label Apr 7, 2026
Address code review findings:
- AgentManifest.validate_id: enforce safe-ID regex so hand-edited YAMLs
  cannot inject arbitrary IDs (e.g. shadowing built-in 'chat' agent)
- AgentRegistry._register: acquire threading.Lock to prevent data races
  during concurrent hot-reloads via register_from_dir
antmikinka pushed a commit to antmikinka/gaia that referenced this pull request Apr 7, 2026
…tration-v1

Analysis of how amd#720 (itomek's agent registry with per-session
agent selection) interacts with our branch's 7 open items and file-level
overlap surface. Produced by planning-analysis-strategist → quality-reviewer
pipeline with Clear Thought MCP sequential reasoning.

Key findings:
- CRITICAL CONFLICT: src/gaia/agents/registry.py mutual new-file collision.
  Our registry (asyncio.Lock, pipeline routing, capability index) and PR amd#720's
  registry (threading.Lock, UI factory pattern, AgentManifest/Pydantic) are
  architecturally incompatible. Resolution: relocate ours to
  src/gaia/pipeline/agent_registry.py before rebasing.
- CONFIRMED BREAK: _model_load_lock rename in _chat_helpers.py will break
  when PR amd#720's session-per-agent dispatch code lands. Must absorb fix.
- BUILD-UPON: PR amd#720's ~/.gaia/agents/ drop-folder + our pipeline routing
  can be unified — extend AgentManifest with optional pipeline: block
  (capabilities, triggers, phases, complexity_range) to make user-defined
  YAML agents pipeline-eligible. Schema proposal in doc section 5.5.

Open items status vs PR amd#720:
- Item 1 (AgentOrchestrator): PR amd#720 partially addresses — complements
  our RoutingAgent, does not replace it; build-upon opportunity identified
- Item 2 (BAIBEL Phase 4): unaffected, still deferred
- Item 3 (Resilience wiring): unaffected, still open
- Item 4 (Capability vocabulary): PR amd#720 introduces parallel vocabulary
  (AgentManifest); coordination needed to avoid duplication
- Item 5 (Spec coherence): unaffected
- Item 7 (YAML frontmatter): unaffected, still open

Action plan: 10 items across P0/P1/P2 tiers with owner annotations.
6 coordination questions for itomek/kovtcharov-amd in section 7.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Override _compose_system_prompt() in BuilderAgent to exclude the base
  class JSON-only response format template, which conflicted with the
  conversational greeting instructions and caused garbled LLM output
- Override process_query() with a minimal chat loop: no planning
  injection, no RAG workflow guards, simple tool-call vs plain-text
  dispatch, guaranteed print_final_answer() for SSE delivery
- Add tool-calling format instructions to BUILDER_SYSTEM_PROMPT so the
  LLM has clear, unambiguous guidance (JSON for tools, plain text for
  conversation)
- Wrap WelcomeScreen buttons in a .welcome-actions flex container so
  they share the same height and have consistent 16px gap; harmonize
  font-size and padding between the two buttons; stack vertically on
  mobile
itomek and others added 9 commits April 8, 2026 12:11
Custom agents created by the Builder Agent are now Python files
(agent.py) that users can edit directly to add tools, change the
system prompt, override the model, and wire up MCP servers. YAML
manifests are dropped entirely — the registry already loads Python
agents natively, and a Python file gives users full control.

Key changes:
- generate_agent_source() builds agent.py via repr() for all
  user-supplied values, eliminating injection/escaping bugs
- _name_to_class_name() converts human names to valid Python class
  names with edge-case guards ("Agent" → "CustomAgent", digit prefix)
- Cleanup on failure uses shutil.rmtree to avoid orphaned directories
  that would permanently block the agent name
- MCP comment block rewritten as 4 labeled steps (a-d) to prevent
  users from missing the class declaration change (MCPClientMixin)
- Example MCP server updated from npx to uvx mcp-server-time
- 46 unit tests covering normalization, class name generation,
  Python output, registry round-trip, and hot-reload paths
Agent directories no longer contain the redundant "-agent" suffix.
"Alpha Agent" creates ~/.gaia/agents/alpha/ instead of alpha-agent/.
CamelCase input like "AlphaAgent" is split before processing.
Display names always end with "Agent" for consistency.

Co-Authored-By: Tomasz Iniewicz <[email protected]>
When creating an agent, the Builder now asks if the user wants MCP server
support. If yes, the generated agent.py has MCPClientMixin, a proper __init__
with _mcp_manager setup before super().__init__(), and _register_tools calling
load_mcp_servers_from_config(). A mcp_servers.json skeleton is also created.

Non-MCP template drops the 40-line comment block in favour of a 1-line docs link.
After create_agent succeeds, the builder emits an agent_created SSE event.
The frontend handles it by immediately re-fetching the agent list so the new
agent appears in the selector without a page reload.

App.tsx also adds 30s fingerprinted polling as a safety net for manually
created or dropped agents.

Changes:
- console.py: add print_agent_created() optional no-op to OutputHandler
- sse_handler.py: override to emit {"type": "agent_created", "agent_id": ...}
- builder/agent.py: call self.console.print_agent_created() after success
- types/index.ts: add agent_created to StreamEventType + agent_id field
- api.ts: handle agent_created event via optional onAgentCreated callback
- ChatView.tsx: onAgentCreated refreshes agent list via api.listAgents()
- App.tsx: replace one-shot agent fetch with fingerprinted 30s polling
Custom agents created by the Builder Agent inherited tools from the
previously-instantiated agent (e.g. create_agent from BuilderAgent)
because _register_tools() did pass without clearing the global registry.

This caused the LLM to believe it had tools it shouldn't have, leading
to unexpected tool calls, infinite loops, and the "Empty response" error.

Adds _TOOL_REGISTRY.clear() to the generated _register_tools() body,
matching the existing pattern in gaia/agent.py, builder/agent.py, and
registry.py. Also fixes the pre-existing alpha agent on disk.

Co-Authored-By: Tomasz Iniewicz <[email protected]>
The base agent asks Qwen3.5-35B for {"thought":..., "answer":...} JSON.
This caused two interacting failures:

1. print_streaming_text Case 0 released the buffer too early: when
   "thought" appeared, it exited the hold even though "answer" hadn't
   been seen yet. The partial {"thought" fragment was emitted as a
   text chunk and later stripped by _THOUGHT_JSON_SUB_RE, leaving an
   empty response.

2. _stream_chat_response cleanup ran _THOUGHT_JSON_SUB_RE before
   _clean_answer_json, stripping the entire JSON blob (including the
   answer value) on any fallback path.

Fixes:
- Case 0 now holds the buffer until "tool" or "answer" is detected,
  with an 8 KB limit for proper JSON objects ({"...}) and 30 bytes
  for plain curly braces in text (preserving existing test behaviour).
- print_final_answer calls _clean_answer_json after think-tag stripping
  so it can extract the answer from {"thought":..., "answer":...} before
  the thought-stripper regex runs.
- _chat_helpers cleanup reorders: _clean_answer_json before
  _THOUGHT_JSON_SUB_RE as a safety net for edge cases.

Co-Authored-By: Tomasz Iniewicz <[email protected]>
- Remove duplicate imports in registry.py (GaiaAgent, BuilderAgent)
- Add encoding="utf-8" to open() calls in registry.py
- Suppress E0110/W0613 pylint warnings for dynamic class generation
- Remove unused imports: DispatchQueue, yaml, patch
- Fix 404 URL in docs/guides/docker.mdx
The agent selector in the chat footer only updated localStorage —
the backend kept using the agent_type frozen at session creation.
Now agent_type is sent with each chat message and the session
record is updated when it changes, so switching agents takes
effect immediately.
GaiaAgent existed solely for boot-time prompt cache warmup, but the
warmup was ineffective: its ~1,500-token system prompt shares no prefix
with ChatAgent's ~7,400-token prompt, so the cache entry was never
reused by real user sessions. Removes the agent entirely along with
_warmup_prompt_cache() and its DispatchQueue job. Boot now completes
3 visible tasks instead of 4.
itomek added 2 commits April 9, 2026 10:12
- Switching agents mid-conversation auto-creates a new session; switching
  on an empty session updates agent_type in place with optimistic rollback
- Agent picker dropdown reflects the current session's agent_type and is
  disabled during streaming
- Sidebar session selection syncs the agent picker via App.tsx useEffect
- Message header now shows "GAIA {Agent Name} | Thinking / time" instead
  of just "GAIA"; agent name resolved from session for history and from
  activeAgentId for the live streaming bubble
- Filter "Agent: {name}" SSE status steps — name is now in the header
- Add agent_type to UpdateSessionRequest with evict_session_agent on change
…on order

- Apply max_length/pattern validation to CreateSessionRequest.agent_type,
  matching the constraints already on ChatRequest and UpdateSessionRequest
- Evict cached agent before DB write in PUT /sessions/:id to close a
  narrow TOCTOU window where a concurrent chat request could use a stale
  cached agent after the agent_type has been updated
@itomek

itomek commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator Author

@claude review this PR

@github-actions

github-actions Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @itomek's task —— View job


PR Review Complete

Thank you for this substantial feature PR! This is a well-structured implementation of agent registry, per-session agent selection, and the Builder Agent. Here's my comprehensive review:


Summary

This PR introduces a powerful extensibility framework for GAIA with three major features:

  1. Agent Registry - Discovery and management of built-in, custom Python, and YAML manifest agents
  2. Builder Agent - Conversational agent creation through the UI
  3. DispatchQueue - Boot-time initialization with frontend progress visibility

Strengths

Architecture

  • Clean separation of concerns: registry (src/gaia/agents/registry.py), builder (src/gaia/agents/builder/), and dispatch (src/gaia/ui/dispatch.py)
  • Thread-safe registry with threading.Lock protection
  • Proper agent caching with eviction on agent_type/model changes in _chat_helpers.py:93-114
  • Dynamic class generation for YAML manifest agents is elegant and avoids code duplication

Security

  • Path traversal protection in _create_agent_impl (agent.py:366-369)
  • Reserved agent IDs blocking (_RESERVED_IDS at agent.py:28)
  • Agent ID validation with regex pattern (registry.py:62-66)
  • AST syntax validation before writing generated code (agent.py:401-405)

Testing

  • Excellent test coverage with 400+ lines for registry and 600+ lines for builder
  • Tests cover edge cases: special characters, path traversal, cleanup on failure, MCP integration
  • Round-trip tests verify generated agents are importable

Issues & Suggestions

🔴 Critical

1. TOCTOU Race in Agent Cache Eviction (_chat_helpers.py:456-463)

if agent_type != stored_agent_type:
    db.update_session(session_id, agent_type=agent_type)

The PR description mentions fixing TOCTOU with "Cached agent evicted before DB write" but in _get_chat_response, the cache check (_get_cached_agent) happens before the DB update. If two requests arrive simultaneously, both could pass the cache check before either evicts.

Suggestion: Move the cache eviction to happen atomically with the DB update in _store_agent or use a session-level lock during the entire check-and-update sequence.

🟡 Important

2. Model Resolution Never Used (registry.py:533-570)
The resolve_model method is implemented but I don't see it being called anywhere in the chat flow. The models field in AgentRegistration is populated but the actual model selection in _chat_helpers.py still uses session.get("model").

Suggestion: Call registry.resolve_model(agent_type, available_models) in _stream_chat_response/_get_chat_response to honor agent model preferences.

3. Manifest Agent Instantiation Fragility (registry.py:426-442)
The dynamic __init__ relies on MCP imports being available. If they fail, _mcp_manager is set to None and the error is only logged at debug level, which could silently disable MCP for manifest agents.

Suggestion: Log at warning level when MCP initialization fails for agents that explicitly define mcp_servers in their manifest.

4. Missing Input Validation in Agents Router (routers/agents.py:50)
The agent_id path parameter uses :path type which allows slashes. While this enables IDs like custom/agent, it could cause confusion or unexpected behavior.

Suggestion: Validate agent_id format matches the expected pattern before lookup.

🟢 Minor

5. Tool Registry Clearing Side Effect (registry.py:389)
_TOOL_REGISTRY.clear() in manifest agent's _register_tools could affect other agents if called in quick succession. The chat_semaphore(1) serialization helps but only within the chat flow.

6. Dependency Timeout (dispatch.py:24)
_DEPENDENCY_TIMEOUT = 600.0 (10 minutes) seems very long for boot dependencies. Consider reducing or making configurable.

7. Documentation Typo (custom-agent.mdx:44)

"The builder creates a fully working agent scaffold in ~/.gaia/agents/<your-agent-name>/agent.yaml"

Should be agent.py since the Builder creates Python agents, not YAML manifests.


Code Quality

Well Done

  • Consistent error handling with user-friendly messages
  • Good use of dataclasses and Pydantic models
  • Comprehensive logging throughout
  • Clean TypeScript with proper typing in frontend components

Suggestions

  • Consider adding docstrings to ChatView.tsx callback functions for better maintainability
  • The _chat_helpers.py file is now 1355 lines - consider splitting agent instantiation into a separate module

Test Plan Verification

All test plan items appear to be properly supported by the implementation:

  • ✅ Unit tests for agents and UI routers
  • ✅ Agent selector in footer and WelcomeScreen
  • ✅ Mid-conversation agent switching creates new session
  • ✅ Builder Agent creates ~/.gaia/agents/<name>/agent.py
  • ✅ MCP scaffolding support
  • ✅ Boot progress banner with DispatchQueue
  • ✅ YAML manifest hot-reload (requires restart, documented)

Recommendation

Approve with minor changes. This is a solid implementation that significantly enhances GAIA's extensibility. The identified issues are relatively minor and can be addressed in follow-up PRs if needed.

Priority fixes before merge:

  1. Update docs to say agent.py instead of agent.yaml for Builder-created agents
  2. Consider the TOCTOU race condition fix

- Call registry.resolve_model() in both _get_chat_response and
  _stream_chat_response so agents can specify preferred models in
  their manifests; custom model override still takes priority
- Upgrade MCP init failure logging from debug to warning in
  registry.py so silently-disabled MCP tools are surfaced
@itomek

itomek commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator Author

@claude review this PR

@github-actions

github-actions Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @itomek's task —— View job


PR Review Complete

This is a substantial and well-architected feature PR that introduces agent extensibility to GAIA. Here's my comprehensive review:


Summary

Three major features:

  1. Agent Registry - Discovery and management of built-in, custom Python, and YAML manifest agents
  2. Builder Agent - Conversational agent creation through the UI
  3. DispatchQueue - Boot-time initialization with frontend progress visibility

Strengths

Architecture

  • Clean separation of concerns: registry (src/gaia/agents/registry.py), builder (src/gaia/agents/builder/), and dispatch (src/gaia/ui/dispatch.py)
  • Thread-safe registry with threading.Lock protection (registry.py:95)
  • Proper agent caching with eviction on agent_type/model changes (_chat_helpers.py:93-114)
  • Dynamic class generation for YAML manifest agents avoids code duplication

Security

  • Path traversal protection in _create_agent_impl (agent.py:366-369)
  • Reserved agent IDs blocking (_RESERVED_IDS at agent.py:28)
  • Agent ID validation with regex pattern (registry.py:62-66)
  • AST syntax validation before writing generated code (agent.py:401-405)

Testing

  • Excellent test coverage: 400+ lines for registry, 600+ lines for builder
  • Tests cover edge cases: special characters, path traversal, cleanup on failure, MCP integration
  • Round-trip tests verify generated agents are importable

Issues & Suggestions

🔴 Critical

1. Documentation Typo (custom-agent.mdx:44)

"The builder creates a fully working agent scaffold in ~/.gaia/agents/<your-agent-name>/agent.yaml"

Should be agent.py since the Builder creates Python agents, not YAML manifests. This will confuse users.

🟡 Important

2. resolve_model Not Wired Into Chat Flow

The resolve_model method (registry.py:533-570) is called in the chat helpers (_chat_helpers.py:468-478 and 719-728), so this is correctly implemented. However, I noticed the call only happens for non-chat agents (agent_type != "chat"). This is intentional since ChatAgent doesn't define model preferences, but worth documenting.

3. Manifest Agent MCP Initialization Logging (registry.py:437-441)

When MCP initialization fails for agents that explicitly define mcp_servers, the failure is logged at warning level, which is correct. However, the error message could include more context:

logger.warning(
    "registry: MCP init failed for %s: %s", _cls.__name__, _mcp_err
)

Consider adding the manifest path or server names to help debugging.

4. Agent Cache TOCTOU Window (_chat_helpers.py:93-114, 456-463)

The previous review mentioned a TOCTOU race. Looking at the code:

  • evict_session_agent() is called in sessions.py:89 before the DB update
  • _get_cached_agent() checks and evicts on mismatch

The fix at sessions.py:88-89 correctly evicts before DB write, closing the TOCTOU window.

5. agent_id Path Parameter Allows Slashes (routers/agents.py:50)

@router.get("/api/agents/{agent_id:path}", response_model=AgentInfo)

Using :path allows IDs with slashes (e.g., custom/agent). While agent IDs are validated at registration time, consider adding explicit validation here to catch malformed requests early.

🟢 Minor

6. Tool Registry Clearing (registry.py:389)

_TOOL_REGISTRY.clear() in manifest agent's _register_tools could affect other agents if called in quick succession. The chat_semaphore(1) serialization helps but only within the chat flow. Consider documenting this as a known limitation.

7. Dependency Timeout (dispatch.py:24)

_DEPENDENCY_TIMEOUT = 600.0 (10 minutes) seems long for boot dependencies. Consider reducing or making it configurable via environment variable.

8. ChatView Complexity (ChatView.tsx)

The file is 600+ lines with complex callback chains. Consider extracting the agent picker logic into a separate component for maintainability.


Code Quality

Well Done

  • Consistent error handling with user-friendly messages
  • Good use of dataclasses and Pydantic models
  • Comprehensive logging throughout
  • Clean TypeScript with proper typing in frontend components

Suggestions

  • _chat_helpers.py is now 1355 lines — consider splitting agent instantiation into _agent_factory.py
  • Add docstrings to ChatView.tsx callback functions (handleAgentChange, etc.)

Test Plan Verification

All test plan items are properly supported by the implementation:

  • ✅ Unit tests for agents and UI routers
  • ✅ Agent selector in footer and WelcomeScreen
  • ✅ Mid-conversation agent switching creates new session
  • ✅ Message header shows agent name
  • ✅ Builder Agent creates ~/.gaia/agents/<name>/agent.py
  • ✅ MCP scaffolding support
  • ✅ Boot progress banner with DispatchQueue
  • ✅ YAML manifest discovery (requires restart, documented)

Required Fix Before Merge

Documentation typo at docs/guides/custom-agent.mdx:44:

Change:

The builder creates a fully working agent scaffold in `~/.gaia/agents/<your-agent-name>/agent.yaml`.

To:

The builder creates a fully working agent scaffold in `~/.gaia/agents/<your-agent-name>/agent.py`.

Recommendation

Approve with minor changes. This is a solid implementation that significantly enhances GAIA's extensibility. The documentation typo should be fixed before merge; other suggestions can be addressed in follow-up PRs.


…e backoff

- register_from_dir: enforce agent_dir is under ~/.gaia/agents/ before
  loading any code (path traversal guard, same check as _create_agent_impl)
- validate_id: fix regex to allow single-character IDs (was silently
  rejecting any ID shorter than 2 characters)
- _create_manifest_agent_class: only add MCPClientMixin to MRO when the
  manifest actually declares mcp_servers (was unconditional)
- _get_available_models: rate-limit Lemonade retries to every 10 s so an
  offline server does not add a 2 s blocking HTTP call per chat request
- docs/guides/custom-agent.mdx: fix typo — builder creates agent.py not
  agent.yaml
@itomek

itomek commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator Author

@claude review this PR

@github-actions

github-actions Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @itomek's task —— View job


PR Review Complete

This is a substantial and well-architected feature PR that introduces agent extensibility to GAIA. Here's my comprehensive review:


Summary

Three major features:

  1. Agent Registry - Discovery and management of built-in, custom Python, and YAML manifest agents
  2. Builder Agent - Conversational agent creation through the UI
  3. DispatchQueue - Boot-time initialization with frontend progress visibility

Strengths

Architecture

  • Clean separation of concerns: registry (src/gaia/agents/registry.py), builder (src/gaia/agents/builder/), and dispatch (src/gaia/ui/dispatch.py)
  • Thread-safe registry with threading.Lock protection (registry.py:97)
  • Proper agent caching with eviction on agent_type/model changes (_chat_helpers.py:93-114)
  • Dynamic class generation for YAML manifest agents avoids code duplication

Security

  • Path traversal protection in _create_agent_impl (agent.py:366-369)
  • Reserved agent IDs blocking (_RESERVED_IDS at agent.py:28)
  • Agent ID validation with regex pattern (registry.py:63 and models.py:140)
  • AST syntax validation before writing generated code (agent.py:401-405)
  • Path containment validation in register_from_dir (registry.py:487-495)

Testing

  • Excellent test coverage: 400+ lines for registry, 600+ lines for builder
  • Tests cover edge cases: special characters, path traversal, cleanup on failure, MCP integration
  • Round-trip tests verify generated agents are importable

Issues & Suggestions

🟡 Important

1. Documentation Typo Fixed — Previous reviews mentioned custom-agent.mdx:44 said agent.yaml instead of agent.py. Looking at line 44:

The builder creates a fully working agent scaffold in `~/.gaia/agents/<your-agent-name>/agent.py`.

This is now correct — the documentation accurately states agent.py.

2. resolve_model Correctly Wired

The resolve_model method (registry.py:545-582) is correctly called in both chat flows:

  • _chat_helpers.py:468-478 (non-streaming)
  • _chat_helpers.py:719-728 (streaming)

The model resolution only happens for non-chat agents (agent_type != "chat"), which is intentional since ChatAgent uses the session/server default model.

3. Cache Eviction Order Correct

The TOCTOU fix is properly implemented:

  • evict_session_agent() is called in sessions.py:89 before the DB update
  • This ensures the cached agent is removed before the session's agent_type is persisted, closing the race window

4. Agent ID Validation in API

The agent_id path parameter uses :path (routers/agents.py:50), which allows slashes. However, this is mitigated by:

  • Registration-time validation with _SAFE_ID_RE pattern
  • The AgentManifest.validate_id field validator enforcing ^[a-z0-9]([a-z0-9-]{0,50}[a-z0-9])?$

🟢 Suggestion: Consider adding explicit validation in get_agent() to reject malformed IDs early with a clear error message.

🟢 Minor

5. Tool Registry Clearing (registry.py:392)

_TOOL_REGISTRY.clear() in manifest agent's _register_tools could affect other agents if called in quick succession. The chat_semaphore(1) serialization helps but only within the chat flow.

6. Dependency Timeout (dispatch.py:24)

_DEPENDENCY_TIMEOUT = 600.0 (10 minutes) seems long for boot dependencies. Consider reducing or making it configurable via environment variable.

7. MCP Initialization Logging (registry.py:441-443)

When MCP initialization fails for agents that explicitly define mcp_servers, the failure is logged at warning level with the class name. Consider including the manifest path or server names to help debugging.

8. Lemonade Backoff Logic (registry.py:584-616)

The _LEMONADE_RETRY_INTERVAL = 10.0 backoff is good for preventing repeated failures from blocking requests. The implementation correctly tracks _lemonade_models_last_fail and rate-limits retries.


Code Quality

Well Done

  • Consistent error handling with user-friendly messages
  • Good use of dataclasses and Pydantic models with validators
  • Comprehensive logging throughout
  • Clean TypeScript with proper typing in frontend components
  • Agent type validation added to CreateSessionRequest (models.py:140)

Suggestions

  • _chat_helpers.py is now 1355 lines — consider splitting agent instantiation into _agent_factory.py in a future PR
  • Add docstrings to ChatView.tsx callback functions (handleAgentChange, etc.) for maintainability

Test Plan Verification

All test plan items are properly supported by the implementation:

  • ✅ Unit tests for agents and UI routers (tests/unit/agents/, tests/unit/chat/ui/)
  • ✅ Agent selector in footer and WelcomeScreen
  • ✅ Mid-conversation agent switching creates new session
  • ✅ Message header shows agent name
  • ✅ Builder Agent creates ~/.gaia/agents/<name>/agent.py
  • ✅ MCP scaffolding support
  • ✅ Boot progress banner with DispatchQueue
  • ✅ YAML manifest discovery (requires restart, documented)

Recommendation

Approve. This is a solid implementation that significantly enhances GAIA's extensibility. The issues identified in previous reviews have been addressed:

  • Documentation typo is fixed
  • resolve_model is correctly wired into the chat flow
  • Cache eviction happens before DB write (TOCTOU fix)
  • Agent ID validation is enforced at multiple layers

The remaining suggestions are minor and can be addressed in follow-up PRs.


@github-actions

github-actions Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @kovtcharov's task —— View job


PR Review Complete

  • Read the full PR diff to understand changes
  • Review architecture and code quality
  • Check security considerations
  • Review test coverage
  • Address reviewer comment on system_prompt.py
  • Provide final assessment

Summary

This is a well-architected feature PR introducing agent extensibility to GAIA with three major components:

  1. Agent Registry — discovers agents from built-in Python, custom Python (~/.gaia/agents/*/agent.py), and YAML manifests
  2. Builder Agent — conversational agent creation through the UI with hot-reload
  3. DispatchQueue — boot-time task orchestration with frontend progress visibility

Strengths

Architecture

  • Clean separation of concerns: registry (registry.py), builder (agents/builder/), dispatch (ui/dispatch.py)
  • Thread-safe registry with threading.Lock (registry.py:97)
  • Agent caching with proper eviction on agent_type/model changes (_chat_helpers.py:93-114)
  • Dynamic class generation for YAML manifest agents is elegant

Security

  • Path traversal protection (agent.py:366-369)
  • Reserved agent ID blocking (_RESERVED_IDS at agent.py:28)
  • Agent ID validation with regex (registry.py:63, models.py:140)
  • AST syntax validation before writing (agent.py:401-405)
  • Path containment in register_from_dir (registry.py:487-495)

Testing

  • Excellent coverage: 400+ lines for registry, 600+ lines for builder
  • Edge cases covered: special characters, path traversal, cleanup on failure, MCP integration
  • Round-trip tests verify generated agents are importable

Review Comments

🟡 Re: @kovtcharov's comment on system_prompt.py:38

The reviewer noted that the tool-calling instructions (lines 38-46) belong in the core agent class. I agree this is good feedback for a future refactor. Currently:

  • system_prompt.py:38-46 contains Builder-specific tool-calling format:

    ## How to call tools
    When you need to call a tool, output ONLY a JSON object on a single line:
    {"tool": "create_agent", "tool_args": {...}}
    
  • agent.py:182-199 already has a generic _response_format_template in the base Agent class

The Builder uses a simplified conversational flow (see BuilderAgent._compose_system_prompt() at agent.py:175-191) that deliberately excludes the base class's planning-heavy format. Moving the tool-calling instructions to the core class would require:

  1. Making the format configurable (conversational vs. planning-heavy)
  2. Updating all agents that override _compose_system_prompt()

Recommendation: This is a valid refactor but could be done in a follow-up PR to keep this one focused.

🟢 Verified: Model Resolution

resolve_model is correctly wired into the chat flow at:

  • _chat_helpers.py:469 (non-streaming)
  • _chat_helpers.py:720 (streaming)

🟢 Verified: TOCTOU Fix

Cache eviction correctly happens before DB write:

  • sessions.py:89 calls evict_session_agent() before db.update_session()

🟢 Documentation

custom-agent.mdx:44 correctly says agent.py (not agent.yaml as noted in earlier reviews).


Minor Suggestions (Non-Blocking)

  1. Agent ID validation in API (routers/agents.py:50): The :path type allows slashes. Consider adding explicit validation before lookup.

  2. Dependency timeout (dispatch.py:24): _DEPENDENCY_TIMEOUT = 600.0 (10 min) seems long; consider making it configurable.

  3. MCP failure logging (registry.py:441-443): When MCP init fails for agents with explicit mcp_servers, consider including the server names in the warning.

  4. File size (_chat_helpers.py): Now 1355 lines — consider splitting agent instantiation into a separate module in a future PR.


Recommendation

Approve. This is a solid implementation that significantly enhances GAIA's extensibility. The architecture is clean, security is well-considered, and test coverage is comprehensive. The reviewer's suggestion about moving tool instructions to the core class is valid but can be addressed in a follow-up PR.


| Branch: feat/issue-612-agent-registry

itomek added 3 commits April 9, 2026 13:24
Add response_mode attribute and _FORMAT_TEMPLATES dict to the base Agent
class so tool-calling instructions are defined once instead of duplicated
across six agents. Agents select "planning" (JSON-only, default) or
"conversational" (plain text + JSON tool calls) mode.

- Move _response_format_template content to class-level _PLANNING_FORMAT
  and _CONVERSATIONAL_FORMAT constants with dict dispatch
- BuilderAgent: set response_mode="conversational", remove
  _compose_system_prompt() override
- Remove duplicate format blocks from Blender, Docker, Jira, SD agents
  (fixes bug where LLM received format instructions twice)
- Add $PREV/$STEP_N placeholder docs to _PLANNING_FORMAT
- Add 19 unit tests with positive and negative assertions
When the LLM returns {"tool": null, "tool_args": {}}, the key-existence
check ("tool" in parsed) passes but the None value propagates to callers
that use it before _execute_tool fires, crashing on tool_name.lower().

- Change tool-call entry guards to value-truthiness (parsed.get("tool"),
  next_step.get("tool")) so None tool names skip execution entirely
- Add null-tool check to plan step validation so malformed steps trigger
  LLM correction rather than silent propagation
- Add defense-in-depth guard at top of _execute_tool for future callers

Adds unit tests covering None and empty-string tool name paths.
…st tool warning

- Align _SAFE_ID_RE in builder/agent.py with AgentManifest.validate_id
  in registry.py to allow single-character agent IDs
- Fix max_steps type annotation from int to Optional[int] in
  BuilderAgent.process_query
- Add logger.warning when a manifest agent requests a tool mixin that
  has no register_<tool>_tools() method, so missing tools are diagnosable
@itomek

itomek commented Apr 9, 2026

Copy link
Copy Markdown
Collaborator Author

@claude review this pr

@github-actions

github-actions Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @itomek's task —— View job


PR Review Complete

  • Read the full PR diff to understand changes
  • Review architecture and code quality
  • Check security considerations
  • Review test coverage
  • Provide final assessment

Summary

This is a well-executed feature PR introducing three major components to GAIA:

  1. Agent Registry — Discovery and lifecycle management for built-in, custom Python, and YAML manifest agents
  2. Builder Agent — Conversational agent creation through the UI with hot-reload
  3. DispatchQueue — Boot-time task orchestration with frontend progress visibility

Strengths

Architecture

  • Clean separation: Registry (registry.py), builder (agents/builder/), and dispatch (ui/dispatch.py) are well-isolated
  • Thread-safe registry with threading.Lock at registry.py:97
  • Agent caching with proper eviction on agent_type/model changes (_chat_helpers.py:93-114)
  • Dynamic class generation for YAML manifest agents is elegant

Security

  • Path traversal protection (agent.py:349-352)
  • Reserved agent ID blocking (_RESERVED_IDS at agent.py:28)
  • Agent ID validation with regex (registry.py:63, models.py:140)
  • AST syntax validation before writing (agent.py:384-388)
  • Path containment in register_from_dir (registry.py:496-504)

Testing

  • Excellent coverage: 400+ lines for registry, 600+ lines for builder
  • Edge cases covered: special characters, path traversal, cleanup on failure, MCP integration
  • Round-trip tests verify generated agents are importable

Verified Items from Previous Reviews

Item Status
Documentation typo (agent.yaml → agent.py) ✅ Fixed at custom-agent.mdx:44
resolve_model wired into chat flow ✅ Confirmed at _chat_helpers.py:468-478 and 719-728
TOCTOU fix (cache eviction before DB write) ✅ Confirmed at sessions.py:88-89
Agent ID validation at multiple layers ✅ Manifest validator + API validation

Review Comment Response

Re: @kovtcharov's comment on system_prompt.py:38

"Minor thing but these really belong in the core agent class."

This is valid feedback. Currently:

  • system_prompt.py:38-42 has Builder-specific tool-calling format
  • agent.py:182-199 already has a generic _response_format_template in the base Agent class

The Builder uses a simplified conversational flow (see BuilderAgent._compose_system_prompt()) that deliberately excludes the base class's planning-heavy format. Moving these instructions to the core class would require making the format configurable (conversational vs. planning-heavy).

Recommendation: Address in a follow-up PR to keep this one focused.


Minor Suggestions (Non-blocking)

# Item Location Suggestion
1 Dependency timeout dispatch.py:23 _DEPENDENCY_TIMEOUT = 600.0 (10 min) seems long; consider making configurable
2 MCP failure logging registry.py:449-451 Consider including server names in warning when MCP init fails for agents with explicit mcp_servers
3 Agent ID validation in API routers/agents.py:50 The :path type allows slashes; consider explicit validation before lookup
4 File size _chat_helpers.py Now 1355 lines — consider splitting agent instantiation into a separate module

Recommendation

Approve. This is a solid implementation that significantly enhances GAIA's extensibility. The architecture is clean, security is well-considered, and test coverage is comprehensive. The reviewer's suggestion about moving tool instructions to the core class is valid but can be addressed in a follow-up PR.

Closes #612, #713.


View job | Branch: feat/issue-612-agent-registry

@itomek
itomek added this pull request to the merge queue Apr 9, 2026
Merged via the queue into main with commit 4d24071 Apr 9, 2026
38 checks passed
@itomek
itomek deleted the feat/issue-612-agent-registry branch April 9, 2026 19:04
@itomek itomek mentioned this pull request Apr 10, 2026
github-merge-queue Bot pushed a commit that referenced this pull request Apr 10, 2026
Release notes for v0.17.2. See
[docs/releases/v0.17.2.mdx](https://github.com/amd/gaia/blob/v0.17.2-release/docs/releases/v0.17.2.mdx)
for the full body.

**Headline features:**
- One-click desktop installers for Windows, macOS, and Linux (#731 +
#743)
- Customizable agents and Builder Agent (#720)
- MCP tool execution visibility in Agent Activity panel (#717)

**Security:** RAG cache integrity verification (#722, closes #447)

**Bug fixes:** drag-and-drop upload in any browser (#729), Linux install
fixes (#743)

**Release & CI:** unified publish workflow (#715), Claude review on fork
PRs (#685), npm OIDC fix (#683), webui package.json sync (#682)

Full changelog: v0.17.1...v0.17.2

---------

Co-authored-by: Tomasz Iniewicz <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Dependency updates documentation Documentation changes electron Electron app changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Agent UI: Agent Registry and Selection

2 participants