Repository navigation
feat: agent registry with per-session agent selection - #720
Conversation
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]>
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
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
…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
7390824 to
b8be3c6
Compare
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.
- 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
|
@claude review this PR |
|
Claude finished @itomek's task —— View job PR Review CompleteThank 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: SummaryThis PR introduces a powerful extensibility framework for GAIA with three major features:
StrengthsArchitecture
Security
Testing
Issues & Suggestions🔴 Critical1. TOCTOU Race in Agent Cache Eviction ( 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 Suggestion: Move the cache eviction to happen atomically with the DB update in 🟡 Important2. Model Resolution Never Used ( Suggestion: Call 3. Manifest Agent Instantiation Fragility ( Suggestion: Log at warning level when MCP initialization fails for agents that explicitly define 4. Missing Input Validation in Agents Router ( Suggestion: Validate 🟢 Minor5. Tool Registry Clearing Side Effect ( 6. Dependency Timeout ( 7. Documentation Typo (
Should be Code QualityWell Done
Suggestions
Test Plan VerificationAll test plan items appear to be properly supported by the implementation:
RecommendationApprove 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:
|
- 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
|
@claude review this PR |
|
Claude finished @itomek's task —— View job PR Review CompleteThis is a substantial and well-architected feature PR that introduces agent extensibility to GAIA. Here's my comprehensive review: SummaryThree major features:
StrengthsArchitecture
Security
Testing
Issues & Suggestions🔴 Critical1. Documentation Typo (
Should be 🟡 Important2. The 3. Manifest Agent MCP Initialization Logging ( When MCP initialization fails for agents that explicitly define 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 ( The previous review mentioned a TOCTOU race. Looking at the code:
The fix at 5. @router.get("/api/agents/{agent_id:path}", response_model=AgentInfo)Using 🟢 Minor6. Tool Registry Clearing (
7. Dependency Timeout (
8. ChatView Complexity ( The file is 600+ lines with complex callback chains. Consider extracting the agent picker logic into a separate component for maintainability. Code QualityWell Done
Suggestions
Test Plan VerificationAll test plan items are properly supported by the implementation:
Required Fix Before MergeDocumentation typo at Change: To: RecommendationApprove 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
|
@claude review this PR |
|
Claude finished @itomek's task —— View job PR Review CompleteThis is a substantial and well-architected feature PR that introduces agent extensibility to GAIA. Here's my comprehensive review: SummaryThree major features:
StrengthsArchitecture
Security
Testing
Issues & Suggestions🟡 Important1. Documentation Typo Fixed — Previous reviews mentioned This is now correct — the documentation accurately states 2. The
The model resolution only happens for non-chat agents ( 3. Cache Eviction Order Correct The TOCTOU fix is properly implemented:
4. Agent ID Validation in API The
🟢 Suggestion: Consider adding explicit validation in 🟢 Minor5. Tool Registry Clearing (
6. Dependency Timeout (
7. MCP Initialization Logging ( When MCP initialization fails for agents that explicitly define 8. Lemonade Backoff Logic ( The Code QualityWell Done
Suggestions
Test Plan VerificationAll test plan items are properly supported by the implementation:
RecommendationApprove. This is a solid implementation that significantly enhances GAIA's extensibility. The issues identified in previous reviews have been addressed:
The remaining suggestions are minor and can be addressed in follow-up PRs. |
|
Claude finished @kovtcharov's task —— View job PR Review Complete
SummaryThis is a well-architected feature PR introducing agent extensibility to GAIA with three major components:
StrengthsArchitecture
Security
Testing
Review Comments🟡 Re: @kovtcharov's comment on
|
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
|
@claude review this pr |
|
Claude finished @itomek's task —— View job PR Review Complete
SummaryThis is a well-executed feature PR introducing three major components to GAIA:
StrengthsArchitecture
Security
Testing
Verified Items from Previous Reviews
Review Comment ResponseRe: @kovtcharov's comment on
|
| # | 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.
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]>
Summary
~/.gaia/agents/*/agent.py), and YAML manifests (~/.gaia/agents/*/agent.yaml)agent_type; the correct agent is instantiated on cache miss~/.gaia/agents/and it appears in the UI after a server restartagent.py(with optional MCP scaffolding) and auto-refreshes the selector without a server restart_check_lemonadeand_import_modulesrun in parallel at startup;_load_modelruns after_check_lemonadecompletes; all tasks report progress to the frontenddocs/guides/custom-agent.mdxCloses #612, #713
Test plan
python -m pytest tests/unit/agents/ tests/unit/chat/ui/— all tests pass~/.gaia/agents/<name>/agent.py; appears in selector immediately~/.gaia/agents/<name>/agent.yamlappears after server restart