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): make SDK tool-result reads navigable + redirect wrong-tool access (#13179)
Zamil Majdy7c23c878ffc9
diff --git a/autogpt_platform/backend/backend/copilot/context.py b/autogpt_platform/backend/backend/copilot/context.pyindex 13aca2241e..b5a422fde4 100644--- a/autogpt_platform/backend/backend/copilot/context.py+++ b/autogpt_platform/backend/backend/copilot/context.py@@ -157,6 +157,101 @@ def is_sdk_tool_path(path: str) -> bool:)+# Anchored matches for host-side SDK tool-result paths. Used by+# wrong-tool detectors (bash_exec, read_workspace_file) to redirect the+# model to ``read_tool_result`` / ``@@agptfile:`` rather than letting it+# bounce off ``Permission denied`` repeatedly.+#+# Two shapes are matched:+# (1) absolute SDK path: /<...>/.claude/projects/<cwd>/<uuid>/tool-results/<file>.json+# (2) model shorthand: tool-(results|outputs)/<toolu|mcp>_<id>.json+#+# The shorthand branch requires the SDK's actual ID prefix so a user+# repo that happens to use a ``tool-outputs/`` directory name does NOT+# trigger a false redirect on legitimate paths like+# ``my-pipeline/tool-outputs/data.json``.+_SDK_TOOL_RESULT_RE = re.compile(+ r"(?:^|[/\s'\"])/?\.claude/projects/[^/\s]+/[^/\s]+/tool-(?:results|outputs)/"+ r"[\w-]+\.json"+ r"|(?:^|[/\s'\"])tool-(?:results|outputs)/(?:toolu|mcp)_[\w-]+\.json",+ re.IGNORECASE,+)+++def looks_like_sdk_tool_result_path(text: str) -> bool:+ """Return True if *text* references a host-side SDK tool-result file.++ Anchored regex match — avoids false positives on user paths that+ happen to contain a ``tool-outputs/`` directory by requiring either+ the full ``.claude/projects/<…>/tool-(results|outputs)/<file>.json``+ shape or the SDK's ``(toolu|mcp)_<id>.json`` filename pattern.+ """+ if not text:+ return False+ return _SDK_TOOL_RESULT_RE.search(text) is not None+++# Shell separators used by ``_extract_offending_segment`` to bound the+# path-like token that triggered the redirect. Quotes are included so a+# quoted SDK path inside a command (e.g. ``cat "/root/.claude/..."``)+# extracts the path without the surrounding quotes.+_SHELL_TOKEN_DELIMS = frozenset(" |;&<>'\"\n\t`()")+++def _extract_offending_segment(text: str) -> str:+ """Return the path-shaped token in *text* that tripped a redirect hint.++ Uses the regex match position as the anchor (so false positives like+ ``my-pipeline/tool-outputs/data.json`` never reach this path) and+ walks outward to shell-token delimiters to capture the full+ surrounding path (handles ``--file=/path/...`` and quoted paths).+ Falls back to the first whitespace-separated token so callers that+ pass an isolated path (e.g. ``read_workspace_file``) still echo+ cleanly.+ """+ match = _SDK_TOOL_RESULT_RE.search(text)+ if match:+ # Walk outward from the matched span to shell-token boundaries+ # so we capture the full path token, not just the regex hit+ # (which excludes the leading slash on the absolute branch).+ end = match.end()+ while end < len(text) and text[end] not in _SHELL_TOKEN_DELIMS:+ end += 1+ start = match.start()+ # Skip any leading delimiter the regex consumed (e.g. the space+ # before "/root/.claude/...").+ while start < end and text[start] in _SHELL_TOKEN_DELIMS:+ start += 1+ while start > 0 and text[start - 1] not in _SHELL_TOKEN_DELIMS:+ start -= 1+ return text[start:end]+ stripped = text.strip()+ return stripped.split()[0] if stripped else ""+++def sdk_tool_result_redirect_hint(path_or_command: str) -> str:+ """User-facing redirect message for wrong-tool access to SDK tool-results.++ Names the two right ways to get at the bytes so the model doesn't+ burn another turn retrying with yet another wrong tool, and quotes+ the *actual* matched SDK path (not just ``bash``/``cat``) so the+ model knows which fragment of its command tripped the redirect.+ """+ fragment = _extract_offending_segment(path_or_command) if path_or_command else ""+ return (+ "This path lives in the Claude Agent SDK's host-side "+ "tool-results directory, which is not mounted into the bash "+ "sandbox / workspace storage. Use one of:\n"+ " - `read_tool_result(file_path=...)` for direct reads "+ "(supports offset/limit; auto-unwraps the MCP envelope).\n"+ " - `@@agptfile:<absolute-path>[<start>-<end>]` inside another "+ "tool's argument to inline a slice of the file's content "+ '(e.g. `bash_exec(command="echo @@agptfile:/root/.claude/'+ 'projects/.../result.json[1-200] | jq .field")`).\n'+ f"Offending fragment: {fragment!r}"+ )++def resolve_sandbox_path(path: str) -> str:"""Normalise *path* to an absolute sandbox path under an allowed directory.diff --git a/autogpt_platform/backend/backend/copilot/context_test.py b/autogpt_platform/backend/backend/copilot/context_test.pyindex bf5fccd186..0c594bc6b2 100644--- a/autogpt_platform/backend/backend/copilot/context_test.py+++ b/autogpt_platform/backend/backend/copilot/context_test.py@@ -242,3 +242,56 @@ def test_resolve_sandbox_path_tmp_escape_raises():def test_resolve_sandbox_path_tmp_prefix_collision_raises():with pytest.raises(ValueError):resolve_sandbox_path("/tmp_evil/malicious.txt")+++class TestSdkToolResultRedirectHint:+ """``sdk_tool_result_redirect_hint`` builds the "Offending fragment"+ line from the path-shaped token in *path_or_command*, not from the+ command's executable. Regression coverage for the case where+ ``cat /…/tool-results/foo.json | jq`` previously echoed+ ``Offending fragment: 'cat'`` — useless to the model."""++ def test_absolute_sdk_path_in_bash_command(self):+ from backend.copilot.context import sdk_tool_result_redirect_hint++ cmd = (+ "cat /root/.claude/projects/-tmp-abc/def/tool-results/"+ "toolu_x.json | jq ."+ )+ msg = sdk_tool_result_redirect_hint(cmd)+ assert (+ "Offending fragment: '/root/.claude/projects/-tmp-abc/def/"+ "tool-results/toolu_x.json'"+ ) in msg+ assert "'cat'" not in msg++ def test_quoted_path_unwraps_quotes(self):+ from backend.copilot.context import sdk_tool_result_redirect_hint++ cmd = 'cat "/root/.claude/projects/-a/b/tool-results/x.json"'+ msg = sdk_tool_result_redirect_hint(cmd)+ assert (+ "Offending fragment: '/root/.claude/projects/-a/b/tool-results/x.json'"+ in msg+ )++ def test_relative_shorthand(self):+ from backend.copilot.context import sdk_tool_result_redirect_hint++ msg = sdk_tool_result_redirect_hint("cat tool-outputs/toolu_x.json | head")+ assert "Offending fragment: 'tool-outputs/toolu_x.json'" in msg++ def test_bare_path_input(self):+ # ``read_workspace_file`` passes a bare path, not a command.+ from backend.copilot.context import sdk_tool_result_redirect_hint++ msg = sdk_tool_result_redirect_hint("tool-outputs/toolu_y.json")+ assert "Offending fragment: 'tool-outputs/toolu_y.json'" in msg++ def test_empty_input_fragment(self):+ from backend.copilot.context import sdk_tool_result_redirect_hint++ # Defensive: never crash on an empty input; the message just+ # echoes an empty fragment.+ msg = sdk_tool_result_redirect_hint("")+ assert "Offending fragment: ''" in msgdiff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.pyindex 5e42977160..4efac1a3c9 100644--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py@@ -421,9 +421,15 @@ async def _read_file_handler(args: dict[str, Any]) -> dict[str, Any]:)file_path = args.get("file_path", "")+ char_offset_arg = args.get("char_offset")+ char_limit_arg = args.get("char_limit")try:offset = max(0, int(args.get("offset", 0)))limit = max(1, int(args.get("limit", 2000)))+ char_offset = (+ max(0, int(char_offset_arg)) if char_offset_arg is not None else None+ )+ char_limit = max(1, int(char_limit_arg)) if char_limit_arg is not None else Noneexcept (ValueError, TypeError):return _mcp_err("Invalid offset/limit \u2014 must be integers.")@@ -460,16 +466,48 @@ async def _read_file_handler(args: dict[str, Any]) -> dict[str, Any]:resolved = os.path.realpath(os.path.expanduser(file_path))try:+ # Read the whole file: tool-result envelopes are usually small JSON+ # but the payload inside is often one massive minified line, so+ # line-based offset/limit applied to the raw bytes is useless.+ # _navigable_tool_result_text() unwraps the envelope and pretty-+ # prints inner JSON so line offsets actually slice the payload.with open(resolved, encoding="utf-8", errors="replace") as f:- selected = list(itertools.islice(f, offset, offset + limit))+ raw = f.read()+ navigable = _navigable_tool_result_text(raw)+ if char_offset is not None or char_limit is not None:+ # Character-mode slicing: precise control for huge payloads+ # where even the pretty-printed inner JSON has multi-KB lines+ # (e.g. base64 blobs in tool results).+ start = char_offset or 0+ end = start + char_limit if char_limit is not None else len(navigable)+ text = navigable[start:end]+ else:+ lines = navigable.splitlines(keepends=True)+ text = "".join(lines[offset : offset + limit])# Cleanup happens in _cleanup_sdk_tool_results after session ends;# don't delete here — the SDK may read in multiple chunks.## 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)+ # CAVEAT: only bridge when the on-disk bytes and what the model+ # just read are the same — i.e. when ``_navigable_tool_result_text``+ # did *not* transform the content. If we pretty-printed an MCP+ # envelope, the model sees a pretty-printed slice while the+ # bridged sandbox file would hold the raw envelope; bash commands+ # operating on the bridged copy would then see different content+ # than the model just read, leading to silent format-mismatch+ # bugs. Same constraint applies to char-mode slices. The new+ # bash_exec SDK-path redirect (added in this PR) covers the+ # alternative workflow when the bridge is skipped — the model+ # can use ``read_tool_result`` again with offsets, or pipe a+ # slice via ``@@agptfile:<path>[<start>-<end>]``.sandbox = _current_sandbox.get(None)- if sandbox is not None:+ if (+ sandbox is not None+ and navigable == raw+ and char_offset is None+ and char_limit is None+ ):annotation = await bridge_and_annotate(sandbox, resolved, offset, limit)if annotation:text += annotation@@ -480,13 +518,60 @@ async def _read_file_handler(args: dict[str, Any]) -> dict[str, Any]:return _mcp_err(f"Error reading file: {e}")+def _navigable_tool_result_text(raw: str) -> str:+ """Return *raw* in a form the model can actually slice with offset/limit.++ Tool-result files are stored as the MCP envelope ``[{"type":"text",+ "text": "<payload>"}]``. The outer list is pretty-printed but the+ inner ``text`` field is one giant minified string, so line-based+ offset/limit on the raw file content slices the *envelope* — useless.++ This helper unwraps the envelope (when the shape matches) and+ pretty-prints the inner payload (when it parses as JSON) so the model+ can navigate ``execution.node_executions[…].error`` etc. with normal+ line offsets. Falls back to the raw text on any mismatch.+ """+ try:+ outer = json.loads(raw)+ except (ValueError, TypeError):+ return raw+ inner = _extract_single_text_block(outer)+ if inner is None:+ return raw+ try:+ return json.dumps(json.loads(inner), indent=2, ensure_ascii=False)+ except (ValueError, TypeError):+ # Inner text wasn't JSON (e.g. a bash command's stdout) — return+ # it raw so the model sees the payload without the envelope noise.+ return inner+++def _extract_single_text_block(envelope: object) -> str | None:+ """Return the text of a single-text-block MCP envelope, else None.++ Matches ``[{"type": "text", "text": <str>}]`` exactly. Returns None+ for envelopes with images, multiple blocks, or any other shape.+ """+ if not isinstance(envelope, list) or len(envelope) != 1:+ return None+ block = envelope[0]+ if not isinstance(block, dict) or block.get("type") != "text":+ return None+ text = block.get("text")+ return text if isinstance(text, str) else None++_READ_TOOL_NAME = "read_tool_result"_READ_TOOL_DESCRIPTION = ("Read an SDK-internal tool-result file or a workspace:// URI. ""Use this tool only for paths under ~/.claude/projects/.../tool-results/ ""or tool-outputs/, and for workspace:// URIs returned by other tools. ""For files in the working directory use read_file instead. "- "Use offset and limit to read specific line ranges for large files."+ "MCP envelopes are auto-unwrapped and JSON payloads pretty-printed, "+ "so offset/limit (line-based) slice into the actual payload, not the "+ "envelope wrapper. For piping a slice into another tool's command, "+ "use `@@agptfile:<absolute-path>[<start>-<end>]` in that tool's "+ "argument instead — it works in bash_exec and avoids a round-trip.")_READ_TOOL_SCHEMA = {"type": "object",@@ -503,6 +588,22 @@ _READ_TOOL_SCHEMA = {"type": "integer","description": "Number of lines to read. Default: 2000",},+ "char_offset": {+ "type": "integer",+ "description": (+ "Character offset to start reading from (0-indexed). "+ "Overrides `offset`. Use when even pretty-printed lines "+ "are too long to slice with line offsets (e.g. base64 "+ "blobs in a tool result)."+ ),+ },+ "char_limit": {+ "type": "integer",+ "description": (+ "Number of characters to read. Pairs with `char_offset` "+ "and overrides `limit`."+ ),+ },},}diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.pyindex 01944d65da..b575ab9602 100644--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter_test.py@@ -722,6 +722,113 @@ class TestReadFileHandlerBridge:finally:_current_sandbox.reset(token)+ @pytest.mark.asyncio+ async def test_bridge_skipped_when_envelope_pretty_printed(+ self, tmp_path, monkeypatch+ ):+ """Pretty-printing the MCP envelope transforms the content the+ model reads. The on-disk bytes are the raw envelope, so bridging+ them to the sandbox would point the model at content that+ doesn't match what ``read_tool_result`` just returned. Skip the+ bridge in that case — the model can re-read or pipe via+ ``@@agptfile:`` if it needs bash access."""+ from backend.copilot.context import _current_sandbox++ from .tool_adapter import _read_file_handler++ # MCP envelope with JSON inner payload — _navigable_tool_result_text+ # will pretty-print this, so navigable != raw.+ test_file = tmp_path / "tool-results" / "envelope.json"+ test_file.parent.mkdir(parents=True, exist_ok=True)+ payload = {"execution": {"node_executions": [{"status": "OK"}]}}+ envelope = json.dumps([{"type": "text", "text": json.dumps(payload)}])+ test_file.write_text(envelope)++ monkeypatch.setattr(+ "backend.copilot.sdk.tool_adapter.is_sdk_tool_path",+ lambda path: True,+ )++ fake_sandbox: Any = object()+ token = _current_sandbox.set(fake_sandbox)+ 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-envelope.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+ # The bridge MUST NOT be called: model sees pretty-printed+ # JSON but the on-disk file holds the raw envelope.+ assert bridge_calls == []+ assert "Sandbox copy" not in result["content"][0]["text"]+ # And the returned text is the pretty-printed payload, not+ # the envelope wrapper, so the slicing is useful.+ assert '"status": "OK"' in result["content"][0]["text"]+ finally:+ _current_sandbox.reset(token)++ @pytest.mark.asyncio+ async def test_bridge_skipped_when_char_offset_used(self, tmp_path, monkeypatch):+ """``char_offset`` slices the navigable content; the on-disk+ bytes don't carry that slice, so bridging would mislead bash+ operations into reading a different range than the model just+ saw. Skip the bridge regardless of whether pretty-printing+ kicked in for this file."""+ from backend.copilot.context import _current_sandbox++ from .tool_adapter import _read_file_handler++ # File whose content is NOT an envelope — navigable == raw.+ # The bridge would normally fire here; char_offset must still+ # suppress it.+ test_file = tmp_path / "tool-results" / "plain.txt"+ test_file.parent.mkdir(parents=True, exist_ok=True)+ test_file.write_text("the quick brown fox " * 100)++ monkeypatch.setattr(+ "backend.copilot.sdk.tool_adapter.is_sdk_tool_path",+ lambda path: True,+ )++ fake_sandbox: Any = object()+ token = _current_sandbox.set(fake_sandbox)+ 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-plain.txt]"++ monkeypatch.setattr(+ "backend.copilot.sdk.tool_adapter.bridge_and_annotate",+ fake_bridge_and_annotate,+ )++ result = await _read_file_handler(+ {+ "file_path": str(test_file),+ "char_offset": 100,+ "char_limit": 50,+ }+ )++ assert result["isError"] is False+ assert bridge_calls == []+ assert "Sandbox copy" not in result["content"][0]["text"]+ finally:+ _current_sandbox.reset(token)+@pytest.mark.asyncioasync def test_bridge_not_called_without_sandbox(self, tmp_path, monkeypatch):"""When no sandbox is set, bridge_and_annotate is not called."""@@ -1079,3 +1186,50 @@ class TestCreateCopilotMcpServerHidden:handler = instance.request_handlers[ListToolsRequest]result = await handler(ListToolsRequest(method="tools/list"))return {t.name for t in result.root.tools}+++class TestNavigableToolResultText:+ """``_navigable_tool_result_text`` unwraps the CLI's MCP envelope and+ pretty-prints inner JSON so line-based offset/limit slice into the+ actual payload, not the envelope wrapper. Regression coverage for+ the bug where the model bounced off ``bash_exec | python3 -c`` to+ parse a tool result it could have read directly."""++ def test_envelope_with_json_payload_is_pretty_printed(self):+ from .tool_adapter import _navigable_tool_result_text++ payload = {"execution": {"node_executions": [{"status": "FAILED"}]}}+ envelope = json.dumps([{"type": "text", "text": json.dumps(payload)}])+ out = _navigable_tool_result_text(envelope)+ # The output should be pretty-printed JSON with multiple lines,+ # not the single minified blob that was inside the envelope.+ assert "\n" in out+ assert '"status": "FAILED"' in out+ assert json.loads(out) == payload++ def test_envelope_with_non_json_text_returns_unwrapped(self):+ from .tool_adapter import _navigable_tool_result_text++ envelope = json.dumps(+ [{"type": "text", "text": "plain shell output\nwith newlines\n"}]+ )+ out = _navigable_tool_result_text(envelope)+ assert out == "plain shell output\nwith newlines\n"++ def test_non_envelope_input_is_returned_unchanged(self):+ from .tool_adapter import _navigable_tool_result_text++ # Files that don't match the envelope shape stay as-is.+ assert _navigable_tool_result_text("not even json") == "not even json"+ assert (+ _navigable_tool_result_text('{"single": "object"}')+ == '{"single": "object"}'+ )+ # Multi-block envelope: don't unwrap (lossy).+ multi = json.dumps(+ [+ {"type": "text", "text": "a"},+ {"type": "image", "data": "..."},+ ]+ )+ assert _navigable_tool_result_text(multi) == multidiff --git a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py b/autogpt_platform/backend/backend/copilot/tools/bash_exec.pyindex 46d1264de5..f122fca2aa 100644--- a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py+++ b/autogpt_platform/backend/backend/copilot/tools/bash_exec.py@@ -21,7 +21,12 @@ from typing import Anyfrom e2b import AsyncSandbox, CommandExitExceptionfrom e2b.exceptions import TimeoutException-from backend.copilot.context import E2B_WORKDIR, get_current_sandbox+from backend.copilot.context import (+ E2B_WORKDIR,+ get_current_sandbox,+ looks_like_sdk_tool_result_path,+ sdk_tool_result_redirect_hint,+)from backend.copilot.integration_creds import (get_github_user_git_identity,get_integration_env_vars,@@ -125,6 +130,16 @@ class BashExecTool(BaseTool):session_id=session_id,)+ # Pre-flight redirect: bash sandbox can't reach host-side SDK+ # tool-result paths. Without this the model burns turns retrying+ # `cat /root/.claude/projects/...` after `Permission denied`.+ if looks_like_sdk_tool_result_path(command):+ return ErrorResponse(+ message=sdk_tool_result_redirect_hint(command),+ error="sdk_tool_result_path_in_bash_command",+ session_id=session_id,+ )+sandbox = get_current_sandbox()if sandbox is not None:return await self._execute_on_e2b(diff --git a/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py b/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.pyindex 497b6aba08..3b64116a0e 100644--- a/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py@@ -7,7 +7,7 @@ from e2b import CommandExitExceptionfrom ._test_data import make_sessionfrom .bash_exec import BashExecTool-from .models import BashExecResponse+from .models import BashExecResponse, ErrorResponse_USER = "user-bash-exec-test"@@ -198,3 +198,118 @@ class TestBashExecE2BTokenInjection:assert "GH_TOKEN" not in call_kwargs["envs"]assert "GIT_AUTHOR_NAME" not in call_kwargs["envs"]assert isinstance(result, BashExecResponse)+++class TestBashExecSdkToolResultRedirect:+ """A command that references an SDK tool-result path (e.g. the model+ tries to ``cat /root/.claude/projects/.../tool-results/foo.json``)+ must be short-circuited with a redirect to ``read_tool_result`` /+ ``@@agptfile`` before the sandbox returns the generic+ ``Permission denied`` that the model can't act on."""++ @pytest.mark.asyncio(loop_scope="session")+ async def test_redirect_on_absolute_sdk_path(self):+ tool = _make_tool()+ session = make_session(user_id=_USER)+ sandbox = _make_sandbox()+ cmd = (+ "cat /root/.claude/projects/-tmp-copilot-abc/"+ "abc/tool-results/toolu_x.json | jq ."+ )+ with patch(+ "backend.copilot.tools.bash_exec.get_current_sandbox",+ return_value=sandbox,+ ):+ result = await tool._execute(+ user_id=_USER,+ session=session,+ command=cmd,+ timeout=10,+ )+ assert isinstance(result, ErrorResponse)+ assert "read_tool_result" in result.message+ assert "@@agptfile" in result.message+ # Offending fragment must be the SDK path, not the executable name+ # — the model needs to know which fragment tripped the redirect.+ assert "tool-results/toolu_x.json" in result.message+ assert "Offending fragment: 'cat'" not in result.message+ # Sandbox must not have been invoked at all.+ sandbox.commands.run.assert_not_called()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_no_redirect_on_user_path_containing_tool_outputs(self):+ """Regression: a user repo path that happens to contain a+ ``tool-outputs`` directory must NOT trigger the redirect, since+ the user's data isn't an SDK tool-result file."""+ tool = _make_tool()+ session = make_session(user_id=_USER)+ sandbox = _make_sandbox(stdout="ok")+ with (+ patch(+ "backend.copilot.tools.bash_exec.get_current_sandbox",+ return_value=sandbox,+ ),+ patch(+ "backend.copilot.tools.bash_exec.get_integration_env_vars",+ new=AsyncMock(return_value={}),+ ),+ patch(+ "backend.copilot.tools.bash_exec.get_github_user_git_identity",+ new=AsyncMock(return_value=None),+ ),+ ):+ result = await tool._execute(+ user_id=_USER,+ session=session,+ command="ls my-pipeline/tool-outputs/data.json",+ timeout=10,+ )+ assert isinstance(result, BashExecResponse)+ sandbox.commands.run.assert_called_once()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_redirect_on_relative_tool_outputs_path(self):+ tool = _make_tool()+ session = make_session(user_id=_USER)+ sandbox = _make_sandbox()+ with patch(+ "backend.copilot.tools.bash_exec.get_current_sandbox",+ return_value=sandbox,+ ):+ result = await tool._execute(+ user_id=_USER,+ session=session,+ command="cat tool-outputs/toolu_x.json | head -50",+ timeout=10,+ )+ assert isinstance(result, ErrorResponse)+ assert "read_tool_result" in result.message+ sandbox.commands.run.assert_not_called()++ @pytest.mark.asyncio(loop_scope="session")+ async def test_normal_command_still_runs(self):+ tool = _make_tool()+ session = make_session(user_id=_USER)+ sandbox = _make_sandbox(stdout="hello")+ with (+ patch(+ "backend.copilot.tools.bash_exec.get_current_sandbox",+ return_value=sandbox,+ ),+ patch(+ "backend.copilot.tools.bash_exec.get_integration_env_vars",+ new=AsyncMock(return_value={}),+ ),+ patch(+ "backend.copilot.tools.bash_exec.get_github_user_git_identity",+ new=AsyncMock(return_value=None),+ ),+ ):+ result = await tool._execute(+ user_id=_USER,+ session=session,+ command="echo hello",+ timeout=10,+ )+ assert isinstance(result, BashExecResponse)+ sandbox.commands.run.assert_called_once()diff --git a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py b/autogpt_platform/backend/backend/copilot/tools/workspace_files.pyindex 33c676da88..8ca6cebd28 100644--- a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py+++ b/autogpt_platform/backend/backend/copilot/tools/workspace_files.py@@ -15,7 +15,9 @@ from backend.copilot.context import (get_sdk_cwd,get_workspace_manager,is_allowed_local_path,+ looks_like_sdk_tool_result_path,resolve_sandbox_path,+ sdk_tool_result_redirect_hint,)from backend.copilot.model import ChatSessionfrom backend.copilot.tools.sandbox import make_session_path@@ -598,10 +600,41 @@ class ReadWorkspaceFileTool(BaseTool):# read it directly instead of failing. The model sometimes# calls read_workspace_file for these paths by mistake.sdk_cwd = get_sdk_cwd()+ # Relative SDK-tool-result shorthand must short-circuit+ # *before* the ``is_allowed_local_path`` fallback: when+ # ``sdk_cwd`` is set, the shorthand resolves under it and+ # passes the allow check, but the file doesn't actually+ # exist at that resolved path → ``_read_local_tool_result``+ # returns a generic "Path not allowed" and the redirect+ # branch below never runs. Catch relative shorthands here+ # so the model sees the helpful redirect on the first try.+ # Absolute SDK paths still take the local-read path below+ # (legit fallback for ``read_workspace_file`` with an+ # absolute SDK tool-results path).+ if (+ path+ and not os.path.isabs(path)+ and not path.startswith("~")+ and looks_like_sdk_tool_result_path(path)+ ):+ return ErrorResponse(+ message=sdk_tool_result_redirect_hint(path),+ session_id=session_id,+ )if path and is_allowed_local_path(path, sdk_cwd):return _read_local_tool_result(path, char_offset, char_length, session_id, sdk_cwd=sdk_cwd)+ # Path looks like SDK tool-results but isn't reachable+ # via the local-read path either (e.g. absolute SDK path+ # not under sdk_cwd) — redirect to read_tool_result /+ # @@agptfile rather than returning a generic+ # "Path not allowed".+ if path and looks_like_sdk_tool_result_path(path):+ return ErrorResponse(+ message=sdk_tool_result_redirect_hint(path),+ session_id=session_id,+ )return resolvedtarget_file_id, file_info = resolveddiff --git a/autogpt_platform/backend/backend/copilot/tools/workspace_files_test.py b/autogpt_platform/backend/backend/copilot/tools/workspace_files_test.pyindex de18572d16..0db2aabd39 100644--- a/autogpt_platform/backend/backend/copilot/tools/workspace_files_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/workspace_files_test.py@@ -625,6 +625,36 @@ async def test_read_workspace_file_no_fallback_when_resolve_succeeds(setup_test_assert base64.b64decode(result.content_base64) == fake_content[email protected](loop_scope="session")+async def test_read_workspace_file_redirects_sdk_tool_result_shorthand(+ setup_test_data,+):+ """A shorthand SDK path (``tool-outputs/<id>.json``) that doesn't+ resolve in cloud workspace and doesn't exist on disk must return the+ redirect hint pointing at ``read_tool_result`` / ``@@agptfile``+ rather than the generic ``Path not allowed``."""+ user = setup_test_data["user"]+ session = make_session(user.id)++ mock_resolve = AsyncMock(+ return_value=ErrorResponse(+ message="Path not allowed",+ session_id=session.session_id,+ )+ )+ with patch("backend.copilot.tools.workspace_files._resolve_file", mock_resolve):+ read_tool = ReadWorkspaceFileTool()+ result = await read_tool._execute(+ user_id=user.id,+ session=session,+ path="tool-outputs/toolu_abc.json",+ )++ assert isinstance(result, ErrorResponse)+ assert "read_tool_result" in result.message+ assert "@@agptfile" in result.message++# ---------------------------------------------------------------------------# WriteWorkspaceFileTool exception handling (quota, virus, scan errors)# ---------------------------------------------------------------------------@@ -697,3 +727,132 @@ class TestWriteWorkspaceFileToolErrorHandling:)assert isinstance(result, ErrorResponse)assert "already exists" in result.message+++class TestReadWorkspaceFileSdkToolResultRedirect:+ """The model sometimes calls read_workspace_file with an SDK+ tool-result shorthand path (e.g. ``tool-outputs/<id>.json``).+ That path is neither in workspace storage nor a resolvable local+ file, so without the redirect branch the model gets a generic+ "Path not allowed" with no pointer to the right tool. This mirrors+ the bash_exec redirect coverage.++ Mocks ``_resolve_file`` and ``get_workspace_manager`` so the unit+ test stays scoped to the redirect branch without touching Prisma /+ workspace storage.+ """++ @pytest.fixture(autouse=True)+ def _clear_sdk_cwd(self):+ """Sibling test classes set ``sdk_cwd`` via the shared ContextVar.+ Clear it so ``is_allowed_local_path`` doesn't claim our relative+ shorthand paths as legitimate sdk_cwd children and short-circuit+ the redirect branch we're testing."""+ from backend.copilot.context import set_execution_context++ set_execution_context(user_id="test", session=None, sandbox=None, sdk_cwd=None)++ @staticmethod+ async def _call_read_with_resolve_failure(path: str):+ read_tool = ReadWorkspaceFileTool()+ session = make_session("user-redirect-test")+ with (+ patch(+ "backend.copilot.tools.workspace_files.get_workspace_manager",+ new=AsyncMock(return_value=AsyncMock()),+ ),+ patch(+ "backend.copilot.tools.workspace_files._resolve_file",+ new=AsyncMock(+ return_value=ErrorResponse(+ message="not found", session_id=session.session_id+ )+ ),+ ),+ ):+ return await read_tool._execute(+ user_id="user-redirect-test",+ session=session,+ path=path,+ )++ @pytest.mark.asyncio+ async def test_relative_tool_outputs_shorthand_returns_redirect_hint(self):+ result = await self._call_read_with_resolve_failure(+ "tool-outputs/toolu_nonexistent.json"+ )+ assert isinstance(result, ErrorResponse)+ assert "read_tool_result" in result.message+ assert "@@agptfile" in result.message++ @pytest.mark.asyncio+ async def test_relative_tool_results_shorthand_returns_redirect_hint(self):+ result = await self._call_read_with_resolve_failure(+ "tool-results/toolu_nonexistent.json"+ )+ assert isinstance(result, ErrorResponse)+ assert "read_tool_result" in result.message++ @pytest.mark.asyncio+ async def test_unrelated_missing_path_does_not_redirect(self):+ """Regression: paths that don't look like SDK tool-results must+ still surface the original resolve error, not the redirect hint."""+ result = await self._call_read_with_resolve_failure(+ "some/random/missing-file.txt"+ )+ assert isinstance(result, ErrorResponse)+ assert "read_tool_result" not in result.message+ assert "@@agptfile" not in result.message++ @pytest.mark.asyncio+ async def test_redirect_wins_over_sdk_cwd_local_fallback(self):+ """When ``sdk_cwd`` is set, the relative shorthand+ ``tool-outputs/<id>.json`` resolves under it and would otherwise+ pass the ``is_allowed_local_path`` check, dispatching to+ ``_read_local_tool_result`` which fails with a generic "Path not+ allowed" — defeating the whole point of the redirect.++ Regression coverage: with ``sdk_cwd`` set, the relative-shorthand+ redirect must still fire before the local-read fallback runs.+ """+ from backend.copilot.context import set_execution_context++ # Override the autouse fixture that cleared sdk_cwd — we+ # specifically want sdk_cwd set here to exercise the bug.+ set_execution_context(+ user_id="user-redirect-test",+ session=None,+ sandbox=None,+ sdk_cwd="/tmp/copilot-redirect-test",+ )++ read_tool = ReadWorkspaceFileTool()+ session = make_session("user-redirect-test")+ with (+ patch(+ "backend.copilot.tools.workspace_files.get_workspace_manager",+ new=AsyncMock(return_value=AsyncMock()),+ ),+ patch(+ "backend.copilot.tools.workspace_files._resolve_file",+ new=AsyncMock(+ return_value=ErrorResponse(+ message="not found", session_id=session.session_id+ )+ ),+ ),+ patch(+ "backend.copilot.tools.workspace_files._read_local_tool_result",+ ) as mock_local_read,+ ):+ result = await read_tool._execute(+ user_id="user-redirect-test",+ session=session,+ path="tool-outputs/toolu_x.json",+ )+ assert isinstance(result, ErrorResponse)+ assert "read_tool_result" in result.message+ assert "@@agptfile" in result.message+ # The local-read fallback must NOT have run — that's the bug+ # this test guards against.+ mock_local_read.assert_not_called()