AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(copilot): local agent generation with validation, fixing, MCP & sub-agent support (#12238)
Zamil Majdy6491cb1e23e5
diff --git a/autogpt_platform/backend/backend/blocks/_base.py b/autogpt_platform/backend/backend/blocks/_base.pyindex 632c5e43b9..10558468a0 100644--- a/autogpt_platform/backend/backend/blocks/_base.py+++ b/autogpt_platform/backend/backend/blocks/_base.py@@ -418,6 +418,8 @@ class BlockWebhookConfig(BlockManualWebhookConfig):class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):+ _optimized_description: ClassVar[str | None] = None+def __init__(self,id: str = "",@@ -470,6 +472,8 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):self.block_type = block_typeself.webhook_config = webhook_configself.is_sensitive_action = is_sensitive_action+ # Read from ClassVar set by initialize_blocks()+ self.optimized_description: str | None = type(self)._optimized_descriptionself.execution_stats: "NodeExecutionStats" = NodeExecutionStats()if self.webhook_config:diff --git a/autogpt_platform/backend/backend/blocks/llm.py b/autogpt_platform/backend/backend/blocks/llm.pyindex eb96122c4d..c71aec8235 100644--- a/autogpt_platform/backend/backend/blocks/llm.py+++ b/autogpt_platform/backend/backend/blocks/llm.py@@ -31,6 +31,7 @@ from backend.data.model import ()from backend.integrations.providers import ProviderNamefrom backend.util import json+from backend.util.clients import OPENROUTER_BASE_URLfrom backend.util.logging import TruncatedLoggerfrom backend.util.prompt import compress_context, estimate_token_countfrom backend.util.text import TextFormatter@@ -825,7 +826,7 @@ async def llm_call(elif provider == "open_router":tools_param = tools if tools else openai.NOT_GIVENclient = openai.AsyncOpenAI(- base_url="https://openrouter.ai/api/v1",+ base_url=OPENROUTER_BASE_URL,api_key=credentials.api_key.get_secret_value(),)diff --git a/autogpt_platform/backend/backend/blocks/perplexity.py b/autogpt_platform/backend/backend/blocks/perplexity.pyindex 270081a3a8..fdb4fdd848 100644--- a/autogpt_platform/backend/backend/blocks/perplexity.py+++ b/autogpt_platform/backend/backend/blocks/perplexity.py@@ -21,6 +21,7 @@ from backend.data.model import (SchemaField,)from backend.integrations.providers import ProviderName+from backend.util.clients import OPENROUTER_BASE_URLfrom backend.util.logging import TruncatedLoggerlogger = TruncatedLogger(logging.getLogger(__name__), "[Perplexity-Block]")@@ -136,7 +137,7 @@ class PerplexityBlock(Block):) -> dict[str, Any]:"""Call Perplexity via OpenRouter and extract annotations."""client = openai.AsyncOpenAI(- base_url="https://openrouter.ai/api/v1",+ base_url=OPENROUTER_BASE_URL,api_key=credentials.api_key.get_secret_value(),)diff --git a/autogpt_platform/backend/backend/copilot/config.py b/autogpt_platform/backend/backend/copilot/config.pyindex d4b0df2d59..7f18e8f129 100644--- a/autogpt_platform/backend/backend/copilot/config.py+++ b/autogpt_platform/backend/backend/copilot/config.py@@ -6,6 +6,8 @@ from typing import Literalfrom pydantic import Field, field_validatorfrom pydantic_settings import BaseSettings+from backend.util.clients import OPENROUTER_BASE_URL+class ChatConfig(BaseSettings):"""Configuration for the chat system."""@@ -20,7 +22,7 @@ class ChatConfig(BaseSettings):)api_key: str | None = Field(default=None, description="OpenAI API key")base_url: str | None = Field(- default="https://openrouter.ai/api/v1",+ default=OPENROUTER_BASE_URL,description="Base URL for API (e.g., for OpenRouter)",)@@ -193,7 +195,7 @@ class ChatConfig(BaseSettings):if not v:v = os.getenv("OPENAI_BASE_URL")if not v:- v = "https://openrouter.ai/api/v1"+ v = OPENROUTER_BASE_URLreturn v@field_validator("use_claude_agent_sdk", mode="before")diff --git a/autogpt_platform/backend/backend/copilot/optimize_blocks.py b/autogpt_platform/backend/backend/copilot/optimize_blocks.pynew file mode 100644index 0000000000..af8c8ffa12--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/optimize_blocks.py@@ -0,0 +1,138 @@+"""Scheduler job to generate LLM-optimized block descriptions.++Runs periodically to rewrite block descriptions into concise, actionable+summaries that help the copilot LLM pick the right blocks during agent+generation.+"""++import asyncio+import logging++from backend.blocks import get_blocks+from backend.util.clients import get_database_manager_client, get_openai_client++logger = logging.getLogger(__name__)++SYSTEM_PROMPT = (+ "You are a technical writer for an automation platform. "+ "Rewrite the following block description to be concise (under 50 words), "+ "informative, and actionable. Focus on what the block does and when to "+ "use it. Output ONLY the rewritten description, nothing else. "+ "Do not use markdown formatting."+)++# Rate-limit delay between sequential LLM calls (seconds)+_RATE_LIMIT_DELAY = 0.5+# Maximum tokens for optimized description generation+_MAX_DESCRIPTION_TOKENS = 150+# Model for generating optimized descriptions (fast, cheap)+_MODEL = "gpt-4o-mini"+++async def _optimize_descriptions(blocks: list[dict[str, str]]) -> dict[str, str]:+ """Call the shared OpenAI client to rewrite each block description."""+ client = get_openai_client()+ if client is None:+ logger.error(+ "No OpenAI client configured, skipping block description optimization"+ )+ return {}++ results: dict[str, str] = {}+ for block in blocks:+ block_id = block["id"]+ block_name = block["name"]+ description = block["description"]++ try:+ response = await client.chat.completions.create(+ model=_MODEL,+ messages=[+ {"role": "system", "content": SYSTEM_PROMPT},+ {+ "role": "user",+ "content": f"Block name: {block_name}\nDescription: {description}",+ },+ ],+ max_tokens=_MAX_DESCRIPTION_TOKENS,+ )+ optimized = (response.choices[0].message.content or "").strip()+ if optimized:+ results[block_id] = optimized+ logger.debug("Optimized description for %s", block_name)+ else:+ logger.warning("Empty response for block %s", block_name)+ except Exception:+ logger.warning(+ "Failed to optimize description for %s", block_name, exc_info=True+ )++ await asyncio.sleep(_RATE_LIMIT_DELAY)++ return results+++def optimize_block_descriptions() -> dict[str, int]:+ """Generate optimized descriptions for blocks that don't have one yet.++ Uses the shared OpenAI client to rewrite block descriptions into concise+ summaries suitable for agent generation prompts.++ Returns:+ Dict with counts: processed, success, failed, skipped.+ """+ db_client = get_database_manager_client()++ blocks = db_client.get_blocks_needing_optimization()+ if not blocks:+ logger.info("All blocks already have optimized descriptions")+ return {"processed": 0, "success": 0, "failed": 0, "skipped": 0}++ logger.info("Found %d blocks needing optimized descriptions", len(blocks))++ non_empty = [b for b in blocks if b.get("description", "").strip()]+ skipped = len(blocks) - len(non_empty)++ new_descriptions = asyncio.run(_optimize_descriptions(non_empty))++ stats = {+ "processed": len(non_empty),+ "success": len(new_descriptions),+ "failed": len(non_empty) - len(new_descriptions),+ "skipped": skipped,+ }++ logger.info(+ "Block description optimization complete: "+ "%d/%d succeeded, %d failed, %d skipped",+ stats["success"],+ stats["processed"],+ stats["failed"],+ stats["skipped"],+ )++ if new_descriptions:+ for block_id, optimized in new_descriptions.items():+ db_client.update_block_optimized_description(block_id, optimized)++ # Update in-memory descriptions first so the cache rebuilds with fresh data.+ try:+ block_classes = get_blocks()+ for block_id, optimized in new_descriptions.items():+ if block_id in block_classes:+ block_classes[block_id]._optimized_description = optimized+ logger.info(+ "Updated %d in-memory block descriptions", len(new_descriptions)+ )+ except Exception:+ logger.warning(+ "Could not update in-memory block descriptions", exc_info=True+ )++ from backend.copilot.tools.agent_generator.blocks import (+ reset_block_caches, # local to avoid circular import+ )++ reset_block_caches()++ return statsdiff --git a/autogpt_platform/backend/backend/copilot/optimize_blocks_test.py b/autogpt_platform/backend/backend/copilot/optimize_blocks_test.pynew file mode 100644index 0000000000..a34fcf998f--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/optimize_blocks_test.py@@ -0,0 +1,91 @@+"""Unit tests for optimize_blocks._optimize_descriptions."""++import asyncio+from unittest.mock import AsyncMock, MagicMock, patch++from backend.copilot.optimize_blocks import _RATE_LIMIT_DELAY, _optimize_descriptions+++def _make_client_response(text: str) -> MagicMock:+ """Build a minimal mock that looks like an OpenAI ChatCompletion response."""+ choice = MagicMock()+ choice.message.content = text+ response = MagicMock()+ response.choices = [choice]+ return response+++def _run(coro):+ return asyncio.get_event_loop().run_until_complete(coro)+++class TestOptimizeDescriptions:+ """Tests for _optimize_descriptions async function."""++ def test_returns_empty_when_no_client(self):+ with patch(+ "backend.copilot.optimize_blocks.get_openai_client", return_value=None+ ):+ result = _run(+ _optimize_descriptions([{"id": "b1", "name": "B", "description": "d"}])+ )+ assert result == {}++ def test_success_single_block(self):+ client = MagicMock()+ client.chat.completions.create = AsyncMock(+ return_value=_make_client_response("Short desc.")+ )+ blocks = [{"id": "b1", "name": "MyBlock", "description": "A block."}]++ with (+ patch(+ "backend.copilot.optimize_blocks.get_openai_client", return_value=client+ ),+ patch(+ "backend.copilot.optimize_blocks.asyncio.sleep", new_callable=AsyncMock+ ),+ ):+ result = _run(_optimize_descriptions(blocks))++ assert result == {"b1": "Short desc."}+ client.chat.completions.create.assert_called_once()++ def test_skips_block_on_exception(self):+ client = MagicMock()+ client.chat.completions.create = AsyncMock(side_effect=Exception("API error"))+ blocks = [{"id": "b1", "name": "MyBlock", "description": "A block."}]++ with (+ patch(+ "backend.copilot.optimize_blocks.get_openai_client", return_value=client+ ),+ patch(+ "backend.copilot.optimize_blocks.asyncio.sleep", new_callable=AsyncMock+ ),+ ):+ result = _run(_optimize_descriptions(blocks))++ assert result == {}++ def test_sleeps_between_blocks(self):+ client = MagicMock()+ client.chat.completions.create = AsyncMock(+ return_value=_make_client_response("desc")+ )+ blocks = [+ {"id": "b1", "name": "B1", "description": "d1"},+ {"id": "b2", "name": "B2", "description": "d2"},+ ]+ sleep_mock = AsyncMock()++ with (+ patch(+ "backend.copilot.optimize_blocks.get_openai_client", return_value=client+ ),+ patch("backend.copilot.optimize_blocks.asyncio.sleep", sleep_mock),+ ):+ _run(_optimize_descriptions(blocks))++ assert sleep_mock.call_count == 2+ sleep_mock.assert_called_with(_RATE_LIMIT_DELAY)diff --git a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.mdnew file mode 100644index 0000000000..3e81220bb3--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md@@ -0,0 +1,155 @@+## Agent Generation Guide++You can create, edit, and customize agents directly. You ARE the brain —+generate the agent JSON yourself using block schemas, then validate and save.++### Workflow for Creating/Editing Agents++1. **Discover blocks**: Call `find_block(query, include_schemas=true)` to+ search for relevant blocks. This returns block IDs, names, descriptions,+ and full input/output schemas.+2. **Find library agents**: Call `find_library_agent` to discover reusable+ agents that can be composed as sub-agents via `AgentExecutorBlock`.+3. **Generate JSON**: Build the agent JSON using block schemas:+ - Use block IDs from step 1 as `block_id` in nodes+ - Wire outputs to inputs using links+ - Set design-time config in `input_default`+ - Use `AgentInputBlock` for values the user provides at runtime+4. **Write to workspace**: Save the JSON to a workspace file so the user+ can review it: `write_workspace_file(filename="agent.json", content=...)`+5. **Validate**: Call `validate_agent_graph` with the agent JSON to check+ for errors+6. **Fix if needed**: Call `fix_agent_graph` to auto-fix common issues,+ or fix manually based on the error descriptions. Iterate until valid.+7. **Save**: Call `create_agent` (new) or `edit_agent` (existing) with+ the final `agent_json`++### Agent JSON Structure++```json+{+ "id": "<UUID v4>", // auto-generated if omitted+ "version": 1,+ "is_active": true,+ "name": "Agent Name",+ "description": "What the agent does",+ "nodes": [+ {+ "id": "<UUID v4>",+ "block_id": "<block UUID from find_block>",+ "input_default": {+ "field_name": "design-time value"+ },+ "metadata": {+ "position": {"x": 0, "y": 0},+ "customized_name": "Optional display name"+ }+ }+ ],+ "links": [+ {+ "id": "<UUID v4>",+ "source_id": "<source node UUID>",+ "source_name": "output_field_name",+ "sink_id": "<sink node UUID>",+ "sink_name": "input_field_name",+ "is_static": false+ }+ ]+}+```++### REQUIRED: AgentInputBlock and AgentOutputBlock++Every agent MUST include at least one AgentInputBlock and one AgentOutputBlock.+These define the agent's interface — what it accepts and what it produces.++**AgentInputBlock** (ID: `c0a8e994-ebf1-4a9c-a4d8-89d09c86741b`):+- Defines a user-facing input field on the agent+- Required `input_default` fields: `name` (str), `value` (default: null)+- Optional: `title`, `description`, `placeholder_values` (for dropdowns)+- Output: `result` — the user-provided value at runtime+- Create one AgentInputBlock per distinct input the agent needs++**AgentOutputBlock** (ID: `363ae599-353e-4804-937e-b2ee3cef3da4`):+- Defines a user-facing output displayed after the agent runs+- Required `input_default` fields: `name` (str)+- The `value` input should be linked from another block's output+- Optional: `title`, `description`, `format` (Jinja2 template)+- Create one AgentOutputBlock per distinct result to show the user++Without these blocks, the agent has no interface and the user cannot provide+inputs or see outputs. NEVER skip them.++### Key Rules++- **Name & description**: Include `name` and `description` in the agent JSON+ when creating a new agent, or when editing and the agent's purpose changed.+ Without these the agent gets a generic default name.+- **Design-time vs runtime**: `input_default` = values known at build time.+ For user-provided values, create an `AgentInputBlock` node and link its+ output to the consuming block's input.+- **Credentials**: Do NOT require credentials upfront. Users configure+ credentials later in the platform UI after the agent is saved.+- **Node spacing**: Position nodes with at least 800 X-units between them.+- **Nested properties**: Use `parentField_#_childField` notation in link+ sink_name/source_name to access nested object fields.+- **is_static links**: Set `is_static: true` when the link carries a+ design-time constant (matches a field in inputSchema with a default).+- **ConditionBlock**: Needs a `StoreValueBlock` wired to its `value2` input.+- **Prompt templates**: Use `{{variable}}` (double curly braces) for+ literal braces in prompt strings — single `{` and `}` are for+ template variables.+- **AgentExecutorBlock**: When composing sub-agents, set `graph_id` and+ `graph_version` in input_default, and wire inputs/outputs to match+ the sub-agent's schema.++### Using Sub-Agents (AgentExecutorBlock)++To compose agents using other agents as sub-agents:+1. Call `find_library_agent` to find the sub-agent — the response includes+ `graph_id`, `graph_version`, `input_schema`, and `output_schema`+2. Create an `AgentExecutorBlock` node (ID: `e189baac-8c20-45a1-94a7-55177ea42565`)+3. Set `input_default`:+ - `graph_id`: from the library agent's `graph_id`+ - `graph_version`: from the library agent's `graph_version`+ - `input_schema`: from the library agent's `input_schema` (JSON Schema)+ - `output_schema`: from the library agent's `output_schema` (JSON Schema)+ - `user_id`: leave as `""` (filled at runtime)+ - `inputs`: `{}` (populated by links at runtime)+4. Wire inputs: link to sink names matching the sub-agent's `input_schema`+ property names (e.g., if input_schema has a `"url"` property, use+ `"url"` as the sink_name)+5. Wire outputs: link from source names matching the sub-agent's+ `output_schema` property names+6. Pass `library_agent_ids` to `create_agent`/`customize_agent` with+ the library agent IDs used, so the fixer can validate schemas++### Using MCP Tools (MCPToolBlock)++To use an MCP (Model Context Protocol) tool as a node in the agent:+1. The user must specify which MCP server URL and tool name they want+2. Create an `MCPToolBlock` node (ID: `a0a4b1c2-d3e4-4f56-a7b8-c9d0e1f2a3b4`)+3. Set `input_default`:+ - `server_url`: the MCP server URL (e.g. `"https://mcp.example.com/sse"`)+ - `selected_tool`: the tool name on that server+ - `tool_input_schema`: JSON Schema for the tool's inputs+ - `tool_arguments`: `{}` (populated by links or hardcoded values)+4. The block requires MCP credentials — the user configures these in the+ platform UI after the agent is saved+5. Wire inputs using the tool argument field name directly as the sink_name+ (e.g., `query`, NOT `tool_arguments_#_query`). The execution engine+ automatically collects top-level fields matching tool_input_schema into+ tool_arguments.+6. Output: `result` (the tool's return value) and `error` (error message)++### Example: Simple AI Text Processor++A minimal agent with input, processing, and output:+- Node 1: `AgentInputBlock` (ID: `c0a8e994-ebf1-4a9c-a4d8-89d09c86741b`,+ input_default: {"name": "user_text", "title": "Text to process"},+ output: "result")+- Node 2: `AITextGeneratorBlock` (input: "prompt" linked from Node 1's "result")+- Node 3: `AgentOutputBlock` (ID: `363ae599-353e-4804-937e-b2ee3cef3da4`,+ input_default: {"name": "summary", "title": "Summary"},+ input: "value" linked from Node 2's output)diff --git a/autogpt_platform/backend/backend/copilot/sdk/mcp_tool_guide.md b/autogpt_platform/backend/backend/copilot/sdk/mcp_tool_guide.mdnew file mode 100644index 0000000000..d44dbf790b--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sdk/mcp_tool_guide.md@@ -0,0 +1,28 @@+## MCP Tool Guide++### Workflow++`run_mcp_tool` follows a two-step pattern:++1. **Discover** — call with only `server_url` to list available tools on the server.+2. **Execute** — call again with `server_url`, `tool_name`, and `tool_arguments` to run a tool.++### Known hosted MCP servers++Use these URLs directly without asking the user:++| Service | URL |+|---|---|+| Notion | `https://mcp.notion.com/mcp` |+| Linear | `https://mcp.linear.app/mcp` |+| Stripe | `https://mcp.stripe.com` |+| Intercom | `https://mcp.intercom.com/mcp` |+| Cloudflare | `https://mcp.cloudflare.com/mcp` |+| Atlassian / Jira | `https://mcp.atlassian.com/mcp` |++For other services, search the MCP registry at https://registry.modelcontextprotocol.io/.++### Authentication++If the server requires credentials, a `SetupRequirementsResponse` is returned with an OAuth+login prompt. Once the user completes the flow and confirms, retry the same call immediately.diff --git a/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.pyindex bf05bb33e2..0999f13886 100644--- a/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py@@ -10,7 +10,6 @@ import osimport pytestfrom .security_hooks import _validate_tool_access, _validate_user_isolation-from .service import _is_tool_error_or_denialSDK_CWD = "/tmp/copilot-abc123"@@ -357,76 +356,3 @@ async def test_task_slot_released_on_failure(_hooks):context={},)assert not _is_denied(result)---# -- _is_tool_error_or_denial ---------------------------------------------------class TestIsToolErrorOrDenial:- def test_none_content(self):- assert _is_tool_error_or_denial(None) is False-- def test_empty_content(self):- assert _is_tool_error_or_denial("") is False-- def test_benign_output(self):- assert _is_tool_error_or_denial("All good, no issues.") is False-- def test_security_marker(self):- assert _is_tool_error_or_denial("[SECURITY] Tool access blocked") is True-- def test_cannot_be_bypassed(self):- assert _is_tool_error_or_denial("This restriction cannot be bypassed.") is True-- def test_not_allowed(self):- assert _is_tool_error_or_denial("Operation not allowed in sandbox") is True-- def test_background_task_denial(self):- assert (- _is_tool_error_or_denial(- "Background task execution is not supported. "- "Run tasks in the foreground instead."- )- is True- )-- def test_subtask_limit_denial(self):- assert (- _is_tool_error_or_denial(- "Maximum 2 concurrent sub-tasks. "- "Wait for running sub-tasks to finish, "- "or continue in the main conversation."- )- is True- )-- def test_denied_marker(self):- assert (- _is_tool_error_or_denial("Access denied: insufficient privileges") is True- )-- def test_blocked_marker(self):- assert _is_tool_error_or_denial("Request blocked by security policy") is True-- def test_failed_marker(self):- assert _is_tool_error_or_denial("Failed to execute tool: timeout") is True-- def test_mcp_iserror(self):- assert _is_tool_error_or_denial('{"isError": true, "content": []}') is True-- def test_benign_error_in_value(self):- """Content like '0 errors found' should not trigger — 'error' was removed."""- assert _is_tool_error_or_denial("0 errors found") is False-- def test_benign_permission_field(self):- """Schema descriptions mentioning 'permission' should not trigger."""- assert (- _is_tool_error_or_denial(- '{"fields": [{"name": "permission_level", "type": "int"}]}'- )- is False- )-- def test_benign_not_found_in_listing(self):- """File listing containing 'not found' in filenames should not trigger."""- assert _is_tool_error_or_denial("readme.md\nfile-not-found-handler.py") is Falsediff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex bfd2262ee2..7db5cbf4ea 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -456,31 +456,6 @@ def _format_conversation_context(messages: list[ChatMessage]) -> str | None:return "<conversation_history>\n" + "\n".join(lines) + "\n</conversation_history>"-def _is_tool_error_or_denial(content: str | None) -> bool:- """Check if a tool message content indicates an error or denial.-- Currently unused — ``_format_conversation_context`` includes all tool- results. Kept as a utility for future selective filtering.- """- if not content:- return False- lower = content.lower()- return any(- marker in lower- for marker in (- "[security]",- "cannot be bypassed",- "not allowed",- "not supported", # background-task denial- "maximum", # subtask-limit denial- "denied",- "blocked",- "failed to", # internal tool execution failures- '"iserror": true', # MCP protocol error flag- )- )--async def _build_query_message(current_message: str,session: ChatSession,@@ -838,7 +813,6 @@ async def stream_chat_completion_sdk(system_prompt = base_system_prompt + get_sdk_supplement(use_e2b=use_e2b, cwd=sdk_cwd)-# Process transcript download resulttranscript_msg_count = 0if dl:@@ -903,6 +877,11 @@ async def stream_chat_completion_sdk(allowed = get_copilot_tool_names(use_e2b=use_e2b)disallowed = get_sdk_disallowed_tools(use_e2b=use_e2b)++ def _on_stderr(line: str) -> None:+ sid = session_id[:12] if session_id else "?"+ logger.info("[SDK] [%s] CLI stderr: %s", sid, line.rstrip())+sdk_options_kwargs: dict[str, Any] = {"system_prompt": system_prompt,"mcp_servers": {"copilot": mcp_server},@@ -911,6 +890,7 @@ async def stream_chat_completion_sdk("hooks": security_hooks,"cwd": sdk_cwd,"max_buffer_size": config.claude_agent_max_buffer_size,+ "stderr": _on_stderr,}if sdk_model:sdk_options_kwargs["model"] = sdk_model@@ -1083,6 +1063,19 @@ async def stream_chat_completion_sdk(len(adapter.resolved_tool_calls),)+ # Log AssistantMessage API errors (e.g. invalid_request)+ # so we can debug Anthropic API 400s surfaced by the CLI.+ sdk_error = getattr(sdk_msg, "error", None)+ if isinstance(sdk_msg, AssistantMessage) and sdk_error:+ logger.error(+ "[SDK] [%s] AssistantMessage has error=%s, "+ "content_blocks=%d, content_preview=%s",+ session_id[:12],+ sdk_error,+ len(sdk_msg.content),+ str(sdk_msg.content)[:500],+ )+# Race-condition fix: SDK hooks (PostToolUse) are# executed asynchronously via start_soon() — the next# message can arrive before the hook stashes output.diff --git a/autogpt_platform/backend/backend/copilot/sdk/service_test.py b/autogpt_platform/backend/backend/copilot/sdk/service_test.pyindex 143687b274..b71ce82518 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service_test.py@@ -213,7 +213,7 @@ class TestPromptSupplement:# Workflows are now in individual tool descriptions (not separate sections)# Check that key workflow concepts appear in tool descriptions- assert "suggested_goal" in docs or "clarifying_questions" in docs+ assert "agent_json" in docs or "find_block" in docsassert "run_mcp_tool" in docsdef test_baseline_supplement_completeness(self):diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.pyindex 8c82003a0a..7389f822a3 100644--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py@@ -19,7 +19,10 @@ from .feature_requests import CreateFeatureRequestTool, SearchFeatureRequestsToofrom .find_agent import FindAgentToolfrom .find_block import FindBlockToolfrom .find_library_agent import FindLibraryAgentTool+from .fix_agent import FixAgentGraphTool+from .get_agent_building_guide import GetAgentBuildingGuideToolfrom .get_doc_page import GetDocPageTool+from .get_mcp_guide import GetMCPGuideToolfrom .manage_folders import (CreateFolderTool,DeleteFolderTool,@@ -32,6 +35,7 @@ from .run_agent import RunAgentToolfrom .run_block import RunBlockToolfrom .run_mcp_tool import RunMCPToolToolfrom .search_docs import SearchDocsTool+from .validate_agent import ValidateAgentGraphToolfrom .web_fetch import WebFetchToolfrom .workspace_files import (DeleteWorkspaceFileTool,@@ -65,9 +69,11 @@ TOOL_REGISTRY: dict[str, BaseTool] = {"run_agent": RunAgentTool(),"run_block": RunBlockTool(),"run_mcp_tool": RunMCPToolTool(),+ "get_mcp_guide": GetMCPGuideTool(),"view_agent_output": AgentOutputTool(),"search_docs": SearchDocsTool(),"get_doc_page": GetDocPageTool(),+ "get_agent_building_guide": GetAgentBuildingGuideTool(),# Web fetch for safe URL retrieval"web_fetch": WebFetchTool(),# Agent-browser multi-step automation (navigate, act, screenshot)@@ -80,6 +86,9 @@ TOOL_REGISTRY: dict[str, BaseTool] = {# Feature request tools"search_feature_requests": SearchFeatureRequestsTool(),"create_feature_request": CreateFeatureRequestTool(),+ # Agent generation tools (local validation/fixing)+ "validate_agent_graph": ValidateAgentGraphTool(),+ "fix_agent_graph": FixAgentGraphTool(),# Workspace tools for CoPilot file operations"list_workspace_files": ListWorkspaceFilesTool(),"read_workspace_file": ReadWorkspaceFileTool(),diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/__init__.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/__init__.pyindex 433431562e..e4afc1e3e3 100644--- a/autogpt_platform/backend/backend/copilot/tools/agent_generator/__init__.py+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/__init__.py@@ -1,20 +1,15 @@"""Agent generator package - Creates agents from natural language."""from .core import (- AgentGeneratorNotConfiguredError,AgentJsonValidationError,AgentSummary,DecompositionResult,DecompositionStep,LibraryAgentSummary,MarketplaceAgentSummary,- customize_template,- decompose_goal,enrich_library_agents_from_steps,extract_search_terms_from_steps,extract_uuids_from_text,- generate_agent,- generate_agent_patch,get_agent_as_json,get_all_relevant_agents_for_generation,get_library_agent_by_graph_id,@@ -27,25 +22,20 @@ from .core import (search_marketplace_agents_for_generation,)from .errors import get_user_message_for_error-from .service import health_check as check_external_service_health-from .service import is_external_service_configured+from .validation import AgentFixer, AgentValidator__all__ = [- "AgentGeneratorNotConfiguredError",+ "AgentFixer",+ "AgentValidator","AgentJsonValidationError","AgentSummary","DecompositionResult","DecompositionStep","LibraryAgentSummary","MarketplaceAgentSummary",- "check_external_service_health",- "customize_template",- "decompose_goal","enrich_library_agents_from_steps","extract_search_terms_from_steps","extract_uuids_from_text",- "generate_agent",- "generate_agent_patch","get_agent_as_json","get_all_relevant_agents_for_generation","get_library_agent_by_graph_id",@@ -54,7 +44,6 @@ __all__ = ["get_library_agents_for_generation","get_user_message_for_error","graph_to_json",- "is_external_service_configured","json_to_graph","save_agent_to_library","search_marketplace_agents_for_generation",diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/blocks.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/blocks.pynew file mode 100644index 0000000000..615f3a6860--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/blocks.py@@ -0,0 +1,66 @@+"""Block management for agent generation.++Provides cached access to block metadata for validation and fixing.+"""++import logging+from typing import Any, Type++from backend.blocks import get_blocks as get_block_classes+from backend.blocks._base import Block++logger = logging.getLogger(__name__)++__all__ = ["get_blocks_as_dicts", "reset_block_caches"]++# ---------------------------------------------------------------------------+# Module-level caches+# ---------------------------------------------------------------------------+_blocks_cache: list[dict[str, Any]] | None = None+++def reset_block_caches() -> None:+ """Reset all module-level caches (useful after updating block descriptions)."""+ global _blocks_cache+ _blocks_cache = None+++# ---------------------------------------------------------------------------+# 1. get_blocks_as_dicts+# ---------------------------------------------------------------------------+++def get_blocks_as_dicts() -> list[dict[str, Any]]:+ """Get all available blocks as dicts (cached after first call).++ Each dict contains the keys returned by ``Block.get_info().model_dump()``:+ id, name, description, inputSchema, outputSchema, categories,+ staticOutput, costs, contributors, uiType.++ Returns:+ List of block info dicts.+ """+ global _blocks_cache+ if _blocks_cache is not None:+ return _blocks_cache++ block_classes: dict[str, Type[Block]] = get_block_classes() # type: ignore[assignment]+ blocks: list[dict[str, Any]] = []+ for block_cls in block_classes.values():+ try:+ instance = block_cls()+ info = instance.get_info().model_dump()+ # Use optimized description if available (loaded at startup)+ if instance.optimized_description:+ info["description"] = instance.optimized_description+ blocks.append(info)+ except Exception:+ logger.warning(+ "Failed to load block info for %s, skipping",+ getattr(block_cls, "__name__", "unknown"),+ exc_info=True,+ )++ _blocks_cache = blocks+ logger.info("Cached %d block dicts", len(blocks))+ return _blocks_cachediff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/core.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/core.pyindex f2c10b879d..593b0d3d44 100644--- a/autogpt_platform/backend/backend/copilot/tools/agent_generator/core.py+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/core.py@@ -10,13 +10,7 @@ from backend.data.db_accessors import graph_db, library_db, store_dbfrom backend.data.graph import Graph, Link, Nodefrom backend.util.exceptions import DatabaseError, NotFoundError-from .service import (- customize_template_external,- decompose_goal_external,- generate_agent_external,- generate_agent_patch_external,- is_external_service_configured,-)+from .helpers import UUID_RE_STRlogger = logging.getLogger(__name__)@@ -78,38 +72,7 @@ class DecompositionResult(TypedDict, total=False):AgentSummary = LibraryAgentSummary | MarketplaceAgentSummary | dict[str, Any]-def _to_dict_list(- agents: Sequence[AgentSummary] | Sequence[dict[str, Any]] | None,-) -> list[dict[str, Any]] | None:- """Convert typed agent summaries to plain dicts for external service calls."""- if agents is None:- return None- return [dict(a) for a in agents]---class AgentGeneratorNotConfiguredError(Exception):- """Raised when the external Agent Generator service is not configured."""-- pass---def _check_service_configured() -> None:- """Check if the external Agent Generator service is configured.-- Raises:- AgentGeneratorNotConfiguredError: If the service is not configured.- """- if not is_external_service_configured():- raise AgentGeneratorNotConfiguredError(- "Agent Generator service is not configured. "- "Set AGENTGENERATOR_HOST environment variable to enable agent generation."- )---_UUID_PATTERN = re.compile(- r"[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}",- re.IGNORECASE,-)+_UUID_PATTERN = re.compile(UUID_RE_STR, re.IGNORECASE)def extract_uuids_from_text(text: str) -> list[str]:@@ -553,69 +516,6 @@ async def enrich_library_agents_from_steps(return all_agents-async def decompose_goal(- description: str,- context: str = "",- library_agents: Sequence[AgentSummary] | None = None,-) -> DecompositionResult | None:- """Break down a goal into steps or return clarifying questions.-- Args:- description: Natural language goal description- context: Additional context (e.g., answers to previous questions)- library_agents: User's library agents available for sub-agent composition-- Returns:- DecompositionResult with either:- - {"type": "clarifying_questions", "questions": [...]}- - {"type": "instructions", "steps": [...]}- Or None on error-- Raises:- AgentGeneratorNotConfiguredError: If the external service is not configured.- """- _check_service_configured()- logger.info("Calling external Agent Generator service for decompose_goal")- result = await decompose_goal_external(- description, context, _to_dict_list(library_agents)- )- return result # type: ignore[return-value]---async def generate_agent(- instructions: DecompositionResult | dict[str, Any],- library_agents: Sequence[AgentSummary] | Sequence[dict[str, Any]] | None = None,-) -> dict[str, Any] | None:- """Generate agent JSON from instructions.-- Args:- instructions: Structured instructions from decompose_goal- library_agents: User's library agents available for sub-agent composition-- Returns:- Agent JSON dict, error dict {"type": "error", ...}, or None on error-- Raises:- AgentGeneratorNotConfiguredError: If the external service is not configured.- """- _check_service_configured()- logger.info("Calling external Agent Generator service for generate_agent")- result = await generate_agent_external(- dict(instructions), _to_dict_list(library_agents)- )-- if result:- if isinstance(result, dict) and result.get("type") == "error":- return result- if "id" not in result:- result["id"] = str(uuid.uuid4())- if "version" not in result:- result["version"] = 1- if "is_active" not in result:- result["is_active"] = True- return result--class AgentJsonValidationError(Exception):"""Raised when agent JSON is invalid or missing required fields."""@@ -792,70 +692,3 @@ async def get_agent_as_json(return Nonereturn graph_to_json(graph)---async def generate_agent_patch(- update_request: str,- current_agent: dict[str, Any],- library_agents: Sequence[AgentSummary] | None = None,-) -> dict[str, Any] | None:- """Update an existing agent using natural language.-- The external Agent Generator service handles:- - Generating the patch- - Applying the patch- - Fixing and validating the result-- Args:- update_request: Natural language description of changes- current_agent: Current agent JSON- library_agents: User's library agents available for sub-agent composition-- Returns:- Updated agent JSON, clarifying questions dict {"type": "clarifying_questions", ...},- error dict {"type": "error", ...}, or None on error-- Raises:- AgentGeneratorNotConfiguredError: If the external service is not configured.- """- _check_service_configured()- logger.info("Calling external Agent Generator service for generate_agent_patch")- return await generate_agent_patch_external(- update_request,- current_agent,- _to_dict_list(library_agents),- )---async def customize_template(- template_agent: dict[str, Any],- modification_request: str,- context: str = "",-) -> dict[str, Any] | None:- """Customize a template/marketplace agent using natural language.-- This is used when users want to modify a template or marketplace agent- to fit their specific needs before adding it to their library.-- The external Agent Generator service handles:- - Understanding the modification request- - Applying changes to the template- - Fixing and validating the result-- Args:- template_agent: The template agent JSON to customize- modification_request: Natural language description of customizations- context: Additional context (e.g., answers to previous questions)-- Returns:- Customized agent JSON, clarifying questions dict {"type": "clarifying_questions", ...},- error dict {"type": "error", ...}, or None on unexpected error-- Raises:- AgentGeneratorNotConfiguredError: If the external service is not configured.- """- _check_service_configured()- logger.info("Calling external Agent Generator service for customize_template")- return await customize_template_external(- template_agent, modification_request, context- )diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/dummy.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/dummy.pydeleted file mode 100644index 3cf2e95316..0000000000--- a/autogpt_platform/backend/backend/copilot/tools/agent_generator/dummy.py+++ /dev/null@@ -1,165 +0,0 @@-"""Dummy Agent Generator for testing.--Returns mock responses matching the format expected from the external service.-Enable via AGENTGENERATOR_USE_DUMMY=true in settings.--WARNING: This is for testing only. Do not use in production.-"""--import asyncio-import logging-import uuid-from typing import Any--logger = logging.getLogger(__name__)--# Dummy decomposition result (instructions type)-DUMMY_DECOMPOSITION_RESULT: dict[str, Any] = {- "type": "instructions",- "steps": [- {- "description": "Get input from user",- "action": "input",- "block_name": "AgentInputBlock",- },- {- "description": "Process the input",- "action": "process",- "block_name": "TextFormatterBlock",- },- {- "description": "Return output to user",- "action": "output",- "block_name": "AgentOutputBlock",- },- ],-}--# Block IDs from backend/blocks/io.py-AGENT_INPUT_BLOCK_ID = "c0a8e994-ebf1-4a9c-a4d8-89d09c86741b"-AGENT_OUTPUT_BLOCK_ID = "363ae599-353e-4804-937e-b2ee3cef3da4"---def _generate_dummy_agent_json() -> dict[str, Any]:- """Generate a minimal valid agent JSON for testing."""- input_node_id = str(uuid.uuid4())- output_node_id = str(uuid.uuid4())-- return {- "id": str(uuid.uuid4()),- "version": 1,- "is_active": True,- "name": "Dummy Test Agent",- "description": "A dummy agent generated for testing purposes",- "nodes": [- {- "id": input_node_id,- "block_id": AGENT_INPUT_BLOCK_ID,- "input_default": {- "name": "input",- "title": "Input",- "description": "Enter your input",- "placeholder_values": [],- },- "metadata": {"position": {"x": 0, "y": 0}},- },- {- "id": output_node_id,- "block_id": AGENT_OUTPUT_BLOCK_ID,- "input_default": {- "name": "output",- "title": "Output",- "description": "Agent output",- "format": "{output}",- },- "metadata": {"position": {"x": 400, "y": 0}},- },- ],- "links": [- {- "id": str(uuid.uuid4()),- "source_id": input_node_id,- "sink_id": output_node_id,- "source_name": "result",- "sink_name": "value",- "is_static": False,- },- ],- }---async def decompose_goal_dummy(- description: str,- context: str = "",- library_agents: list[dict[str, Any]] | None = None,-) -> dict[str, Any]:- """Return dummy decomposition result."""- logger.info("Using dummy agent generator for decompose_goal")- return DUMMY_DECOMPOSITION_RESULT.copy()---async def generate_agent_dummy(- instructions: dict[str, Any],- library_agents: list[dict[str, Any]] | None = None,- operation_id: str | None = None,- session_id: str | None = None,-) -> dict[str, Any]:- """Return dummy agent synchronously (blocks for 30s, returns agent JSON).-- Note: operation_id and session_id parameters are ignored - we always use synchronous mode.- """- logger.info(- "Using dummy agent generator (sync mode): returning agent JSON after 30s"- )- await asyncio.sleep(30)- return _generate_dummy_agent_json()---async def generate_agent_patch_dummy(- update_request: str,- current_agent: dict[str, Any],- library_agents: list[dict[str, Any]] | None = None,- operation_id: str | None = None,- session_id: str | None = None,-) -> dict[str, Any]:- """Return dummy patched agent synchronously (blocks for 30s, returns patched agent JSON).-- Note: operation_id and session_id parameters are ignored - we always use synchronous mode.- """- logger.info(- "Using dummy agent generator patch (sync mode): returning patched agent after 30s"- )- await asyncio.sleep(30)- patched = current_agent.copy()- patched["description"] = (- f"{current_agent.get('description', '')} (updated: {update_request})"- )- return patched---async def customize_template_dummy(- template_agent: dict[str, Any],- modification_request: str,- context: str = "",-) -> dict[str, Any]:- """Return dummy customized template (returns template with updated description)."""- logger.info("Using dummy agent generator for customize_template")- customized = template_agent.copy()- customized["description"] = (- f"{template_agent.get('description', '')} (customized: {modification_request})"- )- return customized---async def get_blocks_dummy() -> list[dict[str, Any]]:- """Return dummy blocks list."""- logger.info("Using dummy agent generator for get_blocks")- return [- {"id": AGENT_INPUT_BLOCK_ID, "name": "AgentInputBlock"},- {"id": AGENT_OUTPUT_BLOCK_ID, "name": "AgentOutputBlock"},- ]---async def health_check_dummy() -> bool:- """Always returns healthy for dummy service."""- return Truediff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/fixer.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/fixer.pynew file mode 100644index 0000000000..a6c8122388--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/fixer.py@@ -0,0 +1,1716 @@+"""AgentFixer — auto-fixes common issues in agent JSON graphs."""++import logging+import re+from typing import Any++from .helpers import (+ AGENT_EXECUTOR_BLOCK_ID,+ MCP_TOOL_BLOCK_ID,+ AgentDict,+ are_types_compatible,+ generate_uuid,+ get_defined_property_type,+ is_uuid,+)++logger = logging.getLogger(__name__)++# Block IDs used by the fixer+_FIX_VALUE2_EMPTY_STRING_BLOCK_IDS = ["715696a0-e1da-45c8-b209-c2fa9c3b0be6"]+_ADDTOLIST_BLOCK_ID = "aeb08fc1-2fc1-4141-bc8e-f758f183a822"+_ADDTODICTIONARY_BLOCK_ID = "31d1064e-7446-4693-a7d4-65e5ca1180d1"+_CREATE_LIST_BLOCK_ID = "a912d5c7-6e00-4542-b2a9-8034136930e4"+_CREATE_DICT_BLOCK_ID = "b924ddf4-de4f-4b56-9a85-358930dcbc91"+_CODE_EXECUTION_BLOCK_ID = "0b02b072-abe7-11ef-8372-fb5d162dd712"+_DATA_SAMPLING_BLOCK_ID = "4a448883-71fa-49cf-91cf-70d793bd7d87"+_STORE_VALUE_BLOCK_ID = "1ff065e9-88e8-4358-9d82-8dc91f622ba9"+_UNIVERSAL_TYPE_CONVERTER_BLOCK_ID = "95d1b990-ce13-4d88-9737-ba5c2070c97b"+_GET_CURRENT_DATE_BLOCK_ID = "b29c1b50-5d0e-4d9f-8f9d-1b0e6fcbf0b1"+_GMAIL_SEND_BLOCK_ID = "6c27abc2-e51d-499e-a85f-5a0041ba94f0"+_TEXT_REPLACE_BLOCK_ID = "7e7c87ab-3469-4bcc-9abe-67705091b713"+++class AgentFixer:+ """+ A comprehensive fixer for AutoGPT agents that applies various fixes to ensure+ agents are valid and functional.+ """++ def __init__(self):+ self.fixes_applied: list[str] = []++ @staticmethod+ def _build_node_lookup(+ agent: AgentDict,+ ) -> dict[str, dict[str, Any]]:+ """Build a node-id → node dict from the agent's nodes list."""+ return {node.get("id", ""): node for node in agent.get("nodes", [])}++ def add_fix_log(self, fix_description: str) -> None:+ """Add a fix description to the applied fixes list."""+ self.fixes_applied.append(fix_description)++ def fix_agent_ids(self, agent: AgentDict) -> AgentDict:+ """+ Fix agent and link IDs to ensure they are valid UUIDs.++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """++ def get_new_id() -> str:+ new_id = generate_uuid()+ return new_id++ # Fix link IDs+ links = []+ for link in agent.get("links", []):+ if not is_uuid(link.get("id", "")):+ link["id"] = get_new_id()+ self.add_fix_log(f"Fixed link ID: {link.get('id', '')}")+ links.append(link)+ agent["links"] = links++ # Fix agent ID+ if not is_uuid(agent.get("id", "")):+ old_id = agent.get("id", "missing")+ agent["id"] = generate_uuid()+ self.add_fix_log(f"Fixed agent ID: {old_id} -> {agent['id']}")++ return agent++ def fix_storevalue_before_condition(self, agent: AgentDict) -> AgentDict:+ """+ Add a StoreValueBlock before each ConditionBlock to provide a value for 'value2'.++ - Creates a StoreValueBlock node with default input and data False+ - Adds a link from the StoreValueBlock 'output' to the ConditionBlock 'value2'+ - Skips if a link to 'value2' already exists for the ConditionBlock+ - Prevents duplicate StoreValueBlocks by checking if one already exists for the+ same condition++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """++ nodes = agent.get("nodes", [])+ links = agent.get("links", []) or []++ # Collect ConditionBlock node ids+ condition_block_id = _FIX_VALUE2_EMPTY_STRING_BLOCK_IDS[0]+ condition_node_ids = {+ node.get("id")+ for node in nodes+ if node.get("block_id") == condition_block_id+ }++ if not condition_node_ids:+ return agent++ new_links = []+ nodes_to_add = []+ store_node_counter = 0 # Counter to ensure unique positions++ for link in links:+ # Identify links going into ConditionBlock.value2+ if (+ link.get("sink_id") in condition_node_ids+ and link.get("sink_name") == "value2"+ ):+ condition_node_id = link.get("sink_id")++ # If the upstream source is already a StoreValueBlock.output, keep as-is+ source_node = next(+ (n for n in nodes if n.get("id") == link.get("source_id")),+ None,+ )+ if (+ source_node+ and source_node.get("block_id") == _STORE_VALUE_BLOCK_ID+ and link.get("source_name") == "output"+ ):+ new_links.append(link)+ continue++ # Check if there's already a StoreValueBlock connected to this+ # condition's value2. This prevents duplicates when the fix runs+ # multiple times.+ existing_storevalue_for_condition = False+ for existing_link in links:+ if (+ existing_link.get("sink_id") == condition_node_id+ and existing_link.get("sink_name") == "value2"+ ):+ existing_source_node = next(+ (+ n+ for n in nodes+ if n.get("id") == existing_link.get("source_id")+ ),+ None,+ )+ if (+ existing_source_node+ and existing_source_node.get("block_id")+ == _STORE_VALUE_BLOCK_ID+ and existing_link.get("source_name") == "output"+ ):+ existing_storevalue_for_condition = True+ break++ if existing_storevalue_for_condition:+ self.add_fix_log(+ f"Skipped adding StoreValueBlock for ConditionBlock "+ f"{condition_node_id} - already has one connected"+ )+ new_links.append(link)+ continue++ # Create StoreValueBlock node (input will be linked; data left+ # default None)+ store_node_id = generate_uuid()+ store_node = {+ "id": store_node_id,+ "block_id": _STORE_VALUE_BLOCK_ID,+ "input_default": {"data": None},+ "metadata": {+ "position": {+ "x": store_node_counter * 200,+ "y": -100,+ }+ },+ "graph_id": agent.get("id"),+ "graph_version": 1,+ }+ nodes_to_add.append(store_node)+ store_node_counter += 1++ # Rewire: old source -> StoreValueBlock.input+ upstream_to_store_link = {+ "id": generate_uuid(),+ "source_id": link.get("source_id"),+ "source_name": link.get("source_name"),+ "sink_id": store_node_id,+ "sink_name": "input",+ }++ # Then StoreValueBlock.output -> ConditionBlock.value2+ store_to_condition_link = {+ "id": generate_uuid(),+ "source_id": store_node_id,+ "source_name": "output",+ "sink_id": condition_node_id,+ "sink_name": "value2",+ }++ new_links.append(upstream_to_store_link)+ new_links.append(store_to_condition_link)++ self.add_fix_log(+ f"Inserted StoreValueBlock {store_node_id} between "+ f"{link.get('source_id')}:{link.get('source_name')} and "+ f"ConditionBlock {condition_node_id} value2"+ )+ else:+ new_links.append(link)++ if nodes_to_add:+ nodes.extend(nodes_to_add)+ agent["nodes"] = nodes+ agent["links"] = new_links++ return agent++ def fix_double_curly_braces(self, agent: AgentDict) -> AgentDict:+ """+ Fix single curly braces to double curly braces in nodes with prompt or+ format fields. Also ensures that prompt_values (passed via links) are+ referenced in the prompt/format. Skips fixing if the block's output will+ be passed to a CodeExecutionBlock.++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """++ nodes = agent.get("nodes", [])+ links = agent.get("links", [])++ # Build a map of node_id -> list of prompt_value names that are linked+ node_prompt_values: dict[str, list[str]] = {}+ for link in links:+ sink_id = link.get("sink_id")+ sink_name = link.get("sink_name", "")++ # Check if this link is passing a prompt_value+ if sink_name == "prompt_values":+ # Direct prompt_values link+ if sink_id not in node_prompt_values:+ node_prompt_values[sink_id] = []+ # We don't have a specific name for this, skip for now+ elif sink_name.startswith("prompt_values_"):+ # Extract value name from pattern: prompt_values_#_[value_name]+ after_prefix = sink_name[len("prompt_values_") :]+ first_underscore_idx = after_prefix.find("_")+ if first_underscore_idx != -1:+ value_name = after_prefix[first_underscore_idx + 1 :]+ if sink_id not in node_prompt_values:+ node_prompt_values[sink_id] = []+ node_prompt_values[sink_id].append(value_name)++ # Process nodes that have prompt or format fields+ for node in nodes:+ node_id = node.get("id")+ input_data = node.get("input_default", {})++ # Check if this node has prompt or format fields+ has_prompt_or_format = "prompt" in input_data or "format" in input_data++ if not has_prompt_or_format:+ continue++ # Check if this block's output is linked to a CodeExecutionBlock+ is_linked_to_code_execution = False+ for link in links:+ if link.get("source_id") == node_id:+ sink_node = next(+ (n for n in nodes if n.get("id") == link.get("sink_id")),+ None,+ )+ if (+ sink_node+ and sink_node.get("block_id") == _CODE_EXECUTION_BLOCK_ID+ ):+ is_linked_to_code_execution = True+ break++ # Skip fixing if this block's output goes to a CodeExecutionBlock+ if is_linked_to_code_execution:+ continue++ # Fix single curly braces to double curly braces+ for key in ("prompt", "format"):+ if key in input_data:+ original_text = input_data[key]+ if not isinstance(original_text, str):+ continue++ # Avoid fixing already double-braced values+ fixed_text = re.sub(+ r"(?<!\{)\{([a-zA-Z_][a-zA-Z0-9_]*)\}(?!\})",+ r"{{\1}}",+ original_text,+ )++ if fixed_text != original_text:+ input_data[key] = fixed_text+ self.add_fix_log(+ f"Fixed {key} in node {node_id}: "+ f"{original_text} -> {fixed_text}"+ )++ # Check if this node has prompt_values linked to it+ if node_id in node_prompt_values:+ prompt_values = node_prompt_values[node_id]++ # Determine which field to add missing values to+ target_field = "prompt" if "prompt" in input_data else "format"++ if target_field in input_data and isinstance(+ input_data[target_field], str+ ):+ current_text = input_data[target_field]+ missing_values = []++ for value_name in prompt_values:+ pattern = r"\{\{" + re.escape(value_name) + r"\}\}"+ if not re.search(pattern, current_text):+ missing_values.append(value_name)++ # Add missing values to the text+ if missing_values:+ additions = "\n".join(+ [f"{{{{{value_name}}}}}" for value_name in missing_values]+ )+ updated_text = current_text + "\n" + additions+ input_data[target_field] = updated_text+ self.add_fix_log(+ f"Added missing prompt_values to {target_field} "+ f"in node {node_id}: {missing_values}"+ )++ return agent++ def fix_addtolist_blocks(self, agent: AgentDict) -> AgentDict:+ """+ Fix AddToList blocks by adding a prerequisite empty AddToList block.++ When an AddToList block is found, this fixer:+ 1. Checks if there's a CreateListBlock before it (directly or through+ StoreValueBlock)+ 2. If CreateListBlock exists (direct link), removes it and its link to+ AddToList block+ 3. If CreateListBlock + StoreValueBlock exists, only removes the link from+ StoreValueBlock to AddToList block+ 4. Adds an empty AddToList block before the original AddToList block+ 5. The first block is standalone (not connected to other blocks)+ 6. The second block receives input from previous blocks and can+ self-reference+ 7. Ensures the original AddToList block has a self-referencing link+ 8. Prevents duplicate prerequisite blocks by checking existing connections++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """+ nodes = agent.get("nodes", [])+ links = agent.get("links", [])+ node_lookup = {node.get("id", ""): node for node in nodes}+ new_nodes: list[dict[str, Any]] = []+ new_links: list[dict[str, Any]] = []+ original_addtolist_node_ids: set[str] = set()++ # First pass: identify CreateListBlock nodes and links to remove+ createlist_nodes_to_remove: set[str] = set()+ links_to_remove: list[dict[str, Any]] = []++ for link in links:+ source_node = node_lookup.get(link.get("source_id", ""))+ sink_node = node_lookup.get(link.get("sink_id", ""))++ # Case 1: CreateListBlock directly linked to AddToList block+ if (+ source_node+ and sink_node+ and source_node.get("block_id") == _CREATE_LIST_BLOCK_ID+ and sink_node.get("block_id") == _ADDTOLIST_BLOCK_ID+ ):+ createlist_nodes_to_remove.add(source_node.get("id"))+ links_to_remove.append(link)+ self.add_fix_log(+ f"Identified CreateListBlock {source_node.get('id')} linked "+ f"to AddToList block {sink_node.get('id')} for removal"+ )++ # Case 2: StoreValueBlock linked to AddToList block+ if (+ source_node+ and sink_node+ and source_node.get("block_id") == _STORE_VALUE_BLOCK_ID+ and sink_node.get("block_id") == _ADDTOLIST_BLOCK_ID+ ):+ storevalue_id = source_node.get("id")+ has_createlist_before = False+ for prev_link in links:+ if prev_link.get("sink_id") == storevalue_id:+ prev_source_node = node_lookup.get(+ prev_link.get("source_id", "")+ )+ if (+ prev_source_node+ and prev_source_node.get("block_id")+ == _CREATE_LIST_BLOCK_ID+ ):+ has_createlist_before = True+ break++ if has_createlist_before:+ links_to_remove.append(link)+ self.add_fix_log(+ f"Identified StoreValueBlock {storevalue_id} (with "+ f"CreateListBlock before it) linked to AddToList block "+ f"{sink_node.get('id')} - removing only the link"+ )++ # Second pass: process nodes, skipping CreateListBlock nodes to remove+ prerequisite_counter = 0+ for node in nodes:+ if node.get("id") in createlist_nodes_to_remove:+ continue++ if node.get("block_id") == _ADDTOLIST_BLOCK_ID:+ original_addtolist_node_ids.add(node.get("id"))+ original_node_id = node.get("id")+ original_node_position = (node.get("metadata") or {}).get(+ "position", {}+ )+ if original_node_position:+ original_node_position_x = original_node_position.get("x", 0)+ original_node_position_y = original_node_position.get("y", 0)+ else:+ original_node_position_x = 0+ original_node_position_y = 0++ # Check if there's already a prerequisite AddToList block+ has_prerequisite_block = False+ for link in links:+ if (+ link.get("sink_id") == original_node_id+ and link.get("sink_name") == "list"+ and link.get("source_name") == "updated_list"+ ):+ source_node = next(+ (n for n in nodes if n.get("id") == link.get("source_id")),+ None,+ )+ if (+ source_node+ and source_node.get("block_id") == _ADDTOLIST_BLOCK_ID+ and source_node.get("id") != original_node_id+ ):+ has_prerequisite_block = True+ break++ # Check if this node is already a prerequisite block+ is_prerequisite_block = (+ node.get("input_default", {}).get("list") == []+ and node.get("input_default", {}).get("entry") is None+ and node.get("input_default", {}).get("entries") == []+ and not any(+ link.get("sink_id") == original_node_id+ and link.get("sink_name") == "list"+ for link in links+ )+ )++ if is_prerequisite_block:+ self.add_fix_log(+ f"Skipped adding prerequisite AddToList block for "+ f"{original_node_id} - this is already a prerequisite "+ f"block"+ )+ elif has_prerequisite_block:+ self.add_fix_log(+ f"Skipped adding prerequisite AddToList block for "+ f"{original_node_id} - already has prerequisite block "+ f"exists"+ )+ else:+ # Before adding prerequisite block, remove all links to+ # the "list" input (except self-referencing)+ links_to_list_input = []+ for link in links:+ if (+ link.get("sink_id") == original_node_id+ and link.get("sink_name") == "list"+ and link.get("source_id") != original_node_id+ ):+ links_to_list_input.append(link)++ for link in links_to_list_input:+ if link not in links_to_remove:+ links_to_remove.append(link)+ self.add_fix_log(+ f"Removed link from "+ f"{link.get('source_id')}:"+ f"{link.get('source_name')} to AddToList "+ f"block {original_node_id} 'list' input "+ f"(will be replaced by prerequisite block)"+ )++ prerequisite_node_id = generate_uuid()++ prerequisite_node = {+ "id": prerequisite_node_id,+ "block_id": _ADDTOLIST_BLOCK_ID,+ "input_default": {+ "list": [],+ "entry": None,+ "entries": [],+ "position": None,+ },+ "metadata": {+ "position": {+ "x": original_node_position_x - 800,+ "y": original_node_position_y + 800,+ }+ },+ "graph_id": agent.get("id"),+ "graph_version": 1,+ }+ prerequisite_counter += 1++ prerequisite_link = {+ "id": generate_uuid(),+ "source_id": prerequisite_node_id,+ "source_name": "updated_list",+ "sink_id": original_node_id,+ "sink_name": "list",+ }++ new_nodes.append(prerequisite_node)+ new_links.append(prerequisite_link)++ self.add_fix_log(+ f"Added prerequisite AddToList block "+ f"{prerequisite_node_id} before {original_node_id}"+ )++ # Add the original node+ new_nodes.append(node)++ # Add all existing links except those marked for removal+ new_links.extend([link for link in links if link not in links_to_remove])++ # Check for original AddToList blocks and ensure they have+ # self-referencing links+ for node in new_nodes:+ if (+ node.get("block_id") == _ADDTOLIST_BLOCK_ID+ and node.get("id") in original_addtolist_node_ids+ ):+ node_id = node.get("id")++ is_prerequisite_block = (+ node.get("input_default", {}).get("list") == []+ and node.get("input_default", {}).get("entry") is None+ and node.get("input_default", {}).get("entries") == []+ and not any(+ link.get("sink_id") == node_id+ and link.get("sink_name") == "list"+ for link in new_links+ )+ )++ if is_prerequisite_block:+ self.add_fix_log(+ f"Skipped adding self-referencing link for "+ f"prerequisite AddToList block {node_id}"+ )+ continue++ has_self_reference = any(+ link.get("source_id") == node_id+ and link.get("sink_id") == node_id+ and link.get("source_name") == "updated_list"+ and link.get("sink_name") == "list"+ for link in new_links+ )++ if not has_self_reference:+ self_reference_link = {+ "id": generate_uuid(),+ "source_id": node_id,+ "source_name": "updated_list",+ "sink_id": node_id,+ "sink_name": "list",+ }+ new_links.append(self_reference_link)+ self.add_fix_log(+ f"Added self-referencing link for original "+ f"AddToList block {node_id}"+ )++ # Update the agent with new nodes and links+ agent["nodes"] = new_nodes+ agent["links"] = new_links++ return agent++ def fix_addtodictionary_blocks(self, agent: AgentDict) -> AgentDict:+ """+ Fix AddToDictionary blocks by removing empty CreateDictionaryBlock nodes+ that are linked to them.++ When an AddToDictionary block is found, this fixer:+ 1. Checks if there's a CreateDictionaryBlock before it+ 2. If CreateDictionaryBlock exists and is linked to AddToDictionary block,+ removes it and its link+ 3. The AddToDictionary block will work with an empty dictionary as default++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """+ nodes = agent.get("nodes", [])+ links = agent.get("links", [])+ node_lookup = {node.get("id", ""): node for node in nodes}++ # First pass: identify CreateDictionaryBlock nodes linked to+ # AddToDictionary blocks+ create_dict_nodes_to_remove: set[str] = set()+ links_to_remove: list[dict[str, Any]] = []++ for link in links:+ source_node = node_lookup.get(link.get("source_id", ""))+ sink_node = node_lookup.get(link.get("sink_id", ""))++ if (+ source_node+ and sink_node+ and source_node.get("block_id") == _CREATE_DICT_BLOCK_ID+ and sink_node.get("block_id") == _ADDTODICTIONARY_BLOCK_ID+ ):+ create_dict_nodes_to_remove.add(source_node.get("id"))+ links_to_remove.append(link)+ self.add_fix_log(+ f"Identified CreateDictionaryBlock "+ f"{source_node.get('id')} linked to AddToDictionary "+ f"block {sink_node.get('id')} for removal"+ )++ # Second pass: process nodes, skipping CreateDictionaryBlock nodes+ new_nodes = []+ for node in nodes:+ if node.get("id") in create_dict_nodes_to_remove:+ continue+ new_nodes.append(node)++ # Remove the links that were marked for removal+ new_links = [link for link in links if link not in links_to_remove]++ # Update the agent with new nodes and links+ agent["nodes"] = new_nodes+ agent["links"] = new_links++ return agent++ def fix_link_static_properties(+ self,+ agent: AgentDict,+ blocks: list[dict[str, Any]],+ node_lookup: dict[str, dict[str, Any]] | None = None,+ ) -> AgentDict:+ """+ Fix the is_static property of links based on the source block's+ staticOutput property.++ If source block's staticOutput is true, link's is_static should be true.+ If source block's staticOutput is false, link's is_static should be false.++ Args:+ agent: The agent dictionary to fix+ blocks: List of available blocks with their schemas++ Returns:+ The fixed agent dictionary+ """+ block_map = {block.get("id"): block for block in blocks}+ if node_lookup is None:+ node_lookup = self._build_node_lookup(agent)++ for link in agent.get("links", []):+ source_node = node_lookup.get(link.get("source_id", ""))+ if not source_node:+ continue++ source_block = block_map.get(source_node.get("block_id"))+ if not source_block:+ continue++ # Check if the source block has staticOutput property+ static_output = source_block.get("staticOutput", False)++ # Update the link's is_static property+ old_is_static = link.get("is_static", False)+ link["is_static"] = static_output++ if old_is_static != static_output:+ self.add_fix_log(+ f"Fixed link {link.get('id')} is_static: "+ f"{old_is_static} -> {static_output} (based on source "+ f"block {source_node.get('block_id')} staticOutput: "+ f"{static_output})"+ )++ return agent++ def fix_code_execution_output(self, agent: AgentDict) -> AgentDict:+ """+ Fix CodeExecutionBlock output by changing source_name from "response"+ to "stdout_logs" in links.++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """++ links = agent.get("links", [])+ node_lookup = {node.get("id", ""): node for node in agent.get("nodes", [])}++ for link in links:+ source_node = node_lookup.get(link.get("source_id", ""))++ if (+ source_node+ and source_node.get("block_id") == _CODE_EXECUTION_BLOCK_ID+ and link.get("source_name") == "response"+ ):+ old_source_name = link.get("source_name")+ link["source_name"] = "stdout_logs"+ self.add_fix_log(+ f"Fixed CodeExecutionBlock link {link.get('id')}: "+ f"source_name {old_source_name} -> stdout_logs"+ )++ return agent++ def fix_data_sampling_sample_size(self, agent: AgentDict) -> AgentDict:+ """+ Fix DataSamplingBlock by setting sample_size to 1 as default.+ If old value is set as default, just reset to 1.+ If old value is from another block, delete that link and set 1 as default.++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """++ nodes = agent.get("nodes", [])+ links = agent.get("links", [])+ links_to_remove: list[dict[str, Any]] = []++ for node in nodes:+ if node.get("block_id") == _DATA_SAMPLING_BLOCK_ID:+ node_id = node.get("id")+ input_default = node.get("input_default", {})++ # Check if there's a link to the sample_size field+ has_sample_size_link = False+ for link in links:+ if (+ link.get("sink_id") == node_id+ and link.get("sink_name") == "sample_size"+ ):+ has_sample_size_link = True+ links_to_remove.append(link)+ self.add_fix_log(+ f"Removed link {link.get('id')} to "+ f"DataSamplingBlock {node_id} sample_size "+ f"field (will set default to 1)"+ )++ # Set sample_size to 1 as default+ old_value = input_default.get("sample_size", None)+ input_default["sample_size"] = 1++ if has_sample_size_link:+ self.add_fix_log(+ f"Fixed DataSamplingBlock {node_id} sample_size: "+ f"removed link and set default to 1"+ )+ elif old_value != 1:+ self.add_fix_log(+ f"Fixed DataSamplingBlock {node_id} sample_size: "+ f"{old_value} -> 1"+ )++ # Remove the links that were marked for removal+ if links_to_remove:+ agent["links"] = [link for link in links if link not in links_to_remove]++ return agent++ def fix_ai_model_parameter(+ self,+ agent: AgentDict,+ blocks: list[dict[str, Any]],+ default_model: str = "gpt-4o",+ ) -> AgentDict:+ """+ Add or fix the model parameter on AI blocks.++ For nodes whose block has category "AI", this function ensures that the+ input_default has a "model" parameter set to one of the allowed models.+ If missing or set to an unsupported value, it is replaced with+ default_model.++ Args:+ agent: The agent dictionary to fix+ blocks: List of available blocks with their schemas+ default_model: The fallback model to use (default "gpt-4o")++ Returns:+ The fixed agent dictionary+ """+ allowed_models = {"gpt-4o", "claude-opus-4-6"}++ # Create a mapping of block_id to block for quick lookup+ block_map = {block.get("id"): block for block in blocks}++ nodes = agent.get("nodes", [])+ fixed_count = 0++ for node in nodes:+ block_id = node.get("block_id")+ block = block_map.get(block_id)++ if not block:+ continue++ # Check if the block has category "AI" in its categories array+ categories = block.get("categories", [])+ is_ai_block = any(+ cat.get("category") == "AI"+ for cat in categories+ if isinstance(cat, dict)+ )++ if is_ai_block:+ node_id = node.get("id")+ input_default = node.get("input_default", {})+ current_model = input_default.get("model")++ if current_model not in allowed_models:+ block_name = block.get("name", "Unknown AI Block")+ if current_model is None:+ self.add_fix_log(+ f"Added model parameter '{default_model}' to AI "+ f"block node {node_id} ({block_name})"+ )+ else:+ self.add_fix_log(+ f"Replaced unsupported model '{current_model}' "+ f"with '{default_model}' on AI block node "+ f"{node_id} ({block_name})"+ )+ input_default["model"] = default_model+ node["input_default"] = input_default+ fixed_count += 1++ if fixed_count > 0:+ logger.debug(f"Fixed model parameter on {fixed_count} AI block nodes")++ return agent++ def fix_data_type_mismatch(+ self, agent: AgentDict, blocks: list[dict[str, Any]]+ ) -> AgentDict:+ """+ Fix data type mismatches by inserting UniversalTypeConverterBlock between+ incompatible connections.++ This function:+ 1. Identifies links with type mismatches using the same logic as+ validate_data_type_compatibility+ 2. Inserts UniversalTypeConverterBlock nodes to convert data types+ 3. Rewires the connections to go through the converter block++ Args:+ agent: The agent dictionary to fix+ blocks: List of available blocks for reference++ Returns:+ The fixed agent dictionary+ """+ nodes = agent.get("nodes", [])+ links = agent.get("links", [])++ block_lookup = {block.get("id", ""): block for block in blocks}+ node_lookup = {node.get("id", ""): node for node in nodes}++ def get_target_type_for_conversion(sink_type: str) -> str:+ """Determine the target type for conversion based on sink+ requirements."""+ type_mapping = {+ "string": "string",+ "text": "string",+ "integer": "number",+ "number": "number",+ "float": "number",+ "boolean": "boolean",+ "bool": "boolean",+ "array": "list",+ "list": "list",+ "object": "dictionary",+ "dict": "dictionary",+ "dictionary": "dictionary",+ }+ return type_mapping.get(sink_type, sink_type)++ new_links: list[dict[str, Any]] = []+ nodes_to_add: list[dict[str, Any]] = []+ converter_counter = 0++ for link in links:+ source_node = node_lookup.get(link.get("source_id"))+ sink_node = node_lookup.get(link.get("sink_id"))++ if not source_node or not sink_node:+ new_links.append(link)+ continue++ source_block = block_lookup.get(source_node.get("block_id"))+ sink_block = block_lookup.get(sink_node.get("block_id"))++ if not source_block or not sink_block:+ new_links.append(link)+ continue++ source_outputs = source_block.get("outputSchema", {}).get("properties", {})+ sink_inputs = sink_block.get("inputSchema", {}).get("properties", {})++ source_type = get_defined_property_type(+ source_outputs, link.get("source_name", "")+ )+ sink_type = get_defined_property_type(+ sink_inputs, link.get("sink_name", "")+ )++ # Check if types are incompatible+ if (+ source_type+ and sink_type+ and not are_types_compatible(source_type, sink_type)+ ):+ # Create UniversalTypeConverterBlock node+ converter_node_id = generate_uuid()+ target_type = get_target_type_for_conversion(sink_type)++ converter_node = {+ "id": converter_node_id,+ "block_id": _UNIVERSAL_TYPE_CONVERTER_BLOCK_ID,+ "input_default": {"type": target_type},+ "metadata": {+ "position": {+ "x": converter_counter * 250,+ "y": 100,+ }+ },+ "graph_id": agent.get("id"),+ "graph_version": 1,+ }+ nodes_to_add.append(converter_node)+ converter_counter += 1++ # Create new links: source -> converter -> sink+ source_to_converter_link = {+ "id": generate_uuid(),+ "source_id": link.get("source_id", ""),+ "source_name": link.get("source_name", ""),+ "sink_id": converter_node_id,+ "sink_name": "value",+ }++ converter_to_sink_link = {+ "id": generate_uuid(),+ "source_id": converter_node_id,+ "source_name": "value",+ "sink_id": link.get("sink_id", ""),+ "sink_name": link.get("sink_name", ""),+ }++ new_links.append(source_to_converter_link)+ new_links.append(converter_to_sink_link)++ source_block_name = source_block.get("name", "Unknown Block")+ sink_block_name = sink_block.get("name", "Unknown Block")+ self.add_fix_log(+ f"Fixed data type mismatch: Inserted "+ f"UniversalTypeConverterBlock {converter_node_id} "+ f"between {source_block_name} ({source_type}) and "+ f"{sink_block_name} ({sink_type}) converting to "+ f"{target_type}"+ )+ else:+ # Keep the original link if types are compatible+ new_links.append(link)++ # Update the agent with new nodes and links+ if nodes_to_add:+ nodes.extend(nodes_to_add)+ agent["nodes"] = nodes+ agent["links"] = new_links++ return agent++ def fix_node_x_coordinates(+ self,+ agent: AgentDict,+ node_lookup: dict[str, dict[str, Any]] | None = None,+ ) -> AgentDict:+ """+ Fix node x-coordinates to ensure adjacent nodes (connected via links)+ have at least 800 units difference in their x-coordinates.++ For each link connecting two nodes, if the x-coordinate difference is+ less than or equal to 800, the sink node's x-coordinate will be adjusted+ to be at least 800 units to the right of the source node.++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """+ links = agent.get("links", [])++ # Create a lookup dictionary for nodes by ID+ if node_lookup is None:+ node_lookup = self._build_node_lookup(agent)++ # Iterate through all links and adjust positions as needed+ for link in links:+ source_id = link.get("source_id")+ sink_id = link.get("sink_id")++ if not source_id or not sink_id:+ continue++ source_node = node_lookup.get(source_id)+ sink_node = node_lookup.get(sink_id)++ if not source_node or not sink_node:+ continue++ # Skip self-referencing links (e.g. AddToList feeding itself)+ if source_id == sink_id:+ continue++ source_pos = (source_node.get("metadata") or {}).get("position", {})+ sink_meta = sink_node.get("metadata") or {}+ sink_pos = sink_meta.get("position", {})+ source_x = source_pos.get("x", 0)+ sink_x = sink_pos.get("x", 0)++ difference = abs(sink_x - source_x)+ if difference < 800:+ required_x = source_x + 800+ if sink_node.get("metadata") is None:+ sink_node["metadata"] = {}+ if sink_node["metadata"].get("position") is None:+ sink_node["metadata"]["position"] = {}+ sink_node["metadata"]["position"]["x"] = required_x+ self.add_fix_log(+ f"Adjusted x-coordinate for node {sink_id}: "+ f"{sink_x} -> {required_x} (source node {source_id} "+ f"at x={source_x}, ensuring minimum 800 unit spacing)"+ )+ else:+ continue++ return agent++ def fix_getcurrentdate_offset(self, agent: AgentDict) -> AgentDict:+ """+ Fix GetCurrentDateBlock offset to ensure it's a positive value.++ If the offset in input_default is negative, it will be changed to its+ absolute value (positive).++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """+ nodes = agent.get("nodes", [])++ for node in nodes:+ if node.get("block_id") == _GET_CURRENT_DATE_BLOCK_ID:+ node_id = node.get("id")+ input_default = node.get("input_default", {})++ # Check if offset exists and is negative+ if "offset" in input_default:+ offset_value = input_default["offset"]++ if isinstance(offset_value, (int, float)) and offset_value < 0:+ old_offset = offset_value+ input_default["offset"] = abs(offset_value)+ self.add_fix_log(+ f"Fixed GetCurrentDateBlock {node_id} offset: "+ f"{old_offset} -> {input_default['offset']}"+ )++ return agent++ def fix_addtolist_gmail_self_reference(self, agent: AgentDict) -> AgentDict:+ """+ Remove self-referencing links from AddToList blocks that are connected+ to GmailSendBlock.++ When an AddToList block has a link to a GmailSendBlock, this fixer:+ 1. Identifies the AddToList block that is linked to a GmailSendBlock+ 2. Removes the self-referencing link (updated_list -> list) from that+ AddToList block++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """+ nodes = agent.get("nodes", [])+ links = agent.get("links", [])++ # Find AddToList blocks that are connected to GmailSendBlock+ addtolist_nodes_linked_to_gmail: set[str] = set()++ for link in links:+ source_node = next(+ (node for node in nodes if node.get("id") == link.get("source_id")),+ None,+ )+ sink_node = next(+ (node for node in nodes if node.get("id") == link.get("sink_id")),+ None,+ )++ if (+ source_node+ and sink_node+ and source_node.get("block_id") == _ADDTOLIST_BLOCK_ID+ and sink_node.get("block_id") == _GMAIL_SEND_BLOCK_ID+ ):+ addtolist_nodes_linked_to_gmail.add(source_node.get("id"))+ self.add_fix_log(+ f"Identified AddToList block {source_node.get('id')} "+ f"linked to GmailSendBlock {sink_node.get('id')}"+ )++ # Remove self-referencing links from identified AddToList blocks+ if addtolist_nodes_linked_to_gmail:+ links_to_remove = []++ for link in links:+ if (+ link.get("source_id") in addtolist_nodes_linked_to_gmail+ and link.get("sink_id") in addtolist_nodes_linked_to_gmail+ and link.get("source_id") == link.get("sink_id")+ and link.get("source_name") == "updated_list"+ and link.get("sink_name") == "list"+ ):+ links_to_remove.append(link)+ self.add_fix_log(+ f"Removed self-referencing link {link.get('id')} "+ f"from AddToList block {link.get('source_id')} "+ f"(linked to GmailSendBlock)"+ )++ if links_to_remove:+ agent["links"] = [link for link in links if link not in links_to_remove]++ return agent++ def fix_text_replace_new_parameter(self, agent: AgentDict) -> AgentDict:+ """+ Fix TextReplaceBlock's 'new' parameter by changing empty string to space.++ When a TextReplaceBlock node has an empty string ("") in its 'new'+ parameter within input_default, this fixer changes it to a space (" ").++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """+ nodes = agent.get("nodes", [])++ for node in nodes:+ if node.get("block_id") == _TEXT_REPLACE_BLOCK_ID:+ node_id = node.get("id")+ input_default = node.get("input_default", {})++ if "new" in input_default and input_default["new"] == "":+ input_default["new"] = " "+ self.add_fix_log(+ f"Fixed TextReplaceBlock {node_id} 'new' parameter: "+ f'empty string ("") -> space (" ")'+ )++ return agent++ def fix_credentials(self, agent: AgentDict) -> AgentDict:+ """+ Delete credentials from input_default if it exists.++ When a node's input_default contains a 'credentials' object,+ this fixer removes the entire 'credentials' field.++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """+ nodes = agent.get("nodes", [])++ for node in nodes:+ node_id = node.get("id")+ input_default = node.get("input_default", {})++ if "credentials" in input_default:+ input_default.pop("credentials")+ self.add_fix_log(f"Deleted credentials in node {node_id}: [REDACTED]")++ return agent++ def fix_agent_executor_blocks(+ self,+ agent: AgentDict,+ library_agents: list[dict[str, Any]] | None = None,+ ) -> AgentDict:+ """+ Fix AgentExecutorBlock nodes to ensure they have valid graph_id+ references.++ This function:+ 1. Validates that AgentExecutorBlock nodes reference valid library agents+ 2. Fills in missing graph_version if graph_id is valid+ 3. Ensures input_default has required fields+ 4. Clears hardcoded inputs (they should be connected via links)+ 5. Logs missing required input links for the LLM to fix++ Args:+ agent: The agent dictionary to fix+ library_agents: List of library agents available for composition++ Returns:+ The fixed agent dictionary+ """+ if not library_agents:+ logger.debug(+ "fix_agent_executor_blocks: No library_agents provided, " "skipping"+ )+ return agent++ nodes = agent.get("nodes", [])+ links = agent.get("links", [])++ # Create lookup for library agents+ library_agent_lookup = {la.get("graph_id", ""): la for la in library_agents}+ logger.debug(+ f"fix_agent_executor_blocks: library_agent_lookup keys = "+ f"{list(library_agent_lookup.keys())}"+ )++ for node in nodes:+ if node.get("block_id") != AGENT_EXECUTOR_BLOCK_ID:+ continue++ node_id = node.get("id")+ input_default = node.get("input_default", {})++ # Check if graph_id references a library agent+ graph_id = input_default.get("graph_id")+ logger.debug(+ f"fix_agent_executor_blocks: Found AgentExecutorBlock "+ f"{node_id}, graph_id={graph_id}"+ )++ if not graph_id:+ logger.warning(+ f"fix_agent_executor_blocks: Node {node_id} has no "+ f"graph_id, skipping"+ )+ continue++ library_agent = library_agent_lookup.get(graph_id)+ if not library_agent:+ logger.warning(+ f"fix_agent_executor_blocks: graph_id {graph_id} not "+ f"found in library_agents lookup"+ )+ continue++ logger.debug(+ f"fix_agent_executor_blocks: Found matching library agent "+ f"'{library_agent.get('name')}', input_schema keys: "+ f"{list(library_agent.get('input_schema', {}).get('properties', {}).keys())}"+ )++ # Fill in graph_version if missing or mismatched+ expected_version = library_agent.get("graph_version")+ current_version = input_default.get("graph_version")++ if current_version != expected_version:+ input_default["graph_version"] = expected_version+ self.add_fix_log(+ f"Fixed AgentExecutorBlock {node_id}: "+ f"graph_version {current_version} -> {expected_version} "+ f"(for library agent '{library_agent.get('name')}')"+ )++ # Ensure user_id is present (can be empty string, filled at runtime)+ if "user_id" not in input_default:+ input_default["user_id"] = ""+ self.add_fix_log(+ f"Fixed AgentExecutorBlock {node_id}: Added missing " f"user_id"+ )++ # Ensure inputs is present+ if "inputs" not in input_default:+ input_default["inputs"] = {}++ # Ensure input_schema is present and valid (copy from library agent)+ current_input_schema = input_default.get("input_schema")+ lib_input_schema = library_agent.get("input_schema", {})+ if not isinstance(lib_input_schema, dict):+ lib_input_schema = {}+ if not isinstance(current_input_schema, dict):+ current_input_schema = {}+ logger.debug(+ f"fix_agent_executor_blocks: current_input_schema="+ f"{current_input_schema}"+ )+ logger.debug(+ f"fix_agent_executor_blocks: lib_input_schema keys="+ f"{list(lib_input_schema.get('properties', {}).keys()) if lib_input_schema else 'None'}"+ )+ if not current_input_schema or not current_input_schema.get("properties"):+ input_default["input_schema"] = lib_input_schema+ logger.debug(+ "fix_agent_executor_blocks: Replaced input_schema "+ "with library agent's schema"+ )+ if not current_input_schema:+ self.add_fix_log(+ f"Fixed AgentExecutorBlock {node_id}: Added "+ f"missing input_schema"+ )+ else:+ self.add_fix_log(+ f"Fixed AgentExecutorBlock {node_id}: Replaced "+ f"empty input_schema with library agent's schema"+ )++ # Populate inputs object with default values from input_schema+ # properties. This matches how the frontend creates+ # AgentExecutorBlock nodes.+ final_input_schema = input_default.get("input_schema", {})+ schema_properties = final_input_schema.get("properties", {})+ inputs_obj = input_default.get("inputs", {})+ if isinstance(schema_properties, dict) and isinstance(inputs_obj, dict):+ for prop_name, prop_schema in schema_properties.items():+ if prop_name not in inputs_obj and isinstance(prop_schema, dict):+ default_value = prop_schema.get("default")+ if default_value is not None:+ inputs_obj[prop_name] = default_value+ input_default["inputs"] = inputs_obj++ # Ensure output_schema is present and valid (copy from library+ # agent)+ current_output_schema = input_default.get("output_schema")+ lib_output_schema = library_agent.get("output_schema", {})+ if not isinstance(lib_output_schema, dict):+ lib_output_schema = {}+ if not isinstance(current_output_schema, dict):+ current_output_schema = {}+ if not current_output_schema or not current_output_schema.get("properties"):+ input_default["output_schema"] = lib_output_schema+ if not current_output_schema:+ self.add_fix_log(+ f"Fixed AgentExecutorBlock {node_id}: Added "+ f"missing output_schema"+ )+ else:+ self.add_fix_log(+ f"Fixed AgentExecutorBlock {node_id}: Replaced "+ f"empty output_schema with library agent's schema"+ )++ # Check for missing required input links and fix sink_name format+ sub_agent_input_schema = library_agent.get("input_schema", {})+ if not isinstance(sub_agent_input_schema, dict):+ sub_agent_input_schema = {}+ sub_agent_required_inputs = sub_agent_input_schema.get("required", [])++ # Get all linked inputs to this node+ sub_agent_properties = sub_agent_input_schema.get("properties", {})+ linked_sub_agent_inputs: set[str] = set()+ for link in links:+ if link.get("sink_id") == node_id:+ sink_name = link.get("sink_name", "")+ # Fix: Convert "inputs_#_<field>" to direct property+ # name "<field>"+ if sink_name.startswith("inputs_#_"):+ prop_name = sink_name[9:] # Remove "inputs_#_"+ if prop_name in sub_agent_properties:+ link["sink_name"] = prop_name+ self.add_fix_log(+ f"Fixed AgentExecutorBlock link: "+ f"sink_name '{sink_name}' -> "+ f"'{prop_name}' (removed inputs_#_ "+ f"prefix)"+ )+ linked_sub_agent_inputs.add(prop_name)+ elif sink_name in sub_agent_properties:+ linked_sub_agent_inputs.add(sink_name)++ missing_inputs = [+ inp+ for inp in sub_agent_required_inputs+ if inp not in linked_sub_agent_inputs+ ]+ if missing_inputs:+ self.add_fix_log(+ f"AgentExecutorBlock {node_id} (sub-agent "+ f"'{library_agent.get('name')}') needs links for "+ f"required inputs: {missing_inputs}."+ )++ node["input_default"] = input_default++ return agent++ def fix_invalid_nested_sink_links(+ self,+ agent: AgentDict,+ blocks: list[dict[str, Any]],+ node_lookup: dict[str, dict[str, Any]] | None = None,+ ) -> AgentDict:+ """+ Fix invalid nested sink links (links with _#_ notation pointing to+ array indices).++ The LLM sometimes generates links like 'values_#_0' for CreateListBlock,+ which is invalid because:+ 1. 'values' is an array type, not an object with named properties+ 2. The _#_ notation is for accessing nested object properties, not array+ indices++ This fix removes such invalid links to prevent validation errors.++ Args:+ agent: The agent dictionary to fix+ blocks: List of available blocks with their schemas++ Returns:+ The fixed agent dictionary+ """+ if not blocks:+ return agent++ block_input_schemas = {+ block.get("id", ""): block.get("inputSchema", {}).get("properties", {})+ for block in blocks+ }+ block_names = {+ block.get("id", ""): block.get("name", "Unknown Block") for block in blocks+ }++ if node_lookup is None:+ node_lookup = self._build_node_lookup(agent)++ links = agent.get("links", [])+ links_to_remove: list[str] = []++ for link in links:+ sink_name = link.get("sink_name", "")++ if "_#_" in sink_name:+ parent, child = sink_name.split("_#_", 1)++ # Check if child is a numeric index (invalid for _#_ notation)+ if child.isdigit():+ sink_node = node_lookup.get(link.get("sink_id", ""))+ if sink_node:+ block_id = sink_node.get("block_id")+ block_name = block_names.get(block_id, "Unknown Block")+ self.add_fix_log(+ f"Removing invalid nested sink link "+ f"'{sink_name}' for block '{block_name}': "+ f"Array indices (like '{child}') are not "+ f"valid with _#_ notation"+ )+ links_to_remove.append(link.get("id", ""))+ continue++ # Check if parent property exists and child is valid+ sink_node = node_lookup.get(link.get("sink_id", ""))+ if sink_node:+ block_id = sink_node.get("block_id")+ input_props = block_input_schemas.get(block_id, {})+ parent_schema = input_props.get(parent)++ # If parent doesn't exist or is an array type, remove+ if parent_schema:+ parent_type = parent_schema.get("type")+ if parent_type == "array":+ block_name = block_names.get(block_id, "Unknown Block")+ self.add_fix_log(+ f"Removing invalid nested sink link "+ f"'{sink_name}' for block "+ f"'{block_name}': '{parent}' is an "+ f"array type, _#_ notation not "+ f"applicable"+ )+ links_to_remove.append(link.get("id", ""))++ # Remove invalid links+ if links_to_remove:+ agent["links"] = [+ link for link in links if link.get("id", "") not in links_to_remove+ ]++ return agent++ def fix_mcp_tool_blocks(self, agent: AgentDict) -> AgentDict:+ """Fix MCPToolBlock nodes to ensure they have required fields.++ Ensures:+ 1. `tool_arguments` is present (defaults to `{}`)+ 2. `tool_input_schema` is present (defaults to `{}`)+ 3. `tool_arguments` is populated with default/null values from+ `tool_input_schema` properties (matching AgentExecutorBlock pattern)++ Args:+ agent: The agent dictionary to fix++ Returns:+ The fixed agent dictionary+ """+ nodes = agent.get("nodes", [])++ for node in nodes:+ if node.get("block_id") != MCP_TOOL_BLOCK_ID:+ continue++ node_id = node.get("id", "unknown")+ input_default = node.setdefault("input_default", {})++ if "tool_input_schema" not in input_default:+ input_default["tool_input_schema"] = {}+ self.add_fix_log(+ f"MCPToolBlock {node_id}: Added missing tool_input_schema"+ )++ if "tool_arguments" not in input_default:+ input_default["tool_arguments"] = {}+ self.add_fix_log(+ f"MCPToolBlock {node_id}: Added missing tool_arguments"+ )++ # Populate tool_arguments with defaults from tool_input_schema+ tool_schema = input_default.get("tool_input_schema", {})+ schema_properties = (+ tool_schema.get("properties", {})+ if isinstance(tool_schema, dict)+ else {}+ )+ tool_args = input_default.get("tool_arguments", {})+ if isinstance(schema_properties, dict) and isinstance(tool_args, dict):+ for prop_name, prop_schema in schema_properties.items():+ if prop_name not in tool_args and isinstance(prop_schema, dict):+ default_value = prop_schema.get("default")+ tool_args[prop_name] = default_value+ self.add_fix_log(+ f"MCPToolBlock {node_id}: Added default value "+ f"for tool argument '{prop_name}'"+ )++ return agent++ def fix_dynamic_block_sink_names(self, agent: AgentDict) -> AgentDict:+ """Fix links that use _#_ notation for dynamic block sink names.++ MCPToolBlock and AgentExecutorBlock use dynamic input schemas where+ tool arguments / sub-agent inputs are flattened to top-level field+ names at execution time. Links should use the bare field name+ (e.g., ``query``) instead of nested notation+ (e.g., ``tool_arguments_#_query`` or ``inputs_#_query``).+ """+ nodes = {n.get("id"): n for n in agent.get("nodes", [])}+ prefixes = {+ MCP_TOOL_BLOCK_ID: "tool_arguments_#_",+ AGENT_EXECUTOR_BLOCK_ID: "inputs_#_",+ }++ for link in agent.get("links", []):+ sink_id = link.get("sink_id")+ sink_name = link.get("sink_name", "")+ sink_node = nodes.get(sink_id)+ if not sink_node:+ continue++ block_id = sink_node.get("block_id")+ prefix = prefixes.get(block_id)+ if prefix and sink_name.startswith(prefix):+ bare_name = sink_name[len(prefix) :]+ link["sink_name"] = bare_name+ self.add_fix_log(+ f"Link to {block_id[:8]}: renamed sink "+ f"'{sink_name}' -> '{bare_name}'"+ )++ return agent++ def apply_all_fixes(+ self,+ agent: AgentDict,+ blocks: list[dict[str, Any]] | None = None,+ library_agents: list[dict[str, Any]] | None = None,+ ) -> AgentDict:+ """+ Apply all available fixes to the agent.++ Args:+ agent: The agent dictionary to fix+ blocks: List of available blocks with their schemas (optional)+ library_agents: List of library agents for AgentExecutorBlock+ validation++ Returns:+ The fixed agent dictionary+ """+ self.fixes_applied = []++ # Apply fixes in order+ agent = self.fix_agent_ids(agent)+ agent = self.fix_double_curly_braces(agent)+ agent = self.fix_storevalue_before_condition(agent)+ agent = self.fix_addtolist_blocks(agent)+ agent = self.fix_addtolist_gmail_self_reference(agent)+ agent = self.fix_addtodictionary_blocks(agent)+ agent = self.fix_code_execution_output(agent)+ agent = self.fix_data_sampling_sample_size(agent)+ agent = self.fix_text_replace_new_parameter(agent)+ agent = self.fix_credentials(agent)+ # Build node lookup once for non-mutating methods below+ node_lookup = self._build_node_lookup(agent)+ agent = self.fix_node_x_coordinates(agent, node_lookup=node_lookup)+ agent = self.fix_getcurrentdate_offset(agent)++ # Apply fixes that require blocks information+ if blocks:+ agent = self.fix_invalid_nested_sink_links(+ agent, blocks, node_lookup=node_lookup+ )+ agent = self.fix_ai_model_parameter(agent, blocks)+ agent = self.fix_link_static_properties(+ agent, blocks, node_lookup=node_lookup+ )+ agent = self.fix_data_type_mismatch(agent, blocks)++ # Fix _#_ notation in links targeting dynamic blocks (MCP/AgentExecutor)+ agent = self.fix_dynamic_block_sink_names(agent)++ # Apply fixes for MCPToolBlock nodes+ agent = self.fix_mcp_tool_blocks(agent)++ # Apply fixes for AgentExecutorBlock nodes (sub-agents)+ if library_agents:+ agent = self.fix_agent_executor_blocks(agent, library_agents)++ logger.debug(f"Applied {len(self.fixes_applied)} fixes to agent")+ for fix in self.fixes_applied:+ logger.debug(f" - {fix}")++ return agent++ def get_fixes_applied(self) -> list[str]:+ """Get a list of all fixes that were applied."""+ return self.fixes_applied.copy()++ def clear_fixes_log(self) -> None:+ """Clear the list of applied fixes."""+ self.fixes_applied = []diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/fixer_test.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/fixer_test.pynew file mode 100644index 0000000000..b8a1620895--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/fixer_test.py@@ -0,0 +1,913 @@+"""Unit tests for AgentFixer."""++from .fixer import (+ _ADDTODICTIONARY_BLOCK_ID,+ _ADDTOLIST_BLOCK_ID,+ _CODE_EXECUTION_BLOCK_ID,+ _DATA_SAMPLING_BLOCK_ID,+ _GET_CURRENT_DATE_BLOCK_ID,+ _STORE_VALUE_BLOCK_ID,+ _TEXT_REPLACE_BLOCK_ID,+ _UNIVERSAL_TYPE_CONVERTER_BLOCK_ID,+ AGENT_EXECUTOR_BLOCK_ID,+ MCP_TOOL_BLOCK_ID,+ AgentFixer,+)+from .helpers import generate_uuid+++def _make_agent(+ nodes: list | None = None,+ links: list | None = None,+ agent_id: str | None = None,+) -> dict:+ """Build a minimal agent dict for testing."""+ return {+ "id": agent_id or generate_uuid(),+ "name": "Test Agent",+ "nodes": nodes or [],+ "links": links or [],+ }+++def _make_node(+ node_id: str | None = None,+ block_id: str = "block-1",+ input_default: dict | None = None,+ position: tuple[int, int] = (0, 0),+) -> dict:+ """Build a minimal node dict for testing."""+ return {+ "id": node_id or generate_uuid(),+ "block_id": block_id,+ "input_default": input_default or {},+ "metadata": {"position": {"x": position[0], "y": position[1]}},+ }+++def _make_link(+ link_id: str | None = None,+ source_id: str = "",+ source_name: str = "output",+ sink_id: str = "",+ sink_name: str = "input",+ is_static: bool = False,+) -> dict:+ """Build a minimal link dict for testing."""+ return {+ "id": link_id or generate_uuid(),+ "source_id": source_id,+ "source_name": source_name,+ "sink_id": sink_id,+ "sink_name": sink_name,+ "is_static": is_static,+ }+++class TestFixAgentIds:+ """Tests for fix_agent_ids."""++ def test_valid_uuids_unchanged(self):+ fixer = AgentFixer()+ agent_id = generate_uuid()+ link_id = generate_uuid()+ agent = _make_agent(agent_id=agent_id, links=[{"id": link_id}])++ result = fixer.fix_agent_ids(agent)++ assert result["id"] == agent_id+ assert result["links"][0]["id"] == link_id+ assert fixer.fixes_applied == []++ def test_invalid_agent_id_replaced(self):+ fixer = AgentFixer()+ agent = _make_agent(agent_id="bad-id")++ result = fixer.fix_agent_ids(agent)++ assert result["id"] != "bad-id"+ assert len(fixer.fixes_applied) == 1+ assert "agent ID" in fixer.fixes_applied[0]++ def test_invalid_link_id_replaced(self):+ fixer = AgentFixer()+ agent = _make_agent(links=[{"id": "not-a-uuid"}])++ result = fixer.fix_agent_ids(agent)++ assert result["links"][0]["id"] != "not-a-uuid"+ assert len(fixer.fixes_applied) == 1+++class TestFixDoubleCurlyBraces:+ """Tests for fix_double_curly_braces."""++ def test_single_braces_converted_to_double(self):+ fixer = AgentFixer()+ node = _make_node(input_default={"prompt": "Hello {name}!"})+ agent = _make_agent(nodes=[node])++ result = fixer.fix_double_curly_braces(agent)++ assert result["nodes"][0]["input_default"]["prompt"] == "Hello {{name}}!"++ def test_double_braces_unchanged(self):+ fixer = AgentFixer()+ node = _make_node(input_default={"prompt": "Hello {{name}}!"})+ agent = _make_agent(nodes=[node])++ result = fixer.fix_double_curly_braces(agent)++ assert result["nodes"][0]["input_default"]["prompt"] == "Hello {{name}}!"+ assert fixer.fixes_applied == []++ def test_non_string_prompt_skipped(self):+ fixer = AgentFixer()+ node = _make_node(input_default={"prompt": 42})+ agent = _make_agent(nodes=[node])++ result = fixer.fix_double_curly_braces(agent)++ assert result["nodes"][0]["input_default"]["prompt"] == 42++ def test_non_string_prompt_with_prompt_values_skipped(self):+ """Ensure non-string prompt fields don't crash re.search in the+ prompt_values path."""+ fixer = AgentFixer()+ node_id = generate_uuid()+ source_id = generate_uuid()+ node = _make_node(+ node_id=node_id, input_default={"prompt": None, "prompt_values": {}}+ )+ source_node = _make_node(node_id=source_id)+ link = _make_link(+ source_id=source_id,+ source_name="output",+ sink_id=node_id,+ sink_name="prompt_values_$_name",+ )+ agent = _make_agent(nodes=[node, source_node], links=[link])++ result = fixer.fix_double_curly_braces(agent)++ # Should not crash and prompt stays None+ assert result["nodes"][0]["input_default"]["prompt"] is None+++class TestFixCredentials:+ """Tests for fix_credentials."""++ def test_credentials_removed(self):+ fixer = AgentFixer()+ node = _make_node(+ input_default={+ "credentials": {"key": "secret"},+ "url": "http://example.com",+ }+ )+ agent = _make_agent(nodes=[node])++ result = fixer.fix_credentials(agent)++ assert "credentials" not in result["nodes"][0]["input_default"]+ assert result["nodes"][0]["input_default"]["url"] == "http://example.com"+ assert len(fixer.fixes_applied) == 1++ def test_no_credentials_unchanged(self):+ fixer = AgentFixer()+ node = _make_node(input_default={"url": "http://example.com"})+ agent = _make_agent(nodes=[node])++ result = fixer.fix_credentials(agent)++ assert result["nodes"][0]["input_default"]["url"] == "http://example.com"+ assert fixer.fixes_applied == []+++class TestFixCodeExecutionOutput:+ """Tests for fix_code_execution_output."""++ def test_response_renamed_to_stdout_logs(self):+ fixer = AgentFixer()+ node = _make_node(node_id="n1", block_id=_CODE_EXECUTION_BLOCK_ID)+ link = _make_link(source_id="n1", source_name="response", sink_id="n2")+ agent = _make_agent(nodes=[node], links=[link])++ result = fixer.fix_code_execution_output(agent)++ assert result["links"][0]["source_name"] == "stdout_logs"+ assert len(fixer.fixes_applied) == 1++ def test_non_response_source_unchanged(self):+ fixer = AgentFixer()+ node = _make_node(node_id="n1", block_id=_CODE_EXECUTION_BLOCK_ID)+ link = _make_link(source_id="n1", source_name="stdout_logs", sink_id="n2")+ agent = _make_agent(nodes=[node], links=[link])++ result = fixer.fix_code_execution_output(agent)++ assert result["links"][0]["source_name"] == "stdout_logs"+ assert fixer.fixes_applied == []+++class TestFixDataSamplingSampleSize:+ """Tests for fix_data_sampling_sample_size."""++ def test_sample_size_set_to_1(self):+ fixer = AgentFixer()+ node = _make_node(+ node_id="n1",+ block_id=_DATA_SAMPLING_BLOCK_ID,+ input_default={"sample_size": 10},+ )+ agent = _make_agent(nodes=[node])++ result = fixer.fix_data_sampling_sample_size(agent)++ assert result["nodes"][0]["input_default"]["sample_size"] == 1++ def test_removes_links_to_sample_size(self):+ fixer = AgentFixer()+ node = _make_node(node_id="n1", block_id=_DATA_SAMPLING_BLOCK_ID)+ link = _make_link(sink_id="n1", sink_name="sample_size", source_id="n2")+ agent = _make_agent(nodes=[node], links=[link])++ result = fixer.fix_data_sampling_sample_size(agent)++ assert len(result["links"]) == 0+ assert result["nodes"][0]["input_default"]["sample_size"] == 1+++class TestFixTextReplaceNewParameter:+ """Tests for fix_text_replace_new_parameter."""++ def test_empty_new_changed_to_space(self):+ fixer = AgentFixer()+ node = _make_node(+ block_id=_TEXT_REPLACE_BLOCK_ID,+ input_default={"new": ""},+ )+ agent = _make_agent(nodes=[node])++ result = fixer.fix_text_replace_new_parameter(agent)++ assert result["nodes"][0]["input_default"]["new"] == " "++ def test_nonempty_new_unchanged(self):+ fixer = AgentFixer()+ node = _make_node(+ block_id=_TEXT_REPLACE_BLOCK_ID,+ input_default={"new": "replacement"},+ )+ agent = _make_agent(nodes=[node])++ result = fixer.fix_text_replace_new_parameter(agent)++ assert result["nodes"][0]["input_default"]["new"] == "replacement"+ assert fixer.fixes_applied == []+++class TestFixGetCurrentDateOffset:+ """Tests for fix_getcurrentdate_offset."""++ def test_negative_offset_made_positive(self):+ fixer = AgentFixer()+ node = _make_node(+ block_id=_GET_CURRENT_DATE_BLOCK_ID,+ input_default={"offset": -5},+ )+ agent = _make_agent(nodes=[node])++ result = fixer.fix_getcurrentdate_offset(agent)++ assert result["nodes"][0]["input_default"]["offset"] == 5++ def test_positive_offset_unchanged(self):+ fixer = AgentFixer()+ node = _make_node(+ block_id=_GET_CURRENT_DATE_BLOCK_ID,+ input_default={"offset": 3},+ )+ agent = _make_agent(nodes=[node])++ result = fixer.fix_getcurrentdate_offset(agent)++ assert result["nodes"][0]["input_default"]["offset"] == 3+ assert fixer.fixes_applied == []+++class TestFixNodeXCoordinates:+ """Tests for fix_node_x_coordinates."""++ def test_close_nodes_spread_apart(self):+ fixer = AgentFixer()+ src_node = _make_node(node_id="src", position=(0, 0))+ sink_node = _make_node(node_id="sink", position=(100, 0))+ link = _make_link(source_id="src", sink_id="sink")+ agent = _make_agent(nodes=[src_node, sink_node], links=[link])++ result = fixer.fix_node_x_coordinates(agent)++ sink = next(n for n in result["nodes"] if n["id"] == "sink")+ assert sink["metadata"]["position"]["x"] >= 800++ def test_far_apart_nodes_unchanged(self):+ fixer = AgentFixer()+ src_node = _make_node(node_id="src", position=(0, 0))+ sink_node = _make_node(node_id="sink", position=(1000, 0))+ link = _make_link(source_id="src", sink_id="sink")+ agent = _make_agent(nodes=[src_node, sink_node], links=[link])++ result = fixer.fix_node_x_coordinates(agent)++ sink = next(n for n in result["nodes"] if n["id"] == "sink")+ assert sink["metadata"]["position"]["x"] == 1000+ assert fixer.fixes_applied == []+++class TestFixAddToDictionaryBlocks:+ """Tests for fix_addtodictionary_blocks."""++ def test_removes_create_dictionary_nodes(self):+ fixer = AgentFixer()+ create_dict_id = "b924ddf4-de4f-4b56-9a85-358930dcbc91"+ dict_node = _make_node(node_id="dict-1", block_id=create_dict_id)+ add_to_dict_node = _make_node(+ node_id="add-1", block_id=_ADDTODICTIONARY_BLOCK_ID+ )+ link = _make_link(source_id="dict-1", sink_id="add-1")+ agent = _make_agent(nodes=[dict_node, add_to_dict_node], links=[link])++ result = fixer.fix_addtodictionary_blocks(agent)++ node_ids = [n["id"] for n in result["nodes"]]+ assert "dict-1" not in node_ids+ assert "add-1" in node_ids+ assert len(result["links"]) == 0+++class TestFixStoreValueBeforeCondition:+ """Tests for fix_storevalue_before_condition."""++ def test_inserts_storevalue_block(self):+ fixer = AgentFixer()+ condition_block_id = "715696a0-e1da-45c8-b209-c2fa9c3b0be6"+ src_node = _make_node(node_id="src")+ cond_node = _make_node(node_id="cond", block_id=condition_block_id)+ link = _make_link(+ source_id="src", source_name="output", sink_id="cond", sink_name="value2"+ )+ agent = _make_agent(nodes=[src_node, cond_node], links=[link])++ result = fixer.fix_storevalue_before_condition(agent)++ # Should have 3 nodes now (original 2 + new StoreValueBlock)+ assert len(result["nodes"]) == 3+ store_nodes = [+ n for n in result["nodes"] if n["block_id"] == _STORE_VALUE_BLOCK_ID+ ]+ assert len(store_nodes) == 1+ assert store_nodes[0]["input_default"]["data"] is None+++class TestFixAddToListBlocks:+ """Tests for fix_addtolist_blocks - self-reference links."""++ def test_addtolist_gets_self_reference_link(self):+ fixer = AgentFixer()+ node = _make_node(node_id="atl-1", block_id=_ADDTOLIST_BLOCK_ID)+ # Source link to AddToList (from some other node)+ link = _make_link(+ source_id="other",+ source_name="output",+ sink_id="atl-1",+ sink_name="item",+ )+ other_node = _make_node(node_id="other")+ agent = _make_agent(nodes=[other_node, node], links=[link])++ result = fixer.fix_addtolist_blocks(agent)++ # Should have a self-reference link: atl-1.updated_list -> atl-1.list+ self_ref_links = [+ lnk+ for lnk in result["links"]+ if lnk["source_id"] == "atl-1"+ and lnk["sink_id"] == "atl-1"+ and lnk["source_name"] == "updated_list"+ and lnk["sink_name"] == "list"+ ]+ assert len(self_ref_links) == 1+++class TestFixLinkStaticProperties:+ """Tests for fix_link_static_properties."""++ def test_sets_is_static_from_block_schema(self):+ fixer = AgentFixer()+ block_id = generate_uuid()+ node = _make_node(node_id="n1", block_id=block_id)+ link = _make_link(source_id="n1", sink_id="n2", is_static=False)+ agent = _make_agent(nodes=[node], links=[link])++ blocks = [{"id": block_id, "staticOutput": True}]++ result = fixer.fix_link_static_properties(agent, blocks)++ assert result["links"][0]["is_static"] is True++ def test_unknown_block_leaves_link_unchanged(self):+ fixer = AgentFixer()+ node = _make_node(node_id="n1", block_id="unknown-block")+ link = _make_link(source_id="n1", sink_id="n2", is_static=True)+ agent = _make_agent(nodes=[node], links=[link])++ result = fixer.fix_link_static_properties(agent, blocks=[])++ # Unknown block → skipped, link stays as-is+ assert result["links"][0]["is_static"] is True+++class TestFixAiModelParameter:+ """Tests for fix_ai_model_parameter."""++ def test_missing_model_gets_default(self):+ fixer = AgentFixer()+ block_id = generate_uuid()+ node = _make_node(node_id="n1", block_id=block_id, input_default={})+ agent = _make_agent(nodes=[node])++ blocks = [+ {+ "id": block_id,+ "categories": [{"category": "AI"}],+ "inputSchema": {+ "properties": {"model": {"type": "string"}},+ },+ }+ ]++ result = fixer.fix_ai_model_parameter(agent, blocks)++ assert result["nodes"][0]["input_default"]["model"] == "gpt-4o"++ def test_valid_model_unchanged(self):+ fixer = AgentFixer()+ block_id = generate_uuid()+ node = _make_node(+ node_id="n1",+ block_id=block_id,+ input_default={"model": "claude-opus-4-6"},+ )+ agent = _make_agent(nodes=[node])++ blocks = [+ {+ "id": block_id,+ "categories": [{"category": "AI"}],+ "inputSchema": {+ "properties": {"model": {"type": "string"}},+ },+ }+ ]++ result = fixer.fix_ai_model_parameter(agent, blocks)++ assert result["nodes"][0]["input_default"]["model"] == "claude-opus-4-6"+++class TestFixAgentExecutorBlocks:+ """Tests for fix_agent_executor_blocks."""++ def test_fills_schemas_from_library_agent(self):+ fixer = AgentFixer()+ lib_agent_id = generate_uuid()+ node = _make_node(+ node_id="n1",+ block_id=AGENT_EXECUTOR_BLOCK_ID,+ input_default={+ "graph_id": lib_agent_id,+ "graph_version": 1,+ "user_id": "user-1",+ },+ )+ agent = _make_agent(nodes=[node])++ # Library agents use graph_id as the lookup key+ library_agents = [+ {+ "graph_id": lib_agent_id,+ "graph_version": 2,+ "input_schema": {"field1": {"type": "string"}},+ "output_schema": {"result": {"type": "string"}},+ }+ ]++ result = fixer.fix_agent_executor_blocks(agent, library_agents)++ node_result = result["nodes"][0]["input_default"]+ assert node_result["graph_version"] == 2+ assert node_result["input_schema"] == {"field1": {"type": "string"}}+ assert node_result["output_schema"] == {"result": {"type": "string"}}+++class TestFixInvalidNestedSinkLinks:+ """Tests for fix_invalid_nested_sink_links."""++ def test_removes_numeric_index_links(self):+ fixer = AgentFixer()+ block_id = generate_uuid()+ node = _make_node(node_id="n1", block_id=block_id)+ link = _make_link(source_id="n2", sink_id="n1", sink_name="values_#_0")+ agent = _make_agent(nodes=[node], links=[link])++ blocks = [+ {+ "id": block_id,+ "inputSchema": {"properties": {"values": {"type": "array"}}},+ }+ ]++ result = fixer.fix_invalid_nested_sink_links(agent, blocks)++ assert len(result["links"]) == 0++ def test_valid_nested_links_kept(self):+ fixer = AgentFixer()+ block_id = generate_uuid()+ node = _make_node(node_id="n1", block_id=block_id)+ link = _make_link(source_id="n2", sink_id="n1", sink_name="values_#_name")+ agent = _make_agent(nodes=[node], links=[link])++ blocks = [+ {+ "id": block_id,+ "inputSchema": {+ "properties": {"values": {"type": "object"}},+ },+ }+ ]++ result = fixer.fix_invalid_nested_sink_links(agent, blocks)++ assert len(result["links"]) == 1+++class TestApplyAllFixes:+ """Tests for apply_all_fixes orchestration."""++ def test_is_sync(self):+ """apply_all_fixes should be a sync function."""+ import inspect++ assert not inspect.iscoroutinefunction(AgentFixer.apply_all_fixes)++ def test_applies_multiple_fixes(self):+ fixer = AgentFixer()+ agent = _make_agent(+ agent_id="bad-id",+ nodes=[+ _make_node(+ block_id=_TEXT_REPLACE_BLOCK_ID,+ input_default={"new": "", "credentials": {"key": "secret"}},+ )+ ],+ )++ result = fixer.apply_all_fixes(agent)++ # Agent ID should be fixed+ assert result["id"] != "bad-id"+ # Credentials should be removed+ assert "credentials" not in result["nodes"][0]["input_default"]+ # Text replace "new" should be space+ assert result["nodes"][0]["input_default"]["new"] == " "+ # Multiple fixes applied+ assert len(fixer.fixes_applied) >= 3++ def test_empty_agent_no_crash(self):+ fixer = AgentFixer()+ agent = _make_agent()++ result = fixer.apply_all_fixes(agent)++ assert "nodes" in result+ assert "links" in result++ def test_returns_deep_copy_behavior(self):+ """Fixer mutates in place — verify the same dict is returned."""+ fixer = AgentFixer()+ agent = _make_agent()+ result = fixer.apply_all_fixes(agent)+ assert result is agent+++class TestFixMCPToolBlocks:+ """Tests for fix_mcp_tool_blocks."""++ def test_adds_missing_tool_arguments(self):+ fixer = AgentFixer()+ node = _make_node(+ node_id="n1",+ block_id=MCP_TOOL_BLOCK_ID,+ input_default={+ "server_url": "https://mcp.example.com/sse",+ "selected_tool": "search",+ "tool_input_schema": {},+ },+ )+ agent = _make_agent(nodes=[node])++ result = fixer.fix_mcp_tool_blocks(agent)++ assert result["nodes"][0]["input_default"]["tool_arguments"] == {}+ assert any("tool_arguments" in f for f in fixer.fixes_applied)++ def test_adds_missing_tool_input_schema(self):+ fixer = AgentFixer()+ node = _make_node(+ node_id="n1",+ block_id=MCP_TOOL_BLOCK_ID,+ input_default={+ "server_url": "https://mcp.example.com/sse",+ "selected_tool": "search",+ "tool_arguments": {},+ },+ )+ agent = _make_agent(nodes=[node])++ result = fixer.fix_mcp_tool_blocks(agent)++ assert result["nodes"][0]["input_default"]["tool_input_schema"] == {}+ assert any("tool_input_schema" in f for f in fixer.fixes_applied)++ def test_populates_tool_arguments_from_schema(self):+ fixer = AgentFixer()+ node = _make_node(+ node_id="n1",+ block_id=MCP_TOOL_BLOCK_ID,+ input_default={+ "server_url": "https://mcp.example.com/sse",+ "selected_tool": "search",+ "tool_input_schema": {+ "properties": {+ "query": {"type": "string", "default": "hello"},+ "limit": {"type": "integer"},+ }+ },+ "tool_arguments": {},+ },+ )+ agent = _make_agent(nodes=[node])++ result = fixer.fix_mcp_tool_blocks(agent)++ tool_args = result["nodes"][0]["input_default"]["tool_arguments"]+ assert tool_args["query"] == "hello"+ assert tool_args["limit"] is None++ def test_no_op_when_already_complete(self):+ fixer = AgentFixer()+ node = _make_node(+ node_id="n1",+ block_id=MCP_TOOL_BLOCK_ID,+ input_default={+ "server_url": "https://mcp.example.com/sse",+ "selected_tool": "search",+ "tool_input_schema": {},+ "tool_arguments": {},+ },+ )+ agent = _make_agent(nodes=[node])++ fixer.fix_mcp_tool_blocks(agent)++ assert len(fixer.fixes_applied) == 0+++class TestFixDynamicBlockSinkNames:+ """Tests for fix_dynamic_block_sink_names."""++ def test_mcp_tool_arguments_prefix_removed(self):+ fixer = AgentFixer()+ node = _make_node(node_id="n1", block_id=MCP_TOOL_BLOCK_ID)+ link = _make_link(+ source_id="src", sink_id="n1", sink_name="tool_arguments_#_query"+ )+ agent = _make_agent(nodes=[node], links=[link])++ fixer.fix_dynamic_block_sink_names(agent)++ assert agent["links"][0]["sink_name"] == "query"+ assert len(fixer.fixes_applied) == 1++ def test_agent_executor_inputs_prefix_removed(self):+ fixer = AgentFixer()+ node = _make_node(node_id="n1", block_id=AGENT_EXECUTOR_BLOCK_ID)+ link = _make_link(source_id="src", sink_id="n1", sink_name="inputs_#_url")+ agent = _make_agent(nodes=[node], links=[link])++ fixer.fix_dynamic_block_sink_names(agent)++ assert agent["links"][0]["sink_name"] == "url"+ assert len(fixer.fixes_applied) == 1++ def test_bare_sink_name_unchanged(self):+ fixer = AgentFixer()+ node = _make_node(node_id="n1", block_id=MCP_TOOL_BLOCK_ID)+ link = _make_link(source_id="src", sink_id="n1", sink_name="query")+ agent = _make_agent(nodes=[node], links=[link])++ fixer.fix_dynamic_block_sink_names(agent)++ assert agent["links"][0]["sink_name"] == "query"+ assert len(fixer.fixes_applied) == 0++ def test_non_dynamic_block_unchanged(self):+ fixer = AgentFixer()+ node = _make_node(node_id="n1", block_id="some-other-block-id")+ link = _make_link(source_id="src", sink_id="n1", sink_name="values_#_key")+ agent = _make_agent(nodes=[node], links=[link])++ fixer.fix_dynamic_block_sink_names(agent)++ assert agent["links"][0]["sink_name"] == "values_#_key"+ assert len(fixer.fixes_applied) == 0+++class TestFixDataTypeMismatch:+ """Tests for fix_data_type_mismatch."""++ @staticmethod+ def _make_block(+ block_id: str,+ name: str = "TestBlock",+ input_schema: dict | None = None,+ output_schema: dict | None = None,+ ) -> dict:+ return {+ "id": block_id,+ "name": name,+ "inputSchema": input_schema or {"properties": {}},+ "outputSchema": output_schema or {"properties": {}},+ }++ def test_inserts_converter_for_incompatible_types(self):+ fixer = AgentFixer()+ src_block_id = generate_uuid()+ sink_block_id = generate_uuid()++ src_node = _make_node(node_id="src", block_id=src_block_id)+ sink_node = _make_node(node_id="sink", block_id=sink_block_id)+ link = _make_link(+ source_id="src",+ source_name="result",+ sink_id="sink",+ sink_name="count",+ )+ agent = _make_agent(nodes=[src_node, sink_node], links=[link])++ blocks = [+ self._make_block(+ src_block_id,+ name="Source",+ output_schema={"properties": {"result": {"type": "string"}}},+ ),+ self._make_block(+ sink_block_id,+ name="Sink",+ input_schema={"properties": {"count": {"type": "integer"}}},+ ),+ ]++ result = fixer.fix_data_type_mismatch(agent, blocks)++ # A converter node should have been inserted+ converter_nodes = [+ n+ for n in result["nodes"]+ if n["block_id"] == _UNIVERSAL_TYPE_CONVERTER_BLOCK_ID+ ]+ assert len(converter_nodes) == 1+ assert converter_nodes[0]["input_default"]["type"] == "number"++ # Original link replaced by two new links through the converter+ assert len(result["links"]) == 2+ src_to_converter = result["links"][0]+ converter_to_sink = result["links"][1]++ assert src_to_converter["source_id"] == "src"+ assert src_to_converter["sink_id"] == converter_nodes[0]["id"]+ assert src_to_converter["sink_name"] == "value"++ assert converter_to_sink["source_id"] == converter_nodes[0]["id"]+ assert converter_to_sink["source_name"] == "value"+ assert converter_to_sink["sink_id"] == "sink"+ assert converter_to_sink["sink_name"] == "count"++ assert len(fixer.fixes_applied) == 1++ def test_compatible_types_unchanged(self):+ fixer = AgentFixer()+ block_id = generate_uuid()++ src_node = _make_node(node_id="src", block_id=block_id)+ sink_node = _make_node(node_id="sink", block_id=block_id)+ link = _make_link(+ source_id="src",+ source_name="output",+ sink_id="sink",+ sink_name="input",+ )+ agent = _make_agent(nodes=[src_node, sink_node], links=[link])++ blocks = [+ self._make_block(+ block_id,+ input_schema={"properties": {"input": {"type": "string"}}},+ output_schema={"properties": {"output": {"type": "string"}}},+ ),+ ]++ result = fixer.fix_data_type_mismatch(agent, blocks)++ # No converter inserted, original link kept+ assert len(result["nodes"]) == 2+ assert len(result["links"]) == 1+ assert result["links"][0] is link+ assert fixer.fixes_applied == []++ def test_missing_block_keeps_link(self):+ """Links referencing unknown blocks are kept unchanged."""+ fixer = AgentFixer()+ src_node = _make_node(node_id="src", block_id="unknown-block")+ sink_node = _make_node(node_id="sink", block_id="unknown-block")+ link = _make_link(source_id="src", sink_id="sink")+ agent = _make_agent(nodes=[src_node, sink_node], links=[link])++ result = fixer.fix_data_type_mismatch(agent, blocks=[])++ assert len(result["links"]) == 1+ assert result["links"][0] is link++ def test_missing_type_info_keeps_link(self):+ """Links where source/sink type is not defined are kept unchanged."""+ fixer = AgentFixer()+ block_id = generate_uuid()+ src_node = _make_node(node_id="src", block_id=block_id)+ sink_node = _make_node(node_id="sink", block_id=block_id)+ link = _make_link(+ source_id="src",+ source_name="output",+ sink_id="sink",+ sink_name="input",+ )+ agent = _make_agent(nodes=[src_node, sink_node], links=[link])++ # Block has no properties defined for the linked fields+ blocks = [self._make_block(block_id)]++ result = fixer.fix_data_type_mismatch(agent, blocks)++ assert len(result["links"]) == 1+ assert fixer.fixes_applied == []++ def test_multiple_mismatches_insert_multiple_converters(self):+ """Each incompatible link gets its own converter node."""+ fixer = AgentFixer()+ src_block_id = generate_uuid()+ sink_block_id = generate_uuid()++ src_node = _make_node(node_id="src", block_id=src_block_id)+ sink1 = _make_node(node_id="sink1", block_id=sink_block_id)+ sink2 = _make_node(node_id="sink2", block_id=sink_block_id)+ link1 = _make_link(+ source_id="src", source_name="out", sink_id="sink1", sink_name="count"+ )+ link2 = _make_link(+ source_id="src", source_name="out", sink_id="sink2", sink_name="count"+ )+ agent = _make_agent(nodes=[src_node, sink1, sink2], links=[link1, link2])++ blocks = [+ self._make_block(+ src_block_id,+ output_schema={"properties": {"out": {"type": "string"}}},+ ),+ self._make_block(+ sink_block_id,+ input_schema={"properties": {"count": {"type": "integer"}}},+ ),+ ]++ result = fixer.fix_data_type_mismatch(agent, blocks)++ converter_nodes = [+ n+ for n in result["nodes"]+ if n["block_id"] == _UNIVERSAL_TYPE_CONVERTER_BLOCK_ID+ ]+ assert len(converter_nodes) == 2+ # Each original link becomes two links through its own converter+ assert len(result["links"]) == 4+ assert len(fixer.fixes_applied) == 2diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/helpers.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/helpers.pynew file mode 100644index 0000000000..6d63e42b4c--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/helpers.py@@ -0,0 +1,67 @@+"""Shared helpers for agent generation."""++import re+import uuid+from typing import Any++from .blocks import get_blocks_as_dicts++__all__ = [+ "AGENT_EXECUTOR_BLOCK_ID",+ "AGENT_INPUT_BLOCK_ID",+ "AGENT_OUTPUT_BLOCK_ID",+ "AgentDict",+ "MCP_TOOL_BLOCK_ID",+ "UUID_REGEX",+ "are_types_compatible",+ "generate_uuid",+ "get_blocks_as_dicts",+ "get_defined_property_type",+ "is_uuid",+]+++# Type alias for the agent JSON structure passed through+# the validation and fixing pipeline.+AgentDict = dict[str, Any]++# Shared base pattern (unanchored, lowercase hex); used for both full-string+# validation (UUID_REGEX) and text extraction (core._UUID_PATTERN).+UUID_RE_STR = r"[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}"++UUID_REGEX = re.compile(r"^" + UUID_RE_STR + r"$")++AGENT_EXECUTOR_BLOCK_ID = "e189baac-8c20-45a1-94a7-55177ea42565"+MCP_TOOL_BLOCK_ID = "a0a4b1c2-d3e4-4f56-a7b8-c9d0e1f2a3b4"+AGENT_INPUT_BLOCK_ID = "c0a8e994-ebf1-4a9c-a4d8-89d09c86741b"+AGENT_OUTPUT_BLOCK_ID = "363ae599-353e-4804-937e-b2ee3cef3da4"+++def is_uuid(value: str) -> bool:+ """Check if a string is a valid UUID."""+ return isinstance(value, str) and UUID_REGEX.match(value) is not None+++def generate_uuid() -> str:+ """Generate a new UUID string."""+ return str(uuid.uuid4())+++def get_defined_property_type(schema: dict[str, Any], name: str) -> str | None:+ """Get property type from a schema, handling nested `_#_` notation."""+ if "_#_" in name:+ parent, child = name.split("_#_", 1)+ parent_schema = schema.get(parent, {})+ if "properties" in parent_schema and isinstance(+ parent_schema["properties"], dict+ ):+ return parent_schema["properties"].get(child, {}).get("type")+ return None+ return schema.get(name, {}).get("type")+++def are_types_compatible(src: str, sink: str) -> bool:+ """Check if two schema types are compatible."""+ if {src, sink} <= {"integer", "number"}:+ return True+ return src == sinkdiff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/pipeline.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/pipeline.pynew file mode 100644index 0000000000..8e7cf32d57--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/pipeline.py@@ -0,0 +1,196 @@+"""Shared fix → validate → preview/save pipeline for agent tools."""++import json+import logging+from typing import Any, cast++from backend.copilot.tools.models import (+ AgentPreviewResponse,+ AgentSavedResponse,+ ErrorResponse,+ ToolResponseBase,+)++from .blocks import get_blocks_as_dicts+from .core import get_library_agents_by_ids, save_agent_to_library+from .fixer import AgentFixer+from .validator import AgentValidator++logger = logging.getLogger(__name__)++MAX_AGENT_JSON_SIZE = 1_000_000 # 1 MB+++async def fetch_library_agents(+ user_id: str | None,+ library_agent_ids: list[str],+) -> list[dict[str, Any]] | None:+ """Fetch library agents by IDs for AgentExecutorBlock validation.++ Returns None if no IDs provided or user is not authenticated.+ """+ if not user_id or not library_agent_ids:+ return None+ try:+ agents = await get_library_agents_by_ids(+ user_id=user_id,+ agent_ids=library_agent_ids,+ )+ return cast(list[dict[str, Any]], agents)+ except Exception as e:+ logger.warning(f"Failed to fetch library agents by IDs: {e}")+ return None+++async def fix_validate_and_save(+ agent_json: dict[str, Any],+ *,+ user_id: str | None,+ session_id: str | None,+ save: bool = True,+ is_update: bool = False,+ default_name: str = "Agent",+ preview_message: str | None = None,+ save_message: str | None = None,+ library_agents: list[dict[str, Any]] | None = None,+ folder_id: str | None = None,+) -> ToolResponseBase:+ """Shared pipeline: auto-fix → validate → preview or save.++ Args:+ agent_json: The agent JSON dict (must already have id/version/is_active set).+ user_id: The authenticated user's ID.+ session_id: The chat session ID.+ save: Whether to save or just preview.+ is_update: Whether this is an update to an existing agent.+ default_name: Fallback name if agent_json has none.+ preview_message: Custom preview message (optional).+ save_message: Custom save success message (optional).+ library_agents: Library agents for AgentExecutorBlock validation/fixing.++ Returns:+ An appropriate ToolResponseBase subclass.+ """+ # Size guard+ json_size = len(json.dumps(agent_json))+ if json_size > MAX_AGENT_JSON_SIZE:+ return ErrorResponse(+ message=(+ f"Agent JSON is too large ({json_size:,} bytes, "+ f"max {MAX_AGENT_JSON_SIZE:,}). Reduce the number of nodes."+ ),+ error="agent_json_too_large",+ session_id=session_id,+ )++ blocks = get_blocks_as_dicts()++ # Auto-fix+ try:+ fixer = AgentFixer()+ agent_json = fixer.apply_all_fixes(agent_json, blocks, library_agents)+ fixes = fixer.get_fixes_applied()+ if fixes:+ logger.info(f"Applied {len(fixes)} auto-fixes to agent JSON")+ except Exception as e:+ logger.warning(f"Auto-fix failed: {e}")++ # Validate+ try:+ validator = AgentValidator()+ is_valid, _ = validator.validate(agent_json, blocks, library_agents)+ if not is_valid:+ errors = validator.errors+ return ErrorResponse(+ message=(+ f"The agent has {len(errors)} validation error(s):\n"+ + "\n".join(f"- {e}" for e in errors[:5])+ ),+ error="validation_failed",+ details={"errors": errors},+ session_id=session_id,+ )+ except Exception as e:+ logger.error(f"Validation failed with exception: {e}", exc_info=True)+ return ErrorResponse(+ message="Failed to validate the agent. Please try again.",+ error="validation_exception",+ details={"exception": str(e)},+ session_id=session_id,+ )++ agent_name = agent_json.get("name", default_name)+ agent_description = agent_json.get("description", "")+ node_count = len(agent_json.get("nodes", []))+ link_count = len(agent_json.get("links", []))++ # Build a warning suffix when name/description is missing or generic+ _GENERIC_NAMES = {+ "agent",+ "generated agent",+ "customized agent",+ "updated agent",+ "new agent",+ "my agent",+ }+ metadata_warnings: list[str] = []+ if not agent_json.get("name") or agent_name.lower().strip() in _GENERIC_NAMES:+ metadata_warnings.append("'name'")+ if not agent_description:+ metadata_warnings.append("'description'")+ metadata_hint = ""+ if metadata_warnings:+ missing = " and ".join(metadata_warnings)+ metadata_hint = (+ f" Note: the agent is missing a meaningful {missing}. "+ f"Please update the agent_json to include them."+ )++ if not save:+ return AgentPreviewResponse(+ message=(+ (+ preview_message+ or f"Agent '{agent_name}' with {node_count} blocks is ready."+ )+ + metadata_hint+ ),+ agent_json=agent_json,+ agent_name=agent_name,+ description=agent_description,+ node_count=node_count,+ link_count=link_count,+ session_id=session_id,+ )++ if not user_id:+ return ErrorResponse(+ message="You must be logged in to save agents.",+ error="auth_required",+ session_id=session_id,+ )++ try:+ created_graph, library_agent = await save_agent_to_library(+ agent_json, user_id, is_update=is_update, folder_id=folder_id+ )+ return AgentSavedResponse(+ message=(+ (save_message or f"Agent '{created_graph.name}' has been saved!")+ + metadata_hint+ ),+ agent_id=created_graph.id,+ agent_name=created_graph.name,+ library_agent_id=library_agent.id,+ library_agent_link=f"/library/agents/{library_agent.id}",+ agent_page_link=f"/build?flowID={created_graph.id}",+ session_id=session_id,+ )+ except Exception as e:+ logger.error(f"Failed to save agent: {e}", exc_info=True)+ return ErrorResponse(+ message=f"Failed to save the agent: {str(e)}",+ error="save_failed",+ details={"exception": str(e)},+ session_id=session_id,+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/service.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/service.pydeleted file mode 100644index f562c2aaa9..0000000000--- a/autogpt_platform/backend/backend/copilot/tools/agent_generator/service.py+++ /dev/null@@ -1,511 +0,0 @@-"""External Agent Generator service client.--This module provides a client for communicating with the external Agent Generator-microservice. When AGENTGENERATOR_HOST is configured, the agent generation functions-will delegate to the external service instead of using the built-in LLM-based implementation.-"""--import logging-from typing import Any--import httpx--from backend.util.settings import Settings--from .dummy import (- customize_template_dummy,- decompose_goal_dummy,- generate_agent_dummy,- generate_agent_patch_dummy,- get_blocks_dummy,- health_check_dummy,-)--logger = logging.getLogger(__name__)--_dummy_mode_warned = False---def _create_error_response(- error_message: str,- error_type: str = "unknown",- details: dict[str, Any] | None = None,-) -> dict[str, Any]:- """Create a standardized error response dict.-- Args:- error_message: Human-readable error message- error_type: Machine-readable error type- details: Optional additional error details-- Returns:- Error dict with type="error" and error details- """- response: dict[str, Any] = {- "type": "error",- "error": error_message,- "error_type": error_type,- }- if details:- response["details"] = details- return response---def _classify_http_error(e: httpx.HTTPStatusError) -> tuple[str, str]:- """Classify an HTTP error into error_type and message.-- Args:- e: The HTTP status error-- Returns:- Tuple of (error_type, error_message)- """- status = e.response.status_code- if status == 429:- return "rate_limit", f"Agent Generator rate limited: {e}"- elif status == 503:- return "service_unavailable", f"Agent Generator unavailable: {e}"- elif status == 504 or status == 408:- return "timeout", f"Agent Generator timed out: {e}"- else:- return "http_error", f"HTTP error calling Agent Generator: {e}"---def _classify_request_error(e: httpx.RequestError) -> tuple[str, str]:- """Classify a request error into error_type and message.-- Args:- e: The request error-- Returns:- Tuple of (error_type, error_message)- """- error_str = str(e).lower()- if "timeout" in error_str or "timed out" in error_str:- return "timeout", f"Agent Generator request timed out: {e}"- elif "connect" in error_str:- return "connection_error", f"Could not connect to Agent Generator: {e}"- else:- return "request_error", f"Request error calling Agent Generator: {e}"---_client: httpx.AsyncClient | None = None-_settings: Settings | None = None---def _get_settings() -> Settings:- """Get or create settings singleton."""- global _settings- if _settings is None:- _settings = Settings()- return _settings---def _is_dummy_mode() -> bool:- """Check if dummy mode is enabled for testing."""- global _dummy_mode_warned- settings = _get_settings()- is_dummy = bool(settings.config.agentgenerator_use_dummy)- if is_dummy and not _dummy_mode_warned:- logger.warning(- "Agent Generator running in DUMMY MODE - returning mock responses. "- "Do not use in production!"- )- _dummy_mode_warned = True- return is_dummy---def is_external_service_configured() -> bool:- """Check if external Agent Generator service is configured (or dummy mode)."""- settings = _get_settings()- return bool(settings.config.agentgenerator_host) or bool(- settings.config.agentgenerator_use_dummy- )---def _get_base_url() -> str:- """Get the base URL for the external service."""- settings = _get_settings()- host = settings.config.agentgenerator_host- port = settings.config.agentgenerator_port- return f"http://{host}:{port}"---def _get_client() -> httpx.AsyncClient:- """Get or create the HTTP client for the external service."""- global _client- if _client is None:- settings = _get_settings()- _client = httpx.AsyncClient(- base_url=_get_base_url(),- timeout=httpx.Timeout(settings.config.agentgenerator_timeout),- )- return _client---async def decompose_goal_external(- description: str,- context: str = "",- library_agents: list[dict[str, Any]] | None = None,-) -> dict[str, Any] | None:- """Call the external service to decompose a goal.-- Args:- description: Natural language goal description- context: Additional context (e.g., answers to previous questions)- library_agents: User's library agents available for sub-agent composition-- Returns:- Dict with either:- - {"type": "clarifying_questions", "questions": [...]}- - {"type": "instructions", "steps": [...]}- - {"type": "unachievable_goal", ...}- - {"type": "vague_goal", ...}- - {"type": "error", "error": "...", "error_type": "..."} on error- Or None on unexpected error- """- if _is_dummy_mode():- return await decompose_goal_dummy(description, context, library_agents)-- client = _get_client()-- if context:- description = f"{description}\n\nAdditional context from user:\n{context}"-- payload: dict[str, Any] = {"description": description}- if library_agents:- payload["library_agents"] = library_agents-- try:- response = await client.post("/api/decompose-description", json=payload)- response.raise_for_status()- data = response.json()-- if not data.get("success"):- error_msg = data.get("error", "Unknown error from Agent Generator")- error_type = data.get("error_type", "unknown")- logger.error(- f"Agent Generator decomposition failed: {error_msg} "- f"(type: {error_type})"- )- return _create_error_response(error_msg, error_type)-- # Map the response to the expected format- response_type = data.get("type")- if response_type == "instructions":- return {"type": "instructions", "steps": data.get("steps", [])}- elif response_type == "clarifying_questions":- return {- "type": "clarifying_questions",- "questions": data.get("questions", []),- }- elif response_type == "unachievable_goal":- return {- "type": "unachievable_goal",- "reason": data.get("reason"),- "suggested_goal": data.get("suggested_goal"),- }- elif response_type == "vague_goal":- return {- "type": "vague_goal",- "suggested_goal": data.get("suggested_goal"),- }- elif response_type == "error":- # Pass through error from the service- return _create_error_response(- data.get("error", "Unknown error"),- data.get("error_type", "unknown"),- )- else:- logger.error(- f"Unknown response type from external service: {response_type}"- )- return _create_error_response(- f"Unknown response type from Agent Generator: {response_type}",- "invalid_response",- )-- except httpx.HTTPStatusError as e:- error_type, error_msg = _classify_http_error(e)- logger.error(error_msg)- return _create_error_response(error_msg, error_type)- except httpx.RequestError as e:- error_type, error_msg = _classify_request_error(e)- logger.error(error_msg)- return _create_error_response(error_msg, error_type)- except Exception as e:- error_msg = f"Unexpected error calling Agent Generator: {e}"- logger.error(error_msg)- return _create_error_response(error_msg, "unexpected_error")---async def generate_agent_external(- instructions: dict[str, Any],- library_agents: list[dict[str, Any]] | None = None,-) -> dict[str, Any] | None:- """Call the external service to generate an agent from instructions.-- Args:- instructions: Structured instructions from decompose_goal- library_agents: User's library agents available for sub-agent composition-- Returns:- Agent JSON dict or error dict {"type": "error", ...} on error- """- if _is_dummy_mode():- return await generate_agent_dummy(instructions, library_agents)-- client = _get_client()-- # Build request payload- payload: dict[str, Any] = {"instructions": instructions}- if library_agents:- payload["library_agents"] = library_agents-- try:- response = await client.post("/api/generate-agent", json=payload)- response.raise_for_status()- data = response.json()-- if not data.get("success"):- error_msg = data.get("error", "Unknown error from Agent Generator")- error_type = data.get("error_type", "unknown")- logger.error(- f"Agent Generator generation failed: {error_msg} (type: {error_type})"- )- return _create_error_response(error_msg, error_type)-- return data.get("agent_json")-- except httpx.HTTPStatusError as e:- error_type, error_msg = _classify_http_error(e)- logger.error(error_msg)- return _create_error_response(error_msg, error_type)- except httpx.RequestError as e:- error_type, error_msg = _classify_request_error(e)- logger.error(error_msg)- return _create_error_response(error_msg, error_type)- except Exception as e:- error_msg = f"Unexpected error calling Agent Generator: {e}"- logger.error(error_msg)- return _create_error_response(error_msg, "unexpected_error")---async def generate_agent_patch_external(- update_request: str,- current_agent: dict[str, Any],- library_agents: list[dict[str, Any]] | None = None,-) -> dict[str, Any] | None:- """Call the external service to generate a patch for an existing agent.-- Args:- update_request: Natural language description of changes- current_agent: Current agent JSON- library_agents: User's library agents available for sub-agent composition- operation_id: Operation ID for async processing (enables Redis Streams callback)- session_id: Session ID for async processing (enables Redis Streams callback)-- Returns:- Updated agent JSON, clarifying questions dict, {"status": "accepted"} for async, or error dict on error- """- if _is_dummy_mode():- return await generate_agent_patch_dummy(- update_request, current_agent, library_agents- )-- client = _get_client()-- # Build request payload- payload: dict[str, Any] = {- "update_request": update_request,- "current_agent_json": current_agent,- }- if library_agents:- payload["library_agents"] = library_agents-- try:- response = await client.post("/api/update-agent", json=payload)- response.raise_for_status()- data = response.json()-- if not data.get("success"):- error_msg = data.get("error", "Unknown error from Agent Generator")- error_type = data.get("error_type", "unknown")- logger.error(- f"Agent Generator patch generation failed: {error_msg} "- f"(type: {error_type})"- )- return _create_error_response(error_msg, error_type)-- # Check if it's clarifying questions- if data.get("type") == "clarifying_questions":- return {- "type": "clarifying_questions",- "questions": data.get("questions", []),- }-- # Check if it's an error passed through- if data.get("type") == "error":- return _create_error_response(- data.get("error", "Unknown error"),- data.get("error_type", "unknown"),- )-- # Otherwise return the updated agent JSON- return data.get("agent_json")-- except httpx.HTTPStatusError as e:- error_type, error_msg = _classify_http_error(e)- logger.error(error_msg)- return _create_error_response(error_msg, error_type)- except httpx.RequestError as e:- error_type, error_msg = _classify_request_error(e)- logger.error(error_msg)- return _create_error_response(error_msg, error_type)- except Exception as e:- error_msg = f"Unexpected error calling Agent Generator: {e}"- logger.error(error_msg)- return _create_error_response(error_msg, "unexpected_error")---async def customize_template_external(- template_agent: dict[str, Any],- modification_request: str,- context: str = "",-) -> dict[str, Any] | None:- """Call the external service to customize a template/marketplace agent.-- Args:- template_agent: The template agent JSON to customize- modification_request: Natural language description of customizations- context: Additional context (e.g., answers to previous questions)- operation_id: Operation ID for async processing (enables Redis Streams callback)- session_id: Session ID for async processing (enables Redis Streams callback)-- Returns:- Customized agent JSON, clarifying questions dict, or error dict on error- """- if _is_dummy_mode():- return await customize_template_dummy(- template_agent, modification_request, context- )-- client = _get_client()-- request = modification_request- if context:- request = f"{modification_request}\n\nAdditional context from user:\n{context}"-- payload: dict[str, Any] = {- "template_agent_json": template_agent,- "modification_request": request,- }-- try:- response = await client.post("/api/template-modification", json=payload)- response.raise_for_status()- data = response.json()-- if not data.get("success"):- error_msg = data.get("error", "Unknown error from Agent Generator")- error_type = data.get("error_type", "unknown")- logger.error(- f"Agent Generator template customization failed: {error_msg} "- f"(type: {error_type})"- )- return _create_error_response(error_msg, error_type)-- # Check if it's clarifying questions- if data.get("type") == "clarifying_questions":- return {- "type": "clarifying_questions",- "questions": data.get("questions", []),- }-- # Check if it's an error passed through- if data.get("type") == "error":- return _create_error_response(- data.get("error", "Unknown error"),- data.get("error_type", "unknown"),- )-- # Otherwise return the customized agent JSON- return data.get("agent_json")-- except httpx.HTTPStatusError as e:- error_type, error_msg = _classify_http_error(e)- logger.error(error_msg)- return _create_error_response(error_msg, error_type)- except httpx.RequestError as e:- error_type, error_msg = _classify_request_error(e)- logger.error(error_msg)- return _create_error_response(error_msg, error_type)- except Exception as e:- error_msg = f"Unexpected error calling Agent Generator: {e}"- logger.error(error_msg)- return _create_error_response(error_msg, "unexpected_error")---async def get_blocks_external() -> list[dict[str, Any]] | None:- """Get available blocks from the external service.-- Returns:- List of block info dicts or None on error- """- if _is_dummy_mode():- return await get_blocks_dummy()-- client = _get_client()-- try:- response = await client.get("/api/blocks")- response.raise_for_status()- data = response.json()-- if not data.get("success"):- logger.error("External service returned error getting blocks")- return None-- return data.get("blocks", [])-- except httpx.HTTPStatusError as e:- logger.error(f"HTTP error getting blocks from external service: {e}")- return None- except httpx.RequestError as e:- logger.error(f"Request error getting blocks from external service: {e}")- return None- except Exception as e:- logger.error(f"Unexpected error getting blocks from external service: {e}")- return None---async def health_check() -> bool:- """Check if the external service is healthy.-- Returns:- True if healthy, False otherwise- """- if not is_external_service_configured():- return False-- if _is_dummy_mode():- return await health_check_dummy()-- client = _get_client()-- try:- response = await client.get("/health")- response.raise_for_status()- data = response.json()- return data.get("status") == "healthy" and data.get("blocks_loaded", False)- except Exception as e:- logger.warning(f"External agent generator health check failed: {e}")- return False---async def close_client() -> None:- """Close the HTTP client."""- global _client- if _client is not None:- await _client.aclose()- _client = Nonediff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validation.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validation.pynew file mode 100644index 0000000000..7c44e0db13--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validation.py@@ -0,0 +1,17 @@+"""Agent generation validation — re-exports from split modules.++This module was split into:+- helpers.py: get_blocks_as_dicts, block cache+- fixer.py: AgentFixer class+- validator.py: AgentValidator class+"""++from .fixer import AgentFixer+from .helpers import get_blocks_as_dicts+from .validator import AgentValidator++__all__ = [+ "AgentFixer",+ "AgentValidator",+ "get_blocks_as_dicts",+]diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.pynew file mode 100644index 0000000000..d27aa814fc--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.py@@ -0,0 +1,939 @@+"""AgentValidator — validates agent JSON graphs for correctness."""++import json+import logging+import re+from typing import Any++from .helpers import (+ AGENT_EXECUTOR_BLOCK_ID,+ AGENT_INPUT_BLOCK_ID,+ AGENT_OUTPUT_BLOCK_ID,+ MCP_TOOL_BLOCK_ID,+ AgentDict,+ are_types_compatible,+ get_defined_property_type,+)++logger = logging.getLogger(__name__)+++class AgentValidator:+ """+ A comprehensive validator for AutoGPT agents that provides detailed error+ reporting for LLM-based fixes.+ """++ def __init__(self):+ self.errors: list[str] = []++ def add_error(self, error_message: str) -> None:+ """Add an error message to the validation errors list."""+ self.errors.append(error_message)++ def _values_equal(self, val1: Any, val2: Any) -> bool:+ """Compare two values, handling complex types like dicts and lists."""+ if type(val1) is not type(val2):+ return False+ if isinstance(val1, dict):+ return json.dumps(val1, sort_keys=True) == json.dumps(val2, sort_keys=True)+ if isinstance(val1, list):+ return json.dumps(val1, sort_keys=True) == json.dumps(val2, sort_keys=True)+ return val1 == val2++ def validate_block_existence(+ self, agent: AgentDict, blocks: list[dict[str, Any]]+ ) -> bool:+ """+ Validate that all block IDs used in the agent actually exist in the+ blocks list. Returns True if all block IDs exist, False otherwise.+ """+ valid = True++ # Create a set of all valid block IDs for fast lookup+ valid_block_ids = {block.get("id") for block in blocks if block.get("id")}++ # Check each node's block_id+ for node in agent.get("nodes", []):+ block_id = node.get("block_id")+ node_id = node.get("id")++ if not block_id:+ self.add_error(+ f"Node '{node_id}' is missing a 'block_id' field. "+ f"Every node must reference a valid block."+ )+ valid = False+ continue++ if block_id not in valid_block_ids:+ self.add_error(+ f"Node '{node_id}' references block_id '{block_id}' "+ f"which does not exist in the available blocks. "+ f"This block may have been deprecated, removed, or "+ f"the ID is incorrect. Please use a valid block from "+ f"the blocks library."+ )+ valid = False++ return valid++ def validate_link_node_references(self, agent: AgentDict) -> bool:+ """+ Validate that all node IDs referenced in links actually exist in the+ agent's nodes. Returns True if all link references are valid, False+ otherwise.+ """+ valid = True++ # Create a set of all valid node IDs for fast lookup+ valid_node_ids = {+ node.get("id") for node in agent.get("nodes", []) if node.get("id")+ }++ # Check each link's source_id and sink_id+ for link in agent.get("links", []):+ link_id = link.get("id", "Unknown")+ source_id = link.get("source_id")+ sink_id = link.get("sink_id")+ source_name = link.get("source_name", "")+ sink_name = link.get("sink_name", "")++ # Check source_id+ if not source_id:+ self.add_error(+ f"Link '{link_id}' is missing a 'source_id' field. "+ f"Every link must reference a valid source node."+ )+ valid = False+ elif source_id not in valid_node_ids:+ self.add_error(+ f"Link '{link_id}' references source_id '{source_id}' "+ f"which does not exist in the agent's nodes. The link "+ f"from '{source_name}' cannot be established because "+ f"the source node is missing."+ )+ valid = False++ # Check sink_id+ if not sink_id:+ self.add_error(+ f"Link '{link_id}' is missing a 'sink_id' field. "+ f"Every link must reference a valid sink (destination) "+ f"node."+ )+ valid = False+ elif sink_id not in valid_node_ids:+ self.add_error(+ f"Link '{link_id}' references sink_id '{sink_id}' "+ f"which does not exist in the agent's nodes. The link "+ f"to '{sink_name}' cannot be established because the "+ f"destination node is missing."+ )+ valid = False++ return valid++ def validate_required_inputs(+ self, agent: AgentDict, blocks: list[dict[str, Any]]+ ) -> bool:+ """+ Validate that all required inputs are provided for each node.+ Returns True if all required inputs are satisfied, False otherwise.+ """+ valid = True++ block_lookup = {b.get("id", ""): b for b in blocks}++ for node in agent.get("nodes", []):+ block_id = node.get("block_id")+ block = block_lookup.get(block_id)++ if not block:+ continue++ required_inputs = block.get("inputSchema", {}).get("required", [])+ input_defaults = node.get("input_default", {})+ node_id = node.get("id")++ linked_inputs = set(+ link.get("sink_name")+ for link in agent.get("links", [])+ if link.get("sink_id") == node_id and link.get("sink_name")+ )++ for req_input in required_inputs:+ if (+ req_input not in input_defaults+ and req_input not in linked_inputs+ and req_input != "credentials"+ ):+ block_name = block.get("name", "Unknown Block")+ self.add_error(+ f"Node '{node_id}' (block '{block_name}' - "+ f"{block_id}) is missing required input "+ f"'{req_input}'. This input must be either "+ f"provided as a default value in the node's "+ f"'input_default' field or connected via a link "+ f"from another node's output."+ )+ valid = False++ return valid++ def validate_data_type_compatibility(+ self, agent: AgentDict, blocks: list[dict[str, Any]]+ ) -> bool:+ """+ Validate that linked data types are compatible between source and sink.+ Returns True if all data types are compatible, False otherwise.+ """+ valid = True+ node_lookup = {node.get("id", ""): node for node in agent.get("nodes", [])}+ block_lookup = {block.get("id", ""): block for block in blocks}++ for link in agent.get("links", []):+ source_id = link.get("source_id")+ sink_id = link.get("sink_id")+ source_name = link.get("source_name")+ sink_name = link.get("sink_name")++ if not all(+ isinstance(v, str) and v+ for v in (source_id, sink_id, source_name, sink_name)+ ):+ self.add_error(+ f"Link '{link.get('id', 'Unknown')}' is missing required "+ f"fields (source_id/sink_id/source_name/sink_name)."+ )+ valid = False+ continue++ source_node = node_lookup.get(source_id, "")+ sink_node = node_lookup.get(sink_id, "")++ if not source_node or not sink_node:+ continue++ source_block = block_lookup.get(source_node.get("block_id", ""))+ sink_block = block_lookup.get(sink_node.get("block_id", ""))++ if not source_block or not sink_block:+ continue++ source_outputs = source_block.get("outputSchema", {}).get("properties", {})+ sink_inputs = sink_block.get("inputSchema", {}).get("properties", {})++ source_type = get_defined_property_type(source_outputs, source_name)+ sink_type = get_defined_property_type(sink_inputs, sink_name)++ if (+ source_type+ and sink_type+ and not are_types_compatible(source_type, sink_type)+ ):+ source_block_name = source_block.get("name", "Unknown Block")+ sink_block_name = sink_block.get("name", "Unknown Block")+ self.add_error(+ f"Data type mismatch in link '{link.get('id')}': "+ f"Source '{source_block_name}' output "+ f"'{link.get('source_name', '')}' outputs '{source_type}' "+ f"type, but sink '{sink_block_name}' input "+ f"'{link.get('sink_name', '')}' expects '{sink_type}' type. "+ f"These types must match for the connection to work "+ f"properly."+ )+ valid = False++ return valid++ def validate_nested_sink_links(+ self, agent: AgentDict, blocks: list[dict[str, Any]]+ ) -> bool:+ """+ Validate nested sink links (links with _#_ notation).+ Returns True if all nested links are valid, False otherwise.+ """+ valid = True+ block_input_schemas = {+ block.get("id", ""): block.get("inputSchema", {}).get("properties", {})+ for block in blocks+ }+ block_names = {+ block.get("id", ""): block.get("name", "Unknown Block") for block in blocks+ }+ node_lookup = {node.get("id", ""): node for node in agent.get("nodes", [])}++ for link in agent.get("links", []):+ sink_name = link.get("sink_name", "")+ sink_id = link.get("sink_id")++ if not sink_name or not sink_id:+ continue++ if "_#_" in sink_name:+ parent, child = sink_name.split("_#_", 1)++ sink_node = node_lookup.get(sink_id)+ if not sink_node:+ continue++ block_id = sink_node.get("block_id")+ input_props = block_input_schemas.get(block_id, {})++ parent_schema = input_props.get(parent)+ if not parent_schema:+ block_name = block_names.get(block_id, "Unknown Block")+ self.add_error(+ f"Invalid nested sink link '{sink_name}' for "+ f"node '{sink_id}' (block "+ f"'{block_name}' - {block_id}): Parent property "+ f"'{parent}' does not exist in the block's "+ f"input schema."+ )+ valid = False+ continue++ # Check if additionalProperties is allowed either directly+ # or via anyOf+ allows_additional_properties = parent_schema.get(+ "additionalProperties", False+ )++ # Check anyOf for additionalProperties+ if not allows_additional_properties and "anyOf" in parent_schema:+ any_of_schemas = parent_schema.get("anyOf", [])+ if isinstance(any_of_schemas, list):+ for schema_option in any_of_schemas:+ if isinstance(schema_option, dict) and schema_option.get(+ "additionalProperties"+ ):+ allows_additional_properties = True+ break++ if not allows_additional_properties:+ if not (+ isinstance(parent_schema, dict)+ and "properties" in parent_schema+ and isinstance(parent_schema["properties"], dict)+ and child in parent_schema["properties"]+ ):+ block_name = block_names.get(block_id, "Unknown Block")+ self.add_error(+ f"Invalid nested sink link '{sink_name}' "+ f"for node '{link.get('sink_id', '')}' (block "+ f"'{block_name}' - {block_id}): Child "+ f"property '{child}' does not exist in "+ f"parent '{parent}' schema. Available "+ f"properties: "+ f"{list(parent_schema.get('properties', {}).keys())}"+ )+ valid = False++ return valid++ def validate_prompt_double_curly_braces_spaces(self, agent: AgentDict) -> bool:+ """+ Validate that prompt parameters do not contain spaces in double curly+ braces.++ Checks the 'prompt' parameter in input_default of each node and reports+ errors if values within double curly braces ({{...}}) contain spaces.+ For example, {{user name}} should be {{user_name}}.++ Args:+ agent: The agent dictionary to validate++ Returns:+ True if all prompts are valid (no spaces in double curly braces),+ False otherwise+ """+ valid = True+ nodes = agent.get("nodes", [])++ for node in nodes:+ node_id = node.get("id")+ input_default = node.get("input_default", {})++ # Check if 'prompt' parameter exists+ if "prompt" not in input_default:+ continue++ prompt_text = input_default["prompt"]++ # Only process if it's a string+ if not isinstance(prompt_text, str):+ continue++ # Find all double curly brace patterns with spaces+ matches = re.finditer(r"\{\{([^}]+)\}\}", prompt_text)++ for match in matches:+ content = match.group(1)+ if " " in content:+ start_pos = match.start()+ snippet_start = max(0, start_pos - 30)+ snippet_end = min(len(prompt_text), match.end() + 30)+ snippet = prompt_text[snippet_start:snippet_end]++ self.add_error(+ f"Node '{node_id}' has spaces in double curly "+ f"braces in prompt parameter: "+ f"'{{{{{content}}}}}' should be "+ f"'{{{{{content.replace(' ', '_')}}}}}'. "+ f"Context: ...{snippet}..."+ )+ valid = False++ return valid++ def validate_source_output_existence(+ self, agent: AgentDict, blocks: list[dict[str, Any]]+ ) -> bool:+ """+ Validate that all source_names in links exist in the corresponding+ block's output schema.++ Checks that for each link, the source_name field references a valid+ output property in the source block's outputSchema. Also handles nested+ outputs with _#_ notation.++ Args:+ agent: The agent dictionary to validate+ blocks: List of available blocks with their schemas++ Returns:+ True if all source output fields exist, False otherwise+ """+ valid = True++ # Create lookup dictionaries for efficiency+ block_output_schemas = {+ block.get("id", ""): block.get("outputSchema", {}).get("properties", {})+ for block in blocks+ }+ block_names = {+ block.get("id", ""): block.get("name", "Unknown Block") for block in blocks+ }+ node_lookup = {node.get("id", ""): node for node in agent.get("nodes", [])}++ for link in agent.get("links", []):+ source_id = link.get("source_id")+ source_name = link.get("source_name", "")+ link_id = link.get("id", "Unknown")++ if not source_name:+ self.add_error(+ f"Link '{link_id}' is missing 'source_name'. "+ f"Every link must specify which output field to read from."+ )+ valid = False+ continue++ source_node = node_lookup.get(source_id)+ if not source_node:+ # This error is already caught by+ # validate_link_node_references+ continue++ block_id = source_node.get("block_id")+ block_name = block_names.get(block_id, "Unknown Block")++ # Special handling for AgentExecutorBlock - use dynamic+ # output_schema from input_default+ if block_id == AGENT_EXECUTOR_BLOCK_ID:+ input_default = source_node.get("input_default", {})+ dynamic_output_schema = input_default.get("output_schema", {})+ if not isinstance(dynamic_output_schema, dict):+ dynamic_output_schema = {}+ output_props = dynamic_output_schema.get("properties", {})+ if not isinstance(output_props, dict):+ output_props = {}+ else:+ output_props = block_output_schemas.get(block_id, {})++ # Handle nested source names (with _#_ notation)+ if "_#_" in source_name:+ parent, child = source_name.split("_#_", 1)++ parent_schema = output_props.get(parent)+ if not parent_schema:+ self.add_error(+ f"Invalid source output field '{source_name}' "+ f"in link '{link_id}' from node '{source_id}' "+ f"(block '{block_name}' - {block_id}): Parent "+ f"property '{parent}' does not exist in the "+ f"block's output schema."+ )+ valid = False+ continue++ # Check if additionalProperties is allowed either directly+ # or via anyOf+ allows_additional_properties = parent_schema.get(+ "additionalProperties", False+ )+ if not allows_additional_properties and "anyOf" in parent_schema:+ any_of_schemas = parent_schema.get("anyOf", [])+ if isinstance(any_of_schemas, list):+ for schema_option in any_of_schemas:+ if isinstance(schema_option, dict) and schema_option.get(+ "additionalProperties"+ ):+ allows_additional_properties = True+ break+ # Also allow when items have+ # additionalProperties (array of objects)+ if (+ isinstance(schema_option, dict)+ and "items" in schema_option+ ):+ items_schema = schema_option.get("items")+ if isinstance(items_schema, dict) and items_schema.get(+ "additionalProperties"+ ):+ allows_additional_properties = True+ break++ # Only require child in properties when+ # additionalProperties is not allowed+ if not allows_additional_properties:+ if not (+ isinstance(parent_schema, dict)+ and "properties" in parent_schema+ and isinstance(parent_schema["properties"], dict)+ and child in parent_schema["properties"]+ ):+ available_props = (+ list(parent_schema.get("properties", {}).keys())+ if isinstance(parent_schema, dict)+ else []+ )+ self.add_error(+ f"Invalid nested source output field "+ f"'{source_name}' in link '{link_id}' from "+ f"node '{source_id}' (block "+ f"'{block_name}' - {block_id}): Child "+ f"property '{child}' does not exist in "+ f"parent '{parent}' output schema. "+ f"Available properties: {available_props}"+ )+ valid = False+ else:+ # Check simple (non-nested) source name+ if source_name not in output_props:+ available_outputs = list(output_props.keys())+ self.add_error(+ f"Invalid source output field '{source_name}' "+ f"in link '{link_id}' from node '{source_id}' "+ f"(block '{block_name}' - {block_id}): Output "+ f"property '{source_name}' does not exist in "+ f"the block's output schema. Available outputs: "+ f"{available_outputs}"+ )+ valid = False++ return valid++ def validate_io_blocks(self, agent: AgentDict) -> bool:+ """+ Validate that the agent has at least one AgentInputBlock and one+ AgentOutputBlock. These blocks define the agent's interface.++ Returns True if both are present, False otherwise.+ """+ valid = True+ block_ids = {node.get("block_id") for node in agent.get("nodes", [])}++ if AGENT_INPUT_BLOCK_ID not in block_ids:+ self.add_error(+ f"Agent is missing an AgentInputBlock (block_id: "+ f"'{AGENT_INPUT_BLOCK_ID}'). Every agent must have at "+ f"least one AgentInputBlock to define user-facing inputs. "+ f"Add a node with block_id '{AGENT_INPUT_BLOCK_ID}' and "+ f"set input_default with 'name' and optionally 'title'."+ )+ valid = False++ if AGENT_OUTPUT_BLOCK_ID not in block_ids:+ self.add_error(+ f"Agent is missing an AgentOutputBlock (block_id: "+ f"'{AGENT_OUTPUT_BLOCK_ID}'). Every agent must have at "+ f"least one AgentOutputBlock to define user-facing outputs. "+ f"Add a node with block_id '{AGENT_OUTPUT_BLOCK_ID}' and "+ f"set input_default with 'name', then link 'value' from "+ f"another block's output."+ )+ valid = False++ return valid++ def validate_agent_executor_blocks(+ self,+ agent: AgentDict,+ library_agents: list[dict[str, Any]] | None = None,+ ) -> bool:+ """+ Validate AgentExecutorBlock nodes have required fields and valid+ references.++ Checks that AgentExecutorBlock nodes:+ 1. Have a valid graph_id in input_default (required)+ 2. If graph_id matches a known library agent, validates version+ consistency+ 3. Sub-agent required inputs are connected via links (not hardcoded)++ Note: Unknown graph_ids are not treated as errors - they could be valid+ direct references to agents by their actual ID (not via library_agents).+ This is consistent with fix_agent_executor_blocks() behavior.++ Args:+ agent: The agent dictionary to validate+ library_agents: List of available library agents (for version+ validation)++ Returns:+ True if all AgentExecutorBlock nodes are valid, False otherwise+ """+ valid = True+ nodes = agent.get("nodes", [])+ links = agent.get("links", [])++ # Create lookup for library agents+ library_agent_lookup: dict[str, dict[str, Any]] = {}+ if library_agents:+ library_agent_lookup = {la.get("graph_id", ""): la for la in library_agents}++ for node in nodes:+ if node.get("block_id") != AGENT_EXECUTOR_BLOCK_ID:+ continue++ node_id = node.get("id")+ input_default = node.get("input_default", {})++ # Check for required graph_id+ graph_id = input_default.get("graph_id")+ if not graph_id:+ self.add_error(+ f"AgentExecutorBlock node '{node_id}' is missing "+ f"required 'graph_id' in input_default. This field "+ f"must reference the ID of the sub-agent to execute."+ )+ valid = False+ continue++ # If graph_id is not in library_agent_lookup, skip validation+ if graph_id not in library_agent_lookup:+ continue++ # Validate version consistency for known library agents+ library_agent = library_agent_lookup[graph_id]+ expected_version = library_agent.get("graph_version")+ current_version = input_default.get("graph_version")+ if (+ current_version+ and expected_version+ and current_version != expected_version+ ):+ self.add_error(+ f"AgentExecutorBlock node '{node_id}' has mismatched "+ f"graph_version: got {current_version}, expected "+ f"{expected_version} for library agent "+ f"'{library_agent.get('name')}'"+ )+ valid = False++ # Validate sub-agent inputs are properly linked (not hardcoded)+ sub_agent_input_schema = library_agent.get("input_schema", {})+ if not isinstance(sub_agent_input_schema, dict):+ sub_agent_input_schema = {}+ sub_agent_required_inputs = sub_agent_input_schema.get("required", [])+ sub_agent_properties = sub_agent_input_schema.get("properties", {})++ # Get all linked inputs to this node+ linked_sub_agent_inputs: set[str] = set()+ for link in links:+ if link.get("sink_id") == node_id:+ sink_name = link.get("sink_name", "")+ if sink_name in sub_agent_properties:+ linked_sub_agent_inputs.add(sink_name)++ # Check for hardcoded inputs that should be linked+ hardcoded_inputs = input_default.get("inputs", {})+ input_schema = input_default.get("input_schema", {})+ schema_properties = (+ input_schema.get("properties", {})+ if isinstance(input_schema, dict)+ else {}+ )+ if isinstance(hardcoded_inputs, dict) and hardcoded_inputs:+ for input_name, value in hardcoded_inputs.items():+ if input_name not in sub_agent_properties:+ continue+ if value is None:+ continue+ # Skip if this input is already linked+ if input_name in linked_sub_agent_inputs:+ continue+ prop_schema = schema_properties.get(input_name, {})+ schema_default = (+ prop_schema.get("default")+ if isinstance(prop_schema, dict)+ else None+ )+ if schema_default is not None and self._values_equal(+ value, schema_default+ ):+ continue+ # This is a non-default hardcoded value without a link+ self.add_error(+ f"AgentExecutorBlock node '{node_id}' has "+ f"hardcoded input '{input_name}'. Sub-agent "+ f"inputs should be connected via links using "+ f"'{input_name}' as sink_name, not hardcoded "+ f"in input_default.inputs. Create a link from "+ f"the appropriate source node."+ )+ valid = False++ # Check for missing required sub-agent inputs.+ # An input is satisfied if it is linked OR has an allowed+ # hardcoded value (i.e. equals the schema default — the+ # previous check already flags non-default hardcoded values).+ hardcoded_inputs_dict = (+ hardcoded_inputs if isinstance(hardcoded_inputs, dict) else {}+ )+ for req_input in sub_agent_required_inputs:+ if req_input in linked_sub_agent_inputs:+ continue+ # Check if fixer populated it with a schema default value+ if req_input in hardcoded_inputs_dict:+ prop_schema = schema_properties.get(req_input, {})+ schema_default = (+ prop_schema.get("default")+ if isinstance(prop_schema, dict)+ else None+ )+ if schema_default is not None and self._values_equal(+ hardcoded_inputs_dict[req_input], schema_default+ ):+ continue+ self.add_error(+ f"AgentExecutorBlock node '{node_id}' is "+ f"missing required sub-agent input "+ f"'{req_input}'. Create a link to this node "+ f"using sink_name '{req_input}' to connect "+ f"the input."+ )+ valid = False++ return valid++ def validate_agent_executor_block_schemas(+ self,+ agent: AgentDict,+ ) -> bool:+ """+ Validate that AgentExecutorBlock nodes have valid input_schema and+ output_schema.++ This validation runs regardless of library_agents availability and+ ensures that the schemas are properly populated to prevent frontend+ crashes.++ Args:+ agent: The agent dictionary to validate++ Returns:+ True if all AgentExecutorBlock nodes have valid schemas, False+ otherwise+ """+ valid = True+ nodes = agent.get("nodes", [])++ for node in nodes:+ if node.get("block_id") != AGENT_EXECUTOR_BLOCK_ID:+ continue++ node_id = node.get("id")+ input_default = node.get("input_default", {})+ customized_name = (node.get("metadata") or {}).get(+ "customized_name", "Unknown"+ )++ # Check input_schema+ input_schema = input_default.get("input_schema")+ if input_schema is None or not isinstance(input_schema, dict):+ self.add_error(+ f"AgentExecutorBlock node '{node_id}' "+ f"({customized_name}) has missing or invalid "+ f"input_schema. The input_schema must be a valid "+ f"JSON Schema object with 'properties' and "+ f"'required' fields."+ )+ valid = False+ elif not input_schema.get("properties") and not input_schema.get("type"):+ # Empty schema like {} is invalid+ self.add_error(+ f"AgentExecutorBlock node '{node_id}' "+ f"({customized_name}) has empty input_schema. The "+ f"input_schema must define the sub-agent's expected "+ f"inputs. This usually indicates the sub-agent "+ f"reference is incomplete or the library agent was "+ f"not properly passed."+ )+ valid = False++ # Check output_schema+ output_schema = input_default.get("output_schema")+ if output_schema is None or not isinstance(output_schema, dict):+ self.add_error(+ f"AgentExecutorBlock node '{node_id}' "+ f"({customized_name}) has missing or invalid "+ f"output_schema. The output_schema must be a valid "+ f"JSON Schema object defining the sub-agent's "+ f"outputs."+ )+ valid = False+ elif not output_schema.get("properties") and not output_schema.get("type"):+ # Empty schema like {} is invalid+ self.add_error(+ f"AgentExecutorBlock node '{node_id}' "+ f"({customized_name}) has empty output_schema. "+ f"The output_schema must define the sub-agent's "+ f"expected outputs. This usually indicates the "+ f"sub-agent reference is incomplete or the library "+ f"agent was not properly passed."+ )+ valid = False++ return valid++ def validate_mcp_tool_blocks(self, agent: AgentDict) -> bool:+ """Validate that MCPToolBlock nodes have required fields.++ Checks that each MCPToolBlock node has:+ 1. A non-empty `server_url` in input_default+ 2. A non-empty `selected_tool` in input_default++ Returns True if all MCPToolBlock nodes are valid, False otherwise.+ """+ valid = True+ nodes = agent.get("nodes", [])++ for node in nodes:+ if node.get("block_id") != MCP_TOOL_BLOCK_ID:+ continue++ node_id = node.get("id", "unknown")+ input_default = node.get("input_default", {})+ customized_name = (node.get("metadata") or {}).get(+ "customized_name", node_id+ )++ server_url = input_default.get("server_url")+ if not server_url:+ self.add_error(+ f"MCPToolBlock node '{customized_name}' ({node_id}) is "+ f"missing required 'server_url' in input_default. "+ f"Set this to the MCP server URL "+ f"(e.g. 'https://mcp.example.com/sse')."+ )+ valid = False++ selected_tool = input_default.get("selected_tool")+ if not selected_tool:+ self.add_error(+ f"MCPToolBlock node '{customized_name}' ({node_id}) is "+ f"missing required 'selected_tool' in input_default. "+ f"Set this to the name of the MCP tool to execute."+ )+ valid = False++ return valid++ def validate(+ self,+ agent: AgentDict,+ blocks: list[dict[str, Any]],+ library_agents: list[dict[str, Any]] | None = None,+ ) -> tuple[bool, str | None]:+ """+ Comprehensive validation of an agent against available blocks.++ Returns:+ Tuple[bool, Optional[str]]: (is_valid, error_message)+ - is_valid: True if agent passes all validations, False otherwise+ - error_message: Detailed error message if validation fails, None+ if successful+ """+ logger.info("Validating agent...")+ self.errors = []++ checks = [+ (+ "Block existence",+ self.validate_block_existence(agent, blocks),+ ),+ (+ "Link node references",+ self.validate_link_node_references(agent),+ ),+ (+ "Required inputs",+ self.validate_required_inputs(agent, blocks),+ ),+ (+ "Data type compatibility",+ self.validate_data_type_compatibility(agent, blocks),+ ),+ (+ "Nested sink links",+ self.validate_nested_sink_links(agent, blocks),+ ),+ (+ "Source output existence",+ self.validate_source_output_existence(agent, blocks),+ ),+ (+ "Prompt double curly braces spaces",+ self.validate_prompt_double_curly_braces_spaces(agent),+ ),+ (+ "IO blocks",+ self.validate_io_blocks(agent),+ ),+ # Always validate AgentExecutorBlock schemas to prevent+ # frontend crashes+ (+ "AgentExecutorBlock schemas",+ self.validate_agent_executor_block_schemas(agent),+ ),+ (+ "MCP tool blocks",+ self.validate_mcp_tool_blocks(agent),+ ),+ ]++ # Add AgentExecutorBlock detailed validation if library_agents+ # provided+ if library_agents:+ checks.append(+ (+ "AgentExecutorBlock references",+ self.validate_agent_executor_blocks(agent, library_agents),+ )+ )++ all_passed = all(check[1] for check in checks)++ if all_passed:+ logger.info("Agent validation successful.")+ return True, None+ else:+ error_message = "Agent validation failed with the following errors:\n\n"+ for i, error in enumerate(self.errors, 1):+ error_message += f"{i}. {error}\n"++ logger.error(f"Agent validation failed: {error_message}")+ return False, error_messagediff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.pynew file mode 100644index 0000000000..1ce54aa7f4--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.py@@ -0,0 +1,710 @@+"""Unit tests for AgentValidator."""++from .helpers import (+ AGENT_EXECUTOR_BLOCK_ID,+ AGENT_INPUT_BLOCK_ID,+ AGENT_OUTPUT_BLOCK_ID,+ MCP_TOOL_BLOCK_ID,+ generate_uuid,+)+from .validator import AgentValidator+++def _make_agent(+ nodes: list | None = None,+ links: list | None = None,+ agent_id: str | None = None,+) -> dict:+ """Build a minimal agent dict for testing."""+ return {+ "id": agent_id or generate_uuid(),+ "name": "Test Agent",+ "nodes": nodes or [],+ "links": links or [],+ }+++def _make_node(+ node_id: str | None = None,+ block_id: str = "block-1",+ input_default: dict | None = None,+ position: tuple[int, int] = (0, 0),+) -> dict:+ return {+ "id": node_id or generate_uuid(),+ "block_id": block_id,+ "input_default": input_default or {},+ "metadata": {"position": {"x": position[0], "y": position[1]}},+ }+++def _make_link(+ link_id: str | None = None,+ source_id: str = "",+ source_name: str = "output",+ sink_id: str = "",+ sink_name: str = "input",+) -> dict:+ return {+ "id": link_id or generate_uuid(),+ "source_id": source_id,+ "source_name": source_name,+ "sink_id": sink_id,+ "sink_name": sink_name,+ }+++def _make_block(+ block_id: str = "block-1",+ name: str = "TestBlock",+ input_schema: dict | None = None,+ output_schema: dict | None = None,+ categories: list | None = None,+ static_output: bool = False,+) -> dict:+ return {+ "id": block_id,+ "name": name,+ "inputSchema": input_schema or {"properties": {}, "required": []},+ "outputSchema": output_schema or {"properties": {}},+ "categories": categories or [],+ "staticOutput": static_output,+ }+++# ============================================================================+# validate_block_existence+# ============================================================================+++class TestValidateBlockExistence:+ def test_valid_blocks_pass(self):+ v = AgentValidator()+ node = _make_node(block_id="b1")+ block = _make_block(block_id="b1")+ agent = _make_agent(nodes=[node])++ assert v.validate_block_existence(agent, [block]) is True+ assert v.errors == []++ def test_missing_block_fails(self):+ v = AgentValidator()+ node = _make_node(block_id="nonexistent")+ agent = _make_agent(nodes=[node])++ assert v.validate_block_existence(agent, []) is False+ assert len(v.errors) == 1+ assert "does not exist" in v.errors[0]++ def test_missing_block_id_field(self):+ v = AgentValidator()+ node = {"id": "n1", "input_default": {}, "metadata": {}}+ agent = _make_agent(nodes=[node])++ assert v.validate_block_existence(agent, []) is False+ assert "missing a 'block_id'" in v.errors[0]+++# ============================================================================+# validate_link_node_references+# ============================================================================+++class TestValidateLinkNodeReferences:+ def test_valid_references_pass(self):+ v = AgentValidator()+ n1 = _make_node(node_id="n1")+ n2 = _make_node(node_id="n2")+ link = _make_link(source_id="n1", sink_id="n2")+ agent = _make_agent(nodes=[n1, n2], links=[link])++ assert v.validate_link_node_references(agent) is True+ assert v.errors == []++ def test_invalid_source_fails(self):+ v = AgentValidator()+ n1 = _make_node(node_id="n1")+ link = _make_link(source_id="missing", sink_id="n1")+ agent = _make_agent(nodes=[n1], links=[link])++ assert v.validate_link_node_references(agent) is False+ assert any("source_id" in e for e in v.errors)++ def test_invalid_sink_fails(self):+ v = AgentValidator()+ n1 = _make_node(node_id="n1")+ link = _make_link(source_id="n1", sink_id="missing")+ agent = _make_agent(nodes=[n1], links=[link])++ assert v.validate_link_node_references(agent) is False+ assert any("sink_id" in e for e in v.errors)+++# ============================================================================+# validate_required_inputs+# ============================================================================+++class TestValidateRequiredInputs:+ def test_satisfied_by_default_passes(self):+ v = AgentValidator()+ block = _make_block(+ block_id="b1",+ input_schema={+ "properties": {"url": {"type": "string"}},+ "required": ["url"],+ },+ )+ node = _make_node(block_id="b1", input_default={"url": "http://example.com"})+ agent = _make_agent(nodes=[node])++ assert v.validate_required_inputs(agent, [block]) is True+ assert v.errors == []++ def test_satisfied_by_link_passes(self):+ v = AgentValidator()+ block = _make_block(+ block_id="b1",+ input_schema={+ "properties": {"url": {"type": "string"}},+ "required": ["url"],+ },+ )+ node = _make_node(node_id="n1", block_id="b1")+ link = _make_link(source_id="n2", sink_id="n1", sink_name="url")+ agent = _make_agent(nodes=[node], links=[link])++ assert v.validate_required_inputs(agent, [block]) is True++ def test_missing_required_input_fails(self):+ v = AgentValidator()+ block = _make_block(+ block_id="b1",+ input_schema={+ "properties": {"url": {"type": "string"}},+ "required": ["url"],+ },+ )+ node = _make_node(block_id="b1", input_default={})+ agent = _make_agent(nodes=[node])++ assert v.validate_required_inputs(agent, [block]) is False+ assert any("missing required input" in e for e in v.errors)++ def test_credentials_always_allowed_missing(self):+ v = AgentValidator()+ block = _make_block(+ block_id="b1",+ input_schema={+ "properties": {"credentials": {"type": "object"}},+ "required": ["credentials"],+ },+ )+ node = _make_node(block_id="b1", input_default={})+ agent = _make_agent(nodes=[node])++ assert v.validate_required_inputs(agent, [block]) is True+++# ============================================================================+# validate_data_type_compatibility+# ============================================================================+++class TestValidateDataTypeCompatibility:+ def test_matching_types_pass(self):+ v = AgentValidator()+ src_block = _make_block(+ block_id="src-b",+ output_schema={"properties": {"out": {"type": "string"}}},+ )+ sink_block = _make_block(+ block_id="sink-b",+ input_schema={"properties": {"inp": {"type": "string"}}, "required": []},+ )+ src_node = _make_node(node_id="n1", block_id="src-b")+ sink_node = _make_node(node_id="n2", block_id="sink-b")+ link = _make_link(+ source_id="n1", source_name="out", sink_id="n2", sink_name="inp"+ )+ agent = _make_agent(nodes=[src_node, sink_node], links=[link])++ assert (+ v.validate_data_type_compatibility(agent, [src_block, sink_block]) is True+ )++ def test_int_number_compatible(self):+ v = AgentValidator()+ src_block = _make_block(+ block_id="src-b",+ output_schema={"properties": {"out": {"type": "integer"}}},+ )+ sink_block = _make_block(+ block_id="sink-b",+ input_schema={"properties": {"inp": {"type": "number"}}, "required": []},+ )+ src_node = _make_node(node_id="n1", block_id="src-b")+ sink_node = _make_node(node_id="n2", block_id="sink-b")+ link = _make_link(+ source_id="n1", source_name="out", sink_id="n2", sink_name="inp"+ )+ agent = _make_agent(nodes=[src_node, sink_node], links=[link])++ assert (+ v.validate_data_type_compatibility(agent, [src_block, sink_block]) is True+ )++ def test_mismatched_types_fail(self):+ v = AgentValidator()+ src_block = _make_block(+ block_id="src-b",+ output_schema={"properties": {"out": {"type": "string"}}},+ )+ sink_block = _make_block(+ block_id="sink-b",+ input_schema={"properties": {"inp": {"type": "integer"}}, "required": []},+ )+ src_node = _make_node(node_id="n1", block_id="src-b")+ sink_node = _make_node(node_id="n2", block_id="sink-b")+ link = _make_link(+ source_id="n1", source_name="out", sink_id="n2", sink_name="inp"+ )+ agent = _make_agent(nodes=[src_node, sink_node], links=[link])++ assert (+ v.validate_data_type_compatibility(agent, [src_block, sink_block]) is False+ )+ assert any("mismatch" in e.lower() for e in v.errors)+++# ============================================================================+# validate_source_output_existence+# ============================================================================+++class TestValidateSourceOutputExistence:+ def test_valid_source_output_passes(self):+ v = AgentValidator()+ block = _make_block(+ block_id="b1",+ output_schema={"properties": {"result": {"type": "string"}}},+ )+ node = _make_node(node_id="n1", block_id="b1")+ link = _make_link(source_id="n1", source_name="result", sink_id="n2")+ agent = _make_agent(nodes=[node], links=[link])++ assert v.validate_source_output_existence(agent, [block]) is True++ def test_invalid_source_output_fails(self):+ v = AgentValidator()+ block = _make_block(+ block_id="b1",+ output_schema={"properties": {"result": {"type": "string"}}},+ )+ node = _make_node(node_id="n1", block_id="b1")+ link = _make_link(source_id="n1", source_name="nonexistent", sink_id="n2")+ agent = _make_agent(nodes=[node], links=[link])++ assert v.validate_source_output_existence(agent, [block]) is False+ assert any("does not exist" in e for e in v.errors)+++# ============================================================================+# validate_prompt_double_curly_braces_spaces+# ============================================================================+++class TestValidatePromptDoubleCurlyBracesSpaces:+ def test_no_spaces_passes(self):+ v = AgentValidator()+ node = _make_node(input_default={"prompt": "Hello {{name}}!"})+ agent = _make_agent(nodes=[node])++ assert v.validate_prompt_double_curly_braces_spaces(agent) is True++ def test_spaces_in_braces_fails(self):+ v = AgentValidator()+ node = _make_node(input_default={"prompt": "Hello {{user name}}!"})+ agent = _make_agent(nodes=[node])++ assert v.validate_prompt_double_curly_braces_spaces(agent) is False+ assert any("spaces" in e for e in v.errors)+++# ============================================================================+# validate_nested_sink_links+# ============================================================================+++class TestValidateNestedSinkLinks:+ def test_valid_nested_link_passes(self):+ v = AgentValidator()+ block = _make_block(+ block_id="b1",+ input_schema={+ "properties": {+ "config": {+ "type": "object",+ "properties": {"key": {"type": "string"}},+ }+ },+ "required": [],+ },+ )+ node = _make_node(node_id="n1", block_id="b1")+ link = _make_link(sink_id="n1", sink_name="config_#_key", source_id="n2")+ agent = _make_agent(nodes=[node], links=[link])++ assert v.validate_nested_sink_links(agent, [block]) is True++ def test_invalid_parent_fails(self):+ v = AgentValidator()+ block = _make_block(block_id="b1")+ node = _make_node(node_id="n1", block_id="b1")+ link = _make_link(sink_id="n1", sink_name="nonexistent_#_key", source_id="n2")+ agent = _make_agent(nodes=[node], links=[link])++ assert v.validate_nested_sink_links(agent, [block]) is False+ assert any("does not exist" in e for e in v.errors)+++# ============================================================================+# validate_agent_executor_block_schemas+# ============================================================================+++class TestValidateAgentExecutorBlockSchemas:+ def test_valid_schemas_pass(self):+ v = AgentValidator()+ node = _make_node(+ block_id=AGENT_EXECUTOR_BLOCK_ID,+ input_default={+ "graph_id": generate_uuid(),+ "input_schema": {"properties": {"q": {"type": "string"}}},+ "output_schema": {"properties": {"result": {"type": "string"}}},+ },+ )+ agent = _make_agent(nodes=[node])++ assert v.validate_agent_executor_block_schemas(agent) is True+ assert v.errors == []++ def test_empty_input_schema_fails(self):+ v = AgentValidator()+ node = _make_node(+ block_id=AGENT_EXECUTOR_BLOCK_ID,+ input_default={+ "graph_id": generate_uuid(),+ "input_schema": {},+ "output_schema": {"properties": {"result": {"type": "string"}}},+ },+ )+ agent = _make_agent(nodes=[node])++ assert v.validate_agent_executor_block_schemas(agent) is False+ assert any("empty input_schema" in e for e in v.errors)++ def test_missing_output_schema_fails(self):+ v = AgentValidator()+ node = _make_node(+ block_id=AGENT_EXECUTOR_BLOCK_ID,+ input_default={+ "graph_id": generate_uuid(),+ "input_schema": {"properties": {"q": {"type": "string"}}},+ },+ )+ agent = _make_agent(nodes=[node])++ assert v.validate_agent_executor_block_schemas(agent) is False+ assert any("output_schema" in e for e in v.errors)+++# ============================================================================+# validate_agent_executor_blocks+# ============================================================================+++class TestValidateAgentExecutorBlocks:+ def test_missing_graph_id_fails(self):+ v = AgentValidator()+ node = _make_node(+ block_id=AGENT_EXECUTOR_BLOCK_ID,+ input_default={},+ )+ agent = _make_agent(nodes=[node])++ assert v.validate_agent_executor_blocks(agent) is False+ assert any("graph_id" in e for e in v.errors)++ def test_valid_graph_id_passes(self):+ v = AgentValidator()+ node = _make_node(+ block_id=AGENT_EXECUTOR_BLOCK_ID,+ input_default={"graph_id": generate_uuid()},+ )+ agent = _make_agent(nodes=[node])++ assert v.validate_agent_executor_blocks(agent) is True++ def test_version_mismatch_with_library_agent(self):+ v = AgentValidator()+ lib_id = generate_uuid()+ node = _make_node(+ node_id="n1",+ block_id=AGENT_EXECUTOR_BLOCK_ID,+ input_default={"graph_id": lib_id, "graph_version": 1},+ )+ agent = _make_agent(nodes=[node])++ library_agents = [{"graph_id": lib_id, "graph_version": 3, "name": "Sub Agent"}]++ assert v.validate_agent_executor_blocks(agent, library_agents) is False+ assert any("mismatched graph_version" in e for e in v.errors)++ def test_required_input_satisfied_by_schema_default_passes(self):+ """Required sub-agent inputs filled with their schema default by the fixer+ should NOT be flagged as missing."""+ v = AgentValidator()+ lib_id = generate_uuid()+ node = _make_node(+ node_id="n1",+ block_id=AGENT_EXECUTOR_BLOCK_ID,+ input_default={+ "graph_id": lib_id,+ "input_schema": {+ "properties": {"mode": {"type": "string", "default": "fast"}}+ },+ "inputs": {"mode": "fast"}, # fixer populated with schema default+ },+ )+ agent = _make_agent(nodes=[node])+ library_agents = [+ {+ "graph_id": lib_id,+ "graph_version": 1,+ "name": "Sub",+ "input_schema": {+ "required": ["mode"],+ "properties": {"mode": {"type": "string", "default": "fast"}},+ },+ "output_schema": {},+ }+ ]++ assert v.validate_agent_executor_blocks(agent, library_agents) is True+ assert v.errors == []++ def test_required_input_not_linked_and_no_default_fails(self):+ """Required sub-agent inputs without a link or schema default must fail."""+ v = AgentValidator()+ lib_id = generate_uuid()+ node = _make_node(+ node_id="n1",+ block_id=AGENT_EXECUTOR_BLOCK_ID,+ input_default={+ "graph_id": lib_id,+ "input_schema": {"properties": {"query": {"type": "string"}}},+ "inputs": {},+ },+ )+ agent = _make_agent(nodes=[node])+ library_agents = [+ {+ "graph_id": lib_id,+ "graph_version": 1,+ "name": "Sub",+ "input_schema": {+ "required": ["query"],+ "properties": {"query": {"type": "string"}},+ },+ "output_schema": {},+ }+ ]++ assert v.validate_agent_executor_blocks(agent, library_agents) is False+ assert any("missing required sub-agent input" in e for e in v.errors)+++# ============================================================================+# validate_io_blocks+# ============================================================================+++class TestValidateIoBlocks:+ def test_missing_input_block_reports_error(self):+ v = AgentValidator()+ # Agent has output block but no input block+ node = _make_node(block_id=AGENT_OUTPUT_BLOCK_ID)+ agent = _make_agent(nodes=[node])++ assert v.validate_io_blocks(agent) is False+ assert len(v.errors) == 1+ assert "AgentInputBlock" in v.errors[0]++ def test_missing_output_block_reports_error(self):+ v = AgentValidator()+ # Agent has input block but no output block+ node = _make_node(block_id=AGENT_INPUT_BLOCK_ID)+ agent = _make_agent(nodes=[node])++ assert v.validate_io_blocks(agent) is False+ assert len(v.errors) == 1+ assert "AgentOutputBlock" in v.errors[0]++ def test_missing_both_io_blocks_reports_two_errors(self):+ v = AgentValidator()+ node = _make_node(block_id="some-other-block")+ agent = _make_agent(nodes=[node])++ assert v.validate_io_blocks(agent) is False+ assert len(v.errors) == 2++ def test_both_io_blocks_present_no_error(self):+ v = AgentValidator()+ input_node = _make_node(block_id=AGENT_INPUT_BLOCK_ID)+ output_node = _make_node(block_id=AGENT_OUTPUT_BLOCK_ID)+ agent = _make_agent(nodes=[input_node, output_node])++ assert v.validate_io_blocks(agent) is True+ assert v.errors == []++ def test_empty_agent_reports_both_missing(self):+ v = AgentValidator()+ agent = _make_agent(nodes=[])++ assert v.validate_io_blocks(agent) is False+ assert len(v.errors) == 2+++# ============================================================================+# validate (integration)+# ============================================================================+++class TestValidate:+ def test_valid_agent_passes(self):+ v = AgentValidator()+ block = _make_block(+ block_id="b1",+ input_schema={+ "properties": {"url": {"type": "string"}},+ "required": ["url"],+ },+ output_schema={"properties": {"result": {"type": "string"}}},+ )+ input_block = _make_block(+ block_id=AGENT_INPUT_BLOCK_ID,+ name="AgentInputBlock",+ output_schema={"properties": {"result": {}}},+ )+ output_block = _make_block(+ block_id=AGENT_OUTPUT_BLOCK_ID,+ name="AgentOutputBlock",+ )+ input_node = _make_node(+ node_id="n-in",+ block_id=AGENT_INPUT_BLOCK_ID,+ input_default={"name": "url"},+ )+ n1 = _make_node(+ node_id="n1", block_id="b1", input_default={"url": "http://example.com"}+ )+ n2 = _make_node(+ node_id="n2", block_id="b1", input_default={"url": "http://example2.com"}+ )+ output_node = _make_node(+ node_id="n-out",+ block_id=AGENT_OUTPUT_BLOCK_ID,+ input_default={"name": "result"},+ )+ link = _make_link(+ source_id="n1", source_name="result", sink_id="n2", sink_name="url"+ )+ agent = _make_agent(nodes=[input_node, n1, n2, output_node], links=[link])++ is_valid, error_message = v.validate(agent, [block, input_block, output_block])++ assert is_valid is True+ assert error_message is None++ def test_invalid_agent_returns_errors(self):+ v = AgentValidator()+ node = _make_node(block_id="nonexistent")+ agent = _make_agent(nodes=[node])++ is_valid, error_message = v.validate(agent, [])++ assert is_valid is False+ assert error_message is not None+ assert "does not exist" in error_message++ def test_empty_agent_fails_io_validation(self):+ v = AgentValidator()+ agent = _make_agent()++ is_valid, error_message = v.validate(agent, [])++ assert is_valid is False+ assert error_message is not None+ assert "AgentInputBlock" in error_message+ assert "AgentOutputBlock" in error_message+++class TestValidateMCPToolBlocks:+ """Tests for validate_mcp_tool_blocks."""++ def test_missing_server_url_reports_error(self):+ v = AgentValidator()+ node = _make_node(+ block_id=MCP_TOOL_BLOCK_ID,+ input_default={"selected_tool": "my_tool"},+ )+ agent = _make_agent(nodes=[node])++ result = v.validate_mcp_tool_blocks(agent)++ assert result is False+ assert any("server_url" in e for e in v.errors)++ def test_missing_selected_tool_reports_error(self):+ v = AgentValidator()+ node = _make_node(+ block_id=MCP_TOOL_BLOCK_ID,+ input_default={"server_url": "https://mcp.example.com/sse"},+ )+ agent = _make_agent(nodes=[node])++ result = v.validate_mcp_tool_blocks(agent)++ assert result is False+ assert any("selected_tool" in e for e in v.errors)++ def test_valid_mcp_block_passes(self):+ v = AgentValidator()+ node = _make_node(+ block_id=MCP_TOOL_BLOCK_ID,+ input_default={+ "server_url": "https://mcp.example.com/sse",+ "selected_tool": "search",+ "tool_input_schema": {"properties": {"query": {"type": "string"}}},+ "tool_arguments": {},+ },+ )+ agent = _make_agent(nodes=[node])++ result = v.validate_mcp_tool_blocks(agent)++ assert result is True+ assert len(v.errors) == 0++ def test_both_missing_reports_two_errors(self):+ v = AgentValidator()+ node = _make_node(+ block_id=MCP_TOOL_BLOCK_ID,+ input_default={},+ )+ agent = _make_agent(nodes=[node])++ v.validate_mcp_tool_blocks(agent)++ assert len(v.errors) == 2diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_search.py b/autogpt_platform/backend/backend/copilot/tools/agent_search.pyindex 67483c8d9b..4226ee0370 100644--- a/autogpt_platform/backend/backend/copilot/tools/agent_search.py+++ b/autogpt_platform/backend/backend/copilot/tools/agent_search.py@@ -208,6 +208,9 @@ def _library_agent_to_info(agent: LibraryAgent) -> AgentInfo:has_external_trigger=agent.has_external_trigger,new_output=agent.new_output,graph_id=agent.graph_id,+ graph_version=agent.graph_version,+ input_schema=agent.input_schema,+ output_schema=agent.output_schema,)diff --git a/autogpt_platform/backend/backend/copilot/tools/create_agent.py b/autogpt_platform/backend/backend/copilot/tools/create_agent.pyindex a2fee7bd22..549e01157e 100644--- a/autogpt_platform/backend/backend/copilot/tools/create_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/create_agent.py@@ -1,34 +1,20 @@-"""CreateAgentTool - Creates agents from natural language descriptions."""+"""CreateAgentTool - Creates agents from pre-built JSON."""import logging+import uuidfrom typing import Anyfrom backend.copilot.model import ChatSession-from .agent_generator import (- AgentGeneratorNotConfiguredError,- decompose_goal,- enrich_library_agents_from_steps,- generate_agent,- get_user_message_for_error,- save_agent_to_library,-)+from .agent_generator.pipeline import fetch_library_agents, fix_validate_and_savefrom .base import BaseTool-from .models import (- AgentPreviewResponse,- AgentSavedResponse,- ClarificationNeededResponse,- ClarifyingQuestion,- ErrorResponse,- SuggestedGoalResponse,- ToolResponseBase,-)+from .models import ErrorResponse, ToolResponseBaselogger = logging.getLogger(__name__)class CreateAgentTool(BaseTool):- """Tool for creating agents from natural language descriptions."""+ """Tool for creating agents from pre-built JSON."""@propertydef name(self) -> str:@@ -37,15 +23,12 @@ class CreateAgentTool(BaseTool):@propertydef description(self) -> str:return (- "Create a new agent workflow from a natural language description. "- "First generates a preview, then saves to library if save=true. "- "\n\nWorkflow: (1) Always check find_library_agent first for existing building blocks. "- "(2) Call create_agent with description and library_agent_ids. "- "(3) If response contains suggested_goal: Present to user, ask for confirmation, "- "then call again with the suggested goal if accepted. "- "(4) If response contains clarifying_questions: Present to user, collect answers, "- "then call again with original description AND answers in the context parameter. "- "\n\nThis feedback loop ensures the generated agent matches user intent."+ "Create a new agent workflow. Pass `agent_json` with the complete "+ "agent graph JSON you generated using block schemas from find_block. "+ "The tool validates, auto-fixes, and saves.\n\n"+ "IMPORTANT: Before calling this tool, search for relevant existing agents "+ "using find_library_agent that could be used as building blocks. "+ "Pass their IDs in the library_agent_ids parameter.")@property@@ -57,34 +40,26 @@ class CreateAgentTool(BaseTool):return {"type": "object","properties": {- "description": {- "type": "string",- "description": (- "Natural language description of what the agent should do. "- "Be specific about inputs, outputs, and the workflow steps."- ),- },- "context": {- "type": "string",+ "agent_json": {+ "type": "object","description": (- "Additional context or answers to previous clarifying questions. "- "Include any preferences or constraints mentioned by the user."+ "The agent JSON to validate and save. "+ "Must contain 'nodes' and 'links' arrays, and optionally "+ "'name' and 'description'."),},"library_agent_ids": {"type": "array","items": {"type": "string"},"description": (- "List of library agent IDs to use as building blocks. "- "Search for relevant agents using find_library_agent first, "- "then pass their IDs here so they can be composed into the new agent."+ "List of library agent IDs to use as building blocks."),},"save": {"type": "boolean","description": (- "Whether to save the agent to the user's library. "- "Default is true. Set to false for preview only."+ "Whether to save the agent. Default is true. "+ "Set to false for preview only."),"default": True,},@@ -97,7 +72,7 @@ class CreateAgentTool(BaseTool):),},},- "required": ["description"],+ "required": ["agent_json"],}async def _execute(@@ -106,278 +81,49 @@ class CreateAgentTool(BaseTool):session: ChatSession,**kwargs,) -> ToolResponseBase:- """Execute the create_agent tool.-- Flow:- 1. Decompose the description into steps (may return clarifying questions)- 2. Generate agent JSON (external service handles fixing and validation)- 3. Preview or save based on the save parameter- """- description = kwargs.get("description", "").strip()- context = kwargs.get("context", "")- library_agent_ids = kwargs.get("library_agent_ids", [])- save = kwargs.get("save", True)- folder_id = kwargs.get("folder_id")+ agent_json: dict[str, Any] | None = kwargs.get("agent_json")session_id = session.session_id if session else None- logger.info(- f"[AGENT_CREATE_DEBUG] START - description_len={len(description)}, "- f"library_agent_ids={library_agent_ids}, save={save}, user_id={user_id}, session_id={session_id}"- )-- if not description:- return ErrorResponse(- message="Please provide a description of what the agent should do.",- error="Missing description parameter",- session_id=session_id,- )-- # Fetch library agents by IDs if provided- library_agents = None- if user_id and library_agent_ids:- try:- from .agent_generator import get_library_agents_by_ids-- library_agents = await get_library_agents_by_ids(- user_id=user_id,- agent_ids=library_agent_ids,- )- logger.debug(- f"Fetched {len(library_agents)} library agents by ID for sub-agent composition"- )- except Exception as e:- logger.warning(f"Failed to fetch library agents by IDs: {e}")-- try:- decomposition_result = await decompose_goal(- description, context, library_agents- )- logger.info(- f"[AGENT_CREATE_DEBUG] DECOMPOSE - type={decomposition_result.get('type') if decomposition_result else None}, "- f"session_id={session_id}"- )- except AgentGeneratorNotConfiguredError:- logger.error(- f"[AGENT_CREATE_DEBUG] ERROR - AgentGeneratorNotConfigured, session_id={session_id}"- )- return ErrorResponse(- message=(- "Agent generation is not available. "- "The Agent Generator service is not configured."- ),- error="service_not_configured",- session_id=session_id,- )-- if decomposition_result is None:- return ErrorResponse(- message="Failed to analyze the goal. The agent generation service may be unavailable. Please try again.",- error="decomposition_failed",- details={"description": description[:100]},- session_id=session_id,- )-- if decomposition_result.get("type") == "error":- error_msg = decomposition_result.get("error", "Unknown error")- error_type = decomposition_result.get("error_type", "unknown")- user_message = get_user_message_for_error(- error_type,- operation="analyze the goal",- llm_parse_message="The AI had trouble understanding this request. Please try rephrasing your goal.",- )- return ErrorResponse(- message=user_message,- error=f"decomposition_failed:{error_type}",- details={- "description": description[:100],- "service_error": error_msg,- "error_type": error_type,- },- session_id=session_id,- )-- if decomposition_result.get("type") == "clarifying_questions":- questions = decomposition_result.get("questions", [])- return ClarificationNeededResponse(- message=(- "I need some more information to create this agent. "- "Please answer the following questions:"- ),- questions=[- ClarifyingQuestion(- question=q.get("question", ""),- keyword=q.get("keyword", ""),- example=q.get("example"),- )- for q in questions- ],- session_id=session_id,- )-- if decomposition_result.get("type") == "unachievable_goal":- suggested = decomposition_result.get("suggested_goal", "")- reason = decomposition_result.get("reason", "")- return SuggestedGoalResponse(- message=(- f"This goal cannot be accomplished with the available blocks. {reason}"- ),- suggested_goal=suggested,- reason=reason,- original_goal=description,- goal_type="unachievable",- session_id=session_id,- )-- if decomposition_result.get("type") == "vague_goal":- suggested = decomposition_result.get("suggested_goal", "")- reason = decomposition_result.get(- "reason", "The goal needs more specific details"- )- return SuggestedGoalResponse(- message="The goal is too vague to create a specific workflow.",- suggested_goal=suggested,- reason=reason,- original_goal=description,- goal_type="vague",- session_id=session_id,- )-- if user_id and library_agents is not None:- try:- library_agents = await enrich_library_agents_from_steps(- user_id=user_id,- decomposition_result=decomposition_result,- existing_agents=library_agents,- include_marketplace=True,- )- logger.debug(- f"After enrichment: {len(library_agents)} total agents for sub-agent composition"- )- except Exception as e:- logger.warning(f"Failed to enrich library agents from steps: {e}")-- try:- agent_json = await generate_agent(- decomposition_result,- library_agents,- )- logger.info(- f"[AGENT_CREATE_DEBUG] GENERATE - "- f"success={agent_json is not None}, "- f"is_error={isinstance(agent_json, dict) and agent_json.get('type') == 'error'}, "- f"session_id={session_id}"- )- except AgentGeneratorNotConfiguredError:- logger.error(- f"[AGENT_CREATE_DEBUG] ERROR - AgentGeneratorNotConfigured during generation, session_id={session_id}"- )+ if not agent_json:return ErrorResponse(message=(- "Agent generation is not available. "- "The Agent Generator service is not configured."+ "Please provide agent_json with the complete agent graph. "+ "Use find_block to discover blocks, then generate the JSON."),- error="service_not_configured",+ error="missing_agent_json",session_id=session_id,)- if agent_json is None:- return ErrorResponse(- message="Failed to generate the agent. The agent generation service may be unavailable. Please try again.",- error="generation_failed",- details={"description": description[:100]},- session_id=session_id,- )+ save = kwargs.get("save", True)+ library_agent_ids = kwargs.get("library_agent_ids", [])+ folder_id: str | None = kwargs.get("folder_id")- if isinstance(agent_json, dict) and agent_json.get("type") == "error":- error_msg = agent_json.get("error", "Unknown error")- error_type = agent_json.get("error_type", "unknown")- user_message = get_user_message_for_error(- error_type,- operation="generate the agent",- llm_parse_message="The AI had trouble generating the agent. Please try again or simplify your goal.",- validation_message=(- "I wasn't able to create a valid agent for this request. "- "The generated workflow had some structural issues. "- "Please try simplifying your goal or breaking it into smaller steps."- ),- error_details=error_msg,- )+ nodes = agent_json.get("nodes", [])+ if not nodes:return ErrorResponse(- message=user_message,- error=f"generation_failed:{error_type}",- details={- "description": description[:100],- "service_error": error_msg,- "error_type": error_type,- },+ message="The agent JSON has no nodes. An agent needs at least one block.",+ error="empty_agent",session_id=session_id,)- agent_name = agent_json.get("name", "Generated Agent")- agent_description = agent_json.get("description", "")- node_count = len(agent_json.get("nodes", []))- link_count = len(agent_json.get("links", []))-- logger.info(- f"[AGENT_CREATE_DEBUG] AGENT_JSON - name={agent_name}, "- f"nodes={node_count}, links={link_count}, save={save}, session_id={session_id}"+ # Ensure top-level fields+ if "id" not in agent_json:+ agent_json["id"] = str(uuid.uuid4())+ if "version" not in agent_json:+ agent_json["version"] = 1+ if "is_active" not in agent_json:+ agent_json["is_active"] = True++ # Fetch library agents for AgentExecutorBlock validation+ library_agents = await fetch_library_agents(user_id, library_agent_ids)++ return await fix_validate_and_save(+ agent_json,+ user_id=user_id,+ session_id=session_id,+ save=save,+ is_update=False,+ default_name="Generated Agent",+ library_agents=library_agents,+ folder_id=folder_id,)-- if not save:- logger.info(- f"[AGENT_CREATE_DEBUG] RETURN - AgentPreviewResponse, session_id={session_id}"- )- return AgentPreviewResponse(- message=(- f"I've generated an agent called '{agent_name}' with {node_count} blocks. "- f"Review it and call create_agent with save=true to save it to your library."- ),- agent_json=agent_json,- agent_name=agent_name,- description=agent_description,- node_count=node_count,- link_count=link_count,- session_id=session_id,- )-- if not user_id:- return ErrorResponse(- message="You must be logged in to save agents.",- error="auth_required",- session_id=session_id,- )-- try:- created_graph, library_agent = await save_agent_to_library(- agent_json, user_id, folder_id=folder_id- )-- logger.info(- f"[AGENT_CREATE_DEBUG] SAVED - graph_id={created_graph.id}, "- f"library_agent_id={library_agent.id}, session_id={session_id}"- )- logger.info(- f"[AGENT_CREATE_DEBUG] RETURN - AgentSavedResponse, session_id={session_id}"- )- return AgentSavedResponse(- message=f"Agent '{created_graph.name}' has been saved to your library!",- agent_id=created_graph.id,- agent_name=created_graph.name,- library_agent_id=library_agent.id,- library_agent_link=f"/library/agents/{library_agent.id}",- agent_page_link=f"/build?flowID={created_graph.id}",- session_id=session_id,- )- except Exception as e:- logger.error(- f"[AGENT_CREATE_DEBUG] ERROR - save_failed: {str(e)}, session_id={session_id}"- )- logger.info(- f"[AGENT_CREATE_DEBUG] RETURN - ErrorResponse (save_failed), session_id={session_id}"- )- return ErrorResponse(- message=f"Failed to save the agent: {str(e)}",- error="save_failed",- details={"exception": str(e)},- session_id=session_id,- )diff --git a/autogpt_platform/backend/backend/copilot/tools/create_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/create_agent_test.pyindex 957b56e4d4..2a9592b81b 100644--- a/autogpt_platform/backend/backend/copilot/tools/create_agent_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/create_agent_test.py@@ -1,19 +1,16 @@-"""Tests for CreateAgentTool response types."""+"""Tests for CreateAgentTool."""-from unittest.mock import AsyncMock, patch+from unittest.mock import MagicMock, patchimport pytestfrom backend.copilot.tools.create_agent import CreateAgentTool-from backend.copilot.tools.models import (- ClarificationNeededResponse,- ErrorResponse,- SuggestedGoalResponse,-)+from backend.copilot.tools.models import AgentPreviewResponse, ErrorResponsefrom ._test_data import make_session_TEST_USER_ID = "test-user-create-agent"+_PIPELINE = "backend.copilot.tools.agent_generator.pipeline"@pytest.fixture@@ -26,102 +23,147 @@ def session():return make_session(_TEST_USER_ID)+# ── Input validation tests ──────────────────────────────────────────────+++async def test_missing_agent_json_returns_error(tool, session):+ """Missing agent_json returns ErrorResponse."""+ result = await tool._execute(user_id=_TEST_USER_ID, session=session)+ assert isinstance(result, ErrorResponse)+ assert result.error == "missing_agent_json"+++# ── Local mode tests ────────────────────────────────────────────────────++@pytest.mark.asyncio-async def test_missing_description_returns_error(tool, session):- """Missing description returns ErrorResponse."""- result = await tool._execute(user_id=_TEST_USER_ID, session=session, description="")+async def test_local_mode_empty_nodes_returns_error(tool, session):+ """Local mode with no nodes returns ErrorResponse."""+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json={"nodes": [], "links": []},+ )assert isinstance(result, ErrorResponse)- assert result.error == "Missing description parameter"+ assert "no nodes" in result.message.lower()@pytest.mark.asyncio-async def test_vague_goal_returns_suggested_goal_response(tool, session):- """vague_goal decomposition result returns SuggestedGoalResponse, not ErrorResponse."""- vague_result = {- "type": "vague_goal",- "suggested_goal": "Monitor Twitter mentions for a specific keyword and send a daily digest email",+async def test_local_mode_preview(tool, session):+ """Local mode with save=false returns AgentPreviewResponse."""+ agent_json = {+ "name": "Test Agent",+ "description": "A test agent",+ "nodes": [+ {+ "id": "node-1",+ "block_id": "block-1",+ "input_default": {},+ "metadata": {"position": {"x": 0, "y": 0}},+ }+ ],+ "links": [],}+ mock_fixer = MagicMock()+ mock_fixer.apply_all_fixes = MagicMock(return_value=agent_json)+ mock_fixer.get_fixes_applied.return_value = []++ mock_validator = MagicMock()+ mock_validator.validate.return_value = (True, None)+ mock_validator.errors = []+with (- patch(- "backend.copilot.tools.create_agent.decompose_goal",- new_callable=AsyncMock,- return_value=vague_result,- ),+ patch(f"{_PIPELINE}.get_blocks_as_dicts", return_value=[]),+ patch(f"{_PIPELINE}.AgentFixer", return_value=mock_fixer),+ patch(f"{_PIPELINE}.AgentValidator", return_value=mock_validator),):result = await tool._execute(user_id=_TEST_USER_ID,session=session,- description="monitor social media",+ agent_json=agent_json,+ save=False,)- assert isinstance(result, SuggestedGoalResponse)- assert result.goal_type == "vague"- assert result.suggested_goal == vague_result["suggested_goal"]- assert result.original_goal == "monitor social media"- assert result.reason == "The goal needs more specific details"- assert not isinstance(result, ErrorResponse)+ assert isinstance(result, AgentPreviewResponse)+ assert result.agent_name == "Test Agent"+ assert result.node_count == 1@pytest.mark.asyncio-async def test_unachievable_goal_returns_suggested_goal_response(tool, session):- """unachievable_goal decomposition result returns SuggestedGoalResponse, not ErrorResponse."""- unachievable_result = {- "type": "unachievable_goal",- "suggested_goal": "Summarize the latest news articles on a topic and send them by email",- "reason": "There are no blocks for mind-reading.",+async def test_local_mode_validation_failure(tool, session):+ """Local mode returns ErrorResponse when validation fails after fixing."""+ agent_json = {+ "nodes": [+ {+ "id": "node-1",+ "block_id": "bad-block",+ "input_default": {},+ "metadata": {},+ }+ ],+ "links": [],}+ mock_fixer = MagicMock()+ mock_fixer.apply_all_fixes = MagicMock(return_value=agent_json)+ mock_fixer.get_fixes_applied.return_value = []++ mock_validator = MagicMock()+ mock_validator.validate.return_value = (False, "Block 'bad-block' not found")+ mock_validator.errors = ["Block 'bad-block' not found"]+with (- patch(- "backend.copilot.tools.create_agent.decompose_goal",- new_callable=AsyncMock,- return_value=unachievable_result,- ),+ patch(f"{_PIPELINE}.get_blocks_as_dicts", return_value=[]),+ patch(f"{_PIPELINE}.AgentFixer", return_value=mock_fixer),+ patch(f"{_PIPELINE}.AgentValidator", return_value=mock_validator),):result = await tool._execute(user_id=_TEST_USER_ID,session=session,- description="read my mind",+ agent_json=agent_json,)- assert isinstance(result, SuggestedGoalResponse)- assert result.goal_type == "unachievable"- assert result.suggested_goal == unachievable_result["suggested_goal"]- assert result.original_goal == "read my mind"- assert result.reason == unachievable_result["reason"]- assert not isinstance(result, ErrorResponse)+ assert isinstance(result, ErrorResponse)+ assert result.error == "validation_failed"+ assert "Block 'bad-block' not found" in result.message@pytest.mark.asyncio-async def test_clarifying_questions_returns_clarification_needed_response(- tool, session-):- """clarifying_questions decomposition result returns ClarificationNeededResponse."""- clarifying_result = {- "type": "clarifying_questions",- "questions": [+async def test_local_mode_no_auth_returns_error(tool, session):+ """Local mode with save=true and no user returns ErrorResponse."""+ agent_json = {+ "nodes": [{- "question": "What platform should be monitored?",- "keyword": "platform",- "example": "Twitter, Reddit",+ "id": "node-1",+ "block_id": "block-1",+ "input_default": {},+ "metadata": {},}],+ "links": [],}+ mock_fixer = MagicMock()+ mock_fixer.apply_all_fixes = MagicMock(return_value=agent_json)+ mock_fixer.get_fixes_applied.return_value = []++ mock_validator = MagicMock()+ mock_validator.validate.return_value = (True, None)+ mock_validator.errors = []+with (- patch(- "backend.copilot.tools.create_agent.decompose_goal",- new_callable=AsyncMock,- return_value=clarifying_result,- ),+ patch(f"{_PIPELINE}.get_blocks_as_dicts", return_value=[]),+ patch(f"{_PIPELINE}.AgentFixer", return_value=mock_fixer),+ patch(f"{_PIPELINE}.AgentValidator", return_value=mock_validator),):result = await tool._execute(- user_id=_TEST_USER_ID,+ user_id=None,session=session,- description="monitor social media and alert me",+ agent_json=agent_json,+ save=True,)- assert isinstance(result, ClarificationNeededResponse)- assert len(result.questions) == 1- assert result.questions[0].keyword == "platform"+ assert isinstance(result, ErrorResponse)+ assert "logged in" in result.message.lower()diff --git a/autogpt_platform/backend/backend/copilot/tools/customize_agent.py b/autogpt_platform/backend/backend/copilot/tools/customize_agent.pyindex bef83dd150..d8e31eb83d 100644--- a/autogpt_platform/backend/backend/copilot/tools/customize_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/customize_agent.py@@ -1,34 +1,20 @@-"""CustomizeAgentTool - Customizes marketplace/template agents using natural language."""+"""CustomizeAgentTool - Customizes marketplace/template agents."""import logging+import uuidfrom typing import Anyfrom backend.copilot.model import ChatSession-from backend.data.db_accessors import store_db as get_store_db-from backend.util.exceptions import NotFoundError-from .agent_generator import (- AgentGeneratorNotConfiguredError,- customize_template,- get_user_message_for_error,- graph_to_json,- save_agent_to_library,-)+from .agent_generator.pipeline import fetch_library_agents, fix_validate_and_savefrom .base import BaseTool-from .models import (- AgentPreviewResponse,- AgentSavedResponse,- ClarificationNeededResponse,- ClarifyingQuestion,- ErrorResponse,- ToolResponseBase,-)+from .models import ErrorResponse, ToolResponseBaselogger = logging.getLogger(__name__)class CustomizeAgentTool(BaseTool):- """Tool for customizing marketplace/template agents using natural language."""+ """Tool for customizing marketplace/template agents."""@propertydef name(self) -> str:@@ -37,9 +23,9 @@ class CustomizeAgentTool(BaseTool):@propertydef description(self) -> str:return (- "Customize a marketplace or template agent using natural language. "- "Takes an existing agent from the marketplace and modifies it based on "- "the user's requirements before adding to their library."+ "Customize a marketplace or template agent. Pass `agent_json` "+ "with the complete customized agent JSON. The tool validates, "+ "auto-fixes, and saves.")@property@@ -51,32 +37,24 @@ class CustomizeAgentTool(BaseTool):return {"type": "object","properties": {- "agent_id": {- "type": "string",- "description": (- "The marketplace agent ID in format 'creator/slug' "- "(e.g., 'autogpt/newsletter-writer'). "- "Get this from find_agent results."- ),- },- "modifications": {- "type": "string",+ "agent_json": {+ "type": "object","description": (- "Natural language description of how to customize the agent. "- "Be specific about what changes you want to make."+ "Complete customized agent JSON to validate and save. "+ "Optionally include 'name' and 'description'."),},- "context": {- "type": "string",+ "library_agent_ids": {+ "type": "array",+ "items": {"type": "string"},"description": (- "Additional context or answers to previous clarifying questions."+ "List of library agent IDs to use as building blocks."),},"save": {"type": "boolean","description": (- "Whether to save the customized agent to the user's library. "- "Default is true. Set to false for preview only."+ "Whether to save the customized agent. Default is true."),"default": True,},@@ -89,7 +67,7 @@ class CustomizeAgentTool(BaseTool):),},},- "required": ["agent_id", "modifications"],+ "required": ["agent_json"],}async def _execute(@@ -98,247 +76,46 @@ class CustomizeAgentTool(BaseTool):session: ChatSession,**kwargs,) -> ToolResponseBase:- """Execute the customize_agent tool.-- Flow:- 1. Parse the agent ID to get creator/slug- 2. Fetch the template agent from the marketplace- 3. Call customize_template with the modification request- 4. Preview or save based on the save parameter- """- agent_id = kwargs.get("agent_id", "").strip()- modifications = kwargs.get("modifications", "").strip()- context = kwargs.get("context", "")- save = kwargs.get("save", True)- folder_id = kwargs.get("folder_id")+ agent_json: dict[str, Any] | None = kwargs.get("agent_json")session_id = session.session_id if session else None- if not agent_id:- return ErrorResponse(- message="Please provide the marketplace agent ID (e.g., 'creator/agent-name').",- error="missing_agent_id",- session_id=session_id,- )-- if not modifications:- return ErrorResponse(- message="Please describe how you want to customize this agent.",- error="missing_modifications",- session_id=session_id,- )-- # Parse agent_id in format "creator/slug"- parts = [p.strip() for p in agent_id.split("/")]- if len(parts) != 2 or not parts[0] or not parts[1]:- return ErrorResponse(- message=(- f"Invalid agent ID format: '{agent_id}'. "- "Expected format is 'creator/agent-name' "- "(e.g., 'autogpt/newsletter-writer')."- ),- error="invalid_agent_id_format",- session_id=session_id,- )-- creator_username, agent_slug = parts-- store_db = get_store_db()-- # Fetch the marketplace agent details- try:- agent_details = await store_db.get_store_agent_details(- username=creator_username, agent_name=agent_slug- )- except NotFoundError:- return ErrorResponse(- message=(- f"Could not find marketplace agent '{agent_id}'. "- "Please check the agent ID and try again."- ),- error="agent_not_found",- session_id=session_id,- )- except Exception as e:- logger.error(f"Error fetching marketplace agent {agent_id}: {e}")- return ErrorResponse(- message="Failed to fetch the marketplace agent. Please try again.",- error="fetch_error",- session_id=session_id,- )-- if not agent_details.store_listing_version_id:- return ErrorResponse(- message=(- f"The agent '{agent_id}' does not have an available version. "- "Please try a different agent."- ),- error="no_version_available",- session_id=session_id,- )-- # Get the full agent graph- try:- graph = await store_db.get_agent(agent_details.store_listing_version_id)- template_agent = graph_to_json(graph)- except Exception as e:- logger.error(f"Error fetching agent graph for {agent_id}: {e}")- return ErrorResponse(- message="Failed to fetch the agent configuration. Please try again.",- error="graph_fetch_error",- session_id=session_id,- )-- # Call customize_template- try:- result = await customize_template(- template_agent=template_agent,- modification_request=modifications,- context=context,- )- except AgentGeneratorNotConfiguredError:+ if not agent_json:return ErrorResponse(message=(- "Agent customization is not available. "- "The Agent Generator service is not configured."+ "Please provide agent_json with the complete customized agent graph."),- error="service_not_configured",- session_id=session_id,- )- except Exception as e:- logger.error(f"Error calling customize_template for {agent_id}: {e}")- return ErrorResponse(- message=(- "Failed to customize the agent due to a service error. "- "Please try again."- ),- error="customization_service_error",+ error="missing_agent_json",session_id=session_id,)- if result is None:- return ErrorResponse(- message=(- "Failed to customize the agent. "- "The agent generation service may be unavailable or timed out. "- "Please try again."- ),- error="customization_failed",- session_id=session_id,- )+ save = kwargs.get("save", True)+ library_agent_ids = kwargs.get("library_agent_ids", [])+ folder_id: str | None = kwargs.get("folder_id")- # Handle error response- if isinstance(result, dict) and result.get("type") == "error":- error_msg = result.get("error", "Unknown error")- error_type = result.get("error_type", "unknown")- user_message = get_user_message_for_error(- error_type,- operation="customize the agent",- llm_parse_message=(- "The AI had trouble customizing the agent. "- "Please try again or simplify your request."- ),- validation_message=(- "The customized agent failed validation. "- "Please try rephrasing your request."- ),- error_details=error_msg,- )+ nodes = agent_json.get("nodes", [])+ if not nodes:return ErrorResponse(- message=user_message,- error=f"customization_failed:{error_type}",+ message="The agent JSON has no nodes.",+ error="empty_agent",session_id=session_id,)- # Handle clarifying questions- if isinstance(result, dict) and result.get("type") == "clarifying_questions":- questions = result.get("questions") or []- if not isinstance(questions, list):- logger.error(- f"Unexpected clarifying questions format: {type(questions)}"- )- questions = []- return ClarificationNeededResponse(- message=(- "I need some more information to customize this agent. "- "Please answer the following questions:"- ),- questions=[- ClarifyingQuestion(- question=q.get("question", ""),- keyword=q.get("keyword", ""),- example=q.get("example"),- )- for q in questions- if isinstance(q, dict)- ],- session_id=session_id,- )+ # Ensure top-level fields before the fixer pipeline+ if "id" not in agent_json:+ agent_json["id"] = str(uuid.uuid4())+ agent_json.setdefault("version", 1)+ agent_json.setdefault("is_active", True)- # Result should be the customized agent JSON- if not isinstance(result, dict):- logger.error(f"Unexpected customize_template response type: {type(result)}")- return ErrorResponse(- message="Failed to customize the agent due to an unexpected response.",- error="unexpected_response_type",- session_id=session_id,- )-- customized_agent = result+ # Fetch library agents for AgentExecutorBlock validation+ library_agents = await fetch_library_agents(user_id, library_agent_ids)- agent_name = customized_agent.get(- "name", f"Customized {agent_details.agent_name}"+ return await fix_validate_and_save(+ agent_json,+ user_id=user_id,+ session_id=session_id,+ save=save,+ is_update=False,+ default_name="Customized Agent",+ library_agents=library_agents,+ folder_id=folder_id,)- agent_description = customized_agent.get("description", "")- nodes = customized_agent.get("nodes")- links = customized_agent.get("links")- node_count = len(nodes) if isinstance(nodes, list) else 0- link_count = len(links) if isinstance(links, list) else 0-- if not save:- return AgentPreviewResponse(- message=(- f"I've customized the agent '{agent_details.agent_name}'. "- f"The customized agent has {node_count} blocks. "- f"Review it and call customize_agent with save=true to save it."- ),- agent_json=customized_agent,- agent_name=agent_name,- description=agent_description,- node_count=node_count,- link_count=link_count,- session_id=session_id,- )-- if not user_id:- return ErrorResponse(- message="You must be logged in to save agents.",- error="auth_required",- session_id=session_id,- )-- # Save to user's library- try:- created_graph, library_agent = await save_agent_to_library(- customized_agent, user_id, is_update=False, folder_id=folder_id- )-- return AgentSavedResponse(- message=(- f"Customized agent '{created_graph.name}' "- f"(based on '{agent_details.agent_name}') "- f"has been saved to your library!"- ),- agent_id=created_graph.id,- agent_name=created_graph.name,- library_agent_id=library_agent.id,- library_agent_link=f"/library/agents/{library_agent.id}",- agent_page_link=f"/build?flowID={created_graph.id}",- session_id=session_id,- )- except Exception as e:- logger.error(f"Error saving customized agent: {e}")- return ErrorResponse(- message="Failed to save the customized agent. Please try again.",- error="save_failed",- session_id=session_id,- )diff --git a/autogpt_platform/backend/backend/copilot/tools/customize_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/customize_agent_test.pynew file mode 100644index 0000000000..3dffc69759--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/customize_agent_test.py@@ -0,0 +1,172 @@+"""Tests for CustomizeAgentTool local mode."""++from unittest.mock import MagicMock, patch++import pytest++from backend.copilot.tools.customize_agent import CustomizeAgentTool+from backend.copilot.tools.models import AgentPreviewResponse, ErrorResponse++from ._test_data import make_session++_TEST_USER_ID = "test-user-customize-agent"+_PIPELINE = "backend.copilot.tools.agent_generator.pipeline"+++def tool():+ return CustomizeAgentTool()+++def session():+ return make_session(_TEST_USER_ID)+++# ── Input validation tests ───────────────────────────────────────────────+++async def test_missing_agent_json_returns_error(tool, session):+ """Missing agent_json returns ErrorResponse."""+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "missing_agent_json"+++# ── Local mode tests (agent_json provided) ───────────────────────────────+++async def test_local_mode_empty_nodes_returns_error(tool, session):+ """Local mode with no nodes returns ErrorResponse."""+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json={"nodes": [], "links": []},+ )+ assert isinstance(result, ErrorResponse)+ assert "no nodes" in result.message.lower()+++async def test_local_mode_preview(tool, session):+ """Local mode with save=false returns AgentPreviewResponse."""+ agent_json = {+ "name": "Customized Agent",+ "description": "A customized agent",+ "nodes": [+ {+ "id": "node-1",+ "block_id": "block-1",+ "input_default": {},+ "metadata": {"position": {"x": 0, "y": 0}},+ }+ ],+ "links": [],+ }++ mock_fixer = MagicMock()+ mock_fixer.apply_all_fixes = MagicMock(return_value=agent_json)+ mock_fixer.get_fixes_applied.return_value = []++ mock_validator = MagicMock()+ mock_validator.validate.return_value = (True, None)+ mock_validator.errors = []++ with (+ patch(f"{_PIPELINE}.get_blocks_as_dicts", return_value=[]),+ patch(f"{_PIPELINE}.AgentFixer", return_value=mock_fixer),+ patch(f"{_PIPELINE}.AgentValidator", return_value=mock_validator),+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json=agent_json,+ save=False,+ )++ assert isinstance(result, AgentPreviewResponse)+ assert result.agent_name == "Customized Agent"+ assert result.node_count == 1+++async def test_local_mode_validation_failure(tool, session):+ """Local mode returns ErrorResponse when validation fails."""+ agent_json = {+ "nodes": [+ {+ "id": "node-1",+ "block_id": "bad-block",+ "input_default": {},+ "metadata": {},+ }+ ],+ "links": [],+ }++ mock_fixer = MagicMock()+ mock_fixer.apply_all_fixes = MagicMock(return_value=agent_json)+ mock_fixer.get_fixes_applied.return_value = []++ mock_validator = MagicMock()+ mock_validator.validate.return_value = (False, "Block 'bad-block' not found")+ mock_validator.errors = ["Block 'bad-block' not found"]++ with (+ patch(f"{_PIPELINE}.get_blocks_as_dicts", return_value=[]),+ patch(f"{_PIPELINE}.AgentFixer", return_value=mock_fixer),+ patch(f"{_PIPELINE}.AgentValidator", return_value=mock_validator),+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json=agent_json,+ )++ assert isinstance(result, ErrorResponse)+ assert result.error == "validation_failed"+ assert "Block 'bad-block' not found" in result.message+++async def test_local_mode_no_auth_returns_error(tool, session):+ """Local mode with save=true and no user returns ErrorResponse."""+ agent_json = {+ "nodes": [+ {+ "id": "node-1",+ "block_id": "block-1",+ "input_default": {},+ "metadata": {},+ }+ ],+ "links": [],+ }++ mock_fixer = MagicMock()+ mock_fixer.apply_all_fixes = MagicMock(return_value=agent_json)+ mock_fixer.get_fixes_applied.return_value = []++ mock_validator = MagicMock()+ mock_validator.validate.return_value = (True, None)+ mock_validator.errors = []++ with (+ patch(f"{_PIPELINE}.get_blocks_as_dicts", return_value=[]),+ patch(f"{_PIPELINE}.AgentFixer", return_value=mock_fixer),+ patch(f"{_PIPELINE}.AgentValidator", return_value=mock_validator),+ ):+ result = await tool._execute(+ user_id=None,+ session=session,+ agent_json=agent_json,+ save=True,+ )++ assert isinstance(result, ErrorResponse)+ assert "logged in" in result.message.lower()diff --git a/autogpt_platform/backend/backend/copilot/tools/edit_agent.py b/autogpt_platform/backend/backend/copilot/tools/edit_agent.pyindex 981a29fcd9..1cabc77012 100644--- a/autogpt_platform/backend/backend/copilot/tools/edit_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/edit_agent.py@@ -1,32 +1,20 @@-"""EditAgentTool - Edits existing agents using natural language."""+"""EditAgentTool - Edits existing agents using pre-built JSON."""import loggingfrom typing import Anyfrom backend.copilot.model import ChatSession-from .agent_generator import (- AgentGeneratorNotConfiguredError,- generate_agent_patch,- get_agent_as_json,- get_user_message_for_error,- save_agent_to_library,-)+from .agent_generator import get_agent_as_json+from .agent_generator.pipeline import fetch_library_agents, fix_validate_and_savefrom .base import BaseTool-from .models import (- AgentPreviewResponse,- AgentSavedResponse,- ClarificationNeededResponse,- ClarifyingQuestion,- ErrorResponse,- ToolResponseBase,-)+from .models import ErrorResponse, ToolResponseBaselogger = logging.getLogger(__name__)class EditAgentTool(BaseTool):- """Tool for editing existing agents using natural language."""+ """Tool for editing existing agents using pre-built JSON."""@propertydef name(self) -> str:@@ -35,11 +23,12 @@ class EditAgentTool(BaseTool):@propertydef description(self) -> str:return (- "Edit an existing agent from the user's library using natural language. "- "Generates updates to the agent while preserving unchanged parts. "- "\n\nIMPORTANT: Before calling this tool, if the changes involve adding new "+ "Edit an existing agent. Pass `agent_json` with the complete "+ "updated agent JSON you generated. The tool validates, auto-fixes, "+ "and saves.\n\n"+ "IMPORTANT: Before calling this tool, if the changes involve adding new ""functionality, search for relevant existing agents using find_library_agent "- "that could be used as building blocks. Pass their IDs in library_agent_ids."+ "that could be used as building blocks.")@property@@ -58,26 +47,20 @@ class EditAgentTool(BaseTool):"Can be a graph ID or library agent ID."),},- "changes": {- "type": "string",- "description": (- "Natural language description of what changes to make. "- "Be specific about what to add, remove, or modify."- ),- },- "context": {- "type": "string",+ "agent_json": {+ "type": "object","description": (- "Additional context or answers to previous clarifying questions."+ "Complete updated agent JSON to validate and save. "+ "Must contain 'nodes' and 'links'. "+ "Include 'name' and/or 'description' if they need "+ "to be updated."),},"library_agent_ids": {"type": "array","items": {"type": "string"},"description": (- "List of library agent IDs to use as building blocks for the changes. "- "If adding new functionality, search for relevant agents using "- "find_library_agent first, then pass their IDs here."+ "List of library agent IDs to use as building blocks for the changes."),},"save": {@@ -89,7 +72,7 @@ class EditAgentTool(BaseTool):"default": True,},},- "required": ["agent_id", "changes"],+ "required": ["agent_id", "agent_json"],}async def _execute(@@ -98,179 +81,59 @@ class EditAgentTool(BaseTool):session: ChatSession,**kwargs,) -> ToolResponseBase:- """Execute the edit_agent tool.-- Flow:- 1. Fetch the current agent- 2. Generate updated agent (external service handles fixing and validation)- 3. Preview or save based on the save parameter- """agent_id = kwargs.get("agent_id", "").strip()- changes = kwargs.get("changes", "").strip()- context = kwargs.get("context", "")- library_agent_ids = kwargs.get("library_agent_ids", [])- save = kwargs.get("save", True)+ agent_json: dict[str, Any] | None = kwargs.get("agent_json")session_id = session.session_id if session else Noneif not agent_id:return ErrorResponse(message="Please provide the agent ID to edit.",- error="Missing agent_id parameter",+ error="missing_agent_id",session_id=session_id,)- if not changes:- return ErrorResponse(- message="Please describe what changes you want to make.",- error="Missing changes parameter",- session_id=session_id,- )-- current_agent = await get_agent_as_json(agent_id, user_id)-- if current_agent is None:- return ErrorResponse(- message=f"Could not find agent with ID '{agent_id}' in your library.",- error="agent_not_found",- session_id=session_id,- )-- # Fetch library agents by IDs if provided- library_agents = None- if user_id and library_agent_ids:- try:- from .agent_generator import get_library_agents_by_ids-- graph_id = current_agent.get("id")- # Filter out the current agent being edited- filtered_ids = [id for id in library_agent_ids if id != graph_id]-- library_agents = await get_library_agents_by_ids(- user_id=user_id,- agent_ids=filtered_ids,- )- logger.debug(- f"Fetched {len(library_agents)} library agents by ID for sub-agent composition"- )- except Exception as e:- logger.warning(f"Failed to fetch library agents by IDs: {e}")-- update_request = changes- if context:- update_request = f"{changes}\n\nAdditional context:\n{context}"-- try:- result = await generate_agent_patch(- update_request,- current_agent,- library_agents,- )- except AgentGeneratorNotConfiguredError:+ if not agent_json:return ErrorResponse(message=(- "Agent editing is not available. "- "The Agent Generator service is not configured."+ "Please provide agent_json with the complete updated agent graph."),- error="service_not_configured",+ error="missing_agent_json",session_id=session_id,)- if result is None:- return ErrorResponse(- message="Failed to generate changes. The agent generation service may be unavailable or timed out. Please try again.",- error="update_generation_failed",- details={"agent_id": agent_id, "changes": changes[:100]},- session_id=session_id,- )+ save = kwargs.get("save", True)+ library_agent_ids = kwargs.get("library_agent_ids", [])- # Check if the result is an error from the external service- if isinstance(result, dict) and result.get("type") == "error":- error_msg = result.get("error", "Unknown error")- error_type = result.get("error_type", "unknown")- user_message = get_user_message_for_error(- error_type,- operation="generate the changes",- llm_parse_message="The AI had trouble generating the changes. Please try again or simplify your request.",- validation_message="The generated changes failed validation. Please try rephrasing your request.",- error_details=error_msg,- )+ nodes = agent_json.get("nodes", [])+ if not nodes:return ErrorResponse(- message=user_message,- error=f"update_generation_failed:{error_type}",- details={- "agent_id": agent_id,- "changes": changes[:100],- "service_error": error_msg,- "error_type": error_type,- },- session_id=session_id,- )-- if result.get("type") == "clarifying_questions":- questions = result.get("questions", [])- return ClarificationNeededResponse(- message=(- "I need some more information about the changes. "- "Please answer the following questions:"- ),- questions=[- ClarifyingQuestion(- question=q.get("question", ""),- keyword=q.get("keyword", ""),- example=q.get("example"),- )- for q in questions- ],- session_id=session_id,- )-- updated_agent = result-- agent_name = updated_agent.get("name", "Updated Agent")- agent_description = updated_agent.get("description", "")- node_count = len(updated_agent.get("nodes", []))- link_count = len(updated_agent.get("links", []))-- if not save:- return AgentPreviewResponse(- message=(- f"I've updated the agent. "- f"The agent now has {node_count} blocks. "- f"Review it and call edit_agent with save=true to save the changes."- ),- agent_json=updated_agent,- agent_name=agent_name,- description=agent_description,- node_count=node_count,- link_count=link_count,+ message="The agent JSON has no nodes.",+ error="empty_agent",session_id=session_id,)- if not user_id:+ # Preserve original agent's ID+ current_agent = await get_agent_as_json(agent_id, user_id)+ if current_agent is None:return ErrorResponse(- message="You must be logged in to save agents.",- error="auth_required",+ message=f"Could not find agent with ID '{agent_id}' in your library.",+ error="agent_not_found",session_id=session_id,)- try:- created_graph, library_agent = await save_agent_to_library(- updated_agent, user_id, is_update=True- )-- return AgentSavedResponse(- message=f"Updated agent '{created_graph.name}' has been saved to your library!",- agent_id=created_graph.id,- agent_name=created_graph.name,- library_agent_id=library_agent.id,- library_agent_link=f"/library/agents/{library_agent.id}",- agent_page_link=f"/build?flowID={created_graph.id}",- session_id=session_id,- )- except Exception as e:- return ErrorResponse(- message=f"Failed to save the updated agent: {str(e)}",- error="save_failed",- details={"exception": str(e)},- session_id=session_id,- )+ agent_json["id"] = current_agent.get("id", agent_id)+ agent_json["version"] = current_agent.get("version", 1)+ agent_json.setdefault("is_active", True)++ # Fetch library agents for AgentExecutorBlock validation+ library_agents = await fetch_library_agents(user_id, library_agent_ids)++ return await fix_validate_and_save(+ agent_json,+ user_id=user_id,+ session_id=session_id,+ save=save,+ is_update=True,+ default_name="Updated Agent",+ library_agents=library_agents,+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/find_block.py b/autogpt_platform/backend/backend/copilot/tools/find_block.pyindex 6b91f88f59..2d458656b7 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_block.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_block.py@@ -32,7 +32,7 @@ COPILOT_EXCLUDED_BLOCK_TYPES = {BlockType.NOTE, # Visual annotation only - no runtime behaviorBlockType.HUMAN_IN_THE_LOOP, # Pauses for human approval - CoPilot IS human-in-the-loopBlockType.AGENT, # AgentExecutorBlock requires execution_context - use run_agent tool- BlockType.MCP_TOOL, # Has dedicated run_mcp_tool tool with proper discovery + auth flow+ BlockType.MCP_TOOL, # Has dedicated run_mcp_tool tool with discovery + auth flow}# Specific block IDs excluded from CoPilot (STANDARD type but still require graph context)@@ -72,6 +72,15 @@ class FindBlockTool(BaseTool):"Use keywords like 'email', 'http', 'text', 'ai', etc."),},+ "include_schemas": {+ "type": "boolean",+ "description": (+ "If true, include full input_schema and output_schema "+ "for each block. Use when generating agent JSON that "+ "needs block schemas. Default is false."+ ),+ "default": False,+ },},"required": ["query"],}@@ -99,6 +108,7 @@ class FindBlockTool(BaseTool):ErrorResponse: Error message"""query = kwargs.get("query", "").strip()+ include_schemas = kwargs.get("include_schemas", False)session_id = session.session_idif not query:@@ -143,15 +153,21 @@ class FindBlockTool(BaseTool):):continue- blocks.append(- BlockInfoSummary(- id=block_id,- name=block.name,- description=block.description or "",- categories=[c.value for c in block.categories],- )+ summary = BlockInfoSummary(+ id=block_id,+ name=block.name,+ description=block.optimized_description or block.description or "",+ categories=[c.value for c in block.categories],)+ if include_schemas:+ info = block.get_info()+ summary.input_schema = info.inputSchema+ summary.output_schema = info.outputSchema+ summary.static_output = info.staticOutput++ blocks.append(summary)+if len(blocks) >= _TARGET_RESULTS:breakdiff --git a/autogpt_platform/backend/backend/copilot/tools/find_block_test.py b/autogpt_platform/backend/backend/copilot/tools/find_block_test.pyindex 19abdf78a1..b80ef7e796 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_block_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_block_test.py@@ -25,6 +25,7 @@ def make_mock_block(input_schema: dict | None = None,output_schema: dict | None = None,credentials_fields: dict | None = None,+ static_output: bool = False,):"""Create a mock block for testing."""mock = MagicMock()@@ -33,6 +34,7 @@ def make_mock_block(mock.description = f"{name} description"mock.block_type = block_typemock.disabled = disabled+ mock.static_output = static_outputmock.input_schema = MagicMock()mock.input_schema.jsonschema.return_value = input_schema or {"properties": {},@@ -42,6 +44,15 @@ def make_mock_block(mock.output_schema = MagicMock()mock.output_schema.jsonschema.return_value = output_schema or {}mock.categories = []+ mock.optimized_description = None++ # Mock get_info() for include_schemas support+ mock_info = MagicMock()+ mock_info.inputSchema = input_schema or {"properties": {}, "required": []}+ mock_info.outputSchema = output_schema or {}+ mock_info.staticOutput = static_output+ mock.get_info.return_value = mock_info+return mock@@ -399,3 +410,92 @@ class TestFindBlockFiltering:f"Average chars per block ({avg_chars}) exceeds 500. "f"Total response: {total_chars} chars for {response.count} blocks.")++ @pytest.mark.asyncio(loop_scope="session")+ async def test_include_schemas_false_omits_schemas(self):+ """Without include_schemas, schemas should be empty dicts."""+ session = make_session(user_id=_TEST_USER_ID)+ input_schema = {"properties": {"url": {"type": "string"}}, "required": ["url"]}+ output_schema = {"properties": {"result": {"type": "string"}}}++ search_results = [{"content_id": "block-1", "score": 0.9}]+ block = make_mock_block(+ "block-1",+ "Test Block",+ BlockType.STANDARD,+ input_schema=input_schema,+ output_schema=output_schema,+ )++ mock_search_db = MagicMock()+ mock_search_db.unified_hybrid_search = AsyncMock(+ return_value=(search_results, 1)+ )++ with (+ patch(+ "backend.copilot.tools.find_block.search",+ return_value=mock_search_db,+ ),+ patch(+ "backend.copilot.tools.find_block.get_block",+ return_value=block,+ ),+ ):+ tool = FindBlockTool()+ response = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ query="test",+ include_schemas=False,+ )++ assert isinstance(response, BlockListResponse)+ assert response.blocks[0].input_schema == {}+ assert response.blocks[0].output_schema == {}+ assert response.blocks[0].static_output is False++ @pytest.mark.asyncio(loop_scope="session")+ async def test_include_schemas_true_populates_schemas(self):+ """With include_schemas=true, schemas should be populated from block info."""+ session = make_session(user_id=_TEST_USER_ID)+ input_schema = {"properties": {"url": {"type": "string"}}, "required": ["url"]}+ output_schema = {"properties": {"result": {"type": "string"}}}++ search_results = [{"content_id": "block-1", "score": 0.9}]+ block = make_mock_block(+ "block-1",+ "Test Block",+ BlockType.STANDARD,+ input_schema=input_schema,+ output_schema=output_schema,+ static_output=True,+ )++ mock_search_db = MagicMock()+ mock_search_db.unified_hybrid_search = AsyncMock(+ return_value=(search_results, 1)+ )++ with (+ patch(+ "backend.copilot.tools.find_block.search",+ return_value=mock_search_db,+ ),+ patch(+ "backend.copilot.tools.find_block.get_block",+ return_value=block,+ ),+ ):+ tool = FindBlockTool()+ response = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ query="test",+ include_schemas=True,+ )++ assert isinstance(response, BlockListResponse)+ assert response.blocks[0].input_schema == input_schema+ assert response.blocks[0].output_schema == output_schema+ assert response.blocks[0].static_output is Truediff --git a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.pyindex 5b8d734ce6..f5964c8bbc 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py@@ -22,6 +22,9 @@ class FindLibraryAgentTool(BaseTool):"Search for or list agents in the user's library. Use this to find ""agents the user has already added to their library, including agents ""they created or added from the marketplace. "+ "When creating agents with sub-agent composition, use this to get "+ "the agent's graph_id, graph_version, input_schema, and output_schema "+ "needed for AgentExecutorBlock nodes. ""Omit the query to list all agents.")diff --git a/autogpt_platform/backend/backend/copilot/tools/fix_agent.py b/autogpt_platform/backend/backend/copilot/tools/fix_agent.pynew file mode 100644index 0000000000..c108b060d0--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/fix_agent.py@@ -0,0 +1,134 @@+"""FixAgentGraphTool - Auto-fixes common agent JSON issues."""++import logging+from typing import Any++from backend.copilot.model import ChatSession++from .agent_generator.validation import AgentFixer, AgentValidator, get_blocks_as_dicts+from .base import BaseTool+from .models import ErrorResponse, FixResultResponse, ToolResponseBase++logger = logging.getLogger(__name__)+++class FixAgentGraphTool(BaseTool):+ """Tool for auto-fixing common issues in agent JSON graphs."""++ @property+ def name(self) -> str:+ return "fix_agent_graph"++ @property+ def description(self) -> str:+ return (+ "Auto-fix common issues in an agent JSON graph. Applies fixes for:\n"+ "- Missing or invalid UUIDs on nodes and links\n"+ "- StoreValueBlock prerequisites for ConditionBlock\n"+ "- Double curly brace escaping in prompt templates\n"+ "- AddToList/AddToDictionary prerequisite blocks\n"+ "- CodeExecutionBlock output field naming\n"+ "- Missing credentials configuration\n"+ "- Node X coordinate spacing (800+ units apart)\n"+ "- AI model default parameters\n"+ "- Link static properties based on input schema\n"+ "- Type mismatches (inserts conversion blocks)\n\n"+ "Returns the fixed agent JSON plus a list of fixes applied. "+ "After fixing, the agent is re-validated. If still invalid, "+ "the remaining errors are included in the response."+ )++ @property+ def requires_auth(self) -> bool:+ return False++ @property+ def parameters(self) -> dict[str, Any]:+ return {+ "type": "object",+ "properties": {+ "agent_json": {+ "type": "object",+ "description": (+ "The agent JSON to fix. Must contain 'nodes' and 'links' arrays."+ ),+ },+ },+ "required": ["agent_json"],+ }++ async def _execute(+ self,+ user_id: str | None,+ session: ChatSession,+ **kwargs,+ ) -> ToolResponseBase:+ agent_json = kwargs.get("agent_json")+ session_id = session.session_id if session else None++ if not agent_json or not isinstance(agent_json, dict):+ return ErrorResponse(+ message="Please provide a valid agent JSON object.",+ error="Missing or invalid agent_json parameter",+ session_id=session_id,+ )++ nodes = agent_json.get("nodes", [])++ if not nodes:+ return ErrorResponse(+ message="The agent JSON has no nodes. An agent needs at least one block.",+ error="empty_agent",+ session_id=session_id,+ )++ try:+ blocks = get_blocks_as_dicts()+ fixer = AgentFixer()+ fixed_agent = fixer.apply_all_fixes(agent_json, blocks)+ fixes_applied = fixer.get_fixes_applied()+ except Exception as e:+ logger.error(f"Fixer error: {e}", exc_info=True)+ return ErrorResponse(+ message=f"Auto-fix encountered an error: {str(e)}",+ error="fix_exception",+ session_id=session_id,+ )++ # Re-validate after fixing+ try:+ validator = AgentValidator()+ is_valid, _ = validator.validate(fixed_agent, blocks)+ remaining_errors = validator.errors if not is_valid else []+ except Exception as e:+ logger.warning(f"Post-fix validation error: {e}", exc_info=True)+ remaining_errors = [f"Post-fix validation failed: {str(e)}"]+ is_valid = False++ if is_valid:+ return FixResultResponse(+ message=(+ f"Applied {len(fixes_applied)} fix(es). "+ "Agent graph is now valid!"+ ),+ fixed_agent_json=fixed_agent,+ fixes_applied=fixes_applied,+ fix_count=len(fixes_applied),+ valid_after_fix=True,+ remaining_errors=[],+ session_id=session_id,+ )++ return FixResultResponse(+ message=(+ f"Applied {len(fixes_applied)} fix(es), but "+ f"{len(remaining_errors)} issue(s) remain. "+ "Review the remaining errors and fix manually."+ ),+ fixed_agent_json=fixed_agent,+ fixes_applied=fixes_applied,+ fix_count=len(fixes_applied),+ valid_after_fix=False,+ remaining_errors=remaining_errors,+ session_id=session_id,+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/fix_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/fix_agent_test.pynew file mode 100644index 0000000000..5664471f07--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/fix_agent_test.py@@ -0,0 +1,189 @@+"""Tests for FixAgentGraphTool."""++from unittest.mock import MagicMock, patch++import pytest++from backend.copilot.tools.fix_agent import FixAgentGraphTool+from backend.copilot.tools.models import ErrorResponse, FixResultResponse++from ._test_data import make_session++_TEST_USER_ID = "test-user-fix-agent"+++def tool():+ return FixAgentGraphTool()+++def session():+ return make_session(_TEST_USER_ID)+++async def test_missing_agent_json_returns_error(tool, session):+ """Missing agent_json returns ErrorResponse."""+ result = await tool._execute(user_id=_TEST_USER_ID, session=session)+ assert isinstance(result, ErrorResponse)+ assert result.error is not None+ assert "agent_json" in result.error.lower()+++async def test_empty_nodes_returns_error(tool, session):+ """Agent JSON with no nodes returns ErrorResponse."""+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json={"nodes": [], "links": []},+ )+ assert isinstance(result, ErrorResponse)+ assert "no nodes" in result.message.lower()+++async def test_fix_and_validate_success(tool, session):+ """Fixer applies fixes and validator passes -> valid_after_fix=True."""+ agent_json = {+ "nodes": [+ {+ "id": "node-1",+ "block_id": "block-1",+ "input_default": {},+ "metadata": {"position": {"x": 0, "y": 0}},+ }+ ],+ "links": [],+ }++ fixed_agent = dict(agent_json) # Fixer returns the full agent dict++ mock_fixer = MagicMock()+ mock_fixer.apply_all_fixes = MagicMock(return_value=fixed_agent)+ mock_fixer.get_fixes_applied.return_value = ["Fixed node UUID format"]++ mock_validator = MagicMock()+ mock_validator.validate.return_value = (True, None)+ mock_validator.errors = []++ with (+ patch(+ "backend.copilot.tools.fix_agent.get_blocks_as_dicts",+ return_value=[],+ ),+ patch(+ "backend.copilot.tools.fix_agent.AgentFixer",+ return_value=mock_fixer,+ ),+ patch(+ "backend.copilot.tools.fix_agent.AgentValidator",+ return_value=mock_validator,+ ),+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json=agent_json,+ )++ assert isinstance(result, FixResultResponse)+ assert result.valid_after_fix is True+ assert result.fix_count == 1+ assert result.fixes_applied == ["Fixed node UUID format"]+ assert result.remaining_errors == []+++async def test_fix_with_remaining_errors(tool, session):+ """Fixer applies some fixes but validation still fails."""+ agent_json = {+ "nodes": [+ {+ "id": "node-1",+ "block_id": "block-1",+ "input_default": {},+ "metadata": {},+ }+ ],+ "links": [+ {+ "id": "link-1",+ "source_id": "node-1",+ "source_name": "output",+ "sink_id": "node-2",+ "sink_name": "input",+ }+ ],+ }++ fixed_agent = dict(agent_json)++ mock_fixer = MagicMock()+ mock_fixer.apply_all_fixes = MagicMock(return_value=fixed_agent)+ mock_fixer.get_fixes_applied.return_value = ["Fixed UUID"]++ mock_validator = MagicMock()+ mock_validator.validate.return_value = (+ False,+ "Link references non-existent node 'node-2'",+ )+ mock_validator.errors = ["Link references non-existent node 'node-2'"]++ with (+ patch(+ "backend.copilot.tools.fix_agent.get_blocks_as_dicts",+ return_value=[],+ ),+ patch(+ "backend.copilot.tools.fix_agent.AgentFixer",+ return_value=mock_fixer,+ ),+ patch(+ "backend.copilot.tools.fix_agent.AgentValidator",+ return_value=mock_validator,+ ),+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json=agent_json,+ )++ assert isinstance(result, FixResultResponse)+ assert result.valid_after_fix is False+ assert result.fix_count == 1+ assert len(result.remaining_errors) == 1+++async def test_fixer_exception_returns_error(tool, session):+ """Fixer exception returns ErrorResponse."""+ agent_json = {+ "nodes": [{"id": "n1", "block_id": "b1", "input_default": {}, "metadata": {}}],+ "links": [],+ }++ mock_fixer = MagicMock()+ mock_fixer.apply_all_fixes = MagicMock(side_effect=RuntimeError("fixer crashed"))++ with (+ patch(+ "backend.copilot.tools.fix_agent.get_blocks_as_dicts",+ return_value=[],+ ),+ patch(+ "backend.copilot.tools.fix_agent.AgentFixer",+ return_value=mock_fixer,+ ),+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json=agent_json,+ )++ assert isinstance(result, ErrorResponse)+ assert result.error is not None+ assert "fix_exception" in result.errordiff --git a/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide.py b/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide.pynew file mode 100644index 0000000000..018fd6df84--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide.py@@ -0,0 +1,84 @@+"""GetAgentBuildingGuideTool - Returns the complete agent building guide."""++import logging+from pathlib import Path+from typing import Any++from backend.copilot.model import ChatSession++from .base import BaseTool+from .models import ErrorResponse, ResponseType, ToolResponseBase++logger = logging.getLogger(__name__)++_GUIDE_CACHE: str | None = None+++def _load_guide() -> str:+ global _GUIDE_CACHE+ if _GUIDE_CACHE is None:+ guide_path = Path(__file__).parent.parent / "sdk" / "agent_generation_guide.md"+ _GUIDE_CACHE = guide_path.read_text(encoding="utf-8")+ return _GUIDE_CACHE+++class AgentBuildingGuideResponse(ToolResponseBase):+ """Response containing the agent building guide."""++ type: ResponseType = ResponseType.AGENT_BUILDER_GUIDE+ content: str+++class GetAgentBuildingGuideTool(BaseTool):+ """Returns the complete guide for building agent JSON graphs.++ Covers block IDs, link structure, AgentInputBlock, AgentOutputBlock,+ AgentExecutorBlock (sub-agent composition), and MCPToolBlock usage.+ """++ @property+ def name(self) -> str:+ return "get_agent_building_guide"++ @property+ def description(self) -> str:+ return (+ "Returns the complete guide for building agent JSON graphs, including "+ "block IDs, link structure, AgentInputBlock, AgentOutputBlock, "+ "AgentExecutorBlock (for sub-agent composition), and MCPToolBlock usage. "+ "Call this before generating agent JSON to ensure correct structure."+ )++ @property+ def parameters(self) -> dict[str, Any]:+ return {+ "type": "object",+ "properties": {},+ "required": [],+ }++ @property+ def requires_auth(self) -> bool:+ return False++ async def _execute(+ self,+ user_id: str | None,+ session: ChatSession,+ **kwargs,+ ) -> ToolResponseBase:+ session_id = session.session_id if session else None+ try:+ content = _load_guide()+ return AgentBuildingGuideResponse(+ message="Agent building guide loaded.",+ content=content,+ session_id=session_id,+ )+ except Exception as e:+ logger.error("Failed to load agent building guide: %s", e)+ return ErrorResponse(+ message="Failed to load agent building guide.",+ error=str(e),+ session_id=session_id,+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/get_mcp_guide.py b/autogpt_platform/backend/backend/copilot/tools/get_mcp_guide.pynew file mode 100644index 0000000000..eff118fa1b--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/get_mcp_guide.py@@ -0,0 +1,79 @@+"""GetMCPGuideTool - Returns the MCP tool usage guide."""++import logging+from pathlib import Path+from typing import Any++from backend.copilot.model import ChatSession++from .base import BaseTool+from .models import ErrorResponse, ResponseType, ToolResponseBase++logger = logging.getLogger(__name__)++_GUIDE_CACHE: str | None = None+++def _load_guide() -> str:+ global _GUIDE_CACHE+ if _GUIDE_CACHE is None:+ guide_path = Path(__file__).parent.parent / "sdk" / "mcp_tool_guide.md"+ _GUIDE_CACHE = guide_path.read_text(encoding="utf-8")+ return _GUIDE_CACHE+++class MCPGuideResponse(ToolResponseBase):+ """Response containing the MCP tool guide."""++ type: ResponseType = ResponseType.MCP_GUIDE+ content: str+++class GetMCPGuideTool(BaseTool):+ """Returns the MCP tool usage guide with known server URLs and auth details."""++ @property+ def name(self) -> str:+ return "get_mcp_guide"++ @property+ def description(self) -> str:+ return (+ "Returns the MCP tool guide: known hosted server URLs (Notion, Linear, "+ "Stripe, Intercom, Cloudflare, Atlassian) and authentication workflow. "+ "Call before using run_mcp_tool if you need a server URL or auth info."+ )++ @property+ def parameters(self) -> dict[str, Any]:+ return {+ "type": "object",+ "properties": {},+ "required": [],+ }++ @property+ def requires_auth(self) -> bool:+ return False++ async def _execute(+ self,+ user_id: str | None,+ session: ChatSession,+ **kwargs,+ ) -> ToolResponseBase:+ session_id = session.session_id if session else None+ try:+ content = _load_guide()+ return MCPGuideResponse(+ message="MCP guide loaded.",+ content=content,+ session_id=session_id,+ )+ except Exception as e:+ logger.error("Failed to load MCP guide: %s", e)+ return ErrorResponse(+ message="Failed to load MCP guide.",+ error=str(e),+ session_id=session_id,+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.pyindex 7f9ec019b5..c36b2b1d21 100644--- a/autogpt_platform/backend/backend/copilot/tools/models.py+++ b/autogpt_platform/backend/backend/copilot/tools/models.py@@ -12,56 +12,72 @@ from backend.data.model import CredentialsMetaInputclass ResponseType(str, Enum):"""Types of tool responses."""+ # General+ ERROR = "error"+ NO_RESULTS = "no_results"+ NEED_LOGIN = "need_login"++ # Agent discovery & executionAGENTS_FOUND = "agents_found"AGENT_DETAILS = "agent_details"SETUP_REQUIREMENTS = "setup_requirements"+ INPUT_VALIDATION_ERROR = "input_validation_error"EXECUTION_STARTED = "execution_started"- NEED_LOGIN = "need_login"- ERROR = "error"- NO_RESULTS = "no_results"AGENT_OUTPUT = "agent_output"UNDERSTANDING_UPDATED = "understanding_updated"- AGENT_PREVIEW = "agent_preview"- AGENT_SAVED = "agent_saved"- CLARIFICATION_NEEDED = "clarification_needed"+ SUGGESTED_GOAL = "suggested_goal"++ # Agent builder (create / edit / validate / fix)+ AGENT_BUILDER_GUIDE = "agent_builder_guide"+ AGENT_BUILDER_PREVIEW = "agent_builder_preview"+ AGENT_BUILDER_SAVED = "agent_builder_saved"+ AGENT_BUILDER_CLARIFICATION_NEEDED = "agent_builder_clarification_needed"+ AGENT_BUILDER_VALIDATION_RESULT = "agent_builder_validation_result"+ AGENT_BUILDER_FIX_RESULT = "agent_builder_fix_result"++ # BlockBLOCK_LIST = "block_list"BLOCK_DETAILS = "block_details"BLOCK_OUTPUT = "block_output"++ # MCP+ MCP_GUIDE = "mcp_guide"+ MCP_TOOLS_DISCOVERED = "mcp_tools_discovered"+ MCP_TOOL_OUTPUT = "mcp_tool_output"++ # DocsDOC_SEARCH_RESULTS = "doc_search_results"DOC_PAGE = "doc_page"- # Workspace response types++ # Workspace filesWORKSPACE_FILE_LIST = "workspace_file_list"WORKSPACE_FILE_CONTENT = "workspace_file_content"WORKSPACE_FILE_METADATA = "workspace_file_metadata"WORKSPACE_FILE_WRITTEN = "workspace_file_written"WORKSPACE_FILE_DELETED = "workspace_file_deleted"- # Long-running operation types- OPERATION_IN_PROGRESS = "operation_in_progress"- # Input validation- INPUT_VALIDATION_ERROR = "input_validation_error"- # Web fetch- WEB_FETCH = "web_fetch"- # Agent-browser multi-step automation (navigate, act, screenshot)++ # Folder management+ FOLDER_CREATED = "folder_created"+ FOLDER_LIST = "folder_list"+ FOLDER_UPDATED = "folder_updated"+ FOLDER_MOVED = "folder_moved"+ FOLDER_DELETED = "folder_deleted"+ AGENTS_MOVED_TO_FOLDER = "agents_moved_to_folder"++ # Browser automationBROWSER_NAVIGATE = "browser_navigate"BROWSER_ACT = "browser_act"BROWSER_SCREENSHOT = "browser_screenshot"+# Code executionBASH_EXEC = "bash_exec"- # Feature request types++ # Web+ WEB_FETCH = "web_fetch"++ # Feature requestsFEATURE_REQUEST_SEARCH = "feature_request_search"FEATURE_REQUEST_CREATED = "feature_request_created"- # Goal refinement- SUGGESTED_GOAL = "suggested_goal"- # MCP tool types- MCP_TOOLS_DISCOVERED = "mcp_tools_discovered"- MCP_TOOL_OUTPUT = "mcp_tool_output"- # Folder management types- FOLDER_CREATED = "folder_created"- FOLDER_LIST = "folder_list"- FOLDER_UPDATED = "folder_updated"- FOLDER_MOVED = "folder_moved"- FOLDER_DELETED = "folder_deleted"- AGENTS_MOVED_TO_FOLDER = "agents_moved_to_folder"# Base response model@@ -92,6 +108,15 @@ class AgentInfo(BaseModel):has_external_trigger: bool | None = Nonenew_output: bool | None = Nonegraph_id: str | None = None+ graph_version: int | None = None+ input_schema: dict[str, Any] | None = Field(+ default=None,+ description="JSON Schema for the agent's inputs (for AgentExecutorBlock)",+ )+ output_schema: dict[str, Any] | None = Field(+ default=None,+ description="JSON Schema for the agent's outputs (for AgentExecutorBlock)",+ )inputs: dict[str, Any] | None = Field(default=None,description="Input schema for the agent, including field names, types, and defaults",@@ -282,7 +307,7 @@ class ClarifyingQuestion(BaseModel):class AgentPreviewResponse(ToolResponseBase):"""Response for previewing a generated agent before saving."""- type: ResponseType = ResponseType.AGENT_PREVIEW+ type: ResponseType = ResponseType.AGENT_BUILDER_PREVIEWagent_json: dict[str, Any]agent_name: strdescription: str@@ -293,7 +318,7 @@ class AgentPreviewResponse(ToolResponseBase):class AgentSavedResponse(ToolResponseBase):"""Response when an agent is saved to the library."""- type: ResponseType = ResponseType.AGENT_SAVED+ type: ResponseType = ResponseType.AGENT_BUILDER_SAVEDagent_id: stragent_name: strlibrary_agent_id: str@@ -304,7 +329,7 @@ class AgentSavedResponse(ToolResponseBase):class ClarificationNeededResponse(ToolResponseBase):"""Response when the LLM needs more information from the user."""- type: ResponseType = ResponseType.CLARIFICATION_NEEDED+ type: ResponseType = ResponseType.AGENT_BUILDER_CLARIFICATION_NEEDEDquestions: list[ClarifyingQuestion] = Field(default_factory=list)@@ -381,6 +406,10 @@ class BlockInfoSummary(BaseModel):default_factory=dict,description="Full JSON schema for block outputs",)+ static_output: bool = Field(+ default=False,+ description="Whether the block produces output without needing input",+ )required_inputs: list[BlockInputFieldInfo] = Field(default_factory=list,description="List of input fields for this block",@@ -429,18 +458,6 @@ class BlockOutputResponse(ToolResponseBase):success: bool = True-# Long-running operation models-class OperationInProgressResponse(ToolResponseBase):- """Response when an operation is already in progress.-- Returned for idempotency when the same tool_call_id is requested again- while the background task is still running.- """-- type: ResponseType = ResponseType.OPERATION_IN_PROGRESS- tool_call_id: str--class WebFetchResponse(ToolResponseBase):"""Response for web_fetch tool."""@@ -548,6 +565,29 @@ class BrowserScreenshotResponse(ToolResponseBase):filename: str+# Agent generation tool response models+++class ValidationResultResponse(ToolResponseBase):+ """Response for validate_agent_graph tool."""++ type: ResponseType = ResponseType.AGENT_BUILDER_VALIDATION_RESULT+ valid: bool+ errors: list[str] = Field(default_factory=list)+ error_count: int = 0+++class FixResultResponse(ToolResponseBase):+ """Response for fix_agent_graph tool."""++ type: ResponseType = ResponseType.AGENT_BUILDER_FIX_RESULT+ fixed_agent_json: dict[str, Any]+ fixes_applied: list[str] = Field(default_factory=list)+ fix_count: int = 0+ valid_after_fix: bool = False+ remaining_errors: list[str] = Field(default_factory=list)++# Folder management modelsdiff --git a/autogpt_platform/backend/backend/copilot/tools/run_block.py b/autogpt_platform/backend/backend/copilot/tools/run_block.pyindex 1d99a10348..ab56a6a222 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_block.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_block.py@@ -7,7 +7,7 @@ from typing import Anyfrom pydantic_core import PydanticUndefined-from backend.blocks import get_block+from backend.blocks import BlockType, get_blockfrom backend.blocks._base import AnyBlockSchemafrom backend.copilot.model import ChatSessionfrom backend.data.db_accessors import workspace_db@@ -149,11 +149,18 @@ class RunBlockTool(BaseTool):block.block_type in COPILOT_EXCLUDED_BLOCK_TYPESor block.id in COPILOT_EXCLUDED_BLOCK_IDS):+ # Provide actionable guidance for blocks with dedicated tools+ if block.block_type == BlockType.MCP_TOOL:+ hint = (+ " Use the `run_mcp_tool` tool instead — it handles "+ "MCP server discovery, authentication, and execution."+ )+ elif block.block_type == BlockType.AGENT:+ hint = " Use the `run_agent` tool instead."+ else:+ hint = " This block is designed for use within graphs only."return ErrorResponse(- message=(- f"Block '{block.name}' cannot be run directly in CoPilot. "- "This block is designed for use within graphs only."- ),+ message=f"Block '{block.name}' cannot be run directly.{hint}",session_id=session_id,)diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.pyindex 7ab4d706a2..1ec82508b4 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py@@ -89,7 +89,7 @@ class TestRunBlockFiltering:)assert isinstance(response, ErrorResponse)- assert "cannot be run directly in CoPilot" in response.message+ assert "cannot be run directly" in response.messageassert "designed for use within graphs only" in response.message@pytest.mark.asyncio(loop_scope="session")@@ -115,7 +115,7 @@ class TestRunBlockFiltering:)assert isinstance(response, ErrorResponse)- assert "cannot be run directly in CoPilot" in response.message+ assert "cannot be run directly" in response.message@pytest.mark.asyncio(loop_scope="session")async def test_non_excluded_block_passes_guard(self):@@ -141,7 +141,7 @@ class TestRunBlockFiltering:# Should NOT be an ErrorResponse about CoPilot exclusion# (may be other errors like missing credentials, but not the exclusion guard)if isinstance(response, ErrorResponse):- assert "cannot be run directly in CoPilot" not in response.message+ assert "cannot be run directly" not in response.messageclass TestRunBlockInputValidation:diff --git a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.pyindex 25522a44ec..e8f9d3842c 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py@@ -53,15 +53,9 @@ class RunMCPToolTool(BaseTool):def description(self) -> str:return ("Connect to an MCP (Model Context Protocol) server to discover and execute its tools. "- "Two-step workflow: (1) Call with just `server_url` to discover available tools. "- "(2) Call again with `server_url`, `tool_name`, and `tool_arguments` to execute. "- "Known hosted servers (use directly): Notion (https://mcp.notion.com/mcp), "- "Linear (https://mcp.linear.app/mcp), Stripe (https://mcp.stripe.com), "- "Intercom (https://mcp.intercom.com/mcp), Cloudflare (https://mcp.cloudflare.com/mcp), "- "Atlassian/Jira (https://mcp.atlassian.com/mcp). "- "For other services, search the MCP registry at https://registry.modelcontextprotocol.io/. "- "Authentication: If the server requires credentials, user will be prompted to complete the MCP credential setup flow."- "Once connected and user confirms, retry the same call immediately."+ "Two-step: (1) call with server_url to list available tools, "+ "(2) call again with server_url + tool_name + tool_arguments to execute. "+ "Call get_mcp_guide for known server URLs and auth details.")@propertydiff --git a/autogpt_platform/backend/backend/copilot/tools/validate_agent.py b/autogpt_platform/backend/backend/copilot/tools/validate_agent.pynew file mode 100644index 0000000000..9367b4b48e--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/validate_agent.py@@ -0,0 +1,116 @@+"""ValidateAgentGraphTool - Validates agent JSON structure."""++import logging+from typing import Any++from backend.copilot.model import ChatSession++from .agent_generator.validation import AgentValidator, get_blocks_as_dicts+from .base import BaseTool+from .models import ErrorResponse, ToolResponseBase, ValidationResultResponse++logger = logging.getLogger(__name__)+++class ValidateAgentGraphTool(BaseTool):+ """Tool for validating agent JSON graphs."""++ @property+ def name(self) -> str:+ return "validate_agent_graph"++ @property+ def description(self) -> str:+ return (+ "Validate an agent JSON graph for correctness. Checks:\n"+ "- All block_ids reference real blocks\n"+ "- All links reference valid source/sink nodes and fields\n"+ "- Required input fields are wired or have defaults\n"+ "- Data types are compatible across links\n"+ "- Nested sink links use correct notation\n"+ "- Prompt templates use proper curly brace escaping\n"+ "- AgentExecutorBlock configurations are valid\n\n"+ "Call this after generating agent JSON to verify correctness. "+ "If validation fails, either fix issues manually based on the error "+ "descriptions, or call fix_agent_graph to auto-fix common problems."+ )++ @property+ def requires_auth(self) -> bool:+ return False++ @property+ def parameters(self) -> dict[str, Any]:+ return {+ "type": "object",+ "properties": {+ "agent_json": {+ "type": "object",+ "description": (+ "The agent JSON to validate. Must contain 'nodes' and 'links' arrays. "+ "Each node needs: id (UUID), block_id, input_default, metadata. "+ "Each link needs: id (UUID), source_id, source_name, sink_id, sink_name."+ ),+ },+ },+ "required": ["agent_json"],+ }++ async def _execute(+ self,+ user_id: str | None,+ session: ChatSession,+ **kwargs,+ ) -> ToolResponseBase:+ agent_json = kwargs.get("agent_json")+ session_id = session.session_id if session else None++ if not agent_json or not isinstance(agent_json, dict):+ return ErrorResponse(+ message="Please provide a valid agent JSON object.",+ error="Missing or invalid agent_json parameter",+ session_id=session_id,+ )++ nodes = agent_json.get("nodes", [])++ if not nodes:+ return ErrorResponse(+ message="The agent JSON has no nodes. An agent needs at least one block.",+ error="empty_agent",+ session_id=session_id,+ )++ try:+ blocks = get_blocks_as_dicts()+ validator = AgentValidator()+ is_valid, error_message = validator.validate(agent_json, blocks)+ except Exception as e:+ logger.error(f"Validation error: {e}", exc_info=True)+ return ErrorResponse(+ message=f"Validation encountered an error: {str(e)}",+ error="validation_exception",+ session_id=session_id,+ )++ if is_valid:+ return ValidationResultResponse(+ message="Agent graph is valid! No issues found.",+ valid=True,+ errors=[],+ error_count=0,+ session_id=session_id,+ )++ # Parse individual errors from the validator's error list+ errors = validator.errors if hasattr(validator, "errors") else []+ if not errors and error_message:+ errors = [error_message]++ return ValidationResultResponse(+ message=f"Found {len(errors)} validation error(s). Fix them and re-validate.",+ valid=False,+ errors=errors,+ error_count=len(errors),+ session_id=session_id,+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/validate_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/validate_agent_test.pynew file mode 100644index 0000000000..52b5ccc27d--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/validate_agent_test.py@@ -0,0 +1,160 @@+"""Tests for ValidateAgentGraphTool."""++from unittest.mock import MagicMock, patch++import pytest++from backend.copilot.tools.models import ErrorResponse, ValidationResultResponse+from backend.copilot.tools.validate_agent import ValidateAgentGraphTool++from ._test_data import make_session++_TEST_USER_ID = "test-user-validate-agent"+++def tool():+ return ValidateAgentGraphTool()+++def session():+ return make_session(_TEST_USER_ID)+++async def test_missing_agent_json_returns_error(tool, session):+ """Missing agent_json returns ErrorResponse."""+ result = await tool._execute(user_id=_TEST_USER_ID, session=session)+ assert isinstance(result, ErrorResponse)+ assert result.error is not None+ assert "agent_json" in result.error.lower()+++async def test_empty_nodes_returns_error(tool, session):+ """Agent JSON with no nodes returns ErrorResponse."""+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json={"nodes": [], "links": []},+ )+ assert isinstance(result, ErrorResponse)+ assert "no nodes" in result.message.lower()+++async def test_valid_agent_returns_success(tool, session):+ """Valid agent returns ValidationResultResponse with valid=True."""+ agent_json = {+ "nodes": [+ {+ "id": "node-1",+ "block_id": "block-1",+ "input_default": {},+ "metadata": {"position": {"x": 0, "y": 0}},+ }+ ],+ "links": [],+ }++ mock_validator = MagicMock()+ mock_validator.validate.return_value = (True, None)+ mock_validator.errors = []++ with (+ patch(+ "backend.copilot.tools.validate_agent.get_blocks_as_dicts",+ return_value=[],+ ),+ patch(+ "backend.copilot.tools.validate_agent.AgentValidator",+ return_value=mock_validator,+ ),+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json=agent_json,+ )++ assert isinstance(result, ValidationResultResponse)+ assert result.valid is True+ assert result.error_count == 0+ assert result.errors == []+++async def test_invalid_agent_returns_errors(tool, session):+ """Invalid agent returns ValidationResultResponse with errors."""+ agent_json = {+ "nodes": [+ {+ "id": "node-1",+ "block_id": "nonexistent-block",+ "input_default": {},+ "metadata": {},+ }+ ],+ "links": [],+ }++ mock_validator = MagicMock()+ mock_validator.validate.return_value = (False, "Validation failed")+ mock_validator.errors = [+ "Block 'nonexistent-block' not found in registry",+ "Missing required input field 'prompt'",+ ]++ with (+ patch(+ "backend.copilot.tools.validate_agent.get_blocks_as_dicts",+ return_value=[],+ ),+ patch(+ "backend.copilot.tools.validate_agent.AgentValidator",+ return_value=mock_validator,+ ),+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json=agent_json,+ )++ assert isinstance(result, ValidationResultResponse)+ assert result.valid is False+ assert result.error_count == 2+ assert len(result.errors) == 2+++async def test_validation_exception_returns_error(tool, session):+ """Validator exception returns ErrorResponse."""+ agent_json = {+ "nodes": [{"id": "n1", "block_id": "b1", "input_default": {}, "metadata": {}}],+ "links": [],+ }++ mock_validator = MagicMock()+ mock_validator.validate.side_effect = RuntimeError("unexpected error")++ with (+ patch(+ "backend.copilot.tools.validate_agent.get_blocks_as_dicts",+ return_value=[],+ ),+ patch(+ "backend.copilot.tools.validate_agent.AgentValidator",+ return_value=mock_validator,+ ),+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_json=agent_json,+ )++ assert isinstance(result, ErrorResponse)+ assert result.error is not None+ assert "validation_exception" in result.errordiff --git a/autogpt_platform/backend/backend/data/block.py b/autogpt_platform/backend/backend/data/block.pyindex a958011bc0..d7273aa059 100644--- a/autogpt_platform/backend/backend/data/block.py+++ b/autogpt_platform/backend/backend/data/block.py@@ -37,6 +37,7 @@ async def initialize_blocks() -> None:name=block.name,inputSchema=json.dumps(block.input_schema.jsonschema()),outputSchema=json.dumps(block.output_schema.jsonschema()),+ description=block.description,))return@@ -48,6 +49,7 @@ async def initialize_blocks() -> None:or block.name != existing_block.nameor input_schema != existing_block.inputSchemaor output_schema != existing_block.outputSchema+ or block.description != existing_block.description):await AgentBlock.prisma().update(where={"id": existing_block.id},@@ -56,6 +58,8 @@ async def initialize_blocks() -> None:"name": block.name,"inputSchema": input_schema,"outputSchema": output_schema,+ "description": block.description,+ "optimizedDescription": None,},)@@ -77,3 +81,45 @@ async def initialize_blocks() -> None:f"Failed to sync {len(failed_blocks)} block(s) to database: "f"{', '.join(failed_blocks)}. These blocks are still available in memory.")++ # Load optimized descriptions from DB onto block classes so that+ # every get_block() instance automatically carries them.+ try:+ all_db_blocks = await AgentBlock.prisma().find_many(+ where={"optimizedDescription": {"not": None}},+ )+ block_classes = get_blocks()+ applied = 0+ for db_block in all_db_blocks:+ if db_block.optimizedDescription and db_block.id in block_classes:+ block_classes[db_block.id]._optimized_description = (+ db_block.optimizedDescription+ )+ applied += 1+ if applied:+ logger.info("Loaded %d optimized block descriptions", applied)+ except Exception:+ logger.error("Could not load optimized descriptions", exc_info=True)+++async def get_blocks_needing_optimization() -> list[dict[str, str]]:+ """Return blocks that have a description but no optimized description yet."""+ blocks = await AgentBlock.prisma().find_many(+ where={+ "description": {"not": None},+ "optimizedDescription": None,+ },+ )+ return [+ {"id": b.id, "name": b.name, "description": b.description or ""} for b in blocks+ ]+++async def update_block_optimized_description(+ block_id: str, optimized_description: str+) -> None:+ """Store an LLM-optimized description for a block."""+ await AgentBlock.prisma().update(+ where={"id": block_id},+ data={"optimizedDescription": optimized_description},+ )diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex 9ffc50524d..4b3c01a816 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -39,6 +39,10 @@ from backend.data.analytics import (get_marketplace_graphs_for_monitoring,)from backend.data.auth.oauth import cleanup_expired_oauth_tokens+from backend.data.block import (+ get_blocks_needing_optimization,+ update_block_optimized_description,+)from backend.data.credit import UsageTransactionMetadata, get_user_credit_modelfrom backend.data.execution import (create_graph_execution,@@ -313,6 +317,10 @@ class DatabaseManager(AppService):get_business_understanding = _(get_business_understanding)upsert_business_understanding = _(upsert_business_understanding)+ # ============ Block Descriptions ============ #+ get_blocks_needing_optimization = _(get_blocks_needing_optimization)+ update_block_optimized_description = _(update_block_optimized_description)+# ============ CoPilot Chat Sessions ============ #get_chat_session = _(chat_db.get_chat_session)create_chat_session = _(chat_db.create_chat_session)@@ -379,6 +387,10 @@ class DatabaseManagerClient(AppServiceClient):backfill_missing_embeddings = _(d.backfill_missing_embeddings)cleanup_orphaned_embeddings = _(d.cleanup_orphaned_embeddings)+ # Block Descriptions+ get_blocks_needing_optimization = _(d.get_blocks_needing_optimization)+ update_block_optimized_description = _(d.update_block_optimized_description)+class DatabaseManagerAsyncClient(AppServiceClient):d = DatabaseManager@@ -495,6 +507,9 @@ class DatabaseManagerAsyncClient(AppServiceClient):get_business_understanding = d.get_business_understandingupsert_business_understanding = d.upsert_business_understanding+ # ============ Block Descriptions ============ #+ get_blocks_needing_optimization = d.get_blocks_needing_optimization+# ============ CoPilot Chat Sessions ============ #get_chat_session = d.get_chat_sessioncreate_chat_session = d.create_chat_sessiondiff --git a/autogpt_platform/backend/backend/data/tally.py b/autogpt_platform/backend/backend/data/tally.pyindex 306273ec3d..03c5d0d138 100644--- a/autogpt_platform/backend/backend/data/tally.py+++ b/autogpt_platform/backend/backend/data/tally.py@@ -14,6 +14,7 @@ from backend.data.understanding import (get_business_understanding,upsert_business_understanding,)+from backend.util.clients import OPENROUTER_BASE_URLfrom backend.util.request import Requestsfrom backend.util.settings import Settings@@ -347,7 +348,7 @@ async def extract_business_understanding("""settings = Settings()api_key = settings.secrets.open_router_api_key- client = AsyncOpenAI(api_key=api_key, base_url="https://openrouter.ai/api/v1")+ client = AsyncOpenAI(api_key=api_key, base_url=OPENROUTER_BASE_URL)try:response = await asyncio.wait_for(diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.pyindex 94829f9837..0d58f97575 100644--- a/autogpt_platform/backend/backend/executor/scheduler.py+++ b/autogpt_platform/backend/backend/executor/scheduler.py@@ -24,6 +24,7 @@ from dotenv import load_dotenvfrom pydantic import BaseModel, Field, ValidationErrorfrom sqlalchemy import MetaData, create_engine+from backend.copilot.optimize_blocks import optimize_block_descriptionsfrom backend.data.execution import GraphExecutionWithNodesfrom backend.data.model import CredentialsMetaInput, GraphInputfrom backend.executor import utils as execution_utils@@ -604,6 +605,19 @@ class Scheduler(AppService):jobstore=Jobstores.EXECUTION.value,)+ # Block Description Optimization - Every 24 hours+ # Generates concise LLM-optimized block descriptions for+ # agent generation. Only processes blocks missing descriptions.+ self.scheduler.add_job(+ optimize_block_descriptions,+ id="optimize_block_descriptions",+ trigger="interval",+ hours=24,+ replace_existing=True,+ max_instances=1,+ jobstore=Jobstores.EXECUTION.value,+ )+self.scheduler.add_listener(job_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)self.scheduler.add_listener(job_missed_listener, EVENT_JOB_MISSED)self.scheduler.add_listener(job_max_instances_listener, EVENT_JOB_MAX_INSTANCES)diff --git a/autogpt_platform/backend/backend/util/clients.py b/autogpt_platform/backend/backend/util/clients.pyindex ed884e9e6c..dfbec6101c 100644--- a/autogpt_platform/backend/backend/util/clients.py+++ b/autogpt_platform/backend/backend/util/clients.py@@ -7,6 +7,8 @@ from typing import TYPE_CHECKINGfrom backend.util.cache import cached, thread_cachedfrom backend.util.settings import Settings+OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"+settings = Settings()if TYPE_CHECKING:@@ -165,14 +167,20 @@ def get_openai_client() -> "AsyncOpenAI | None":"""Get a process-cached async OpenAI client for embeddings.- Returns None if API key is not configured.+ Prefers openai_internal_api_key (direct OpenAI). Falls back to+ open_router_api_key via OpenRouter's OpenAI-compatible endpoint.+ Returns None if neither key is configured."""from openai import AsyncOpenAI- api_key = settings.secrets.openai_internal_api_key- if not api_key:- return None- return AsyncOpenAI(api_key=api_key)+ if settings.secrets.openai_internal_api_key:+ return AsyncOpenAI(api_key=settings.secrets.openai_internal_api_key)+ if settings.secrets.open_router_api_key:+ return AsyncOpenAI(+ api_key=settings.secrets.open_router_api_key,+ base_url=OPENROUTER_BASE_URL,+ )+ return None# ============ Notification Queue Helpers ============ #diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex 35cf71c887..39ec1a0bc8 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -363,23 +363,6 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):description="Whether to mark failed scans as clean or not",)- agentgenerator_host: str = Field(- default="",- description="The host for the Agent Generator service (empty to use built-in)",- )- agentgenerator_port: int = Field(- default=8000,- description="The port for the Agent Generator service",- )- agentgenerator_timeout: int = Field(- default=1800,- description="The timeout in seconds for Agent Generator service requests (includes retries for rate limits)",- )- agentgenerator_use_dummy: bool = Field(- default=False,- description="Use dummy agent generator responses for testing (bypasses external service)",- )-enable_example_blocks: bool = Field(default=False,description="Whether to enable example blocks in production",diff --git a/autogpt_platform/backend/migrations/20260303120000_add_block_descriptions/migration.sql b/autogpt_platform/backend/migrations/20260303120000_add_block_descriptions/migration.sqlnew file mode 100644index 0000000000..8405e2f5c4--- /dev/null+++ b/autogpt_platform/backend/migrations/20260303120000_add_block_descriptions/migration.sql@@ -0,0 +1,3 @@+-- AlterTable+ALTER TABLE "AgentBlock" ADD COLUMN "description" TEXT,+ADD COLUMN "optimizedDescription" TEXT;diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex ed992ec20f..52c7df5cde 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -505,6 +505,11 @@ model AgentBlock {inputSchema StringoutputSchema String+ // Block description synced from Python block definitions.+ description String?+ // LLM-optimized description for agent generation (concise, actionable).+ optimizedDescription String?+// Prisma requires explicit back-references.ReferencedByAgentNode AgentNode[]}diff --git a/autogpt_platform/backend/test/agent_generator/test_core_integration.py b/autogpt_platform/backend/test/agent_generator/test_core_integration.pydeleted file mode 100644index 6e549630d1..0000000000--- a/autogpt_platform/backend/test/agent_generator/test_core_integration.py+++ /dev/null@@ -1,272 +0,0 @@-"""-Tests for the Agent Generator core module.--This test suite verifies that the core functions correctly delegate to-the external Agent Generator service.-"""--from unittest.mock import AsyncMock, patch--import pytest--from backend.copilot.tools.agent_generator import core-from backend.copilot.tools.agent_generator.core import AgentGeneratorNotConfiguredError---class TestServiceNotConfigured:- """Test that functions raise AgentGeneratorNotConfiguredError when service is not configured."""-- @pytest.mark.asyncio- async def test_decompose_goal_raises_when_not_configured(self):- """Test that decompose_goal raises error when service not configured."""- with patch.object(core, "is_external_service_configured", return_value=False):- with pytest.raises(AgentGeneratorNotConfiguredError):- await core.decompose_goal("Build a chatbot")-- @pytest.mark.asyncio- async def test_generate_agent_raises_when_not_configured(self):- """Test that generate_agent raises error when service not configured."""- with patch.object(core, "is_external_service_configured", return_value=False):- with pytest.raises(AgentGeneratorNotConfiguredError):- await core.generate_agent({"steps": []})-- @pytest.mark.asyncio- async def test_generate_agent_patch_raises_when_not_configured(self):- """Test that generate_agent_patch raises error when service not configured."""- with patch.object(core, "is_external_service_configured", return_value=False):- with pytest.raises(AgentGeneratorNotConfiguredError):- await core.generate_agent_patch("Add a node", {"nodes": []})---class TestDecomposeGoal:- """Test decompose_goal function service delegation."""-- @pytest.mark.asyncio- async def test_calls_external_service(self):- """Test that decompose_goal calls the external service."""- expected_result = {"type": "instructions", "steps": ["Step 1"]}-- with patch.object(- core, "is_external_service_configured", return_value=True- ), patch.object(- core, "decompose_goal_external", new_callable=AsyncMock- ) as mock_external:- mock_external.return_value = expected_result-- result = await core.decompose_goal("Build a chatbot")-- # library_agents defaults to None- mock_external.assert_called_once_with("Build a chatbot", "", None)- assert result == expected_result-- @pytest.mark.asyncio- async def test_passes_context_to_external_service(self):- """Test that decompose_goal passes context to external service."""- expected_result = {"type": "instructions", "steps": ["Step 1"]}-- with patch.object(- core, "is_external_service_configured", return_value=True- ), patch.object(- core, "decompose_goal_external", new_callable=AsyncMock- ) as mock_external:- mock_external.return_value = expected_result-- await core.decompose_goal("Build a chatbot", "Use Python")-- # library_agents defaults to None- mock_external.assert_called_once_with("Build a chatbot", "Use Python", None)-- @pytest.mark.asyncio- async def test_returns_none_on_service_failure(self):- """Test that decompose_goal returns None when external service fails."""- with patch.object(- core, "is_external_service_configured", return_value=True- ), patch.object(- core, "decompose_goal_external", new_callable=AsyncMock- ) as mock_external:- mock_external.return_value = None-- result = await core.decompose_goal("Build a chatbot")-- assert result is None---class TestGenerateAgent:- """Test generate_agent function service delegation."""-- @pytest.mark.asyncio- async def test_calls_external_service(self):- """Test that generate_agent calls the external service."""- expected_result = {"name": "Test Agent", "nodes": [], "links": []}-- with patch.object(- core, "is_external_service_configured", return_value=True- ), patch.object(- core, "generate_agent_external", new_callable=AsyncMock- ) as mock_external:- mock_external.return_value = expected_result-- instructions = {"type": "instructions", "steps": ["Step 1"]}- result = await core.generate_agent(instructions)-- mock_external.assert_called_once_with(instructions, None)- assert result is not None- assert result["name"] == "Test Agent"- assert "id" in result- assert result["version"] == 1- assert result["is_active"] is True-- @pytest.mark.asyncio- async def test_preserves_existing_id_and_version(self):- """Test that external service result preserves existing id and version."""- expected_result = {- "id": "existing-id",- "version": 3,- "is_active": False,- "name": "Test Agent",- }-- with patch.object(- core, "is_external_service_configured", return_value=True- ), patch.object(- core, "generate_agent_external", new_callable=AsyncMock- ) as mock_external:- mock_external.return_value = expected_result.copy()-- result = await core.generate_agent({"steps": []})-- assert result is not None- assert result["id"] == "existing-id"- assert result["version"] == 3- assert result["is_active"] is False-- @pytest.mark.asyncio- async def test_returns_none_when_external_service_fails(self):- """Test that generate_agent returns None when external service fails."""- with patch.object(- core, "is_external_service_configured", return_value=True- ), patch.object(- core, "generate_agent_external", new_callable=AsyncMock- ) as mock_external:- mock_external.return_value = None-- result = await core.generate_agent({"steps": []})-- assert result is None---class TestGenerateAgentPatch:- """Test generate_agent_patch function service delegation."""-- @pytest.mark.asyncio- async def test_calls_external_service(self):- """Test that generate_agent_patch calls the external service."""- expected_result = {"name": "Updated Agent", "nodes": [], "links": []}-- with patch.object(- core, "is_external_service_configured", return_value=True- ), patch.object(- core, "generate_agent_patch_external", new_callable=AsyncMock- ) as mock_external:- mock_external.return_value = expected_result-- current_agent = {"nodes": [], "links": []}- result = await core.generate_agent_patch("Add a node", current_agent)-- mock_external.assert_called_once_with("Add a node", current_agent, None)- assert result == expected_result-- @pytest.mark.asyncio- async def test_returns_clarifying_questions(self):- """Test that generate_agent_patch returns clarifying questions."""- expected_result = {- "type": "clarifying_questions",- "questions": [{"question": "What type of node?"}],- }-- with patch.object(- core, "is_external_service_configured", return_value=True- ), patch.object(- core, "generate_agent_patch_external", new_callable=AsyncMock- ) as mock_external:- mock_external.return_value = expected_result-- result = await core.generate_agent_patch("Add a node", {"nodes": []})-- assert result == expected_result-- @pytest.mark.asyncio- async def test_returns_none_when_external_service_fails(self):- """Test that generate_agent_patch returns None when service fails."""- with patch.object(- core, "is_external_service_configured", return_value=True- ), patch.object(- core, "generate_agent_patch_external", new_callable=AsyncMock- ) as mock_external:- mock_external.return_value = None-- result = await core.generate_agent_patch("Add a node", {"nodes": []})-- assert result is None---class TestJsonToGraph:- """Test json_to_graph function."""-- def test_converts_agent_json_to_graph(self):- """Test conversion of agent JSON to Graph model."""- agent_json = {- "id": "test-id",- "version": 2,- "is_active": True,- "name": "Test Agent",- "description": "A test agent",- "nodes": [- {- "id": "node1",- "block_id": "block1",- "input_default": {"key": "value"},- "metadata": {"x": 100},- }- ],- "links": [- {- "id": "link1",- "source_id": "node1",- "sink_id": "output",- "source_name": "result",- "sink_name": "input",- "is_static": False,- }- ],- }-- graph = core.json_to_graph(agent_json)-- assert graph.id == "test-id"- assert graph.version == 2- assert graph.is_active is True- assert graph.name == "Test Agent"- assert graph.description == "A test agent"- assert len(graph.nodes) == 1- assert graph.nodes[0].id == "node1"- assert graph.nodes[0].block_id == "block1"- assert len(graph.links) == 1- assert graph.links[0].source_id == "node1"-- def test_generates_ids_if_missing(self):- """Test that missing IDs are generated."""- agent_json = {- "name": "Test Agent",- "nodes": [{"block_id": "block1"}],- "links": [],- }-- graph = core.json_to_graph(agent_json)-- assert graph.id is not None- assert graph.nodes[0].id is not None---if __name__ == "__main__":- pytest.main([__file__, "-v"])diff --git a/autogpt_platform/backend/test/agent_generator/test_service.py b/autogpt_platform/backend/test/agent_generator/test_service.pydeleted file mode 100644index 587a64cbac..0000000000--- a/autogpt_platform/backend/test/agent_generator/test_service.py+++ /dev/null@@ -1,575 +0,0 @@-"""-Tests for the Agent Generator external service client.--This test suite verifies the external Agent Generator service integration,-including service detection, API calls, and error handling.-"""--from unittest.mock import AsyncMock, MagicMock, patch--import httpx-import pytest--from backend.copilot.tools.agent_generator import service---class TestServiceConfiguration:- """Test service configuration detection."""-- def setup_method(self):- """Reset settings singleton before each test."""- service._settings = None- service._client = None-- def test_external_service_not_configured_when_host_empty(self):- """Test that external service is not configured when host is empty."""- mock_settings = MagicMock()- mock_settings.config.agentgenerator_host = ""- mock_settings.config.agentgenerator_use_dummy = False-- with patch.object(service, "_get_settings", return_value=mock_settings):- assert service.is_external_service_configured() is False-- def test_external_service_configured_when_host_set(self):- """Test that external service is configured when host is set."""- mock_settings = MagicMock()- mock_settings.config.agentgenerator_host = "agent-generator.local"-- with patch.object(service, "_get_settings", return_value=mock_settings):- assert service.is_external_service_configured() is True-- def test_get_base_url(self):- """Test base URL construction."""- mock_settings = MagicMock()- mock_settings.config.agentgenerator_host = "agent-generator.local"- mock_settings.config.agentgenerator_port = 8000-- with patch.object(service, "_get_settings", return_value=mock_settings):- url = service._get_base_url()- assert url == "http://agent-generator.local:8000"---class TestDecomposeGoalExternal:- """Test decompose_goal_external function."""-- def setup_method(self):- """Reset client singleton before each test."""- service._settings = None- service._client = None-- @pytest.mark.asyncio- async def test_decompose_goal_returns_instructions(self):- """Test successful decomposition returning instructions."""- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "type": "instructions",- "steps": ["Step 1", "Step 2"],- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.decompose_goal_external("Build a chatbot")-- assert result == {"type": "instructions", "steps": ["Step 1", "Step 2"]}- mock_client.post.assert_called_once_with(- "/api/decompose-description", json={"description": "Build a chatbot"}- )-- @pytest.mark.asyncio- async def test_decompose_goal_returns_clarifying_questions(self):- """Test decomposition returning clarifying questions."""- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "type": "clarifying_questions",- "questions": ["What platform?", "What language?"],- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.decompose_goal_external("Build something")-- assert result == {- "type": "clarifying_questions",- "questions": ["What platform?", "What language?"],- }-- @pytest.mark.asyncio- async def test_decompose_goal_with_context(self):- """Test decomposition with additional context enriched into description."""- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "type": "instructions",- "steps": ["Step 1"],- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- await service.decompose_goal_external(- "Build a chatbot", context="Use Python"- )-- expected_description = (- "Build a chatbot\n\nAdditional context from user:\nUse Python"- )- mock_client.post.assert_called_once_with(- "/api/decompose-description",- json={"description": expected_description},- )-- @pytest.mark.asyncio- async def test_decompose_goal_returns_unachievable_goal(self):- """Test decomposition returning unachievable goal response."""- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "type": "unachievable_goal",- "reason": "Cannot do X",- "suggested_goal": "Try Y instead",- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.decompose_goal_external("Do something impossible")-- assert result == {- "type": "unachievable_goal",- "reason": "Cannot do X",- "suggested_goal": "Try Y instead",- }-- @pytest.mark.asyncio- async def test_decompose_goal_handles_http_error(self):- """Test decomposition handles HTTP errors gracefully."""- mock_response = MagicMock()- mock_response.status_code = 500- mock_client = AsyncMock()- mock_client.post.side_effect = httpx.HTTPStatusError(- "Server error", request=MagicMock(), response=mock_response- )-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.decompose_goal_external("Build a chatbot")-- assert result is not None- assert result.get("type") == "error"- assert result.get("error_type") == "http_error"- assert "Server error" in result.get("error", "")-- @pytest.mark.asyncio- async def test_decompose_goal_handles_request_error(self):- """Test decomposition handles request errors gracefully."""- mock_client = AsyncMock()- mock_client.post.side_effect = httpx.RequestError("Connection failed")-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.decompose_goal_external("Build a chatbot")-- assert result is not None- assert result.get("type") == "error"- assert result.get("error_type") == "connection_error"- assert "Connection failed" in result.get("error", "")-- @pytest.mark.asyncio- async def test_decompose_goal_handles_service_error(self):- """Test decomposition handles service returning error."""- mock_response = MagicMock()- mock_response.json.return_value = {- "success": False,- "error": "Internal error",- "error_type": "internal_error",- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.decompose_goal_external("Build a chatbot")-- assert result is not None- assert result.get("type") == "error"- assert result.get("error") == "Internal error"- assert result.get("error_type") == "internal_error"---class TestGenerateAgentExternal:- """Test generate_agent_external function."""-- def setup_method(self):- """Reset client singleton before each test."""- service._settings = None- service._client = None-- @pytest.mark.asyncio- async def test_generate_agent_success(self):- """Test successful agent generation."""- agent_json = {- "name": "Test Agent",- "nodes": [],- "links": [],- }- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "agent_json": agent_json,- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- instructions = {"type": "instructions", "steps": ["Step 1"]}-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.generate_agent_external(instructions)-- assert result == agent_json- mock_client.post.assert_called_once_with(- "/api/generate-agent", json={"instructions": instructions}- )-- @pytest.mark.asyncio- async def test_generate_agent_handles_error(self):- """Test agent generation handles errors gracefully."""- mock_client = AsyncMock()- mock_client.post.side_effect = httpx.RequestError("Connection failed")-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.generate_agent_external({"steps": []})-- assert result is not None- assert result.get("type") == "error"- assert result.get("error_type") == "connection_error"- assert "Connection failed" in result.get("error", "")---class TestGenerateAgentPatchExternal:- """Test generate_agent_patch_external function."""-- def setup_method(self):- """Reset client singleton before each test."""- service._settings = None- service._client = None-- @pytest.mark.asyncio- async def test_generate_patch_returns_updated_agent(self):- """Test successful patch generation returning updated agent."""- updated_agent = {- "name": "Updated Agent",- "nodes": [{"id": "1", "block_id": "test"}],- "links": [],- }- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "agent_json": updated_agent,- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- current_agent = {"name": "Old Agent", "nodes": [], "links": []}-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.generate_agent_patch_external(- "Add a new node", current_agent- )-- assert result == updated_agent- mock_client.post.assert_called_once_with(- "/api/update-agent",- json={- "update_request": "Add a new node",- "current_agent_json": current_agent,- },- )-- @pytest.mark.asyncio- async def test_generate_patch_returns_clarifying_questions(self):- """Test patch generation returning clarifying questions."""- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "type": "clarifying_questions",- "questions": ["What type of node?"],- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.generate_agent_patch_external(- "Add something", {"nodes": []}- )-- assert result == {- "type": "clarifying_questions",- "questions": ["What type of node?"],- }---class TestHealthCheck:- """Test health_check function."""-- def setup_method(self):- """Reset singletons before each test."""- service._settings = None- service._client = None-- @pytest.mark.asyncio- async def test_health_check_returns_false_when_not_configured(self):- """Test health check returns False when service not configured."""- with patch.object(- service, "is_external_service_configured", return_value=False- ):- result = await service.health_check()- assert result is False-- @pytest.mark.asyncio- async def test_health_check_returns_true_when_healthy(self):- """Test health check returns True when service is healthy."""- mock_response = MagicMock()- mock_response.json.return_value = {- "status": "healthy",- "blocks_loaded": True,- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.get.return_value = mock_response-- with patch.object(service, "is_external_service_configured", return_value=True):- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.health_check()-- assert result is True- mock_client.get.assert_called_once_with("/health")-- @pytest.mark.asyncio- async def test_health_check_returns_false_when_not_healthy(self):- """Test health check returns False when service is not healthy."""- mock_response = MagicMock()- mock_response.json.return_value = {- "status": "unhealthy",- "blocks_loaded": False,- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.get.return_value = mock_response-- with patch.object(service, "is_external_service_configured", return_value=True):- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.health_check()-- assert result is False-- @pytest.mark.asyncio- async def test_health_check_returns_false_on_error(self):- """Test health check returns False on connection error."""- mock_client = AsyncMock()- mock_client.get.side_effect = httpx.RequestError("Connection failed")-- with patch.object(service, "is_external_service_configured", return_value=True):- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.health_check()-- assert result is False---class TestGetBlocksExternal:- """Test get_blocks_external function."""-- def setup_method(self):- """Reset client singleton before each test."""- service._settings = None- service._client = None-- @pytest.mark.asyncio- async def test_get_blocks_success(self):- """Test successful blocks retrieval."""- blocks = [- {"id": "block1", "name": "Block 1"},- {"id": "block2", "name": "Block 2"},- ]- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "blocks": blocks,- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.get.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.get_blocks_external()-- assert result == blocks- mock_client.get.assert_called_once_with("/api/blocks")-- @pytest.mark.asyncio- async def test_get_blocks_handles_error(self):- """Test blocks retrieval handles errors gracefully."""- mock_client = AsyncMock()- mock_client.get.side_effect = httpx.RequestError("Connection failed")-- with patch.object(service, "_get_client", return_value=mock_client):- result = await service.get_blocks_external()-- assert result is None---class TestLibraryAgentsPassthrough:- """Test that library_agents are passed correctly in all requests."""-- def setup_method(self):- """Reset client singleton before each test."""- service._settings = None- service._client = None-- @pytest.mark.asyncio- async def test_decompose_goal_passes_library_agents(self):- """Test that library_agents are included in decompose goal payload."""- library_agents = [- {- "graph_id": "agent-123",- "graph_version": 1,- "name": "Email Sender",- "description": "Sends emails",- "input_schema": {"properties": {"to": {"type": "string"}}},- "output_schema": {"properties": {"sent": {"type": "boolean"}}},- },- ]-- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "type": "instructions",- "steps": ["Step 1"],- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- await service.decompose_goal_external(- "Send an email",- library_agents=library_agents,- )-- # Verify library_agents was passed in the payload- call_args = mock_client.post.call_args- assert call_args[1]["json"]["library_agents"] == library_agents-- @pytest.mark.asyncio- async def test_generate_agent_passes_library_agents(self):- """Test that library_agents are included in generate agent payload."""- library_agents = [- {- "graph_id": "agent-456",- "graph_version": 2,- "name": "Data Fetcher",- "description": "Fetches data from API",- "input_schema": {"properties": {"url": {"type": "string"}}},- "output_schema": {"properties": {"data": {"type": "object"}}},- },- ]-- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "agent_json": {"name": "Test Agent", "nodes": []},- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- await service.generate_agent_external(- {"steps": ["Step 1"]},- library_agents=library_agents,- )-- # Verify library_agents was passed in the payload- call_args = mock_client.post.call_args- assert call_args[1]["json"]["library_agents"] == library_agents-- @pytest.mark.asyncio- async def test_generate_agent_patch_passes_library_agents(self):- """Test that library_agents are included in patch generation payload."""- library_agents = [- {- "graph_id": "agent-789",- "graph_version": 1,- "name": "Slack Notifier",- "description": "Sends Slack messages",- "input_schema": {"properties": {"message": {"type": "string"}}},- "output_schema": {"properties": {"success": {"type": "boolean"}}},- },- ]-- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "agent_json": {"name": "Updated Agent", "nodes": []},- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- await service.generate_agent_patch_external(- "Add error handling",- {"name": "Original Agent", "nodes": []},- library_agents=library_agents,- )-- # Verify library_agents was passed in the payload- call_args = mock_client.post.call_args- assert call_args[1]["json"]["library_agents"] == library_agents-- @pytest.mark.asyncio- async def test_decompose_goal_without_library_agents(self):- """Test that decompose goal works without library_agents."""- mock_response = MagicMock()- mock_response.json.return_value = {- "success": True,- "type": "instructions",- "steps": ["Step 1"],- }- mock_response.raise_for_status = MagicMock()-- mock_client = AsyncMock()- mock_client.post.return_value = mock_response-- with patch.object(service, "_get_client", return_value=mock_client):- await service.decompose_goal_external("Build a workflow")-- # Verify library_agents was NOT passed when not provided- call_args = mock_client.post.call_args- assert "library_agents" not in call_args[1]["json"]---if __name__ == "__main__":- pytest.main([__file__, "-v"])diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.tsindex 9a1950d65a..006cbf2aa5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts@@ -35,10 +35,10 @@ const INTERACTIVE_RESPONSE_TYPES: ReadonlySet<string> = new Set([ResponseType.block_details,ResponseType.need_login,ResponseType.input_validation_error,- ResponseType.clarification_needed,+ ResponseType.agent_builder_clarification_needed,ResponseType.suggested_goal,- ResponseType.agent_preview,- ResponseType.agent_saved,+ ResponseType.agent_builder_preview,+ ResponseType.agent_builder_saved,]);export function isCompletedToolPart(part: MessagePart): part is ToolUIPart {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsxindex 8a9f2739fd..5f861bdeb7 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsx@@ -1133,7 +1133,7 @@ export default function StyleguidePage() {toolCallId: uid(),state: "output-available",output: {- type: ResponseType.agent_preview,+ type: ResponseType.agent_builder_preview,agent_name: "Email Summarizer",description:"An agent that summarizes your unread emails into a daily digest.",@@ -1161,7 +1161,7 @@ export default function StyleguidePage() {toolCallId: uid(),state: "output-available",output: {- type: ResponseType.agent_saved,+ type: ResponseType.agent_builder_saved,agent_id: "agent-789",agent_name: "Email Summarizer",library_agent_id: "lib-agent-789",@@ -1181,7 +1181,7 @@ export default function StyleguidePage() {toolCallId: uid(),state: "output-available",output: {- type: ResponseType.clarification_needed,+ type: ResponseType.agent_builder_clarification_needed,message:"I need a bit more information before creating this agent.",questions: [@@ -1255,7 +1255,7 @@ export default function StyleguidePage() {toolCallId: uid(),state: "output-available",output: {- type: ResponseType.agent_preview,+ type: ResponseType.agent_builder_preview,agent_name: "Email Summarizer v2",description:"Updated agent with improved summarization and Slack integration.",@@ -1285,7 +1285,7 @@ export default function StyleguidePage() {toolCallId: uid(),state: "output-available",output: {- type: ResponseType.agent_saved,+ type: ResponseType.agent_builder_saved,agent_id: "agent-789",agent_name: "Email Summarizer v2",library_agent_id: "lib-agent-789",@@ -1305,7 +1305,7 @@ export default function StyleguidePage() {toolCallId: uid(),state: "output-available",output: {- type: ResponseType.clarification_needed,+ type: ResponseType.agent_builder_clarification_needed,message:"I need to clarify a few things about the edits you want.",questions: [@@ -2066,7 +2066,7 @@ export default function StyleguidePage() {"An agent that checks website uptime",},output: {- type: ResponseType.agent_saved,+ type: ResponseType.agent_builder_saved,message: "Agent saved to your library!",agent_id: "graph-123",agent_name: "Website Uptime Checker",diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/helpers.tsxindex 2f0992793a..d8768808c4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/helpers.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/helpers.tsx@@ -33,9 +33,9 @@ function parseOutput(output: unknown): CreateAgentToolOutput | null {if (typeof output === "object") {const type = (output as { type?: unknown }).type;if (- type === ResponseType.agent_preview ||- type === ResponseType.agent_saved ||- type === ResponseType.clarification_needed ||+ type === ResponseType.agent_builder_preview ||+ type === ResponseType.agent_builder_saved ||+ type === ResponseType.agent_builder_clarification_needed ||type === ResponseType.suggested_goal ||type === ResponseType.error) {@@ -63,14 +63,17 @@ export function getCreateAgentToolOutput(export function isAgentPreviewOutput(output: CreateAgentToolOutput,): output is AgentPreviewResponse {- return output.type === ResponseType.agent_preview || "agent_json" in output;+ return (+ output.type === ResponseType.agent_builder_preview || "agent_json" in output+ );}export function isAgentSavedOutput(output: CreateAgentToolOutput,): output is AgentSavedResponse {return (- output.type === ResponseType.agent_saved || "agent_page_link" in output+ output.type === ResponseType.agent_builder_saved ||+ "agent_page_link" in output);}@@ -78,7 +81,8 @@ export function isClarificationNeededOutput(output: CreateAgentToolOutput,): output is ClarificationNeededResponse {return (- output.type === ResponseType.clarification_needed || "questions" in output+ output.type === ResponseType.agent_builder_clarification_needed ||+ "questions" in output);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/EditAgent/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/EditAgent/helpers.tsxindex 54465ccbe6..e57e9dedf6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/EditAgent/helpers.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/EditAgent/helpers.tsx@@ -31,9 +31,9 @@ function parseOutput(output: unknown): EditAgentToolOutput | null {if (typeof output === "object") {const type = (output as { type?: unknown }).type;if (- type === ResponseType.agent_preview ||- type === ResponseType.agent_saved ||- type === ResponseType.clarification_needed ||+ type === ResponseType.agent_builder_preview ||+ type === ResponseType.agent_builder_saved ||+ type === ResponseType.agent_builder_clarification_needed ||type === ResponseType.error) {return output as EditAgentToolOutput;@@ -59,14 +59,17 @@ export function getEditAgentToolOutput(export function isAgentPreviewOutput(output: EditAgentToolOutput,): output is AgentPreviewResponse {- return output.type === ResponseType.agent_preview || "agent_json" in output;+ return (+ output.type === ResponseType.agent_builder_preview || "agent_json" in output+ );}export function isAgentSavedOutput(output: EditAgentToolOutput,): output is AgentSavedResponse {return (- output.type === ResponseType.agent_saved || "agent_page_link" in output+ output.type === ResponseType.agent_builder_saved ||+ "agent_page_link" in output);}@@ -74,7 +77,8 @@ export function isClarificationNeededOutput(output: EditAgentToolOutput,): output is ClarificationNeededResponse {return (- output.type === ResponseType.clarification_needed || "questions" in output+ output.type === ResponseType.agent_builder_clarification_needed ||+ "questions" in output);}diff --git a/autogpt_platform/frontend/src/app/api/__generated__/models/responseType.ts b/autogpt_platform/frontend/src/app/api/__generated__/models/responseType.tsnew file mode 100644index 0000000000..ca49d639ae--- /dev/null+++ b/autogpt_platform/frontend/src/app/api/__generated__/models/responseType.ts@@ -0,0 +1,60 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * AutoGPT Agent Server+ * This server is used to execute agents that are created by the AutoGPT system.+ * OpenAPI spec version: 0.1+ */++/**+ * Types of tool responses.+ */+export type ResponseType = typeof ResponseType[keyof typeof ResponseType];+++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ResponseType = {+ error: 'error',+ no_results: 'no_results',+ need_login: 'need_login',+ agents_found: 'agents_found',+ agent_details: 'agent_details',+ setup_requirements: 'setup_requirements',+ input_validation_error: 'input_validation_error',+ execution_started: 'execution_started',+ agent_output: 'agent_output',+ understanding_updated: 'understanding_updated',+ suggested_goal: 'suggested_goal',+ agent_builder_guide: 'agent_builder_guide',+ agent_builder_preview: 'agent_builder_preview',+ agent_builder_saved: 'agent_builder_saved',+ agent_builder_clarification_needed: 'agent_builder_clarification_needed',+ agent_builder_validation_result: 'agent_builder_validation_result',+ agent_builder_fix_result: 'agent_builder_fix_result',+ block_list: 'block_list',+ block_details: 'block_details',+ block_output: 'block_output',+ mcp_guide: 'mcp_guide',+ mcp_tools_discovered: 'mcp_tools_discovered',+ mcp_tool_output: 'mcp_tool_output',+ doc_search_results: 'doc_search_results',+ doc_page: 'doc_page',+ workspace_file_list: 'workspace_file_list',+ workspace_file_content: 'workspace_file_content',+ workspace_file_metadata: 'workspace_file_metadata',+ workspace_file_written: 'workspace_file_written',+ workspace_file_deleted: 'workspace_file_deleted',+ folder_created: 'folder_created',+ folder_list: 'folder_list',+ folder_updated: 'folder_updated',+ folder_moved: 'folder_moved',+ folder_deleted: 'folder_deleted',+ agents_moved_to_folder: 'agents_moved_to_folder',+ browser_navigate: 'browser_navigate',+ browser_act: 'browser_act',+ browser_screenshot: 'browser_screenshot',+ bash_exec: 'bash_exec',+ web_fetch: 'web_fetch',+ feature_request_search: 'feature_request_search',+ feature_request_created: 'feature_request_created',+} as const;diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 8f2d734025..50edca37e0 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -7175,6 +7175,26 @@"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Graph Id"},+ "graph_version": {+ "anyOf": [{ "type": "integer" }, { "type": "null" }],+ "title": "Graph Version"+ },+ "input_schema": {+ "anyOf": [+ { "additionalProperties": true, "type": "object" },+ { "type": "null" }+ ],+ "title": "Input Schema",+ "description": "JSON Schema for the agent's inputs (for AgentExecutorBlock)"+ },+ "output_schema": {+ "anyOf": [+ { "additionalProperties": true, "type": "object" },+ { "type": "null" }+ ],+ "title": "Output Schema",+ "description": "JSON Schema for the agent's outputs (for AgentExecutorBlock)"+ },"inputs": {"anyOf": [{ "additionalProperties": true, "type": "object" },@@ -7241,7 +7261,7 @@"properties": {"type": {"$ref": "#/components/schemas/ResponseType",- "default": "agent_preview"+ "default": "agent_builder_preview"},"message": { "type": "string", "title": "Message" },"session_id": {@@ -7277,7 +7297,7 @@"properties": {"type": {"$ref": "#/components/schemas/ResponseType",- "default": "agent_saved"+ "default": "agent_builder_saved"},"message": { "type": "string", "title": "Message" },"session_id": {@@ -7732,6 +7752,12 @@"title": "Output Schema","description": "Full JSON schema for block outputs"},+ "static_output": {+ "type": "boolean",+ "title": "Static Output",+ "description": "Whether the block produces output without needing input",+ "default": false+ },"required_inputs": {"items": { "$ref": "#/components/schemas/BlockInputFieldInfo" },"type": "array",@@ -8107,7 +8133,7 @@"properties": {"type": {"$ref": "#/components/schemas/ResponseType",- "default": "clarification_needed"+ "default": "agent_builder_clarification_needed"},"message": { "type": "string", "title": "Message" },"session_id": {@@ -11511,21 +11537,29 @@"ResponseType": {"type": "string","enum": [+ "error",+ "no_results",+ "need_login","agents_found","agent_details","setup_requirements",+ "input_validation_error","execution_started",- "need_login",- "error",- "no_results","agent_output","understanding_updated",- "agent_preview",- "agent_saved",- "clarification_needed",+ "suggested_goal",+ "agent_builder_guide",+ "agent_builder_preview",+ "agent_builder_saved",+ "agent_builder_clarification_needed",+ "agent_builder_validation_result",+ "agent_builder_fix_result","block_list","block_details","block_output",+ "mcp_guide",+ "mcp_tools_discovered",+ "mcp_tool_output","doc_search_results","doc_page","workspace_file_list",@@ -11533,24 +11567,19 @@"workspace_file_metadata","workspace_file_written","workspace_file_deleted",- "operation_in_progress",- "input_validation_error",- "web_fetch",- "browser_navigate",- "browser_act",- "browser_screenshot",- "bash_exec",- "feature_request_search",- "feature_request_created",- "suggested_goal",- "mcp_tools_discovered",- "mcp_tool_output","folder_created","folder_list","folder_updated","folder_moved","folder_deleted",- "agents_moved_to_folder"+ "agents_moved_to_folder",+ "browser_navigate",+ "browser_act",+ "browser_screenshot",+ "bash_exec",+ "web_fetch",+ "feature_request_search",+ "feature_request_created"],"title": "ResponseType","description": "Types of tool responses."