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): fix tool output file reading between E2B and host (#12646)
Zamil Majdy1aef8b71557b
diff --git a/autogpt_platform/backend/backend/copilot/context.py b/autogpt_platform/backend/backend/copilot/context.pyindex b43aa10c2f..446fed589c 100644--- a/autogpt_platform/backend/backend/copilot/context.py+++ b/autogpt_platform/backend/backend/copilot/context.py@@ -149,7 +149,8 @@ def is_allowed_local_path(path: str, sdk_cwd: str | None = None) -> bool:Allowed:- Files under *sdk_cwd* (``/tmp/copilot-<session>/``)- - Files under ``~/.claude/projects/<encoded-cwd>/<uuid>/tool-results/...``.+ - Files under ``~/.claude/projects/<encoded-cwd>/<uuid>/tool-results/...``+ or ``tool-outputs/...``.The SDK nests tool-results under a conversation UUID directory;the UUID segment is validated with ``_UUID_RE``."""@@ -174,17 +175,20 @@ def is_allowed_local_path(path: str, sdk_cwd: str | None = None) -> bool:# Defence-in-depth: ensure project_dir didn't escape the base.if not project_dir.startswith(SDK_PROJECTS_DIR + os.sep):return False- # Only allow: <encoded-cwd>/<uuid>/tool-results/<file>+ # Only allow: <encoded-cwd>/<uuid>/<tool-dir>/<file># The SDK always creates a conversation UUID directory between- # the project dir and tool-results/.+ # the project dir and the tool directory.+ # Accept both "tool-results" (SDK's persisted outputs) and+ # "tool-outputs" (the model sometimes confuses workspace paths+ # with filesystem paths and generates this variant).if resolved.startswith(project_dir + os.sep):relative = resolved[len(project_dir) + 1 :]parts = relative.split(os.sep)- # Require exactly: [<uuid>, "tool-results", <file>, ...]+ # Require exactly: [<uuid>, "tool-results"|"tool-outputs", <file>, ...]if (len(parts) >= 3and _UUID_RE.match(parts[0])- and parts[1] == "tool-results"+ and parts[1] in ("tool-results", "tool-outputs")):return Truediff --git a/autogpt_platform/backend/backend/copilot/context_test.py b/autogpt_platform/backend/backend/copilot/context_test.pyindex a17bca0de3..bf5fccd186 100644--- a/autogpt_platform/backend/backend/copilot/context_test.py+++ b/autogpt_platform/backend/backend/copilot/context_test.py@@ -134,6 +134,21 @@ def test_is_allowed_local_path_tool_results_with_uuid():_current_project_dir.set("")+def test_is_allowed_local_path_tool_outputs_with_uuid():+ """Files under <encoded-cwd>/<uuid>/tool-outputs/ are also allowed."""+ encoded = "test-encoded-dir"+ conv_uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"+ path = os.path.join(+ SDK_PROJECTS_DIR, encoded, conv_uuid, "tool-outputs", "output.json"+ )++ _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_tool_results_without_uuid_rejected():"""Direct <encoded-cwd>/tool-results/ (no UUID) is rejected."""encoded = "test-encoded-dir"@@ -159,7 +174,7 @@ def test_is_allowed_local_path_sibling_of_tool_results_is_rejected():def test_is_allowed_local_path_valid_uuid_wrong_segment_name_rejected():- """A valid UUID dir but non-'tool-results' second segment is rejected."""+ """A valid UUID dir but non-'tool-results'/'tool-outputs' second segment is rejected."""encoded = "test-encoded-dir"uuid_str = "12345678-1234-5678-9abc-def012345678"path = os.path.join(diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.pyindex 4c4656bc8c..2c95c1721b 100644--- a/autogpt_platform/backend/backend/copilot/prompting.py+++ b/autogpt_platform/backend/backend/copilot/prompting.py@@ -18,6 +18,18 @@ After `write_workspace_file`, embed the `download_url` in Markdown:- Image: ``- Video: ``+### Handling binary/image data in tool outputs — CRITICAL+When a tool output contains base64-encoded binary data (images, PDFs, etc.):+1. **NEVER** try to inline or render the base64 content in your response.+2. **Save** the data to workspace using `write_workspace_file` (pass the base64 data URI as content).+3. **Show** the result via the workspace download URL in Markdown: ``.++### Passing large data between tools — CRITICAL+When tool outputs produce large text that you need to feed into another tool:+- **NEVER** copy-paste the full text into the next tool call argument.+- **Save** the output to a file (workspace or local), then use `@@agptfile:` references.+- This avoids token limits and ensures data integrity.+### File references — @@agptfile:Pass large file content to tools by reference: `@@agptfile:<uri>[<start>-<end>]`- `workspace://<file_id>` or `workspace:///<path>` — workspace files@@ -138,6 +150,11 @@ parent autopilot handles orchestration.# E2B-only notes — E2B has full internet access so gh CLI works there.# Not shown in local (bubblewrap) mode: --unshare-net blocks all network._E2B_TOOL_NOTES = """+### SDK tool-result files in E2B+When you `Read` an SDK tool-result file, it is automatically copied into the+sandbox so `bash_exec` can access it for further processing.+The exact sandbox path is shown in the `[Sandbox copy available at ...]` note.+### GitHub CLI (`gh`) and git- If the user has connected their GitHub account, both `gh` and `git` arepre-authenticated — use them directly without any manual login step.@@ -203,19 +220,22 @@ def _build_storage_supplement(- Files here **survive across sessions indefinitely**### Moving files between storages-- **{file_move_name_1_to_2}**: Copy to persistent workspace-- **{file_move_name_2_to_1}**: Download for processing+- **{file_move_name_1_to_2}**: `write_workspace_file(filename="output.json", source_path="/path/to/local/file")`+- **{file_move_name_2_to_1}**: `read_workspace_file(path="tool-outputs/data.json", save_to_path="{working_dir}/data.json")`### File persistenceImportant files (code, configs, outputs) should be saved to workspace to ensure they persist.### SDK tool-result filesWhen tool outputs are large, the SDK truncates them and saves the full output to-a local file under `~/.claude/projects/.../tool-results/`. To read these files,-always use `Read` (NOT `bash_exec`, NOT `read_workspace_file`).-These files are on the host filesystem — `bash_exec` runs in the sandbox and-CANNOT access them. `read_workspace_file` reads from cloud workspace storage,-where SDK tool-results are NOT stored.+a local file under `~/.claude/projects/.../tool-results/` (or `tool-outputs/`).+To read these files, use `Read` — it reads from the host filesystem.++### Large tool outputs saved to workspace+When a tool output contains `<tool-output-truncated workspace_path="...">`, the+full output is in workspace storage (NOT on the local filesystem). To access it:+- Use `read_workspace_file(path="...", offset=..., length=50000)` for reading sections.+- To process in the sandbox, use `read_workspace_file(path="...", save_to_path="{working_dir}/file.json")` first, then use `bash_exec` on the local copy.{_SHARED_TOOL_NOTES}{extra_notes}"""diff --git a/autogpt_platform/backend/backend/copilot/sdk/conftest.py b/autogpt_platform/backend/backend/copilot/sdk/conftest.pyindex 99f125afd4..879e7b346e 100644--- a/autogpt_platform/backend/backend/copilot/sdk/conftest.py+++ b/autogpt_platform/backend/backend/copilot/sdk/conftest.py@@ -2,14 +2,30 @@from __future__ import annotations+from collections.abc import AsyncIteratorfrom unittest.mock import patchfrom uuid import uuid4import pytest+import pytest_asynciofrom backend.util import json+@pytest_asyncio.fixture(scope="session", loop_scope="session", name="server")+async def _server_noop() -> None:+ """No-op server stub — SDK tests don't need the full backend."""+ return None+++@pytest_asyncio.fixture(+ scope="session", loop_scope="session", autouse=True, name="graph_cleanup"+)+async def _graph_cleanup_noop() -> AsyncIterator[None]:+ """No-op graph cleanup stub."""+ yield++@pytest.fixture()def mock_chat_config():"""Mock ChatConfig so compact_transcript tests skip real config lookup."""diff --git a/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.py b/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.pyindex 03a3132042..a8669a301c 100644--- a/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.py+++ b/autogpt_platform/backend/backend/copilot/sdk/e2b_file_tools.py@@ -8,6 +8,9 @@ SDK-internal paths (``~/.claude/projects/…/tool-results/``) are handledby the separate ``Read`` MCP tool registered in ``tool_adapter.py``."""+import asyncio+import base64+import hashlibimport itertoolsimport jsonimport logging@@ -28,6 +31,12 @@ from backend.copilot.context import (logger = logging.getLogger(__name__)+# Default number of lines returned by ``read_file`` when the caller does not+# specify a limit. Also used as the threshold in ``bridge_to_sandbox`` to+# decide whether the model is requesting the full file (and thus whether the+# bridge copy is worthwhile).+_DEFAULT_READ_LIMIT = 2000+async def _check_sandbox_symlink_escape(sandbox: Any,@@ -89,7 +98,7 @@ def _get_sandbox_and_path(return sandbox, remote-async def _sandbox_write(sandbox: Any, path: str, content: str) -> None:+async def _sandbox_write(sandbox: Any, path: str, content: str | bytes) -> None:"""Write *content* to *path* inside the sandbox.The E2B filesystem API (``sandbox.files.write``) and the command API@@ -102,11 +111,14 @@ async def _sandbox_write(sandbox: Any, path: str, content: str) -> None:To work around this, writes targeting ``/tmp`` are performed via``tee`` through the command API, which runs as the sandbox ``user``and can therefore always overwrite user-owned files.++ *content* may be ``str`` (text) or ``bytes`` (binary). Both paths+ are handled correctly: text is encoded to bytes for the base64 shell+ pipe, and raw bytes are passed through without any encoding."""if path == "/tmp" or path.startswith("/tmp/"):- import base64 as _b64-- encoded = _b64.b64encode(content.encode()).decode()+ raw = content.encode() if isinstance(content, str) else content+ encoded = base64.b64encode(raw).decode()result = await sandbox.commands.run(f"echo {shlex.quote(encoded)} | base64 -d > {shlex.quote(path)}",cwd=E2B_WORKDIR,@@ -128,14 +140,25 @@ 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)))+ limit: int = max(1, int(args.get("limit", _DEFAULT_READ_LIMIT)))if not file_path:return _mcp("file_path is required", error=True)- # SDK-internal paths (tool-results, ephemeral working dir) stay on the host.+ # SDK-internal paths (tool-results/tool-outputs, ephemeral working dir)+ # stay on the host. When E2B is active, also copy the file into the+ # sandbox so bash_exec can access it for further processing.if _is_allowed_local(file_path):- return _read_local(file_path, offset, limit)+ result = _read_local(file_path, offset, limit)+ if not result.get("isError"):+ sandbox = _get_sandbox()+ if sandbox is not None:+ annotation = await bridge_and_annotate(+ sandbox, file_path, offset, limit+ )+ if annotation:+ result["content"][0]["text"] += annotation+ return resultresult = _get_sandbox_and_path(file_path)if isinstance(result, dict):@@ -302,6 +325,103 @@ async def _handle_grep(args: dict[str, Any]) -> dict[str, Any]:return _mcp(output if output else "No matches found.")+# Bridging: copy SDK-internal files into E2B sandbox++# Files larger than this are written to /home/user/ via sandbox.files.write()+# instead of /tmp/ via shell base64, to avoid shell argument length limits+# and E2B command timeouts. Base64 expands content by ~33%, so keep this+# well under the typical Linux ARG_MAX (128 KB).+_BRIDGE_SHELL_MAX_BYTES = 32 * 1024 # 32 KB+# Files larger than this are skipped entirely to avoid excessive transfer times.+_BRIDGE_SKIP_BYTES = 50 * 1024 * 1024 # 50 MB+++async def bridge_to_sandbox(+ sandbox: Any, file_path: str, offset: int, limit: int+) -> str | None:+ """Best-effort copy of a host-side SDK file into the E2B sandbox.++ When the model reads an SDK-internal file (e.g. tool-results), it often+ wants to process the data with bash. Copying the file into the sandbox+ under a stable name lets ``bash_exec`` access it without extra steps.++ Only copies when offset=0 and limit is large enough to indicate the model+ wants the full file. Errors are logged but never propagated.++ Returns the sandbox path on success, or ``None`` on skip/failure.++ Size handling:+ - <= 32 KB: written to ``/tmp/<hash>-<basename>`` via shell base64+ (``_sandbox_write``). Kept small to stay within ARG_MAX.+ - 32 KB - 50 MB: written to ``/home/user/<hash>-<basename>`` via+ ``sandbox.files.write()`` to avoid shell argument length limits.+ - > 50 MB: skipped entirely with a warning.++ The sandbox filename is prefixed with a short hash of the full source+ path to avoid collisions when different source files share the same+ basename (e.g. multiple ``result.json`` files).+ """+ if offset != 0 or limit < _DEFAULT_READ_LIMIT:+ return None+ try:+ expanded = os.path.realpath(os.path.expanduser(file_path))+ basename = os.path.basename(expanded)+ source_id = hashlib.sha256(expanded.encode()).hexdigest()[:12]+ unique_name = f"{source_id}-{basename}"+ file_size = os.path.getsize(expanded)+ if file_size > _BRIDGE_SKIP_BYTES:+ logger.warning(+ "[E2B] Skipping bridge for large file (%d bytes): %s",+ file_size,+ basename,+ )+ return None++ def _read_bytes() -> bytes:+ with open(expanded, "rb") as fh:+ return fh.read()++ raw_content = await asyncio.to_thread(_read_bytes)+ try:+ text_content: str | None = raw_content.decode("utf-8")+ except UnicodeDecodeError:+ text_content = None+ data: str | bytes = text_content if text_content is not None else raw_content+ if file_size <= _BRIDGE_SHELL_MAX_BYTES:+ sandbox_path = f"/tmp/{unique_name}"+ await _sandbox_write(sandbox, sandbox_path, data)+ else:+ sandbox_path = f"/home/user/{unique_name}"+ await sandbox.files.write(sandbox_path, data)+ logger.info(+ "[E2B] Bridged SDK file to sandbox: %s -> %s", basename, sandbox_path+ )+ return sandbox_path+ except Exception:+ logger.warning(+ "[E2B] Failed to bridge SDK file to sandbox: %s",+ file_path,+ exc_info=True,+ )+ return None+++async def bridge_and_annotate(+ sandbox: Any, file_path: str, offset: int, limit: int+) -> str | None:+ """Bridge a host file to the sandbox and return a newline-prefixed annotation.++ Combines ``bridge_to_sandbox`` with the standard annotation suffix so+ callers don't need to duplicate the pattern. Returns a string like+ ``"\\n[Sandbox copy available at /tmp/abc-file.txt]"`` on success, or+ ``None`` if bridging was skipped or failed.+ """+ sandbox_path = await bridge_to_sandbox(sandbox, file_path, offset, limit)+ if sandbox_path is None:+ return None+ return f"\n[Sandbox copy available at {sandbox_path}]"++# Local read (for SDK-internal paths)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 707b7ac956..f4d690f335 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@@ -3,6 +3,7 @@Pure unit tests with no external dependencies (no E2B, no sandbox)."""+import hashlibimport osimport shutilfrom types import SimpleNamespace@@ -13,12 +14,26 @@ import pytestfrom backend.copilot.context import E2B_WORKDIR, SDK_PROJECTS_DIR, _current_project_dirfrom .e2b_file_tools import (+ _BRIDGE_SHELL_MAX_BYTES,+ _BRIDGE_SKIP_BYTES,+ _DEFAULT_READ_LIMIT,_check_sandbox_symlink_escape,_read_local,_sandbox_write,+ bridge_and_annotate,+ bridge_to_sandbox,resolve_sandbox_path,)++def _expected_bridge_path(file_path: str, prefix: str = "/tmp") -> str:+ """Compute the expected sandbox path for a bridged file."""+ expanded = os.path.realpath(os.path.expanduser(file_path))+ basename = os.path.basename(expanded)+ source_id = hashlib.sha256(expanded.encode()).hexdigest()[:12]+ return f"{prefix}/{source_id}-{basename}"++# ---------------------------------------------------------------------------# resolve_sandbox_path — sandbox path normalisation & boundary enforcement# ---------------------------------------------------------------------------@@ -91,9 +106,9 @@ class TestResolveSandboxPath:# ---------------------------------------------------------------------------# _read_local — host filesystem reads with allowlist enforcement#-# In E2B mode, _read_local only allows tool-results paths (via-# is_allowed_local_path without sdk_cwd). Regular files live on the-# sandbox, not the host.+# In E2B mode, _read_local only allows tool-results/tool-outputs paths+# (via is_allowed_local_path without sdk_cwd). Regular files live on+# the sandbox, not the host.# ---------------------------------------------------------------------------@@ -119,7 +134,7 @@ class TestReadLocal:)token = _current_project_dir.set(encoded)try:- result = _read_local(filepath, offset=0, limit=2000)+ result = _read_local(filepath, offset=0, limit=_DEFAULT_READ_LIMIT)assert result["isError"] is Falseassert "line 1" in result["content"][0]["text"]assert "line 2" in result["content"][0]["text"]@@ -127,6 +142,25 @@ class TestReadLocal:_current_project_dir.reset(token)os.unlink(filepath)+ def test_read_tool_outputs_file(self):+ """Reading a tool-outputs file should also succeed."""+ encoded = "-tmp-copilot-e2b-test-read-outputs"+ tool_outputs_dir = os.path.join(+ SDK_PROJECTS_DIR, encoded, self._CONV_UUID, "tool-outputs"+ )+ os.makedirs(tool_outputs_dir, exist_ok=True)+ filepath = os.path.join(tool_outputs_dir, "sdk-abc123.json")+ with open(filepath, "w") as f:+ f.write('{"data": "test"}\n')+ token = _current_project_dir.set(encoded)+ try:+ result = _read_local(filepath, offset=0, limit=_DEFAULT_READ_LIMIT)+ assert result["isError"] is False+ assert "test" in result["content"][0]["text"]+ finally:+ _current_project_dir.reset(token)+ shutil.rmtree(os.path.join(SDK_PROJECTS_DIR, encoded), ignore_errors=True)+def test_read_disallowed_path_blocked(self):"""Reading /etc/passwd should be blocked by the allowlist."""result = _read_local("/etc/passwd", offset=0, limit=10)@@ -335,3 +369,199 @@ class TestSandboxWrite:encoded_in_cmd = call_args.split("echo ")[1].split(" |")[0].strip("'")decoded = base64.b64decode(encoded_in_cmd).decode()assert decoded == content+++# ---------------------------------------------------------------------------+# bridge_to_sandbox — copy SDK-internal files into E2B sandbox+# ---------------------------------------------------------------------------+++def _make_bridge_sandbox() -> SimpleNamespace:+ """Build a sandbox mock suitable for bridge_to_sandbox tests."""+ run_result = SimpleNamespace(stdout="", stderr="", exit_code=0)+ commands = SimpleNamespace(run=AsyncMock(return_value=run_result))+ files = SimpleNamespace(write=AsyncMock())+ return SimpleNamespace(commands=commands, files=files)+++class TestBridgeToSandbox:+ @pytest.mark.asyncio+ async def test_happy_path_small_file(self, tmp_path):+ """A small file is bridged to /tmp/<hash>-<basename> via _sandbox_write."""+ f = tmp_path / "result.json"+ f.write_text('{"ok": true}')+ sandbox = _make_bridge_sandbox()++ result = await bridge_to_sandbox(+ sandbox, str(f), offset=0, limit=_DEFAULT_READ_LIMIT+ )++ expected = _expected_bridge_path(str(f))+ assert result == expected+ sandbox.commands.run.assert_called_once()+ cmd = sandbox.commands.run.call_args[0][0]+ assert "result.json" in cmd+ sandbox.files.write.assert_not_called()++ @pytest.mark.asyncio+ async def test_skip_when_offset_nonzero(self, tmp_path):+ """Bridging is skipped when offset != 0 (partial read)."""+ f = tmp_path / "data.txt"+ f.write_text("content")+ sandbox = _make_bridge_sandbox()++ result = await bridge_to_sandbox(+ sandbox, str(f), offset=10, limit=_DEFAULT_READ_LIMIT+ )++ assert result is None+ sandbox.commands.run.assert_not_called()+ sandbox.files.write.assert_not_called()++ @pytest.mark.asyncio+ async def test_skip_when_limit_too_small(self, tmp_path):+ """Bridging is skipped when limit < _DEFAULT_READ_LIMIT (partial read)."""+ f = tmp_path / "data.txt"+ f.write_text("content")+ sandbox = _make_bridge_sandbox()++ await bridge_to_sandbox(sandbox, str(f), offset=0, limit=100)++ sandbox.commands.run.assert_not_called()+ sandbox.files.write.assert_not_called()++ @pytest.mark.asyncio+ async def test_nonexistent_file_does_not_raise(self, tmp_path):+ """Bridging a non-existent file logs but does not propagate errors."""+ sandbox = _make_bridge_sandbox()++ await bridge_to_sandbox(+ sandbox, str(tmp_path / "ghost.txt"), offset=0, limit=_DEFAULT_READ_LIMIT+ )++ sandbox.commands.run.assert_not_called()+ sandbox.files.write.assert_not_called()++ @pytest.mark.asyncio+ async def test_sandbox_write_failure_returns_none(self, tmp_path):+ """If sandbox write fails, returns None (best-effort)."""+ f = tmp_path / "data.txt"+ f.write_text("content")+ sandbox = _make_bridge_sandbox()+ sandbox.commands.run.side_effect = RuntimeError("E2B timeout")++ result = await bridge_to_sandbox(+ sandbox, str(f), offset=0, limit=_DEFAULT_READ_LIMIT+ )++ assert result is None++ @pytest.mark.asyncio+ async def test_large_file_uses_files_api(self, tmp_path):+ """Files > 32 KB but <= 50 MB are written to /home/user/ via files.write."""+ f = tmp_path / "big.json"+ f.write_bytes(b"x" * (_BRIDGE_SHELL_MAX_BYTES + 1))+ sandbox = _make_bridge_sandbox()++ result = await bridge_to_sandbox(+ sandbox, str(f), offset=0, limit=_DEFAULT_READ_LIMIT+ )++ expected = _expected_bridge_path(str(f), prefix="/home/user")+ assert result == expected+ sandbox.files.write.assert_called_once()+ call_args = sandbox.files.write.call_args[0]+ assert call_args[0] == expected+ sandbox.commands.run.assert_not_called()++ @pytest.mark.asyncio+ async def test_small_binary_file_preserves_bytes(self, tmp_path):+ """A small binary file is bridged to /tmp via base64 without corruption."""+ binary_data = bytes(range(256))+ f = tmp_path / "image.png"+ f.write_bytes(binary_data)+ sandbox = _make_bridge_sandbox()++ result = await bridge_to_sandbox(+ sandbox, str(f), offset=0, limit=_DEFAULT_READ_LIMIT+ )++ expected = _expected_bridge_path(str(f))+ assert result == expected+ sandbox.commands.run.assert_called_once()+ cmd = sandbox.commands.run.call_args[0][0]+ assert "base64" in cmd+ sandbox.files.write.assert_not_called()++ @pytest.mark.asyncio+ async def test_large_binary_file_writes_raw_bytes(self, tmp_path):+ """A large binary file is bridged to /home/user/ as raw bytes."""+ binary_data = bytes(range(256)) * 200+ f = tmp_path / "photo.jpg"+ f.write_bytes(binary_data)+ sandbox = _make_bridge_sandbox()++ result = await bridge_to_sandbox(+ sandbox, str(f), offset=0, limit=_DEFAULT_READ_LIMIT+ )++ expected = _expected_bridge_path(str(f), prefix="/home/user")+ assert result == expected+ sandbox.files.write.assert_called_once()+ call_args = sandbox.files.write.call_args[0]+ assert call_args[0] == expected+ assert call_args[1] == binary_data+ sandbox.commands.run.assert_not_called()++ @pytest.mark.asyncio+ async def test_very_large_file_skipped(self, tmp_path):+ """Files > 50 MB are skipped entirely."""+ f = tmp_path / "huge.bin"+ # Create a sparse file to avoid actually writing 50 MB+ with open(f, "wb") as fh:+ fh.seek(_BRIDGE_SKIP_BYTES + 1)+ fh.write(b"\0")+ sandbox = _make_bridge_sandbox()++ result = await bridge_to_sandbox(+ sandbox, str(f), offset=0, limit=_DEFAULT_READ_LIMIT+ )++ assert result is None++ sandbox.commands.run.assert_not_called()+ sandbox.files.write.assert_not_called()+++# ---------------------------------------------------------------------------+# bridge_and_annotate — shared helper wrapping bridge_to_sandbox + annotation+# ---------------------------------------------------------------------------+++class TestBridgeAndAnnotate:+ @pytest.mark.asyncio+ async def test_returns_annotation_on_success(self, tmp_path):+ """On success, returns a newline-prefixed annotation with the sandbox path."""+ f = tmp_path / "data.json"+ f.write_text('{"ok": true}')+ sandbox = _make_bridge_sandbox()++ annotation = await bridge_and_annotate(+ sandbox, str(f), offset=0, limit=_DEFAULT_READ_LIMIT+ )++ expected_path = _expected_bridge_path(str(f))+ assert annotation == f"\n[Sandbox copy available at {expected_path}]"++ @pytest.mark.asyncio+ async def test_returns_none_when_skipped(self, tmp_path):+ """When bridging is skipped (e.g. offset != 0), returns None."""+ f = tmp_path / "data.json"+ f.write_text("content")+ sandbox = _make_bridge_sandbox()++ annotation = await bridge_and_annotate(+ sandbox, str(f), offset=10, limit=_DEFAULT_READ_LIMIT+ )++ assert annotation is Nonediff --git a/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.pyindex 2699b0a008..3dd9de093d 100644--- a/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/security_hooks_test.py@@ -136,8 +136,20 @@ def test_read_tool_results_allowed():_current_project_dir.reset(token)+def test_read_tool_outputs_allowed():+ """tool-outputs/ paths should be allowed, same as tool-results/."""+ home = os.path.expanduser("~")+ path = f"{home}/.claude/projects/-tmp-copilot-abc123/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tool-outputs/12345.txt"+ token = _current_project_dir.set("-tmp-copilot-abc123")+ try:+ result = _validate_tool_access("Read", {"file_path": path}, sdk_cwd=SDK_CWD)+ assert result == {}+ finally:+ _current_project_dir.reset(token)++def test_read_claude_projects_settings_json_denied():- """SDK-internal artifacts like settings.json are NOT accessible — only tool-results/ is."""+ """SDK-internal artifacts like settings.json are NOT accessible — only tool-results/tool-outputs is."""home = os.path.expanduser("~")path = f"{home}/.claude/projects/-tmp-copilot-abc123/settings.json"token = _current_project_dir.set("-tmp-copilot-abc123")diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.pyindex b2af3c9183..8a2eae5224 100644--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py@@ -38,7 +38,7 @@ from backend.copilot.tools import TOOL_REGISTRYfrom backend.copilot.tools.base import BaseToolfrom backend.util.truncate import truncate-from .e2b_file_tools import E2B_FILE_TOOL_NAMES, E2B_FILE_TOOLS+from .e2b_file_tools import E2B_FILE_TOOL_NAMES, E2B_FILE_TOOLS, bridge_and_annotateif TYPE_CHECKING:from e2b import AsyncSandbox@@ -387,7 +387,16 @@ async def _read_file_handler(args: dict[str, Any]) -> dict[str, Any]:selected = list(itertools.islice(f, offset, offset + limit))# Cleanup happens in _cleanup_sdk_tool_results after session ends;# don't delete here — the SDK may read in multiple chunks.- return _mcp_ok("".join(selected))+ #+ # When E2B is active, also copy the file into the sandbox so+ # bash_exec can process it (the model often uses Read then bash).+ text = "".join(selected)+ sandbox = _current_sandbox.get(None)+ if sandbox is not None:+ annotation = await bridge_and_annotate(sandbox, resolved, offset, limit)+ if annotation:+ text += annotation+ return _mcp_ok(text)except FileNotFoundError:return _mcp_err(f"File not found: {file_path}")except Exception as e:diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.pyindex 107c302844..1187dcc97c 100644--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py@@ -619,3 +619,95 @@ class TestSDKDisallowedTools:def test_webfetch_tool_is_disallowed(self):"""WebFetch is disallowed due to SSRF risk."""assert "WebFetch" in SDK_DISALLOWED_TOOLS+++# ---------------------------------------------------------------------------+# _read_file_handler — bridge_and_annotate integration+# ---------------------------------------------------------------------------+++class TestReadFileHandlerBridge:+ """Verify that _read_file_handler calls bridge_and_annotate when a sandbox is active."""++ @pytest.fixture(autouse=True)+ def _init_context(self):+ set_execution_context(+ user_id="test",+ session=None, # type: ignore[arg-type]+ sandbox=None,+ sdk_cwd="/tmp/copilot-bridge-test",+ )++ @pytest.mark.asyncio+ async def test_bridge_called_when_sandbox_active(self, tmp_path, monkeypatch):+ """When a sandbox is set, bridge_and_annotate is called and its annotation appended."""+ from backend.copilot.context import _current_sandbox++ from .tool_adapter import _read_file_handler++ test_file = tmp_path / "tool-results" / "data.json"+ test_file.parent.mkdir(parents=True, exist_ok=True)+ test_file.write_text('{"ok": true}\n')++ monkeypatch.setattr(+ "backend.copilot.sdk.tool_adapter.is_allowed_local_path",+ lambda path, cwd: True,+ )++ fake_sandbox = object()+ token = _current_sandbox.set(fake_sandbox) # type: ignore[arg-type]+ try:+ bridge_calls: list[tuple] = []++ async def fake_bridge_and_annotate(sandbox, file_path, offset, limit):+ bridge_calls.append((sandbox, file_path, offset, limit))+ return "\n[Sandbox copy available at /tmp/abc-data.json]"++ monkeypatch.setattr(+ "backend.copilot.sdk.tool_adapter.bridge_and_annotate",+ fake_bridge_and_annotate,+ )++ result = await _read_file_handler(+ {"file_path": str(test_file), "offset": 0, "limit": 2000}+ )++ assert result["isError"] is False+ assert len(bridge_calls) == 1+ assert bridge_calls[0][0] is fake_sandbox+ assert "/tmp/abc-data.json" in result["content"][0]["text"]+ finally:+ _current_sandbox.reset(token)++ @pytest.mark.asyncio+ async def test_bridge_not_called_without_sandbox(self, tmp_path, monkeypatch):+ """When no sandbox is set, bridge_and_annotate is not called."""+ from .tool_adapter import _read_file_handler++ test_file = tmp_path / "tool-results" / "data.json"+ test_file.parent.mkdir(parents=True, exist_ok=True)+ test_file.write_text('{"ok": true}\n')++ monkeypatch.setattr(+ "backend.copilot.sdk.tool_adapter.is_allowed_local_path",+ lambda path, cwd: True,+ )++ bridge_calls: list[tuple] = []++ async def fake_bridge_and_annotate(sandbox, file_path, offset, limit):+ bridge_calls.append((sandbox, file_path, offset, limit))+ return "\n[Sandbox copy available at /tmp/abc-data.json]"++ monkeypatch.setattr(+ "backend.copilot.sdk.tool_adapter.bridge_and_annotate",+ fake_bridge_and_annotate,+ )++ result = await _read_file_handler(+ {"file_path": str(test_file), "offset": 0, "limit": 2000}+ )++ assert result["isError"] is False+ assert len(bridge_calls) == 0+ assert "Sandbox copy" not in result["content"][0]["text"]diff --git a/autogpt_platform/backend/backend/copilot/tools/base.py b/autogpt_platform/backend/backend/copilot/tools/base.pyindex 87820a1bf9..3de0ff7c36 100644--- a/autogpt_platform/backend/backend/copilot/tools/base.py+++ b/autogpt_platform/backend/backend/copilot/tools/base.py@@ -91,10 +91,16 @@ async def _persist_and_summarize(f"\nFull output ({total:,} chars) saved to workspace. "f"Use read_workspace_file("f'path="{file_path}", offset=<char_offset>, length=50000) '- f"to read any section."+ f"to read any section. "+ f"To process the file in the sandbox/working dir, use "+ f"read_workspace_file("+ f'path="{file_path}", save_to_path="<working_dir>/{tool_call_id}.json") '+ f"first, then use bash_exec to work with the local copy.")+ # Use workspace:// prefix so the model doesn't confuse the workspace path+ # with a local filesystem path (e.g. ~/.claude/projects/.../tool-outputs/).return (- f'<tool-output-truncated total_chars={total} path="{file_path}">\n'+ f'<tool-output-truncated total_chars={total} workspace_path="{file_path}">\n'f"{preview}\n"f"{retrieval}\n"f"</tool-output-truncated>"diff --git a/autogpt_platform/backend/backend/copilot/tools/base_test.py b/autogpt_platform/backend/backend/copilot/tools/base_test.pyindex 803b76baba..101481a48e 100644--- a/autogpt_platform/backend/backend/copilot/tools/base_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/base_test.py@@ -67,7 +67,7 @@ class TestPersistAndSummarize:assert "<tool-output-truncated" in resultassert "</tool-output-truncated>" in resultassert "total_chars=200000" in result- assert 'path="tool-outputs/tc-123.json"' in result+ assert 'workspace_path="tool-outputs/tc-123.json"' in resultassert "read_workspace_file" in result# Middle-out sentinel from truncate()assert "omitted" in result