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(platform/copilot): @@agptfile: file-ref protocol for tool call inputs + block input toggle (#12332)
Zamil Majdyf1945d6a2fbe
diff --git a/autogpt_platform/backend/backend/copilot/config_test.py b/autogpt_platform/backend/backend/copilot/config_test.pyindex 2f52c5329c..e80f406e27 100644--- a/autogpt_platform/backend/backend/copilot/config_test.py+++ b/autogpt_platform/backend/backend/copilot/config_test.py@@ -1,7 +1,23 @@"""Unit tests for ChatConfig."""+import pytest+from .config import ChatConfig+# Env vars that the ChatConfig validators read — must be cleared so they don't+# override the explicit constructor values we pass in each test.+_E2B_ENV_VARS = (+ "CHAT_USE_E2B_SANDBOX",+ "CHAT_E2B_API_KEY",+ "E2B_API_KEY",+)++[email protected](autouse=True)+def _clean_e2b_env(monkeypatch: pytest.MonkeyPatch) -> None:+ for var in _E2B_ENV_VARS:+ monkeypatch.delenv(var, raising=False)+class TestE2BActive:"""Tests for the e2b_active property — single source of truth for E2B usage."""diff --git a/autogpt_platform/backend/backend/copilot/context.py b/autogpt_platform/backend/backend/copilot/context.pynew file mode 100644index 0000000000..4ef8090c50--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/context.py@@ -0,0 +1,115 @@+"""Shared execution context for copilot SDK tool handlers.++All context variables and their accessors live here so that+``tool_adapter``, ``file_ref``, and ``e2b_file_tools`` can import them+without creating circular dependencies.+"""++import os+import re+from contextvars import ContextVar+from typing import TYPE_CHECKING++from backend.copilot.model import ChatSession++if TYPE_CHECKING:+ from e2b import AsyncSandbox++# Allowed base directory for the Read tool.+_SDK_PROJECTS_DIR = os.path.realpath(os.path.expanduser("~/.claude/projects"))++# Encoded project-directory name for the current session (e.g.+# "-private-tmp-copilot-<uuid>"). Set by set_execution_context() so path+# validation can scope tool-results reads to the current session.+_current_project_dir: ContextVar[str] = ContextVar("_current_project_dir", default="")++_current_user_id: ContextVar[str | None] = ContextVar("current_user_id", default=None)+_current_session: ContextVar[ChatSession | None] = ContextVar(+ "current_session", default=None+)+_current_sandbox: ContextVar["AsyncSandbox | None"] = ContextVar(+ "_current_sandbox", default=None+)+_current_sdk_cwd: ContextVar[str] = ContextVar("_current_sdk_cwd", default="")+++def _encode_cwd_for_cli(cwd: str) -> str:+ """Encode a working directory path the same way the Claude CLI does."""+ return re.sub(r"[^a-zA-Z0-9]", "-", os.path.realpath(cwd))+++def set_execution_context(+ user_id: str | None,+ session: ChatSession,+ sandbox: "AsyncSandbox | None" = None,+ sdk_cwd: str | None = None,+) -> None:+ """Set per-turn context variables used by file-resolution tool handlers."""+ _current_user_id.set(user_id)+ _current_session.set(session)+ _current_sandbox.set(sandbox)+ _current_sdk_cwd.set(sdk_cwd or "")+ _current_project_dir.set(_encode_cwd_for_cli(sdk_cwd) if sdk_cwd else "")+++def get_execution_context() -> tuple[str | None, ChatSession | None]:+ """Return the current (user_id, session) pair for the active request."""+ return _current_user_id.get(), _current_session.get()+++def get_current_sandbox() -> "AsyncSandbox | None":+ """Return the E2B sandbox for the current session, or None if not active."""+ return _current_sandbox.get()+++def get_sdk_cwd() -> str:+ """Return the SDK working directory for the current session (empty string if unset)."""+ return _current_sdk_cwd.get()+++E2B_WORKDIR = "/home/user"+++def resolve_sandbox_path(path: str) -> str:+ """Normalise *path* to an absolute sandbox path under ``/home/user``.++ Raises :class:`ValueError` if the resolved path escapes the sandbox.+ """+ candidate = path if os.path.isabs(path) else os.path.join(E2B_WORKDIR, path)+ normalized = os.path.normpath(candidate)+ if normalized != E2B_WORKDIR and not normalized.startswith(E2B_WORKDIR + "/"):+ raise ValueError(f"Path must be within {E2B_WORKDIR}: {path}")+ return normalized+++def is_allowed_local_path(path: str, sdk_cwd: str | None = None) -> bool:+ """Return True if *path* is within an allowed host-filesystem location.++ Allowed:+ - Files under *sdk_cwd* (``/tmp/copilot-<session>/``)+ - Files under ``~/.claude/projects/<encoded-cwd>/tool-results/`` (SDK tool-results)+ """+ if not path:+ return False++ if path.startswith("~"):+ resolved = os.path.realpath(os.path.expanduser(path))+ elif not os.path.isabs(path) and sdk_cwd:+ resolved = os.path.realpath(os.path.join(sdk_cwd, path))+ else:+ resolved = os.path.realpath(path)++ if sdk_cwd:+ norm_cwd = os.path.realpath(sdk_cwd)+ if resolved == norm_cwd or resolved.startswith(norm_cwd + os.sep):+ return True++ encoded = _current_project_dir.get("")+ if encoded:+ tool_results_dir = os.path.join(_SDK_PROJECTS_DIR, encoded, "tool-results")+ if resolved == tool_results_dir or resolved.startswith(+ tool_results_dir + os.sep+ ):+ return True++ return Falsediff --git a/autogpt_platform/backend/backend/copilot/context_test.py b/autogpt_platform/backend/backend/copilot/context_test.pynew file mode 100644index 0000000000..6cd02f4206--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/context_test.py@@ -0,0 +1,163 @@+"""Tests for context.py — execution context variables and path helpers."""++from __future__ import annotations++import os+import tempfile+from unittest.mock import MagicMock++import pytest++from backend.copilot.context import (+ _SDK_PROJECTS_DIR,+ _current_project_dir,+ get_current_sandbox,+ get_execution_context,+ get_sdk_cwd,+ is_allowed_local_path,+ resolve_sandbox_path,+ set_execution_context,+)+++def _make_session() -> MagicMock:+ s = MagicMock()+ s.session_id = "test-session"+ return s+++# ---------------------------------------------------------------------------+# Context variable getters+# ---------------------------------------------------------------------------+++def test_get_execution_context_defaults():+ """get_execution_context returns (None, session) when user_id is not set."""+ set_execution_context(None, _make_session())+ user_id, session = get_execution_context()+ assert user_id is None+ assert session is not None+++def test_set_and_get_execution_context():+ """set_execution_context stores user_id and session."""+ mock_session = _make_session()+ set_execution_context("user-abc", mock_session)+ user_id, session = get_execution_context()+ assert user_id == "user-abc"+ assert session is mock_session+++def test_get_current_sandbox_none_by_default():+ """get_current_sandbox returns None when no sandbox is set."""+ set_execution_context("u1", _make_session(), sandbox=None)+ assert get_current_sandbox() is None+++def test_get_current_sandbox_returns_set_value():+ """get_current_sandbox returns the sandbox set via set_execution_context."""+ mock_sandbox = MagicMock()+ set_execution_context("u1", _make_session(), sandbox=mock_sandbox)+ assert get_current_sandbox() is mock_sandbox+++def test_get_sdk_cwd_empty_when_not_set():+ """get_sdk_cwd returns empty string when sdk_cwd is not set."""+ set_execution_context("u1", _make_session(), sdk_cwd=None)+ assert get_sdk_cwd() == ""+++def test_get_sdk_cwd_returns_set_value():+ """get_sdk_cwd returns the value set via set_execution_context."""+ set_execution_context("u1", _make_session(), sdk_cwd="/tmp/copilot-test")+ assert get_sdk_cwd() == "/tmp/copilot-test"+++# ---------------------------------------------------------------------------+# is_allowed_local_path+# ---------------------------------------------------------------------------+++def test_is_allowed_local_path_empty():+ assert not is_allowed_local_path("")+++def test_is_allowed_local_path_inside_sdk_cwd():+ with tempfile.TemporaryDirectory() as cwd:+ path = os.path.join(cwd, "file.txt")+ assert is_allowed_local_path(path, cwd)+++def test_is_allowed_local_path_sdk_cwd_itself():+ with tempfile.TemporaryDirectory() as cwd:+ assert is_allowed_local_path(cwd, cwd)+++def test_is_allowed_local_path_outside_sdk_cwd():+ with tempfile.TemporaryDirectory() as cwd:+ assert not is_allowed_local_path("/etc/passwd", cwd)+++def test_is_allowed_local_path_no_sdk_cwd_no_project_dir():+ """Without sdk_cwd or project_dir, all paths are rejected."""+ _current_project_dir.set("")+ assert not is_allowed_local_path("/tmp/some-file.txt", sdk_cwd=None)+++def test_is_allowed_local_path_tool_results_dir():+ """Files under the tool-results directory for the current project are allowed."""+ encoded = "test-encoded-dir"+ tool_results_dir = os.path.join(_SDK_PROJECTS_DIR, encoded, "tool-results")+ path = os.path.join(tool_results_dir, "output.txt")++ _current_project_dir.set(encoded)+ try:+ assert is_allowed_local_path(path, sdk_cwd=None)+ finally:+ _current_project_dir.set("")+++def test_is_allowed_local_path_sibling_of_tool_results_is_rejected():+ """A path adjacent to tool-results/ but not inside it is rejected."""+ encoded = "test-encoded-dir"+ sibling_path = os.path.join(_SDK_PROJECTS_DIR, encoded, "other-dir", "file.txt")++ _current_project_dir.set(encoded)+ try:+ assert not is_allowed_local_path(sibling_path, sdk_cwd=None)+ finally:+ _current_project_dir.set("")+++# ---------------------------------------------------------------------------+# resolve_sandbox_path+# ---------------------------------------------------------------------------+++def test_resolve_sandbox_path_absolute_valid():+ assert (+ resolve_sandbox_path("/home/user/project/main.py")+ == "/home/user/project/main.py"+ )+++def test_resolve_sandbox_path_relative():+ assert resolve_sandbox_path("project/main.py") == "/home/user/project/main.py"+++def test_resolve_sandbox_path_workdir_itself():+ assert resolve_sandbox_path("/home/user") == "/home/user"+++def test_resolve_sandbox_path_normalizes_dots():+ assert resolve_sandbox_path("/home/user/a/../b") == "/home/user/b"+++def test_resolve_sandbox_path_escape_raises():+ with pytest.raises(ValueError, match="/home/user"):+ resolve_sandbox_path("/home/user/../../etc/passwd")+++def test_resolve_sandbox_path_absolute_outside_raises():+ with pytest.raises(ValueError, match="/home/user"):+ resolve_sandbox_path("/etc/passwd")diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.pyindex 7c42233686..bbd47b6013 100644--- a/autogpt_platform/backend/backend/copilot/prompting.py+++ b/autogpt_platform/backend/backend/copilot/prompting.py@@ -26,6 +26,33 @@ your message as a Markdown link or image:The `download_url` field in the `write_workspace_file` response is alreadyin the correct format — paste it directly after the `(` in the Markdown.+### Passing file content to tools — @@agptfile: references+Instead of copying large file contents into a tool argument, pass a file+reference and the platform will load the content for you.++Syntax: `@@agptfile:<uri>[<start>-<end>]`++- `<uri>` **must** start with `workspace://` or `/` (absolute path):+ - `workspace://<file_id>` — workspace file by ID+ - `workspace:///<path>` — workspace file by virtual path+ - `/absolute/local/path` — ephemeral or sdk_cwd file+ - E2B sandbox absolute path (e.g. `/home/user/script.py`)+- `[<start>-<end>]` is an optional 1-indexed inclusive line range.+- URIs that do not start with `workspace://` or `/` are **not** expanded.++Examples:+```+@@agptfile:workspace://abc123+@@agptfile:workspace://abc123[10-50]+@@agptfile:workspace:///reports/q1.md+@@agptfile:/tmp/copilot-<session>/output.py[1-80]+@@agptfile:/home/user/script.py+```++You can embed a reference inside any string argument, or use it as the entire+value. Multiple references in one argument are all expanded.++### Sub-agent tasks- When using the Task tool, NEVER set `run_in_background` to true.All tasks must run in the foreground.diff --git a/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.py b/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.pyindex 5041bd0668..c30d5f7435 100644--- a/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.py+++ b/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.py@@ -8,8 +8,6 @@ SDK-internal paths (``~/.claude/projects/…/tool-results/``) are handledby the separate ``Read`` MCP tool registered in ``tool_adapter.py``."""-from __future__ import annotations-import itertoolsimport jsonimport logging@@ -17,36 +15,23 @@ import osimport shlexfrom typing import Any, Callable-from backend.copilot.tools.e2b_sandbox import E2B_WORKDIR+from backend.copilot.context import (+ E2B_WORKDIR,+ get_current_sandbox,+ get_sdk_cwd,+ is_allowed_local_path,+ resolve_sandbox_path,+)logger = logging.getLogger(__name__)-# Lazy imports to break circular dependency with tool_adapter.---def _get_sandbox(): # type: ignore[return]- from .tool_adapter import get_current_sandbox # noqa: E402-+def _get_sandbox():return get_current_sandbox()def _is_allowed_local(path: str) -> bool:- from .tool_adapter import is_allowed_local_path # noqa: E402-- return is_allowed_local_path(path)---def _resolve_remote(path: str) -> str:- """Normalise *path* to an absolute sandbox path under ``/home/user``.-- Raises :class:`ValueError` if the resolved path escapes the sandbox.- """- candidate = path if os.path.isabs(path) else os.path.join(E2B_WORKDIR, path)- normalized = os.path.normpath(candidate)- if normalized != E2B_WORKDIR and not normalized.startswith(E2B_WORKDIR + "/"):- raise ValueError(f"Path must be within {E2B_WORKDIR}: {path}")- return normalized+ return is_allowed_local_path(path, get_sdk_cwd())def _mcp(text: str, *, error: bool = False) -> dict[str, Any]:@@ -63,7 +48,7 @@ def _get_sandbox_and_path(if sandbox is None:return _mcp("No E2B sandbox available", error=True)try:- remote = _resolve_remote(file_path)+ remote = resolve_sandbox_path(file_path)except ValueError as exc:return _mcp(str(exc), error=True)return sandbox, remote@@ -73,6 +58,7 @@ def _get_sandbox_and_path(async def _handle_read_file(args: dict[str, Any]) -> dict[str, Any]:+ """Read lines from a sandbox file, falling back to the local host for SDK-internal paths."""file_path: str = args.get("file_path", "")offset: int = max(0, int(args.get("offset", 0)))limit: int = max(1, int(args.get("limit", 2000)))@@ -104,6 +90,7 @@ async def _handle_read_file(args: dict[str, Any]) -> dict[str, Any]:async def _handle_write_file(args: dict[str, Any]) -> dict[str, Any]:+ """Write content to a sandbox file, creating parent directories as needed."""file_path: str = args.get("file_path", "")content: str = args.get("content", "")@@ -127,6 +114,7 @@ async def _handle_write_file(args: dict[str, Any]) -> dict[str, Any]:async def _handle_edit_file(args: dict[str, Any]) -> dict[str, Any]:+ """Replace a substring in a sandbox file, with optional replace-all support."""file_path: str = args.get("file_path", "")old_string: str = args.get("old_string", "")new_string: str = args.get("new_string", "")@@ -172,6 +160,7 @@ async def _handle_edit_file(args: dict[str, Any]) -> dict[str, Any]:async def _handle_glob(args: dict[str, Any]) -> dict[str, Any]:+ """Find files matching a name pattern inside the sandbox using ``find``."""pattern: str = args.get("pattern", "")path: str = args.get("path", "")@@ -183,7 +172,7 @@ async def _handle_glob(args: dict[str, Any]) -> dict[str, Any]:return _mcp("No E2B sandbox available", error=True)try:- search_dir = _resolve_remote(path) if path else E2B_WORKDIR+ search_dir = resolve_sandbox_path(path) if path else E2B_WORKDIRexcept ValueError as exc:return _mcp(str(exc), error=True)@@ -198,6 +187,7 @@ async def _handle_glob(args: dict[str, Any]) -> dict[str, Any]:async def _handle_grep(args: dict[str, Any]) -> dict[str, Any]:+ """Search file contents by regex inside the sandbox using ``grep -rn``."""pattern: str = args.get("pattern", "")path: str = args.get("path", "")include: str = args.get("include", "")@@ -210,7 +200,7 @@ async def _handle_grep(args: dict[str, Any]) -> dict[str, Any]:return _mcp("No E2B sandbox available", error=True)try:- search_dir = _resolve_remote(path) if path else E2B_WORKDIR+ search_dir = resolve_sandbox_path(path) if path else E2B_WORKDIRexcept ValueError as exc:return _mcp(str(exc), error=True)@@ -238,7 +228,7 @@ def _read_local(file_path: str, offset: int, limit: int) -> dict[str, Any]:return _mcp(f"Path not allowed: {file_path}", error=True)expanded = os.path.realpath(os.path.expanduser(file_path))try:- with open(expanded) as fh:+ with open(expanded, encoding="utf-8", errors="replace") as fh:selected = list(itertools.islice(fh, offset, offset + limit))numbered = "".join(f"{i + offset + 1:>6}\t{line}" for i, line in enumerate(selected)diff --git a/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools_test.py b/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools_test.pyindex 5d3276f3c3..3f72957d6d 100644--- a/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools_test.py@@ -7,59 +7,60 @@ import osimport pytest-from .e2b_file_tools import _read_local, _resolve_remote-from .tool_adapter import _current_project_dir+from backend.copilot.context import _current_project_dir++from .e2b_file_tools import _read_local, resolve_sandbox_path_SDK_PROJECTS_DIR = os.path.realpath(os.path.expanduser("~/.claude/projects"))# ----------------------------------------------------------------------------# _resolve_remote — sandbox path normalisation & boundary enforcement+# resolve_sandbox_path — sandbox path normalisation & boundary enforcement# ----------------------------------------------------------------------------class TestResolveRemote:+class TestResolveSandboxPath:def test_relative_path_resolved(self):- assert _resolve_remote("src/main.py") == "/home/user/src/main.py"+ assert resolve_sandbox_path("src/main.py") == "/home/user/src/main.py"def test_absolute_within_sandbox(self):- assert _resolve_remote("/home/user/file.txt") == "/home/user/file.txt"+ assert resolve_sandbox_path("/home/user/file.txt") == "/home/user/file.txt"def test_workdir_itself(self):- assert _resolve_remote("/home/user") == "/home/user"+ assert resolve_sandbox_path("/home/user") == "/home/user"def test_relative_dotslash(self):- assert _resolve_remote("./README.md") == "/home/user/README.md"+ assert resolve_sandbox_path("./README.md") == "/home/user/README.md"def test_traversal_blocked(self):with pytest.raises(ValueError, match="must be within /home/user"):- _resolve_remote("../../etc/passwd")+ resolve_sandbox_path("../../etc/passwd")def test_absolute_traversal_blocked(self):with pytest.raises(ValueError, match="must be within /home/user"):- _resolve_remote("/home/user/../../etc/passwd")+ resolve_sandbox_path("/home/user/../../etc/passwd")def test_absolute_outside_sandbox_blocked(self):with pytest.raises(ValueError, match="must be within /home/user"):- _resolve_remote("/etc/passwd")+ resolve_sandbox_path("/etc/passwd")def test_root_blocked(self):with pytest.raises(ValueError, match="must be within /home/user"):- _resolve_remote("/")+ resolve_sandbox_path("/")def test_home_other_user_blocked(self):with pytest.raises(ValueError, match="must be within /home/user"):- _resolve_remote("/home/other/file.txt")+ resolve_sandbox_path("/home/other/file.txt")def test_deep_nested_allowed(self):- assert _resolve_remote("a/b/c/d/e.txt") == "/home/user/a/b/c/d/e.txt"+ assert resolve_sandbox_path("a/b/c/d/e.txt") == "/home/user/a/b/c/d/e.txt"def test_trailing_slash_normalised(self):- assert _resolve_remote("src/") == "/home/user/src"+ assert resolve_sandbox_path("src/") == "/home/user/src"def test_double_dots_within_sandbox_ok(self):"""Path that resolves back within /home/user is allowed."""- assert _resolve_remote("a/b/../c.txt") == "/home/user/a/c.txt"+ assert resolve_sandbox_path("a/b/../c.txt") == "/home/user/a/c.txt"# ---------------------------------------------------------------------------diff --git a/autogpt_platform/backend/backend/copilot/sdk/file_ref.py b/autogpt_platform/backend/backend/copilot/sdk/file_ref.pynew file mode 100644index 0000000000..d27f3b6d78--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sdk/file_ref.py@@ -0,0 +1,281 @@+"""File reference protocol for tool call inputs.++Allows the LLM to pass a file reference instead of embedding large content+inline. The processor expands ``@@agptfile:<uri>[<start>-<end>]`` tokens in tool+arguments before the tool is executed.++Protocol+--------++ @@agptfile:<uri>[<start>-<end>]++``<uri>`` (required)+ - ``workspace://<file_id>`` — workspace file by ID+ - ``workspace://<file_id>#<mime>`` — same, MIME hint is ignored for reads+ - ``workspace:///<path>`` — workspace file by virtual path+ - ``/absolute/local/path`` — ephemeral or sdk_cwd file (validated by+ :func:`~backend.copilot.sdk.tool_adapter.is_allowed_local_path`)+ - Any absolute path that resolves inside the E2B sandbox+ (``/home/user/...``) when a sandbox is active++``[<start>-<end>]`` (optional)+ Line range, 1-indexed inclusive. Examples: ``[1-100]``, ``[50-200]``.+ Omit to read the entire file.++Examples+--------+ @@agptfile:workspace://abc123+ @@agptfile:workspace://abc123[10-50]+ @@agptfile:workspace:///reports/q1.md+ @@agptfile:/tmp/copilot-<session>/output.py[1-80]+ @@agptfile:/home/user/script.sh+"""++import itertools+import logging+import os+import re+from dataclasses import dataclass+from typing import Any++from backend.copilot.context import (+ get_current_sandbox,+ get_sdk_cwd,+ is_allowed_local_path,+ resolve_sandbox_path,+)+from backend.copilot.model import ChatSession+from backend.copilot.tools.workspace_files import get_manager+from backend.util.file import parse_workspace_uri+++class FileRefExpansionError(Exception):+ """Raised when a ``@@agptfile:`` reference in tool call args fails to resolve.++ Separating this from inline substitution lets callers (e.g. the MCP tool+ wrapper) block tool execution and surface a helpful error to the model+ rather than passing an ``[file-ref error: …]`` string as actual input.+ """+++logger = logging.getLogger(__name__)++FILE_REF_PREFIX = "@@agptfile:"++# Matches: @@agptfile:<uri>[start-end]?+# Group 1 – URI; must start with '/' (absolute path) or 'workspace://'+# Group 2 – start line (optional)+# Group 3 – end line (optional)+_FILE_REF_RE = re.compile(+ re.escape(FILE_REF_PREFIX) + r"((?:workspace://|/)[^\[\s]*)(?:\[(\d+)-(\d+)\])?"+)++# Maximum characters returned for a single file reference expansion.+_MAX_EXPAND_CHARS = 200_000+# Maximum total characters across all @@agptfile: expansions in one string.+_MAX_TOTAL_EXPAND_CHARS = 1_000_000+++@dataclass+class FileRef:+ uri: str+ start_line: int | None # 1-indexed, inclusive+ end_line: int | None # 1-indexed, inclusive+++def parse_file_ref(text: str) -> FileRef | None:+ """Return a :class:`FileRef` if *text* is a bare file reference token.++ A "bare token" means the entire string matches the ``@@agptfile:...`` pattern+ (after stripping whitespace). Use :func:`expand_file_refs_in_string` to+ expand references embedded in larger strings.+ """+ m = _FILE_REF_RE.fullmatch(text.strip())+ if not m:+ return None+ start = int(m.group(2)) if m.group(2) else None+ end = int(m.group(3)) if m.group(3) else None+ if start is not None and start < 1:+ return None+ if end is not None and end < 1:+ return None+ if start is not None and end is not None and end < start:+ return None+ return FileRef(uri=m.group(1), start_line=start, end_line=end)+++def _apply_line_range(text: str, start: int | None, end: int | None) -> str:+ """Slice *text* to the requested 1-indexed line range (inclusive)."""+ if start is None and end is None:+ return text+ lines = text.splitlines(keepends=True)+ s = (start - 1) if start is not None else 0+ e = end if end is not None else len(lines)+ selected = list(itertools.islice(lines, s, e))+ return "".join(selected)+++async def read_file_bytes(+ uri: str,+ user_id: str | None,+ session: ChatSession,+) -> bytes:+ """Resolve *uri* to raw bytes using workspace, local, or E2B path logic.++ Raises :class:`ValueError` if the URI cannot be resolved.+ """+ # Strip MIME fragment (e.g. workspace://id#mime) before dispatching.+ plain = uri.split("#")[0] if uri.startswith("workspace://") else uri++ if plain.startswith("workspace://"):+ if not user_id:+ raise ValueError("workspace:// file references require authentication")+ manager = await get_manager(user_id, session.session_id)+ ws = parse_workspace_uri(plain)+ try:+ return await (+ manager.read_file(ws.file_ref)+ if ws.is_path+ else manager.read_file_by_id(ws.file_ref)+ )+ except FileNotFoundError:+ raise ValueError(f"File not found: {plain}")+ except Exception as exc:+ raise ValueError(f"Failed to read {plain}: {exc}") from exc++ if is_allowed_local_path(plain, get_sdk_cwd()):+ resolved = os.path.realpath(os.path.expanduser(plain))+ try:+ with open(resolved, "rb") as fh:+ return fh.read()+ except FileNotFoundError:+ raise ValueError(f"File not found: {plain}")+ except Exception as exc:+ raise ValueError(f"Failed to read {plain}: {exc}") from exc++ sandbox = get_current_sandbox()+ if sandbox is not None:+ try:+ remote = resolve_sandbox_path(plain)+ except ValueError as exc:+ raise ValueError(+ f"Path is not allowed (not in workspace, sdk_cwd, or sandbox): {plain}"+ ) from exc+ try:+ return bytes(await sandbox.files.read(remote, format="bytes"))+ except Exception as exc:+ raise ValueError(f"Failed to read from sandbox: {plain}: {exc}") from exc++ raise ValueError(+ f"Path is not allowed (not in workspace, sdk_cwd, or sandbox): {plain}"+ )+++async def resolve_file_ref(+ ref: FileRef,+ user_id: str | None,+ session: ChatSession,+) -> str:+ """Resolve a :class:`FileRef` to its text content."""+ raw = await read_file_bytes(ref.uri, user_id, session)+ return _apply_line_range(+ raw.decode("utf-8", errors="replace"), ref.start_line, ref.end_line+ )+++async def expand_file_refs_in_string(+ text: str,+ user_id: str | None,+ session: "ChatSession",+ *,+ raise_on_error: bool = False,+) -> str:+ """Expand all ``@@agptfile:...`` tokens in *text*, returning the substituted string.++ Non-reference text is passed through unchanged.++ If *raise_on_error* is ``False`` (default), expansion errors are surfaced+ inline as ``[file-ref error: <message>]`` — useful for display/log contexts+ where partial expansion is acceptable.++ If *raise_on_error* is ``True``, any resolution failure raises+ :class:`FileRefExpansionError` immediately so the caller can block the+ operation and surface a clean error to the model.+ """+ if FILE_REF_PREFIX not in text:+ return text++ result: list[str] = []+ last_end = 0+ total_chars = 0+ for m in _FILE_REF_RE.finditer(text):+ result.append(text[last_end : m.start()])+ start = int(m.group(2)) if m.group(2) else None+ end = int(m.group(3)) if m.group(3) else None+ if (start is not None and start < 1) or (end is not None and end < 1):+ msg = f"line numbers must be >= 1: {m.group(0)}"+ if raise_on_error:+ raise FileRefExpansionError(msg)+ result.append(f"[file-ref error: {msg}]")+ last_end = m.end()+ continue+ if start is not None and end is not None and end < start:+ msg = f"end line must be >= start line: {m.group(0)}"+ if raise_on_error:+ raise FileRefExpansionError(msg)+ result.append(f"[file-ref error: {msg}]")+ last_end = m.end()+ continue+ ref = FileRef(uri=m.group(1), start_line=start, end_line=end)+ try:+ content = await resolve_file_ref(ref, user_id, session)+ if len(content) > _MAX_EXPAND_CHARS:+ content = content[:_MAX_EXPAND_CHARS] + "\n... [truncated]"+ remaining = _MAX_TOTAL_EXPAND_CHARS - total_chars+ if remaining <= 0:+ content = "[file-ref budget exhausted: total expansion limit reached]"+ elif len(content) > remaining:+ content = content[:remaining] + "\n... [total budget exhausted]"+ total_chars += len(content)+ result.append(content)+ except ValueError as exc:+ logger.warning("file-ref expansion failed for %r: %s", m.group(0), exc)+ if raise_on_error:+ raise FileRefExpansionError(str(exc)) from exc+ result.append(f"[file-ref error: {exc}]")+ last_end = m.end()++ result.append(text[last_end:])+ return "".join(result)+++async def expand_file_refs_in_args(+ args: dict[str, Any],+ user_id: str | None,+ session: "ChatSession",+) -> dict[str, Any]:+ """Recursively expand ``@@agptfile:...`` references in tool call arguments.++ String values are expanded in-place. Nested dicts and lists are+ traversed. Non-string scalars are returned unchanged.++ Raises :class:`FileRefExpansionError` if any reference fails to resolve,+ so the tool is *not* executed with an error string as its input. The+ caller (the MCP tool wrapper) should convert this into an MCP error+ response that lets the model correct the reference before retrying.+ """+ if not args:+ return args++ async def _expand(value: Any) -> Any:+ if isinstance(value, str):+ return await expand_file_refs_in_string(+ value, user_id, session, raise_on_error=True+ )+ if isinstance(value, dict):+ return {k: await _expand(v) for k, v in value.items()}+ if isinstance(value, list):+ return [await _expand(item) for item in value]+ return value++ return {k: await _expand(v) for k, v in args.items()}diff --git a/autogpt_platform/backend/backend/copilot/sdk/file_ref_integration_test.py b/autogpt_platform/backend/backend/copilot/sdk/file_ref_integration_test.pynew file mode 100644index 0000000000..fe49067ac7--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sdk/file_ref_integration_test.py@@ -0,0 +1,328 @@+"""Integration tests for @@agptfile: reference expansion in tool calls.++These tests verify the end-to-end behaviour of the file reference protocol:+- Parsing @@agptfile: tokens from tool arguments+- Resolving local-filesystem paths (sdk_cwd / ephemeral)+- Expanding references inside the tool-call pipeline (_execute_tool_sync)+- The extended Read tool handler (workspace:// pass-through via session context)++No real LLM or database is required; workspace reads are stubbed where needed.+"""++from __future__ import annotations++import os+import tempfile+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.copilot.sdk.file_ref import (+ FileRef,+ expand_file_refs_in_args,+ expand_file_refs_in_string,+ read_file_bytes,+ resolve_file_ref,+)+from backend.copilot.sdk.tool_adapter import _read_file_handler++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_session(session_id: str = "integ-sess") -> MagicMock:+ s = MagicMock()+ s.session_id = session_id+ return s+++# ---------------------------------------------------------------------------+# Local-file resolution (sdk_cwd)+# ---------------------------------------------------------------------------+++async def test_resolve_file_ref_local_path():+ """resolve_file_ref reads a real local file when it's within sdk_cwd."""+ with tempfile.TemporaryDirectory() as sdk_cwd:+ # Write a test file inside sdk_cwd+ test_file = os.path.join(sdk_cwd, "hello.txt")+ with open(test_file, "w") as f:+ f.write("line1\nline2\nline3\n")++ session = _make_session()+ with patch("backend.copilot.context._current_sdk_cwd") as mock_cwd_var:+ mock_cwd_var.get.return_value = sdk_cwd++ ref = FileRef(uri=test_file, start_line=None, end_line=None)+ content = await resolve_file_ref(ref, user_id="u1", session=session)++ assert content == "line1\nline2\nline3\n"+++async def test_resolve_file_ref_local_path_with_line_range():+ """resolve_file_ref respects line ranges for local files."""+ with tempfile.TemporaryDirectory() as sdk_cwd:+ test_file = os.path.join(sdk_cwd, "multi.txt")+ lines = [f"line{i}\n" for i in range(1, 11)] # line1 … line10+ with open(test_file, "w") as f:+ f.writelines(lines)++ session = _make_session()+ with patch("backend.copilot.context._current_sdk_cwd") as mock_cwd_var:+ mock_cwd_var.get.return_value = sdk_cwd++ ref = FileRef(uri=test_file, start_line=3, end_line=5)+ content = await resolve_file_ref(ref, user_id="u1", session=session)++ assert content == "line3\nline4\nline5\n"+++async def test_resolve_file_ref_rejects_path_outside_sdk_cwd():+ """resolve_file_ref raises ValueError for paths outside sdk_cwd."""+ with tempfile.TemporaryDirectory() as sdk_cwd:+ with patch("backend.copilot.context._current_sdk_cwd") as mock_cwd_var, patch(+ "backend.copilot.context._current_sandbox"+ ) as mock_sandbox_var:+ mock_cwd_var.get.return_value = sdk_cwd+ mock_sandbox_var.get.return_value = None++ ref = FileRef(uri="/etc/passwd", start_line=None, end_line=None)+ with pytest.raises(ValueError, match="not allowed"):+ await resolve_file_ref(ref, user_id="u1", session=_make_session())+++# ---------------------------------------------------------------------------+# expand_file_refs_in_string — integration with real files+# ---------------------------------------------------------------------------+++async def test_expand_string_with_real_file():+ """expand_file_refs_in_string replaces @@agptfile: token with actual content."""+ with tempfile.TemporaryDirectory() as sdk_cwd:+ test_file = os.path.join(sdk_cwd, "data.txt")+ with open(test_file, "w") as f:+ f.write("hello world\n")++ with patch("backend.copilot.context._current_sdk_cwd") as mock_cwd_var:+ mock_cwd_var.get.return_value = sdk_cwd++ result = await expand_file_refs_in_string(+ f"Content: @@agptfile:{test_file}",+ user_id="u1",+ session=_make_session(),+ )++ assert result == "Content: hello world\n"+++async def test_expand_string_missing_file_is_surfaced_inline():+ """Missing file ref yields [file-ref error: …] inline rather than raising."""+ with tempfile.TemporaryDirectory() as sdk_cwd:+ missing = os.path.join(sdk_cwd, "does_not_exist.txt")++ with patch("backend.copilot.context._current_sdk_cwd") as mock_cwd_var:+ mock_cwd_var.get.return_value = sdk_cwd++ result = await expand_file_refs_in_string(+ f"@@agptfile:{missing}",+ user_id="u1",+ session=_make_session(),+ )++ assert "[file-ref error:" in result+ assert "not found" in result.lower() or "not allowed" in result.lower()+++# ---------------------------------------------------------------------------+# expand_file_refs_in_args — dict traversal with real files+# ---------------------------------------------------------------------------+++async def test_expand_args_replaces_file_ref_in_nested_dict():+ """Nested @@agptfile: references in args are fully expanded."""+ with tempfile.TemporaryDirectory() as sdk_cwd:+ file_a = os.path.join(sdk_cwd, "a.txt")+ file_b = os.path.join(sdk_cwd, "b.txt")+ with open(file_a, "w") as f:+ f.write("AAA")+ with open(file_b, "w") as f:+ f.write("BBB")++ with patch("backend.copilot.context._current_sdk_cwd") as mock_cwd_var:+ mock_cwd_var.get.return_value = sdk_cwd++ result = await expand_file_refs_in_args(+ {+ "outer": {+ "content_a": f"@@agptfile:{file_a}",+ "content_b": f"start @@agptfile:{file_b} end",+ },+ "count": 42,+ },+ user_id="u1",+ session=_make_session(),+ )++ assert result["outer"]["content_a"] == "AAA"+ assert result["outer"]["content_b"] == "start BBB end"+ assert result["count"] == 42+++# ---------------------------------------------------------------------------+# _read_file_handler — extended to accept workspace:// and local paths+# ---------------------------------------------------------------------------+++async def test_read_file_handler_local_file():+ """_read_file_handler reads a local file when it's within sdk_cwd."""+ with tempfile.TemporaryDirectory() as sdk_cwd:+ test_file = os.path.join(sdk_cwd, "read_test.txt")+ lines = [f"L{i}\n" for i in range(1, 6)]+ with open(test_file, "w") as f:+ f.writelines(lines)++ with patch("backend.copilot.context._current_sdk_cwd") as mock_cwd_var, patch(+ "backend.copilot.context._current_project_dir"+ ) as mock_proj_var, patch(+ "backend.copilot.sdk.tool_adapter.get_execution_context",+ return_value=("user-1", _make_session()),+ ):+ mock_cwd_var.get.return_value = sdk_cwd+ mock_proj_var.get.return_value = ""++ result = await _read_file_handler(+ {"file_path": test_file, "offset": 0, "limit": 5}+ )++ assert not result["isError"]+ text = result["content"][0]["text"]+ assert "L1" in text+ assert "L5" in text+++async def test_read_file_handler_workspace_uri():+ """_read_file_handler handles workspace:// URIs via the workspace manager."""+ mock_session = _make_session()+ mock_manager = AsyncMock()+ mock_manager.read_file_by_id.return_value = b"workspace file content\nline two\n"++ with patch(+ "backend.copilot.sdk.tool_adapter.get_execution_context",+ return_value=("user-1", mock_session),+ ), patch(+ "backend.copilot.sdk.file_ref.get_manager",+ new=AsyncMock(return_value=mock_manager),+ ):+ result = await _read_file_handler(+ {"file_path": "workspace://file-id-abc", "offset": 0, "limit": 10}+ )++ assert not result["isError"], result["content"][0]["text"]+ text = result["content"][0]["text"]+ assert "workspace file content" in text+ assert "line two" in text+++async def test_read_file_handler_workspace_uri_no_session():+ """_read_file_handler returns error when workspace:// is used without session."""+ with patch(+ "backend.copilot.sdk.tool_adapter.get_execution_context",+ return_value=(None, None),+ ):+ result = await _read_file_handler({"file_path": "workspace://some-id"})++ assert result["isError"]+ assert "session" in result["content"][0]["text"].lower()+++async def test_read_file_handler_access_denied():+ """_read_file_handler rejects paths outside allowed locations."""+ with patch("backend.copilot.context._current_sdk_cwd") as mock_cwd, patch(+ "backend.copilot.context._current_sandbox"+ ) as mock_sandbox, patch(+ "backend.copilot.sdk.tool_adapter.get_execution_context",+ return_value=("user-1", _make_session()),+ ):+ mock_cwd.get.return_value = "/tmp/safe-dir"+ mock_sandbox.get.return_value = None++ result = await _read_file_handler({"file_path": "/etc/passwd"})++ assert result["isError"]+ assert "not allowed" in result["content"][0]["text"].lower()+++# ---------------------------------------------------------------------------+# read_file_bytes — workspace:///path (virtual path) and E2B sandbox branch+# ---------------------------------------------------------------------------+++async def test_read_file_bytes_workspace_virtual_path():+ """workspace:///path resolves via manager.read_file (is_path=True path)."""+ session = _make_session()+ mock_manager = AsyncMock()+ mock_manager.read_file.return_value = b"virtual path content"++ with patch(+ "backend.copilot.sdk.file_ref.get_manager",+ new=AsyncMock(return_value=mock_manager),+ ):+ result = await read_file_bytes("workspace:///reports/q1.md", "user-1", session)++ assert result == b"virtual path content"+ mock_manager.read_file.assert_awaited_once_with("/reports/q1.md")+++async def test_read_file_bytes_e2b_sandbox_branch():+ """read_file_bytes reads from the E2B sandbox when a sandbox is active."""+ session = _make_session()+ mock_sandbox = AsyncMock()+ mock_sandbox.files.read.return_value = bytearray(b"sandbox content")++ with patch("backend.copilot.context._current_sdk_cwd") as mock_cwd, patch(+ "backend.copilot.context._current_sandbox"+ ) as mock_sandbox_var, patch(+ "backend.copilot.context._current_project_dir"+ ) as mock_proj:+ mock_cwd.get.return_value = ""+ mock_sandbox_var.get.return_value = mock_sandbox+ mock_proj.get.return_value = ""++ result = await read_file_bytes("/home/user/script.sh", None, session)++ assert result == b"sandbox content"+ mock_sandbox.files.read.assert_awaited_once_with(+ "/home/user/script.sh", format="bytes"+ )+++async def test_read_file_bytes_e2b_path_escapes_sandbox_raises():+ """read_file_bytes raises ValueError for paths that escape the sandbox root."""+ session = _make_session()+ mock_sandbox = AsyncMock()++ with patch("backend.copilot.context._current_sdk_cwd") as mock_cwd, patch(+ "backend.copilot.context._current_sandbox"+ ) as mock_sandbox_var, patch(+ "backend.copilot.context._current_project_dir"+ ) as mock_proj:+ mock_cwd.get.return_value = ""+ mock_sandbox_var.get.return_value = mock_sandbox+ mock_proj.get.return_value = ""++ with pytest.raises(ValueError, match="not allowed"):+ await read_file_bytes("/etc/passwd", None, session)diff --git a/autogpt_platform/backend/backend/copilot/sdk/file_ref_test.py b/autogpt_platform/backend/backend/copilot/sdk/file_ref_test.pynew file mode 100644index 0000000000..5625830f09--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sdk/file_ref_test.py@@ -0,0 +1,382 @@+"""Tests for the @@agptfile: reference protocol (file_ref.py)."""++from __future__ import annotations++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.copilot.sdk.file_ref import (+ _MAX_EXPAND_CHARS,+ FileRef,+ FileRefExpansionError,+ _apply_line_range,+ expand_file_refs_in_args,+ expand_file_refs_in_string,+ parse_file_ref,+)++# ---------------------------------------------------------------------------+# parse_file_ref+# ---------------------------------------------------------------------------+++def test_parse_file_ref_workspace_id():+ ref = parse_file_ref("@@agptfile:workspace://abc123")+ assert ref == FileRef(uri="workspace://abc123", start_line=None, end_line=None)+++def test_parse_file_ref_workspace_id_with_mime():+ ref = parse_file_ref("@@agptfile:workspace://abc123#text/plain")+ assert ref is not None+ assert ref.uri == "workspace://abc123#text/plain"+ assert ref.start_line is None+++def test_parse_file_ref_workspace_path():+ ref = parse_file_ref("@@agptfile:workspace:///reports/q1.md")+ assert ref is not None+ assert ref.uri == "workspace:///reports/q1.md"+++def test_parse_file_ref_with_line_range():+ ref = parse_file_ref("@@agptfile:workspace://abc123[10-50]")+ assert ref == FileRef(uri="workspace://abc123", start_line=10, end_line=50)+++def test_parse_file_ref_local_path():+ ref = parse_file_ref("@@agptfile:/tmp/copilot-session/output.py[1-100]")+ assert ref is not None+ assert ref.uri == "/tmp/copilot-session/output.py"+ assert ref.start_line == 1+ assert ref.end_line == 100+++def test_parse_file_ref_no_match():+ assert parse_file_ref("just a normal string") is None+ assert parse_file_ref("workspace://abc123") is None # missing @@agptfile: prefix+ assert (+ parse_file_ref("@@agptfile:workspace://abc123 extra") is None+ ) # not full match+++def test_parse_file_ref_strips_whitespace():+ ref = parse_file_ref(" @@agptfile:workspace://abc123 ")+ assert ref is not None+ assert ref.uri == "workspace://abc123"+++def test_parse_file_ref_invalid_range_zero_start():+ assert parse_file_ref("@@agptfile:workspace://abc123[0-5]") is None+++def test_parse_file_ref_invalid_range_end_less_than_start():+ assert parse_file_ref("@@agptfile:workspace://abc123[10-5]") is None+++def test_parse_file_ref_invalid_range_zero_end():+ assert parse_file_ref("@@agptfile:workspace://abc123[1-0]") is None+++# ---------------------------------------------------------------------------+# _apply_line_range+# ---------------------------------------------------------------------------+++TEXT = "line1\nline2\nline3\nline4\nline5\n"+++def test_apply_line_range_no_range():+ assert _apply_line_range(TEXT, None, None) == TEXT+++def test_apply_line_range_start_only():+ result = _apply_line_range(TEXT, 3, None)+ assert result == "line3\nline4\nline5\n"+++def test_apply_line_range_full():+ result = _apply_line_range(TEXT, 2, 4)+ assert result == "line2\nline3\nline4\n"+++def test_apply_line_range_single_line():+ result = _apply_line_range(TEXT, 2, 2)+ assert result == "line2\n"+++def test_apply_line_range_beyond_eof():+ result = _apply_line_range(TEXT, 4, 999)+ assert result == "line4\nline5\n"+++# ---------------------------------------------------------------------------+# expand_file_refs_in_string+# ---------------------------------------------------------------------------+++def _make_session(session_id: str = "sess-1") -> MagicMock:+ session = MagicMock()+ session.session_id = session_id+ return session+++async def _resolve_always(ref: FileRef, _user_id: str | None, _session: object) -> str:+ """Stub resolver that returns the URI and range as a descriptive string."""+ if ref.start_line is not None:+ return f"content:{ref.uri}[{ref.start_line}-{ref.end_line}]"+ return f"content:{ref.uri}"+++async def test_expand_no_refs():+ result = await expand_file_refs_in_string(+ "no references here", user_id="u1", session=_make_session()+ )+ assert result == "no references here"+++async def test_expand_single_ref():+ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_resolve_always),+ ):+ result = await expand_file_refs_in_string(+ "@@agptfile:workspace://abc123",+ user_id="u1",+ session=_make_session(),+ )+ assert result == "content:workspace://abc123"+++async def test_expand_ref_with_range():+ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_resolve_always),+ ):+ result = await expand_file_refs_in_string(+ "@@agptfile:workspace://abc123[10-50]",+ user_id="u1",+ session=_make_session(),+ )+ assert result == "content:workspace://abc123[10-50]"+++async def test_expand_ref_embedded_in_text():+ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_resolve_always),+ ):+ result = await expand_file_refs_in_string(+ "Here is the file: @@agptfile:workspace://abc123 — done",+ user_id="u1",+ session=_make_session(),+ )+ assert result == "Here is the file: content:workspace://abc123 — done"+++async def test_expand_multiple_refs():+ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_resolve_always),+ ):+ result = await expand_file_refs_in_string(+ "@@agptfile:workspace://file1 and @@agptfile:workspace://file2[1-5]",+ user_id="u1",+ session=_make_session(),+ )+ assert result == "content:workspace://file1 and content:workspace://file2[1-5]"+++async def test_expand_invalid_range_zero_start_surfaces_inline():+ """expand_file_refs_in_string surfaces [file-ref error: ...] for zero-start ranges."""+ result = await expand_file_refs_in_string(+ "@@agptfile:workspace://abc123[0-5]",+ user_id="u1",+ session=_make_session(),+ )+ assert "[file-ref error:" in result+ assert "line numbers must be >= 1" in result+++async def test_expand_invalid_range_end_less_than_start_surfaces_inline():+ """expand_file_refs_in_string surfaces [file-ref error: ...] when end < start."""+ result = await expand_file_refs_in_string(+ "prefix @@agptfile:workspace://abc123[10-5] suffix",+ user_id="u1",+ session=_make_session(),+ )+ assert "[file-ref error:" in result+ assert "end line must be >= start line" in result+ assert "prefix" in result+ assert "suffix" in result+++async def test_expand_ref_error_surfaces_inline():+ async def _raise(*args, **kwargs): # noqa: ARG001+ raise ValueError("file not found")++ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_raise),+ ):+ result = await expand_file_refs_in_string(+ "@@agptfile:workspace://bad",+ user_id="u1",+ session=_make_session(),+ )+ assert "[file-ref error:" in result+ assert "file not found" in result+++# ---------------------------------------------------------------------------+# expand_file_refs_in_args+# ---------------------------------------------------------------------------+++async def test_expand_args_flat():+ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_resolve_always),+ ):+ result = await expand_file_refs_in_args(+ {"content": "@@agptfile:workspace://abc123", "other": 42},+ user_id="u1",+ session=_make_session(),+ )+ assert result["content"] == "content:workspace://abc123"+ assert result["other"] == 42+++async def test_expand_args_nested_dict():+ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_resolve_always),+ ):+ result = await expand_file_refs_in_args(+ {"outer": {"inner": "@@agptfile:workspace://nested"}},+ user_id="u1",+ session=_make_session(),+ )+ assert result["outer"]["inner"] == "content:workspace://nested"+++async def test_expand_args_list():+ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_resolve_always),+ ):+ result = await expand_file_refs_in_args(+ {+ "items": [+ "@@agptfile:workspace://a",+ "plain",+ "@@agptfile:workspace://b[1-3]",+ ]+ },+ user_id="u1",+ session=_make_session(),+ )+ assert result["items"] == [+ "content:workspace://a",+ "plain",+ "content:workspace://b[1-3]",+ ]+++async def test_expand_args_empty():+ result = await expand_file_refs_in_args({}, user_id="u1", session=_make_session())+ assert result == {}+++async def test_expand_args_no_refs():+ result = await expand_file_refs_in_args(+ {"key": "no refs here", "num": 1},+ user_id="u1",+ session=_make_session(),+ )+ assert result == {"key": "no refs here", "num": 1}+++async def test_expand_args_raises_on_file_ref_error():+ """expand_file_refs_in_args raises FileRefExpansionError instead of passing+ the inline error string to the tool, blocking tool execution."""++ async def _raise(*args, **kwargs): # noqa: ARG001+ raise ValueError("path does not exist")++ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_raise),+ ):+ with pytest.raises(FileRefExpansionError) as exc_info:+ await expand_file_refs_in_args(+ {"prompt": "@@agptfile:/home/user/missing.txt"},+ user_id="u1",+ session=_make_session(),+ )+ assert "path does not exist" in str(exc_info.value)+++# ---------------------------------------------------------------------------+# Per-file truncation and aggregate budget+# ---------------------------------------------------------------------------+++async def test_expand_per_file_truncation():+ """Content exceeding _MAX_EXPAND_CHARS is truncated with a marker."""+ oversized = "x" * (_MAX_EXPAND_CHARS + 100)++ async def _resolve_oversized(ref: FileRef, _uid: str | None, _s: object) -> str:+ return oversized++ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_resolve_oversized),+ ):+ result = await expand_file_refs_in_string(+ "@@agptfile:workspace://big-file",+ user_id="u1",+ session=_make_session(),+ )++ assert len(result) <= _MAX_EXPAND_CHARS + len("\n... [truncated]") + 10+ assert "[truncated]" in result+++async def test_expand_aggregate_budget_exhausted():+ """When the aggregate budget is exhausted, later refs get the budget message."""+ # Each file returns just under 300K; after ~4 files the 1M budget is used.+ big_chunk = "y" * 300_000++ async def _resolve_big(ref: FileRef, _uid: str | None, _s: object) -> str:+ return big_chunk++ with patch(+ "backend.copilot.sdk.file_ref.resolve_file_ref",+ new=AsyncMock(side_effect=_resolve_big),+ ):+ # 5 refs @ 300K each = 1.5M → last ref(s) should hit the aggregate limit+ refs = " ".join(f"@@agptfile:workspace://f{i}" for i in range(5))+ result = await expand_file_refs_in_string(+ refs,+ user_id="u1",+ session=_make_session(),+ )++ assert "budget exhausted" in resultdiff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.pyindex 27b32d95b4..67e5de619b 100644--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py@@ -536,10 +536,12 @@ async def test_wait_for_stash_signaled():result = await wait_for_stash(timeout=1.0)assert result is True- assert _pto.get({}).get("WebSearch") == ["result data"]+ pto = _pto.get()+ assert pto is not None+ assert pto.get("WebSearch") == ["result data"]# Cleanup- _pto.set({}) # type: ignore[arg-type]+ _pto.set({})_stash_event.set(None)@@ -554,7 +556,7 @@ async def test_wait_for_stash_timeout():assert result is False# Cleanup- _pto.set({}) # type: ignore[arg-type]+ _pto.set({})_stash_event.set(None)@@ -573,10 +575,12 @@ async def test_wait_for_stash_already_stashed():assert result is True# But the stash itself is populated- assert _pto.get({}).get("Read") == ["file contents"]+ pto = _pto.get()+ assert pto is not None+ assert pto.get("Read") == ["file contents"]# Cleanup- _pto.set({}) # type: ignore[arg-type]+ _pto.set({})_stash_event.set(None)diff --git a/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py b/autogpt_platform/backend/backend/copilot/sdk/security_hooks.pyindex e2dc2062d2..01eb8083bd 100644--- a/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks.py@@ -10,12 +10,13 @@ import refrom collections.abc import Callablefrom typing import Any, cast+from backend.copilot.context import is_allowed_local_path+from .tool_adapter import (BLOCKED_TOOLS,DANGEROUS_PATTERNS,MCP_TOOL_PREFIX,WORKSPACE_SCOPED_TOOLS,- is_allowed_local_path,stash_pending_tool_output,)diff --git a/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.pyindex 0999f13886..b4cfef8f60 100644--- a/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py@@ -9,6 +9,8 @@ import osimport pytest+from backend.copilot.context import _current_project_dir+from .security_hooks import _validate_tool_access, _validate_user_isolationSDK_CWD = "/tmp/copilot-abc123"@@ -119,8 +121,6 @@ def test_read_no_cwd_denies_absolute():def test_read_tool_results_allowed():- from .tool_adapter import _current_project_dir-home = os.path.expanduser("~")path = f"{home}/.claude/projects/-tmp-copilot-abc123/tool-results/12345.txt"# is_allowed_local_path requires the session's encoded cwd to be set@@ -132,16 +132,14 @@ def test_read_tool_results_allowed():_current_project_dir.reset(token)-def test_read_claude_projects_session_dir_allowed():- """Files within the current session's project dir are allowed."""- from .tool_adapter import _current_project_dir-+def test_read_claude_projects_settings_json_denied():+ """SDK-internal artifacts like settings.json are NOT accessible — only tool-results/ is."""home = os.path.expanduser("~")path = f"{home}/.claude/projects/-tmp-copilot-abc123/settings.json"token = _current_project_dir.set("-tmp-copilot-abc123")try:result = _validate_tool_access("Read", {"file_path": path}, sdk_cwd=SDK_CWD)- assert not _is_denied(result)+ assert _is_denied(result)finally:_current_project_dir.reset(token)diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.pyindex 6815b77535..46e2d8b3a7 100644--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py@@ -9,14 +9,29 @@ import itertoolsimport jsonimport loggingimport os-import reimport uuidfrom contextvars import ContextVarfrom typing import TYPE_CHECKING, Anyfrom claude_agent_sdk import create_sdk_mcp_server, tool+from backend.copilot.context import (+ _current_project_dir,+ _current_sandbox,+ _current_sdk_cwd,+ _current_session,+ _current_user_id,+ _encode_cwd_for_cli,+ get_execution_context,+ get_sdk_cwd,+ is_allowed_local_path,+)from backend.copilot.model import ChatSession+from backend.copilot.sdk.file_ref import (+ FileRefExpansionError,+ expand_file_refs_in_args,+ read_file_bytes,+)from backend.copilot.tools import TOOL_REGISTRYfrom backend.copilot.tools.base import BaseToolfrom backend.util.truncate import truncate@@ -28,84 +43,13 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-# Allowed base directory for the Read tool (SDK saves oversized tool results here).-# Restricted to ~/.claude/projects/ and further validated to require "tool-results"-# in the path — prevents reading settings, credentials, or other sensitive files.-_SDK_PROJECTS_DIR = os.path.realpath(os.path.expanduser("~/.claude/projects"))-# Max MCP response size in chars — keeps tool output under the SDK's 10 MB JSON buffer._MCP_MAX_CHARS = 500_000-# Context variable holding the encoded project directory name for the current-# session (e.g. "-private-tmp-copilot-<uuid>"). Set by set_execution_context()-# so that path validation can scope tool-results reads to the current session.-_current_project_dir: ContextVar[str] = ContextVar("_current_project_dir", default="")---def _encode_cwd_for_cli(cwd: str) -> str:- """Encode a working directory path the same way the Claude CLI does.-- The CLI replaces all non-alphanumeric characters with ``-``.- """- return re.sub(r"[^a-zA-Z0-9]", "-", os.path.realpath(cwd))---def is_allowed_local_path(path: str, sdk_cwd: str | None = None) -> bool:- """Check whether *path* is an allowed host-filesystem path.-- Allowed:- - Files under *sdk_cwd* (``/tmp/copilot-<session>/``)- - Files under ``~/.claude/projects/<encoded-cwd>/`` — the SDK's- project directory for this session (tool-results, transcripts, etc.)-- Both checks are scoped to the **current session** so sessions cannot- read each other's data.- """- if not path:- return False-- if path.startswith("~"):- resolved = os.path.realpath(os.path.expanduser(path))- elif not os.path.isabs(path) and sdk_cwd:- resolved = os.path.realpath(os.path.join(sdk_cwd, path))- else:- resolved = os.path.realpath(path)-- # Allow access within the SDK working directory- if sdk_cwd:- norm_cwd = os.path.realpath(sdk_cwd)- if resolved == norm_cwd or resolved.startswith(norm_cwd + os.sep):- return True-- # Allow access within the current session's CLI project directory- # (~/.claude/projects/<encoded-cwd>/).- encoded = _current_project_dir.get("")- if encoded:- session_project = os.path.join(_SDK_PROJECTS_DIR, encoded)- if resolved == session_project or resolved.startswith(session_project + os.sep):- return True-- return False--# MCP server naming - the SDK prefixes tool names as "mcp__{server_name}__{tool}"MCP_SERVER_NAME = "copilot"MCP_TOOL_PREFIX = f"mcp__{MCP_SERVER_NAME}__"-# Context variables to pass user/session info to tool execution-_current_user_id: ContextVar[str | None] = ContextVar("current_user_id", default=None)-_current_session: ContextVar[ChatSession | None] = ContextVar(- "current_session", default=None-)-# E2B cloud sandbox for the current turn (None when E2B is not configured).-# Passed to bash_exec so commands run on E2B instead of the local bwrap sandbox.-_current_sandbox: ContextVar["AsyncSandbox | None"] = ContextVar(- "_current_sandbox", default=None-)-# Raw SDK working directory path (e.g. /tmp/copilot-<session_id>).-# Used by workspace tools to save binary files for the CLI's built-in Read.-_current_sdk_cwd: ContextVar[str] = ContextVar("_current_sdk_cwd", default="")-# Stash for MCP tool outputs before the SDK potentially truncates them.# Keyed by tool_name → full output string. Consumed (popped) by the# response adapter when it builds StreamToolOutputAvailable.@@ -149,24 +93,6 @@ def set_execution_context(_stash_event.set(asyncio.Event())-def get_current_sandbox() -> "AsyncSandbox | None":- """Return the E2B sandbox for the current turn, or None."""- return _current_sandbox.get()---def get_sdk_cwd() -> str:- """Return the SDK ephemeral working directory for the current turn."""- return _current_sdk_cwd.get()---def get_execution_context() -> tuple[str | None, ChatSession | None]:- """Get the current execution context."""- return (- _current_user_id.get(),- _current_session.get(),- )--def pop_pending_tool_output(tool_name: str) -> str | None:"""Pop and return the oldest stashed output for *tool_name*.@@ -259,7 +185,11 @@ async def _execute_tool_sync(session: ChatSession,args: dict[str, Any],) -> dict[str, Any]:- """Execute a tool synchronously and return MCP-formatted response."""+ """Execute a tool synchronously and return MCP-formatted response.++ Note: ``@@agptfile:`` expansion is handled upstream in the ``_truncating`` wrapper+ so all registered handlers (BaseTool, E2B, Read) expand uniformly.+ """effective_id = f"sdk-{uuid.uuid4().hex[:12]}"result = await base_tool.execute(user_id=user_id,@@ -320,42 +250,50 @@ def _build_input_schema(base_tool: BaseTool) -> dict[str, Any]:async def _read_file_handler(args: dict[str, Any]) -> dict[str, Any]:- """Read a local file with optional offset/limit.+ """Read a file with optional offset/limit.- Only allows paths that pass :func:`is_allowed_local_path` — the current- session's tool-results directory and ephemeral working directory.+ Supports ``workspace://`` URIs (delegated to the workspace manager) and+ local paths within the session's allowed directories (sdk_cwd + tool-results)."""file_path = args.get("file_path", "")- offset = args.get("offset", 0)- limit = args.get("limit", 2000)+ offset = max(0, int(args.get("offset", 0)))+ limit = max(1, int(args.get("limit", 2000)))- if not is_allowed_local_path(file_path):- return {- "content": [{"type": "text", "text": f"Access denied: {file_path}"}],- "isError": True,- }+ def _mcp_err(text: str) -> dict[str, Any]:+ return {"content": [{"type": "text", "text": text}], "isError": True}++ def _mcp_ok(text: str) -> dict[str, Any]:+ return {"content": [{"type": "text", "text": text}], "isError": False}++ if file_path.startswith("workspace://"):+ user_id, session = get_execution_context()+ if session is None:+ return _mcp_err("workspace:// file references require an active session")+ try:+ raw = await read_file_bytes(file_path, user_id, session)+ except ValueError as exc:+ return _mcp_err(str(exc))+ lines = raw.decode("utf-8", errors="replace").splitlines(keepends=True)+ selected = list(itertools.islice(lines, offset, offset + limit))+ numbered = "".join(+ f"{i + offset + 1:>6}\t{line}" for i, line in enumerate(selected)+ )+ return _mcp_ok(numbered)++ if not is_allowed_local_path(file_path, get_sdk_cwd()):+ return _mcp_err(f"Path not allowed: {file_path}")resolved = os.path.realpath(os.path.expanduser(file_path))try:with open(resolved) as f:selected = list(itertools.islice(f, offset, offset + limit))- content = "".join(selected)# Cleanup happens in _cleanup_sdk_tool_results after session ends;# don't delete here — the SDK may read in multiple chunks.- return {- "content": [{"type": "text", "text": content}],- "isError": False,- }+ return _mcp_ok("".join(selected))except FileNotFoundError:- return {- "content": [{"type": "text", "text": f"File not found: {file_path}"}],- "isError": True,- }+ return _mcp_err(f"File not found: {file_path}")except Exception as e:- return {- "content": [{"type": "text", "text": f"Error reading file: {e}"}],- "isError": True,- }+ return _mcp_err(f"Error reading file: {e}")_READ_TOOL_NAME = "Read"@@ -414,9 +352,23 @@ def create_copilot_mcp_server(*, use_e2b: bool = False):SDK's 10 MB JSON buffer, and stash the (truncated) output for theresponse adapter before the SDK can apply its own head-truncation.+ Also expands ``@@agptfile:`` references in args so every registered tool+ (BaseTool, E2B file tools, Read) receives resolved content uniformly.+Applied once to every registered tool."""async def wrapper(args: dict[str, Any]) -> dict[str, Any]:+ user_id, session = get_execution_context()+ if session is not None:+ try:+ args = await expand_file_refs_in_args(args, user_id, session)+ except FileRefExpansionError as exc:+ return _mcp_error(+ f"@@agptfile: reference could not be resolved: {exc}. "+ "Ensure the file exists before referencing it. "+ "For sandbox paths use bash_exec to verify the file exists first; "+ "for workspace files use a workspace:// URI."+ )result = await fn(args)truncated = truncate(result, _MCP_MAX_CHARS)diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.pyindex ace6c1f552..149ef72d0d 100644--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py@@ -2,12 +2,12 @@import pytest+from backend.copilot.context import get_sdk_cwdfrom backend.util.truncate import truncatefrom .tool_adapter import (_MCP_MAX_CHARS,_text_from_mcp_result,- get_sdk_cwd,pop_pending_tool_output,set_execution_context,stash_pending_tool_output,diff --git a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py b/autogpt_platform/backend/backend/copilot/tools/bash_exec.pyindex dd861ea259..1768e97c54 100644--- a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py+++ b/autogpt_platform/backend/backend/copilot/tools/bash_exec.py@@ -21,10 +21,10 @@ from typing import Anyfrom e2b import AsyncSandboxfrom e2b.exceptions import TimeoutException+from backend.copilot.context import E2B_WORKDIR, get_current_sandboxfrom backend.copilot.model import ChatSessionfrom .base import BaseTool-from .e2b_sandbox import E2B_WORKDIRfrom .models import BashExecResponse, ErrorResponse, ToolResponseBasefrom .sandbox import get_workspace_dir, has_full_sandbox, run_sandboxed@@ -94,9 +94,6 @@ class BashExecTool(BaseTool):session_id=session_id,)- # E2B path: run on remote cloud sandbox when available.- from backend.copilot.sdk.tool_adapter import get_current_sandbox-sandbox = get_current_sandbox()if sandbox is not None:return await self._execute_on_e2b(sandbox, command, timeout, session_id)diff --git a/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox.py b/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox.pyindex 383a0dabf9..5f912bdb0e 100644--- a/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox.py+++ b/autogpt_platform/backend/backend/copilot/tools/e2b_sandbox.py@@ -47,7 +47,6 @@ logger = logging.getLogger(__name__)_SANDBOX_KEY_PREFIX = "copilot:e2b:sandbox:"_CREATING_SENTINEL = "creating"-E2B_WORKDIR = "/home/user"# Short TTL for the "creating" sentinel — if the process dies mid-creation the# lock auto-expires so other callers are not blocked forever.diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block.py b/autogpt_platform/backend/backend/copilot/tools/run_block.pyindex ab56a6a222..16c5ec8cbc 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_block.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_block.py@@ -83,7 +83,7 @@ class RunBlockTool(BaseTool):),},},- "required": ["block_id", "input_data"],+ "required": ["block_id", "block_name", "input_data"],}@propertydiff --git a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py b/autogpt_platform/backend/backend/copilot/tools/workspace_files.pyindex f6a1b3356f..143ab10084 100644--- a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py+++ b/autogpt_platform/backend/backend/copilot/tools/workspace_files.py@@ -7,8 +7,12 @@ from typing import Any, Optionalfrom pydantic import BaseModel+from backend.copilot.context import (+ E2B_WORKDIR,+ get_current_sandbox,+ resolve_sandbox_path,+)from backend.copilot.model import ChatSession-from backend.copilot.tools.e2b_sandbox import E2B_WORKDIRfrom backend.copilot.tools.sandbox import make_session_pathfrom backend.data.db_accessors import workspace_dbfrom backend.util.settings import Config@@ -83,13 +87,11 @@ def _resolve_sandbox_path() -> str | ErrorResponse:"""Normalize *path* to an absolute sandbox path under :data:`E2B_WORKDIR`.- Delegates to :func:`~backend.copilot.sdk.e2b_file_tools._resolve_remote`+ Delegates to :func:`~backend.copilot.sdk.e2b_file_tools.resolve_sandbox_path`and wraps any ``ValueError`` into an :class:`ErrorResponse`."""- from backend.copilot.sdk.e2b_file_tools import _resolve_remote-try:- return _resolve_remote(path)+ return resolve_sandbox_path(path)except ValueError:return ErrorResponse(message=f"{param_name} must be within {E2B_WORKDIR}",@@ -99,7 +101,6 @@ def _resolve_sandbox_path(async def _read_source_path(source_path: str, session_id: str) -> bytes | ErrorResponse:"""Read *source_path* from E2B sandbox or local ephemeral directory."""- from backend.copilot.sdk.tool_adapter import get_current_sandboxsandbox = get_current_sandbox()if sandbox is not None:@@ -143,7 +144,6 @@ async def _save_to_path(Returns the resolved path on success, or an ``ErrorResponse`` on failure."""- from backend.copilot.sdk.tool_adapter import get_current_sandboxsandbox = get_current_sandbox()if sandbox is not None:diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsxindex d1c0ce6b0a..8fd9b8fe26 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx@@ -4,6 +4,7 @@ import type { ToolUIPart } from "ai";import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";import { BlockDetailsCard } from "./components/BlockDetailsCard/BlockDetailsCard";+import { BlockInputCard } from "./components/BlockInputCard/BlockInputCard";import { BlockOutputCard } from "./components/BlockOutputCard/BlockOutputCard";import { ErrorCard } from "./components/ErrorCard/ErrorCard";import { SetupRequirementsCard } from "./components/SetupRequirementsCard/SetupRequirementsCard";@@ -17,6 +18,7 @@ import {isRunBlockSetupRequirementsOutput,ToolIcon,} from "./helpers";+import type { RunBlockInput } from "./helpers";export interface RunBlockToolPart {type: string;@@ -36,6 +38,8 @@ export function RunBlockTool({ part }: Props) {part.state === "input-streaming" || part.state === "input-available";const output = getRunBlockToolOutput(part);+ const inputData = (part.input as RunBlockInput | undefined)?.input_data;+ const hasInputData = inputData != null && Object.keys(inputData).length > 0;const isError =part.state === "output-error" ||(!!output && isRunBlockErrorOutput(output));@@ -72,6 +76,8 @@ export function RunBlockTool({ part }: Props) {{hasExpandableContent && output && (<ToolAccordion {...getAccordionMeta(output)}>+ {hasInputData && <BlockInputCard inputData={inputData} />}+{isRunBlockBlockOutput(output) && <BlockOutputCard output={output} />}{isRunBlockDetailsOutput(output) && (diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/BlockInputCard/BlockInputCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/BlockInputCard/BlockInputCard.tsxnew file mode 100644index 0000000000..5ea5f74a8b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/BlockInputCard/BlockInputCard.tsx@@ -0,0 +1,48 @@+"use client";++import { useState } from "react";++import {+ ContentCard,+ ContentCardTitle,+ ContentGrid,+} from "../../../../components/ToolAccordion/AccordionContent";++interface Props {+ inputData: Record<string, unknown>;+}++function renderValue(value: unknown): string {+ if (typeof value === "string") return value;+ return JSON.stringify(value, null, 2);+}++export function BlockInputCard({ inputData }: Props) {+ const [expanded, setExpanded] = useState(false);+ const entries = Object.entries(inputData);++ if (entries.length === 0) return null;++ return (+ <div>+ <button+ className="text-xs text-muted-foreground transition-colors hover:text-foreground"+ onClick={() => setExpanded((prev) => !prev)}+ >+ {expanded ? "Hide inputs" : `Show inputs (${entries.length})`}+ </button>+ {expanded && (+ <ContentGrid className="mb-2 mt-2">+ {entries.map(([key, value]) => (+ <ContentCard key={key}>+ <ContentCardTitle className="text-xs">{key}</ContentCardTitle>+ <pre className="mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-words text-xs text-muted-foreground">+ {renderValue(value)}+ </pre>+ </ContentCard>+ ))}+ </ContentGrid>+ )}+ </div>+ );+}