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.
fix(backend/copilot): accept agent graph by reference so AutoPilot edits don't drop it (#13441)
Krzysztof Czerwinski45fc0716336f
diff --git a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.mdindex ebd604da38..bf1d570cef 100644--- a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md+++ b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md@@ -56,8 +56,12 @@ sampling (step 2), not by deliberation.English; put block class names and wiring verbs in the separate`block_name` and `action` fields.4. **If editing**: First narrow to the specific agent by UUID, then fetch its- graph: `find_library_agent(query="<agent_id>", include_graph=true)`. This- returns the full graph structure (nodes + links). **Never edit blindly** —+ graph: `find_library_agent(agent_id="<agent_id>",+ write_graph_to="agent.json")`. This writes the full graph (nodes + links)+ to a workspace file and returns an `@@agptfile` ref — inspect and edit the+ file with your file tools instead of pulling the whole graph through+ context. (`include_graph=true` returns it inline instead; only use that+ for small graphs.) **Never edit blindly** —always inspect the current graph first so you know exactly what to change.Avoid using `include_graph=true` with broad keyword searches, as fetchingmultiple graphs at once is expensive and consumes LLM context budget.diff --git a/autogpt_platform/backend/backend/copilot/sdk/file_ref.py b/autogpt_platform/backend/backend/copilot/sdk/file_ref.pyindex 73d8c48bf1..e0ccaee62d 100644--- a/autogpt_platform/backend/backend/copilot/sdk/file_ref.py+++ b/autogpt_platform/backend/backend/copilot/sdk/file_ref.py@@ -375,11 +375,22 @@ async def expand_file_refs_in_args(# define inner properties, skip expansion — the caller (e.g.# RunBlockTool) will expand with the actual nested schema.# ``type`` may be a union list, e.g. ["object", "string"] on- # ``agent_json`` parameters.- if prop_schema is not None and "properties" not in prop_schema:+ # ``agent_json`` parameters. Union object/string slots are the+ # "inline graph or file-ref" contract: an inline dict must pass+ # through untouched even when the schema carries decoder-guiding+ # ``properties`` — recursing would expand @@agptfile tokens found+ # inside graph metadata strings (name/description) and corrupt+ # them, or raise on ones that don't resolve.+ if prop_schema is not None:prop_type = prop_schema.get("type")- if prop_type == "object" or (+ is_object_typed = prop_type == "object" or (isinstance(prop_type, list) and "object" in prop_type+ )+ accepts_ref_string = (+ isinstance(prop_type, list) and "string" in prop_type+ )+ if is_object_typed and (+ "properties" not in prop_schema or accepts_ref_string):return valuenested_props = (prop_schema or {}).get("properties", {})diff --git a/autogpt_platform/backend/backend/copilot/sdk/file_ref_test.py b/autogpt_platform/backend/backend/copilot/sdk/file_ref_test.pyindex f876a0eec4..4432a882e6 100644--- a/autogpt_platform/backend/backend/copilot/sdk/file_ref_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/file_ref_test.py@@ -2033,3 +2033,36 @@ async def test_union_object_string_dict_skips_inner_expansion():input_schema=schema,)assert result["agent_json"] is agent+++async def test_union_object_string_dict_with_properties_skips_inner_expansion():+ """Same contract when the slot schema declares decoder-guiding+ ``properties`` (the structured AGENT_JSON_SCHEMA shape): an inline graph+ dict passes through untouched, so @@agptfile tokens inside metadata+ strings like name/description are never expanded or raised on."""+ from backend.copilot.tools.agent_json_input import AGENT_JSON_SCHEMA++ schema = {+ "type": "object",+ "properties": {"agent_json": AGENT_JSON_SCHEMA},+ "required": [],+ }+ agent = {+ "name": "Uses @@agptfile:/x.json in its name",+ "description": "@@agptfile:workspace:///notes.md",+ "nodes": [{"id": "n1", "input_default": {"prompt": "@@agptfile:/x.json"}}],+ "links": [],+ }++ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=AssertionError("should not be called")),+ ):+ result = await expand_file_refs_in_args(+ {"agent_json": agent},+ user_id="u1",+ session=_make_session(),+ input_schema=schema,+ )+ assert result["agent_json"] is agentdiff --git a/autogpt_platform/backend/backend/copilot/tools/agent_json_input.py b/autogpt_platform/backend/backend/copilot/tools/agent_json_input.pynew file mode 100644index 0000000000..1b7fc27768--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/agent_json_input.py@@ -0,0 +1,257 @@+"""Shared schema and input resolution for tools that take a full agent graph.++The full agent graph is the largest argument the assistant ever emits inline,+so on the SDK/OpenRouter path it is frequently truncated or dropped before the+tool ever runs (OPEN-3188). Two mitigations live here:++1. ``AGENT_JSON_SCHEMA`` — a *structured* object schema (``nodes``/``links``/…)+ instead of a bare ``{"type": "object"}``. Constrained tool-argument decoders+ need something to follow; an unconstrained object commonly collapses to+ ``{}`` or is omitted entirely.+2. ``agent_json_ref`` — a string parameter letting the model point at the+ workspace ``agent.json`` file it already wrote (see the agent-generation+ guide) instead of re-emitting the whole graph inline.++``resolve_agent_json_input`` accepts either form and returns the parsed graph,+working on both the SDK path (where the file-ref wrapper has already expanded a+``@@agptfile:`` token to file text) and the baseline path (where it has not).+``write_agent_json_to_workspace`` is the outbound counterpart: it writes a+graph to a workspace file and returns the ``@@agptfile:`` ref to hand back to+the model instead of the inline JSON.+"""++import json+import logging+import os+import re+from typing import Any++from backend.copilot.context import get_workspace_manager+from backend.copilot.model import ChatSession+from backend.copilot.sdk.file_ref import (+ FILE_REF_PREFIX,+ parse_file_ref,+ read_file_bytes,+)++from .models import ErrorResponse++logger = logging.getLogger(__name__)++# Structured (not bare ``{"type": "object"}``) so constrained tool-arg decoders+# have keys to follow instead of collapsing the value to ``{}``. Nested props are+# kept type-only to stay within the schema char budget. The ``string`` type is+# part of the contract: constrained decoders must be allowed to emit an+# ``@@agptfile:<path>`` reference here instead of the inline graph.+AGENT_JSON_SCHEMA: dict[str, Any] = {+ "type": ["object", "string"],+ "description": (+ "Full agent graph, or the string '@@agptfile:<path>' referencing a "+ "JSON file. For large/existing agents pass a file reference "+ "(or use agent_json_ref) instead of inlining the graph."+ ),+ "properties": {+ "id": {"type": "string"},+ "version": {"type": "integer"},+ "is_active": {"type": "boolean"},+ "name": {"type": "string"},+ "description": {"type": "string"},+ "nodes": {"type": "array", "items": {"type": "object"}},+ "links": {"type": "array", "items": {"type": "object"}},+ },+ "additionalProperties": True,+}++AGENT_JSON_REF_SCHEMA: dict[str, Any] = {+ "type": "string",+ "description": (+ "Workspace file holding the full agent graph (e.g. "+ "'workspace:///agent.json'). Use instead of agent_json for large/existing "+ "agents so the graph is loaded server-side, not re-emitted inline."+ ),+}+++async def resolve_agent_json_input(+ agent_json: Any,+ agent_json_ref: Any,+ user_id: str | None,+ session: ChatSession,+) -> tuple[dict[str, Any] | None, str | None]:+ """Resolve the agent graph from ``agent_json`` or ``agent_json_ref``.++ Returns ``(graph, None)`` on success or ``(None, error_message)`` when the+ input is missing or cannot be parsed. ``agent_json`` (inline) wins when both+ are supplied. A string ``agent_json`` that isn't inline JSON (e.g. a bare+ ``@@agptfile:`` token on the baseline path) is resolved as a file reference,+ same as ``agent_json_ref``. A returned ``(None, None)`` means neither+ argument carried a usable value — the caller decides which "missing" message+ to surface.+ """+ inline = _coerce_to_graph(agent_json)+ if inline is not None:+ return inline, None++ if isinstance(agent_json, str) and agent_json.strip():+ return await _resolve_ref(agent_json.strip(), user_id, session)++ if isinstance(agent_json_ref, str) and agent_json_ref.strip():+ return await _resolve_ref(agent_json_ref.strip(), user_id, session)++ return None, None+++async def resolve_agent_json_or_error(+ *,+ agent_json: Any,+ agent_json_ref: Any,+ user_id: str | None,+ session: ChatSession,+ session_id: str | None,+ missing_message: str,+ missing_error: str = "missing_agent_json",+ invalid_error: str = "invalid_agent_json",+) -> tuple[dict[str, Any] | None, ErrorResponse | None]:+ """Resolve the graph or build the tool-facing ``ErrorResponse``.++ Wraps :func:`resolve_agent_json_input` with the resolve-error / missing-input+ branching every agent-graph tool repeats. Returns ``(graph, None)`` on+ success or ``(None, error)`` ready to return from ``_execute``.+ """+ graph, resolve_error = await resolve_agent_json_input(+ agent_json, agent_json_ref, user_id, session+ )+ if resolve_error is not None:+ return None, ErrorResponse(+ message=resolve_error, error=invalid_error, session_id=session_id+ )+ if not graph:+ return None, ErrorResponse(+ message=missing_message, error=missing_error, session_id=session_id+ )+ return graph, None+++def _coerce_to_graph(value: Any) -> dict[str, Any] | None:+ """Return a graph dict from an inline object or stringified-JSON object."""+ if isinstance(value, dict) and value:+ return value+ if isinstance(value, str) and value.strip():+ parsed = _try_parse_json(value)+ if isinstance(parsed, dict) and parsed:+ return parsed+ return None+++async def _resolve_ref(+ ref: str, user_id: str | None, session: ChatSession+) -> tuple[dict[str, Any] | None, str | None]:+ """Load and parse an agent graph reference into a graph dict.++ Reached from ``agent_json_ref`` or from a string ``agent_json``. Handles+ three forms: already-expanded JSON text (SDK path), a bare ``@@agptfile:``+ token (baseline path), and a plain ``workspace://`` URI or filename.+ """+ # SDK path: the file-ref wrapper already expanded the token to file text.+ inline = _coerce_to_graph(ref)+ if inline is not None:+ return inline, None++ uri = _ref_to_uri(ref)+ if uri is None:+ return None, (+ f"Could not interpret agent graph reference "+ f"'{os.path.basename(ref)[:80]}' as a workspace file reference. "+ "Pass the agent graph inline as agent_json, or a "+ "'workspace:///agent.json' reference as agent_json_ref."+ )++ # Sanitize the reference in error messages so we never echo the raw+ # exception text or the full workspace/directory path back to the model.+ ref_name = os.path.basename(uri) or uri+ try:+ data = await read_file_bytes(uri, user_id, session)+ except ValueError:+ return None, f"Could not read referenced agent graph file '{ref_name}'."++ parsed = _try_parse_json(data.decode("utf-8", errors="replace"))+ if not isinstance(parsed, dict) or not parsed:+ return None, (+ f"Referenced agent graph file '{ref_name}' did not contain a JSON "+ "object. Ensure the file holds the full agent graph before "+ "referencing it."+ )+ return parsed, None+++def _ref_to_uri(ref: str) -> str | None:+ """Normalise an ``agent_json_ref`` value to a workspace URI.++ Only workspace references are accepted — ``agent_json_ref`` is meant to+ point at the workspace ``agent.json`` the assistant wrote. Absolute local /+ sandbox paths are rejected so this input can't be used to read arbitrary+ files. (A ``@@agptfile:`` token still routes through the audited file-ref+ resolver, which enforces its own path allow-list.)+ """+ if ref.startswith(FILE_REF_PREFIX):+ file_ref = parse_file_ref(ref)+ return file_ref.uri if file_ref is not None else None+ if ref.startswith("workspace://"):+ return ref+ if ref.startswith("/"):+ return None+ # Treat a bare value (e.g. "agent.json") as a workspace virtual path.+ return f"workspace:///{ref}"+++def _try_parse_json(text: str) -> Any:+ try:+ return json.loads(text)+ except (json.JSONDecodeError, ValueError):+ return None+++async def write_agent_json_to_workspace(+ agent_json: dict[str, Any],+ write_to: str,+ user_id: str | None,+ session_id: str | None,+ *,+ label: str,+ pass_to: str,+ fallback_note: str,+) -> tuple[str | None, str]:+ """Write an agent graph to a workspace file, pretty-printed.++ Returns ``(file reference to pass onward, message note)``. On any failure+ the reference is None and the note explains the fallback (``fallback_note``+ is the caller-specific "what to do instead" clause).+ """+ if not re.fullmatch(r"[\w][\w.-]*", write_to):+ # Don't echo the rejected value — it may carry directory structure.+ return None, (+ f" NOTE: write_to must be a plain filename without directories; "+ f"{fallback_note}"+ )+ if not user_id or not session_id:+ return None, (+ f" NOTE: write_to requires an authenticated session; {fallback_note}"+ )+ try:+ manager = await get_workspace_manager(user_id, session_id)+ rec = await manager.write_file(+ content=json.dumps(agent_json, indent=2).encode("utf-8"),+ filename=write_to,+ overwrite=True,+ metadata={"origin": "agent-created"},+ )+ except Exception as e:+ logger.warning(f"Failed to write agent JSON to {write_to!r}: {e}")+ return None, (+ f" NOTE: could not write {os.path.basename(write_to)}; {fallback_note}"+ )+ ref = f"{FILE_REF_PREFIX}workspace://{rec.path}"+ return ref, (+ f" {label} written to workspace file {rec.path} — pass "+ f'agent_json="{ref}" to {pass_to} (do not re-emit the JSON).'+ )diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_json_input_test.py b/autogpt_platform/backend/backend/copilot/tools/agent_json_input_test.pynew file mode 100644index 0000000000..e2404c235e--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/agent_json_input_test.py@@ -0,0 +1,227 @@+"""Tests for resolve_agent_json_input — the OPEN-3188 file-reference fallback.++The full agent graph is the largest argument the assistant emits inline, so it+is frequently truncated/dropped on the SDK path. These tests pin the two ways a+graph can now reach a tool: inline ``agent_json`` and a ``agent_json_ref``+pointing at a workspace file.+"""++import pytest++from backend.copilot.tools.agent_json_input import (+ AGENT_JSON_SCHEMA,+ resolve_agent_json_input,+ resolve_agent_json_or_error,+)+from backend.copilot.tools.models import ErrorResponse++from ._test_data import make_session++_USER_ID = "test-user-agent-json-input"+_MODULE = "backend.copilot.tools.agent_json_input"++_GRAPH = {"nodes": [{"id": "n1"}], "links": []}+++def test_schema_is_structured_not_bare_object():+ """The schema must describe nodes/links so decoders don't collapse it to {}."""+ props = AGENT_JSON_SCHEMA.get("properties", {})+ assert "nodes" in props+ assert "links" in props+ assert AGENT_JSON_SCHEMA.get("additionalProperties") is True+++async def test_inline_object_wins():+ session = make_session(_USER_ID)+ graph, err = await resolve_agent_json_input(_GRAPH, None, _USER_ID, session)+ assert err is None+ assert graph == _GRAPH+++async def test_inline_stringified_json_is_parsed():+ """Some models emit the object as a JSON string — accept that too."""+ session = make_session(_USER_ID)+ graph, err = await resolve_agent_json_input(+ '{"nodes": [{"id": "n1"}], "links": []}', None, _USER_ID, session+ )+ assert err is None+ assert graph == _GRAPH+++async def test_ref_already_expanded_to_text():+ """SDK path: the file-ref wrapper already turned the token into file text."""+ session = make_session(_USER_ID)+ graph, err = await resolve_agent_json_input(+ None, '{"nodes": [{"id": "n1"}], "links": []}', _USER_ID, session+ )+ assert err is None+ assert graph == _GRAPH+++async def test_ref_workspace_uri_is_read(mocker):+ """Baseline path: a plain workspace URI is read server-side and parsed."""+ session = make_session(_USER_ID)+ read = mocker.patch(+ f"{_MODULE}.read_file_bytes",+ return_value=b'{"nodes": [{"id": "n1"}], "links": []}',+ )+ graph, err = await resolve_agent_json_input(+ None, "workspace:///agent.json", _USER_ID, session+ )+ assert err is None+ assert graph == _GRAPH+ read.assert_awaited_once()+ assert read.call_args.args[0] == "workspace:///agent.json"+++async def test_ref_agptfile_token_is_read(mocker):+ """An unexpanded @@agptfile: token resolves to its URI before reading."""+ session = make_session(_USER_ID)+ read = mocker.patch(+ f"{_MODULE}.read_file_bytes",+ return_value=b'{"nodes": [{"id": "n1"}], "links": []}',+ )+ graph, err = await resolve_agent_json_input(+ None, "@@agptfile:workspace:///agent.json", _USER_ID, session+ )+ assert err is None+ assert graph == _GRAPH+ assert read.call_args.args[0] == "workspace:///agent.json"+++async def test_agent_json_string_agptfile_token_is_read(mocker):+ """An @@agptfile: token passed via agent_json itself (the flow the+ agent-generation guide documents) resolves like agent_json_ref."""+ session = make_session(_USER_ID)+ read = mocker.patch(+ f"{_MODULE}.read_file_bytes",+ return_value=b'{"nodes": [{"id": "n1"}], "links": []}',+ )+ graph, err = await resolve_agent_json_input(+ "@@agptfile:workspace:///agent.json", None, _USER_ID, session+ )+ assert err is None+ assert graph == _GRAPH+ assert read.call_args.args[0] == "workspace:///agent.json"+++async def test_bare_filename_becomes_workspace_path(mocker):+ session = make_session(_USER_ID)+ read = mocker.patch(+ f"{_MODULE}.read_file_bytes",+ return_value=b'{"nodes": [{"id": "n1"}], "links": []}',+ )+ await resolve_agent_json_input(None, "agent.json", _USER_ID, session)+ assert read.call_args.args[0] == "workspace:///agent.json"+++async def test_nothing_provided_returns_none_none():+ session = make_session(_USER_ID)+ graph, err = await resolve_agent_json_input(None, None, _USER_ID, session)+ assert graph is None+ assert err is None+++async def test_ref_file_read_error_is_sanitized(mocker):+ """Read failures must not leak the raw exception text or full path —+ only the basename is echoed back to the model."""+ session = make_session(_USER_ID)+ mocker.patch(+ f"{_MODULE}.read_file_bytes",+ side_effect=ValueError("File not found: workspace:///secret/dir/missing.json"),+ )+ graph, err = await resolve_agent_json_input(+ None, "workspace:///secret/dir/missing.json", _USER_ID, session+ )+ assert graph is None+ assert err is not None+ assert "missing.json" in err+ assert "secret/dir" not in err+ assert "File not found" not in err+++async def test_ref_absolute_local_path_is_rejected(mocker):+ """agent_json_ref must not be usable to read arbitrary local files."""+ session = make_session(_USER_ID)+ read = mocker.patch(f"{_MODULE}.read_file_bytes")+ graph, err = await resolve_agent_json_input(None, "/etc/passwd", _USER_ID, session)+ assert graph is None+ assert err is not None+ read.assert_not_called()+++async def test_or_error_returns_graph_on_success():+ session = make_session(_USER_ID)+ graph, err = await resolve_agent_json_or_error(+ agent_json=_GRAPH,+ agent_json_ref=None,+ user_id=_USER_ID,+ session=session,+ session_id="s1",+ missing_message="missing",+ )+ assert graph == _GRAPH+ assert err is None+++async def test_or_error_builds_missing_error_response():+ session = make_session(_USER_ID)+ graph, err = await resolve_agent_json_or_error(+ agent_json=None,+ agent_json_ref=None,+ user_id=_USER_ID,+ session=session,+ session_id="s1",+ missing_message="please provide it",+ missing_error="missing_agent_json",+ )+ assert graph is None+ assert isinstance(err, ErrorResponse)+ assert err.error == "missing_agent_json"+ assert err.message == "please provide it"+++async def test_or_error_builds_invalid_error_response(mocker):+ session = make_session(_USER_ID)+ mocker.patch(+ f"{_MODULE}.read_file_bytes",+ side_effect=ValueError("boom: /secret/path.json"),+ )+ graph, err = await resolve_agent_json_or_error(+ agent_json=None,+ agent_json_ref="workspace:///agent.json",+ user_id=_USER_ID,+ session=session,+ session_id="s1",+ missing_message="missing",+ invalid_error="invalid_agent_json",+ )+ assert graph is None+ assert isinstance(err, ErrorResponse)+ assert err.error == "invalid_agent_json"+ assert "/secret/path" not in err.message+++async def test_ref_file_non_object_errors(mocker):+ session = make_session(_USER_ID)+ mocker.patch(f"{_MODULE}.read_file_bytes", return_value=b"[1, 2, 3]")+ graph, err = await resolve_agent_json_input(+ None, "workspace:///agent.json", _USER_ID, session+ )+ assert graph is None+ assert err is not None+ assert "JSON object" in errdiff --git a/autogpt_platform/backend/backend/copilot/tools/create_agent.py b/autogpt_platform/backend/backend/copilot/tools/create_agent.pyindex d5f4914825..a874f509b7 100644--- a/autogpt_platform/backend/backend/copilot/tools/create_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/create_agent.py@@ -8,8 +8,13 @@ from backend.copilot.model import ChatSessionfrom backend.copilot.tracking import track_library_check_outcomefrom .agent_generator.pipeline import fetch_library_agents, fix_validate_and_save+from .agent_json_input import (+ AGENT_JSON_REF_SCHEMA,+ AGENT_JSON_SCHEMA,+ resolve_agent_json_or_error,+)from .base import BaseTool-from .helpers import coerce_agent_json, require_guide_read, require_library_check+from .helpers import require_guide_read, require_library_checkfrom .models import ErrorResponse, ToolResponseBaselogger = logging.getLogger(__name__)@@ -39,14 +44,8 @@ class CreateAgentTool(BaseTool):return {"type": "object","properties": {- "agent_json": {- "type": ["object", "string"],- "description": (- "Agent graph with 'nodes' and 'links' arrays, or the "- 'string "@@agptfile:<path>" to a JSON file '- "(preferred for large graphs)."- ),- },+ "agent_json": AGENT_JSON_SCHEMA,+ "agent_json_ref": AGENT_JSON_REF_SCHEMA,"library_agent_ids": {"type": "array","items": {"type": "string"},@@ -77,7 +76,7 @@ class CreateAgentTool(BaseTool):"default": False,},},- "required": ["agent_json"],+ "required": [],}async def _execute(@@ -85,6 +84,7 @@ class CreateAgentTool(BaseTool):user_id: str | None,session: ChatSession,agent_json: dict[str, Any] | str | None = None,+ agent_json_ref: str | None = None,save: bool = True,library_agent_ids: list[str] | None = None,folder_id: str | None = None,@@ -109,18 +109,22 @@ class CreateAgentTool(BaseTool):user_id=user_id, session_id=session_id, outcome="bypassed_ack")- agent_json = coerce_agent_json(agent_json)- if not agent_json:- return ErrorResponse(- message=(- "Please provide agent_json with the complete agent graph "- "as a JSON object, or as the string "- '"@@agptfile:<path>" referencing a JSON file. '- "Use find_block to discover blocks, then generate the JSON."- ),- error="missing_agent_json",- session_id=session_id,- )+ agent_json, resolve_error = await resolve_agent_json_or_error(+ agent_json=agent_json,+ agent_json_ref=agent_json_ref,+ user_id=user_id,+ session=session,+ session_id=session_id,+ missing_message=(+ "Please provide agent_json with the complete agent graph "+ '(inline or as an "@@agptfile:<path>" string), or '+ "agent_json_ref pointing at the workspace agent file. "+ "Use find_block to discover blocks, then generate the JSON."+ ),+ )+ if resolve_error is not None:+ return resolve_error+ assert agent_json is not None # narrowed: resolve_error covers the None caseif library_agent_ids is None:library_agent_ids = []diff --git a/autogpt_platform/backend/backend/copilot/tools/customize_agent.py b/autogpt_platform/backend/backend/copilot/tools/customize_agent.pyindex d4c7a36930..770deccfd2 100644--- a/autogpt_platform/backend/backend/copilot/tools/customize_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/customize_agent.py@@ -7,6 +7,11 @@ from typing import Anyfrom backend.copilot.model import ChatSessionfrom .agent_generator.pipeline import fetch_library_agents, fix_validate_and_save+from .agent_json_input import (+ AGENT_JSON_REF_SCHEMA,+ AGENT_JSON_SCHEMA,+ resolve_agent_json_or_error,+)from .base import BaseToolfrom .models import ErrorResponse, ToolResponseBase@@ -35,10 +40,8 @@ class CustomizeAgentTool(BaseTool):return {"type": "object","properties": {- "agent_json": {- "type": "object",- "description": "Customized agent JSON with nodes and links.",- },+ "agent_json": AGENT_JSON_SCHEMA,+ "agent_json_ref": AGENT_JSON_REF_SCHEMA,"library_agent_ids": {"type": "array","items": {"type": "string"},@@ -54,14 +57,15 @@ class CustomizeAgentTool(BaseTool):"description": "Folder ID to save into (default: root).",},},- "required": ["agent_json"],+ "required": [],}async def _execute(self,user_id: str | None,session: ChatSession,- agent_json: dict[str, Any] | None = None,+ agent_json: dict[str, Any] | str | None = None,+ agent_json_ref: str | None = None,save: bool = True,library_agent_ids: list[str] | None = None,folder_id: str | None = None,@@ -69,14 +73,20 @@ class CustomizeAgentTool(BaseTool):) -> ToolResponseBase:session_id = session.session_id if session else None- if not agent_json:- return ErrorResponse(- message=(- "Please provide agent_json with the complete customized agent graph."- ),- error="missing_agent_json",- session_id=session_id,- )+ agent_json, resolve_error = await resolve_agent_json_or_error(+ agent_json=agent_json,+ agent_json_ref=agent_json_ref,+ user_id=user_id,+ session=session,+ session_id=session_id,+ missing_message=(+ "Please provide agent_json with the complete customized agent "+ "graph, or agent_json_ref pointing at the workspace agent file."+ ),+ )+ if resolve_error is not None:+ return resolve_error+ assert agent_json is not None # narrowed: resolve_error covers the None caseif library_agent_ids is None:library_agent_ids = []diff --git a/autogpt_platform/backend/backend/copilot/tools/edit_agent.py b/autogpt_platform/backend/backend/copilot/tools/edit_agent.pyindex fcbdeeee88..bc2a66507e 100644--- a/autogpt_platform/backend/backend/copilot/tools/edit_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/edit_agent.py@@ -9,8 +9,13 @@ from backend.data.model import is_credentials_field_namefrom .agent_generator import get_agent_as_jsonfrom .agent_generator.pipeline import fetch_library_agents, fix_validate_and_save+from .agent_json_input import (+ AGENT_JSON_REF_SCHEMA,+ AGENT_JSON_SCHEMA,+ resolve_agent_json_or_error,+)from .base import BaseTool-from .helpers import coerce_agent_json, require_guide_read+from .helpers import require_guide_readfrom .models import ErrorResponse, ToolResponseBaselogger = logging.getLogger(__name__)@@ -43,14 +48,8 @@ class EditAgentTool(BaseTool):"type": "string","description": "Graph ID or library agent ID to edit.",},- "agent_json": {- "type": ["object", "string"],- "description": (- "Updated agent JSON with nodes and links, or the "- 'string "@@agptfile:<path>" to a JSON file '- "(preferred for large graphs)."- ),- },+ "agent_json": AGENT_JSON_SCHEMA,+ "agent_json_ref": AGENT_JSON_REF_SCHEMA,"library_agent_ids": {"type": "array","items": {"type": "string"},@@ -62,7 +61,7 @@ class EditAgentTool(BaseTool):"default": True,},},- "required": ["agent_id", "agent_json"],+ "required": ["agent_id"],}async def _execute(@@ -71,6 +70,7 @@ class EditAgentTool(BaseTool):session: ChatSession,agent_id: str = "",agent_json: dict[str, Any] | str | None = None,+ agent_json_ref: str | None = None,save: bool = True,library_agent_ids: list[str] | None = None,**kwargs,@@ -109,17 +109,21 @@ class EditAgentTool(BaseTool):session_id=session_id,)- agent_json = coerce_agent_json(agent_json)- if not agent_json:- return ErrorResponse(- message=(- "Please provide agent_json with the complete updated agent "- "graph as a JSON object, or as the string "- '"@@agptfile:<path>" referencing a JSON file.'- ),- error="missing_agent_json",- session_id=session_id,- )+ agent_json, resolve_error = await resolve_agent_json_or_error(+ agent_json=agent_json,+ agent_json_ref=agent_json_ref,+ user_id=user_id,+ session=session,+ session_id=session_id,+ missing_message=(+ "Please provide agent_json with the complete updated agent "+ 'graph (inline or as an "@@agptfile:<path>" string), or '+ "agent_json_ref pointing at the workspace agent file."+ ),+ )+ if resolve_error is not None:+ return resolve_error+ assert agent_json is not None # narrowed: resolve_error covers the None casenodes = agent_json.get("nodes", [])if not nodes:diff --git a/autogpt_platform/backend/backend/copilot/tools/edit_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/edit_agent_test.pyindex 0fc57d251e..14fbadb108 100644--- a/autogpt_platform/backend/backend/copilot/tools/edit_agent_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/edit_agent_test.py@@ -220,6 +220,58 @@ async def test_execute_blocks_trigger_config_edit(tool, mocker) -> None:assert "setup_agent_webhook_trigger" in result.message+async def test_edit_accepts_agent_json_ref(tool, mocker) -> None:+ """OPEN-3188: the graph may arrive via agent_json_ref (a workspace file)+ instead of inline agent_json, so a dropped/truncated inline object no longer+ blocks the edit."""+ session = make_session(_USER_ID)+ session.metadata = ChatSessionMetadata(builder_graph_id="graph-x")++ mocker.patch(+ f"{_EDIT_MODULE}.get_agent_as_json",+ return_value={"id": "graph-x", "version": 3, "nodes": [{"id": "n1"}]},+ )+ mocker.patch(f"{_EDIT_MODULE}.fetch_library_agents", return_value=[])+ sentinel = ErrorResponse(message="pipeline-reached", error="sentinel")+ saved = mocker.patch(f"{_EDIT_MODULE}.fix_validate_and_save", return_value=sentinel)+ # The referenced workspace file holds the full graph.+ mocker.patch(+ "backend.copilot.tools.agent_json_input.read_file_bytes",+ return_value=b'{"nodes": [{"id": "n1"}], "links": []}',+ )++ result = await tool._execute(+ user_id=_USER_ID,+ session=session,+ agent_id="graph-x",+ agent_json=None,+ agent_json_ref="workspace:///agent.json",+ )++ assert result is sentinel+ saved.assert_called_once()+++async def test_edit_missing_both_inputs_errors(tool) -> None:+ """With neither agent_json nor agent_json_ref, the edit reports the graph+ is missing rather than crashing."""+ session = make_session(_USER_ID)+ session.metadata = ChatSessionMetadata(builder_graph_id="graph-x")++ result = await tool._execute(+ user_id=_USER_ID,+ session=session,+ agent_id="graph-x",+ agent_json=None,+ agent_json_ref=None,+ )++ assert isinstance(result, ErrorResponse)+ assert result.error == "missing_agent_json"++@pytest.mark.asyncioasync def test_execute_allows_non_trigger_edit(tool, mocker) -> None:"""An edit that leaves trigger config untouched flows past the guard intodiff --git a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.pyindex f97465a1a4..4f69627e1a 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py@@ -4,13 +4,15 @@ from typing import Anyfrom backend.copilot.model import ChatSession+from .agent_generator import get_agent_as_json+from .agent_json_input import write_agent_json_to_workspacefrom .agent_search import (lookup_library_agent_by_id,search_agents,search_library_for_creation,)from .base import BaseTool-from .models import ToolResponseBase+from .models import AgentsFoundResponse, ErrorResponse, ToolResponseBaseclass FindLibraryAgentTool(BaseTool):@@ -54,6 +56,17 @@ class FindLibraryAgentTool(BaseTool):),"default": False,},+ "write_graph_to": {+ "type": "string",+ "description": (+ "Workspace filename (no directories) to write the "+ "agent's full graph JSON to (pretty-printed, "+ "overwrites) instead of returning it inline. Requires "+ "agent_id. The response includes an @@agptfile ref to "+ "pass to edit_agent — avoids pulling a large graph "+ "through context when editing an existing agent."+ ),+ },"for_creation": {"type": "boolean","description": "Pre-create similarity check.",@@ -80,6 +93,7 @@ class FindLibraryAgentTool(BaseTool):query: str = "",agent_id: str = "",include_graph: bool = False,+ write_graph_to: str = "",for_creation: bool = False,goal_summary: str = "",**kwargs,@@ -92,13 +106,29 @@ class FindLibraryAgentTool(BaseTool):session_id=session.session_id,user_id=user_id,)+ write_graph_to = write_graph_to.strip()+ if write_graph_to and not agent_id.strip():+ return ErrorResponse(+ message=(+ "write_graph_to requires agent_id — pass the library agent "+ "or graph id whose graph should be written to the file."+ ),+ error="missing_agent_id",+ session_id=session.session_id,+ )if agent_id := agent_id.strip():- return await lookup_library_agent_by_id(+ result = await lookup_library_agent_by_id(agent_id=agent_id,session_id=session.session_id,user_id=user_id,- include_graph=include_graph,+ include_graph=include_graph and not write_graph_to,)+ if write_graph_to and isinstance(result, AgentsFoundResponse):+ note = await _write_graph_note(+ agent_id, write_graph_to, user_id, session.session_id+ )+ result.message = f"{result.message}\n\n{note.strip()}"+ return resultreturn await search_agents(query=query.strip(),source="library",@@ -106,3 +136,34 @@ class FindLibraryAgentTool(BaseTool):user_id=user_id,include_graph=include_graph,)+++async def _write_graph_note(+ agent_id: str, write_to: str, user_id: str | None, session_id: str | None+) -> str:+ """Write the agent's graph to a workspace file; return the message note.++ The note either carries the @@agptfile ref to pass to edit_agent, or+ explains why the write failed and what to do instead. Never raises —+ the agent lookup already succeeded, so a graph-write hiccup must degrade+ to a note on that result, not replace it with a generic tool error.+ """+ try:+ agent_json = await get_agent_as_json(agent_id, user_id)+ except Exception:+ agent_json = None+ if agent_json is None:+ return (+ "NOTE: could not load the agent's graph to write it to a file; "+ "retry with include_graph=true to inspect it inline."+ )+ _ref, note = await write_agent_json_to_workspace(+ agent_json,+ write_to,+ user_id,+ session_id,+ label="Agent graph",+ pass_to="edit_agent / validate_agent_graph",+ fallback_note="retry with include_graph=true to inspect the graph inline.",+ )+ return notediff --git a/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.pyindex 4962eafa53..694ca42a63 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py@@ -288,3 +288,171 @@ async def test_missing_user_returns_error(tool, session):)assert isinstance(result, ErrorResponse)+++def _write_graph_patches(lib_db, graph_json):+ """Patches for the agent_id + write_graph_to flow."""+ mock_record = MagicMock()+ mock_record.path = "/agent.json"+ mock_manager = MagicMock()+ mock_manager.write_file = AsyncMock(return_value=mock_record)+ return (+ mock_manager,+ patch("backend.copilot.tools.agent_search.library_db", return_value=lib_db),+ patch(+ "backend.copilot.tools.find_library_agent.get_agent_as_json",+ new=AsyncMock(return_value=graph_json),+ ),+ patch(+ "backend.copilot.tools.agent_json_input.get_workspace_manager",+ new=AsyncMock(return_value=mock_manager),+ ),+ )+++def _lookup_lib_db() -> MagicMock:+ lib_db = MagicMock()+ lib_db.get_library_agent_by_graph_id = AsyncMock(return_value=None)+ lib_db.get_library_agent = AsyncMock(+ return_value=_mock_library_agent("lib-1", "Weather Bot")+ )+ return lib_db+++async def test_write_graph_to_returns_file_ref_not_inline_graph(tool, session):+ """write_graph_to writes the graph to a workspace file and puts an+ @@agptfile ref in the message instead of inlining the graph."""+ graph = {"nodes": [{"id": "n1"}], "links": []}+ manager, p1, p2, p3 = _write_graph_patches(_lookup_lib_db(), graph)++ with p1, p2, p3:+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_id="lib-1",+ write_graph_to="agent.json",+ )++ assert isinstance(result, AgentsFoundResponse)+ assert "@@agptfile:workspace:///agent.json" in result.message+ assert result.agents[0].graph is None++ written = manager.write_file.call_args.kwargs+ assert written["filename"] == "agent.json"+ assert written["overwrite"] is True+ assert b'\n "nodes"' in written["content"] # pretty-printed+++async def test_write_graph_to_suppresses_include_graph(tool, session):+ """include_graph is ignored when the graph goes to a file — the point is+ to keep the graph out of context."""+ graph = {"nodes": [{"id": "n1"}], "links": []}+ manager, p1, p2, p3 = _write_graph_patches(_lookup_lib_db(), graph)++ with (+ p1,+ p2,+ p3,+ patch(+ "backend.copilot.tools.agent_search._enrich_agents_with_graph",+ new=AsyncMock(return_value=None),+ ) as enrich,+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_id="lib-1",+ include_graph=True,+ write_graph_to="agent.json",+ )++ assert isinstance(result, AgentsFoundResponse)+ enrich.assert_not_awaited()+ manager.write_file.assert_awaited_once()+++async def test_write_graph_to_unloadable_graph_notes_fallback(tool, session):+ """When the graph can't be loaded for writing, the response still carries+ the agent info plus a note steering to include_graph=true."""+ manager, p1, p2, p3 = _write_graph_patches(_lookup_lib_db(), None)++ with p1, p2, p3:+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_id="lib-1",+ write_graph_to="agent.json",+ )++ assert isinstance(result, AgentsFoundResponse)+ assert "could not load" in result.message+ assert "include_graph=true" in result.message+ manager.write_file.assert_not_awaited()+++async def test_write_graph_to_without_agent_id_is_rejected(tool, session):+ """write_graph_to must not be silently discarded on the search path."""+ with patch(+ "backend.copilot.tools.find_library_agent.search_agents",+ new=AsyncMock(),+ ) as mock_search:+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ query="weather",+ write_graph_to="agent.json",+ )++ assert isinstance(result, ErrorResponse)+ assert "agent_id" in result.message+ mock_search.assert_not_awaited()+++async def test_write_graph_to_loader_exception_notes_fallback(tool, session):+ """An exception while loading the graph degrades to the fallback note —+ the successful lookup result must not be replaced by a generic error."""+ manager, p1, p2, p3 = _write_graph_patches(_lookup_lib_db(), None)++ with (+ p1,+ p3,+ patch(+ "backend.copilot.tools.find_library_agent.get_agent_as_json",+ new=AsyncMock(side_effect=RuntimeError("db hiccup")),+ ),+ ):+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_id="lib-1",+ write_graph_to="agent.json",+ )++ assert isinstance(result, AgentsFoundResponse)+ assert "could not load" in result.message+ manager.write_file.assert_not_awaited()+++async def test_write_graph_to_write_failure_notes_fallback(tool, session):+ """A workspace write failure degrades to a note, not an error response."""+ graph = {"nodes": [{"id": "n1"}], "links": []}+ manager, p1, p2, p3 = _write_graph_patches(_lookup_lib_db(), graph)+ manager.write_file = AsyncMock(side_effect=RuntimeError("disk full"))++ with p1, p2, p3:+ result = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ agent_id="lib-1",+ write_graph_to="agent.json",+ )++ assert isinstance(result, AgentsFoundResponse)+ assert "could not write" in result.message+ assert "include_graph=true" in result.messagediff --git a/autogpt_platform/backend/backend/copilot/tools/fix_agent.py b/autogpt_platform/backend/backend/copilot/tools/fix_agent.pyindex 5ef72a520f..3d9570f8fb 100644--- a/autogpt_platform/backend/backend/copilot/tools/fix_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/fix_agent.py@@ -3,16 +3,19 @@import difflibimport jsonimport logging-import os-import refrom typing import Any-from backend.copilot.context import get_workspace_managerfrom backend.copilot.model import ChatSessionfrom .agent_generator.validation import AgentFixer, AgentValidator, get_blocks_as_dicts+from .agent_json_input import (+ AGENT_JSON_REF_SCHEMA,+ AGENT_JSON_SCHEMA,+ resolve_agent_json_or_error,+ write_agent_json_to_workspace,+)from .base import BaseTool-from .helpers import coerce_agent_json, require_guide_read+from .helpers import require_guide_readfrom .models import ErrorResponse, FixResultResponse, ToolResponseBaselogger = logging.getLogger(__name__)@@ -43,14 +46,8 @@ class FixAgentGraphTool(BaseTool):return {"type": "object","properties": {- "agent_json": {- "type": ["object", "string"],- "description": (- "The agent JSON to fix ('nodes' + 'links' arrays), or "- 'the string "@@agptfile:<path>" to a JSON file '- "(preferred for large graphs)."- ),- },+ "agent_json": AGENT_JSON_SCHEMA,+ "agent_json_ref": AGENT_JSON_REF_SCHEMA,"write_to": {"type": "string","description": (@@ -61,7 +58,7 @@ class FixAgentGraphTool(BaseTool):),},},- "required": ["agent_json"],+ "required": [],}async def _execute(@@ -69,6 +66,7 @@ class FixAgentGraphTool(BaseTool):user_id: str | None,session: ChatSession,agent_json: dict | str | None = None,+ agent_json_ref: str | None = None,write_to: str = "",**kwargs,) -> ToolResponseBase:@@ -78,16 +76,23 @@ class FixAgentGraphTool(BaseTool):if guide_gate is not None:return guide_gate- agent_json = coerce_agent_json(agent_json)- if not agent_json:- return ErrorResponse(- message=(- "Please provide a valid agent JSON object, or the string "- '"@@agptfile:<path>" referencing a JSON file.'- ),- error="Missing or invalid agent_json parameter",- session_id=session_id,- )+ agent_json, resolve_error = await resolve_agent_json_or_error(+ agent_json=agent_json,+ agent_json_ref=agent_json_ref,+ user_id=user_id,+ session=session,+ session_id=session_id,+ missing_message=(+ "Please provide a valid agent JSON object via agent_json (inline "+ 'or an "@@agptfile:<path>" string), or agent_json_ref pointing '+ "at the workspace agent file."+ ),+ missing_error="Missing or invalid agent_json parameter",+ invalid_error="Missing or invalid agent_json parameter",+ )+ if resolve_error is not None:+ return resolve_error+ assert agent_json is not None # narrowed: resolve_error covers the None casenodes = agent_json.get("nodes", [])@@ -133,8 +138,14 @@ class FixAgentGraphTool(BaseTool):fixed_ref: str | None = Nonefix_diff: str | None = Noneif write_to := write_to.strip():- fixed_ref, write_note = await _write_fixed_agent(- fixed_agent, write_to, user_id, session_id+ fixed_ref, write_note = await write_agent_json_to_workspace(+ fixed_agent,+ write_to,+ user_id,+ session_id,+ label="Fixed JSON",+ pass_to="create_agent/edit_agent",+ fallback_note="returning the fixed JSON inline instead.",)message += write_noteif fixed_ref and fixes_applied:@@ -153,50 +164,6 @@ class FixAgentGraphTool(BaseTool):)-async def _write_fixed_agent(- fixed_agent: dict[str, Any],- write_to: str,- user_id: str | None,- session_id: str | None,-) -> tuple[str | None, str]:- """Write the fixed agent JSON to a workspace file, pretty-printed.-- Returns (file reference to pass to create_agent/edit_agent, message- note). On any failure the reference is None and the note explains the- fallback to inline JSON.- """- if not re.fullmatch(r"[\w][\w.-]*", write_to):- return None, (- f" NOTE: write_to must be a plain filename (got {write_to!r}); "- "returning the fixed JSON inline instead."- )- if not user_id or not session_id:- return None, (- " NOTE: write_to requires an authenticated session; "- "returning the fixed JSON inline instead."- )- try:- manager = await get_workspace_manager(user_id, session_id)- rec = await manager.write_file(- content=json.dumps(fixed_agent, indent=2).encode("utf-8"),- filename=write_to,- overwrite=True,- metadata={"origin": "agent-created"},- )- except Exception as e:- logger.warning(f"fix_agent_graph: failed to write {write_to!r}: {e}")- return None, (- f" NOTE: could not write {os.path.basename(write_to)}; "- "returning the fixed JSON inline instead."- )- ref = f"@@agptfile:workspace://{rec.path}"- return ref, (- f" Fixed JSON written to workspace file {rec.path} — pass "- f'agent_json="{ref}" to create_agent/edit_agent (do not re-emit '- "the JSON)."- )--_MAX_DIFF_CHARS = 4000diff --git a/autogpt_platform/backend/backend/copilot/tools/fix_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/fix_agent_test.pyindex 6f3062b245..4393d08237 100644--- a/autogpt_platform/backend/backend/copilot/tools/fix_agent_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/fix_agent_test.py@@ -241,7 +241,7 @@ async def test_write_to_returns_file_ref_and_diff(tool, session):p2,p3,patch(- "backend.copilot.tools.fix_agent.get_workspace_manager",+ "backend.copilot.tools.agent_json_input.get_workspace_manager",new=AsyncMock(return_value=mock_manager),),):@@ -296,7 +296,7 @@ async def test_write_to_failure_falls_back_inline(tool, session):p2,p3,patch(- "backend.copilot.tools.fix_agent.get_workspace_manager",+ "backend.copilot.tools.agent_json_input.get_workspace_manager",new=AsyncMock(side_effect=RuntimeError("workspace down")),),):diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.pyindex 89bb1fecfb..f21e60ca83 100644--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py@@ -1111,26 +1111,3 @@ def require_library_check(session: ChatSession, tool_name: str):),session_id=session.session_id,)---def coerce_agent_json(- agent_json: dict[str, Any] | str | None,-) -> dict[str, Any] | None:- """Coerce an ``agent_json`` tool argument into a dict.-- A bare ``@@agptfile:`` reference is expanded and JSON-parsed into a dict- by the SDK layer before the tool runs, but a raw JSON string can still- arrive — e.g. a reference embedded in surrounding text, or a file that- failed structured parsing. Returns None when the value cannot be- interpreted as a JSON object.- """- if isinstance(agent_json, dict):- return agent_json- if isinstance(agent_json, str) and agent_json.strip():- try:- parsed = json.loads(agent_json)- except json.JSONDecodeError:- return None- if isinstance(parsed, dict):- return parsed- return Nonediff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.pyindex 2a87a84ec6..e40c68c3bf 100644--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py@@ -11,7 +11,6 @@ from backend.copilot.constants import COPILOT_NODE_PREFIX, COPILOT_SESSION_PREFIfrom backend.copilot.tools.helpers import (BlockPreparation,check_hitl_review,- coerce_agent_json,execute_block,prepare_block_for_execution,require_library_check,@@ -1549,26 +1548,3 @@ class TestRequireLibraryCheck:session = make_session("user-lib-check", guide_read=False, library_check=False)session.metadata.builder_graph_id = "some-graph-id"assert require_library_check(session, "create_agent") is None---class TestCoerceAgentJson:- def test_dict_passes_through(self):- agent = {"nodes": [{"id": "n1"}], "links": []}- assert coerce_agent_json(agent) is agent-- def test_json_object_string_is_parsed(self):- assert coerce_agent_json('{"nodes": [], "links": []}') == {- "nodes": [],- "links": [],- }-- def test_unparseable_string_returns_none(self):- assert coerce_agent_json("@@agptfile:/home/user/agent.json") is None-- def test_json_non_object_string_returns_none(self):- assert coerce_agent_json('["nodes"]') is None-- def test_none_and_empty_return_none(self):- assert coerce_agent_json(None) is None- assert coerce_agent_json("") is None- assert coerce_agent_json(" ") is Nonediff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.pyindex 6f1ac10d35..98b14c0adb 100644--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py@@ -90,7 +90,14 @@ from backend.copilot.tools import TOOL_REGISTRY# Bumped 47000 -> 47800 on the post-#13601 dev merge: the registry now carries# the full merged tool set (webhook-trigger + preset lifecycle + docs/building# tools) at 47461 chars; ~340 headroom so routine wording tweaks don't trip it.-_CHAR_BUDGET = 47_800+# Bumped 47800 -> 51500 for OPEN-3188: the five agent-graph tools (create/edit/+# customize/validate/fix) replaced their bare ``{"type": "object"}`` agent_json+# with a structured schema (nodes/links/...) and gained an agent_json_ref string+# param. The structure is what stops constrained decoders collapsing the graph to+# ``{}`` and dropping it; nested props are kept type-only to minimise the spend.+# Merged registry measures 50915 chars (incl. find_library_agent's+# write_graph_to); ~580 headroom for wording tweaks.+_CHAR_BUDGET = 51_500@pytest.fixture(scope="module")diff --git a/autogpt_platform/backend/backend/copilot/tools/validate_agent.py b/autogpt_platform/backend/backend/copilot/tools/validate_agent.pyindex 68ce954a79..ad2a80bc84 100644--- a/autogpt_platform/backend/backend/copilot/tools/validate_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/validate_agent.py@@ -6,8 +6,13 @@ from typing import Anyfrom backend.copilot.model import ChatSessionfrom .agent_generator.validation import AgentValidator, get_blocks_as_dicts+from .agent_json_input import (+ AGENT_JSON_REF_SCHEMA,+ AGENT_JSON_SCHEMA,+ resolve_agent_json_or_error,+)from .base import BaseTool-from .helpers import coerce_agent_json, require_guide_read+from .helpers import require_guide_readfrom .models import ErrorResponse, ToolResponseBase, ValidationResultResponselogger = logging.getLogger(__name__)@@ -38,16 +43,10 @@ class ValidateAgentGraphTool(BaseTool):return {"type": "object","properties": {- "agent_json": {- "type": ["object", "string"],- "description": (- "Agent JSON with 'nodes' and 'links' arrays, or the "- 'string "@@agptfile:<path>" to a JSON file '- "(preferred for large graphs)."- ),- },+ "agent_json": AGENT_JSON_SCHEMA,+ "agent_json_ref": AGENT_JSON_REF_SCHEMA,},- "required": ["agent_json"],+ "required": [],}async def _execute(@@ -55,6 +54,7 @@ class ValidateAgentGraphTool(BaseTool):user_id: str | None,session: ChatSession,agent_json: dict | str | None = None,+ agent_json_ref: str | None = None,**kwargs,) -> ToolResponseBase:session_id = session.session_id if session else None@@ -63,16 +63,23 @@ class ValidateAgentGraphTool(BaseTool):if guide_gate is not None:return guide_gate- agent_json = coerce_agent_json(agent_json)- if not agent_json:- return ErrorResponse(- message=(- "Please provide a valid agent JSON object, or the string "- '"@@agptfile:<path>" referencing a JSON file.'- ),- error="Missing or invalid agent_json parameter",- session_id=session_id,- )+ agent_json, resolve_error = await resolve_agent_json_or_error(+ agent_json=agent_json,+ agent_json_ref=agent_json_ref,+ user_id=user_id,+ session=session,+ session_id=session_id,+ missing_message=(+ "Please provide a valid agent JSON object via agent_json (inline "+ 'or an "@@agptfile:<path>" string), or agent_json_ref pointing '+ "at the workspace agent file."+ ),+ missing_error="Missing or invalid agent_json parameter",+ invalid_error="Missing or invalid agent_json parameter",+ )+ if resolve_error is not None:+ return resolve_error+ assert agent_json is not None # narrowed: resolve_error covers the None casenodes = agent_json.get("nodes", [])diff --git a/autogpt_platform/backend/backend/copilot/tools/validate_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/validate_agent_test.pyindex 1fe63568db..9db08fd47b 100644--- a/autogpt_platform/backend/backend/copilot/tools/validate_agent_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/validate_agent_test.py@@ -195,11 +195,13 @@ async def test_agent_json_as_json_string(tool, session):@pytest.mark.asyncioasync def test_agent_json_unresolved_file_ref_string_returns_error(tool, session):- """An unexpanded @@agptfile reference (not valid JSON) returns a clear error."""+ """An unexpanded @@agptfile reference to an unreadable path returns a+ sanitized error (resolved server-side, path never echoed back)."""result = await tool._execute(user_id=_TEST_USER_ID,session=session,agent_json="@@agptfile:/home/user/agent.json",)assert isinstance(result, ErrorResponse)- assert "@@agptfile" in result.message+ assert "agent.json" in result.message+ assert "/home/user" not in result.message