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(backend): start every Claude Code CLI from an allow-listed environment (#15951)
Nicholas Tindle9caf6447dba0
diff --git a/autogpt_platform/backend/backend/blocks/orchestrator.py b/autogpt_platform/backend/backend/blocks/orchestrator.pyindex 426f9c8fb9..330a499f67 100644--- a/autogpt_platform/backend/backend/blocks/orchestrator.py+++ b/autogpt_platform/backend/backend/blocks/orchestrator.py@@ -1,6 +1,7 @@import asyncioimport contextvarsimport logging+import osimport reimport shutilimport tempfile@@ -29,6 +30,8 @@ from backend.blocks.agent import AgentExecutorBlockfrom backend.copilot.sdk.cli_version import require_verbatim_prompts_clifrom backend.copilot.sdk.env import DISABLE_SLASH_COMMANDS_FLAG, cli_prompt_textfrom backend.copilot.sdk.env import config as copilot_config+from backend.copilot.sdk.env import without_url_credentials+from backend.copilot.sdk.launch_env import launch_optionsfrom backend.data.dynamic_fields import (extract_base_field_name,get_dynamic_field_description,@@ -1747,8 +1750,13 @@ class OrchestratorBlock(Block):"ANTHROPIC_API_KEY": api_key,}else:- # Direct Anthropic key+ # Direct Anthropic key, sent wherever the deployment points+ # Anthropic traffic: the launch keeps nothing else of the+ # backend's environment (``launch_env.py``), nor a user name and+ # password the deployment embedded in that URL.sdk_env = {"ANTHROPIC_API_KEY": api_key}+ if base_url := os.environ.get("ANTHROPIC_BASE_URL"):+ sdk_env["ANTHROPIC_BASE_URL"] = without_url_credentials(base_url)# Use an execution-specific working directory to prevent concurrent# SDK executions from colliding. tempfile.mkdtemp() respects TMPDIR@@ -1841,7 +1849,7 @@ class OrchestratorBlock(Block):options.cli_path = await asyncio.to_thread(require_verbatim_prompts_cli, options.cli_path)- async with ClaudeSDKClient(options=options) as client:+ async with ClaudeSDKClient(options=launch_options(options)) as client:await client.query(user_message)msg_iter = client.receive_response().__aiter__()diff --git a/autogpt_platform/backend/backend/copilot/billing_e2e/sdk_turns.py b/autogpt_platform/backend/backend/copilot/billing_e2e/sdk_turns.pyindex 7ab3640033..3eb4cbbcae 100644--- a/autogpt_platform/backend/backend/copilot/billing_e2e/sdk_turns.py+++ b/autogpt_platform/backend/backend/copilot/billing_e2e/sdk_turns.py@@ -72,12 +72,18 @@ class SdkTurns:# files from the same place.monkeypatch.setenv("HOME", str(tmp_path / "home"))monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(self._config_dir))- # Where a direct-Anthropic CLI sends its requests; the key is never- # checked. OpenRouter and Codex turns override both.+ # Where a direct-Anthropic CLI sends its requests, which that route+ # carries over from this process; the key is never checked.+ # OpenRouter and Codex turns override both.monkeypatch.setenv("ANTHROPIC_BASE_URL", f"{provider.url}/anthropic")monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-billing-e2e")- if cli_max_retries is not None:- monkeypatch.setenv("CLAUDE_CODE_MAX_RETRIES", str(cli_max_retries))+ # The CLI keeps nothing else of this process's environment, so a+ # setting for it goes in the launch's own.+ self._cli_env = (+ {"CLAUDE_CODE_MAX_RETRIES": str(cli_max_retries)}+ if cli_max_retries is not None+ else {}+ )monkeypatch.setattr(sdk_env, "config", config)monkeypatch.setattr(openrouter_cost,@@ -168,6 +174,7 @@ class SdkTurns:options.hooks = Noneoptions.allowed_tools = []options.disallowed_tools = []+ options.env = {**options.env, **self._cli_env}return ClaudeSDKClient(*args, options=options, **kwargs)def _governor(self, **kwargs: Any) -> TurnGovernor:diff --git a/autogpt_platform/backend/backend/copilot/executor/processor.py b/autogpt_platform/backend/backend/copilot/executor/processor.pyindex 58d28a3186..258252b692 100644--- a/autogpt_platform/backend/backend/copilot/executor/processor.py+++ b/autogpt_platform/backend/backend/copilot/executor/processor.py@@ -46,6 +46,7 @@ from backend.copilot.response_model import ()from backend.copilot.sdk import service as sdk_servicefrom backend.copilot.sdk.dummy import stream_chat_completion_dummy+from backend.copilot.sdk.launch_env import inherited_envfrom backend.copilot.stream_heartbeat import wrap_stream_with_heartbeatfrom backend.copilot.tools.agent_browser import close_browser_daemonfrom backend.copilot.trial_cost_context import trial_cost_context@@ -421,6 +422,7 @@ class CoPilotProcessor:[cli_path, "-v"],capture_output=True,timeout=10,+ env=inherited_env(),)if result.returncode == 0:logger.info(f"CLI pre-warm done: {cli_path}")diff --git a/autogpt_platform/backend/backend/copilot/sdk/cli_builtin_tools_test.py b/autogpt_platform/backend/backend/copilot/sdk/cli_builtin_tools_test.pyindex b3aaa6f65b..55dcadbbdd 100644--- a/autogpt_platform/backend/backend/copilot/sdk/cli_builtin_tools_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/cli_builtin_tools_test.py@@ -8,6 +8,7 @@ import pytestfrom claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, SystemMessagefrom .env import build_sdk_env+from .launch_env import launch_optionsfrom .tool_adapter import (create_copilot_mcp_server,get_copilot_tool_names,@@ -21,7 +22,11 @@ async def test_cli_offers_only_allowed_tools(use_e2b: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):# A run inside Claude Code inherits its CLAUDE_* flags, which change the tool set.- for key in [k for k in os.environ if k.startswith("CLAUDE")]:+ for key in [+ k+ for k in os.environ+ if k.startswith("CLAUDE") and k != "CLAUDE_AGENT_SDK_SKIP_VERSION_CHECK"+ ]:monkeypatch.delenv(key)allowed = get_copilot_tool_names(use_e2b=use_e2b)offered = await asyncio.wait_for(@@ -64,7 +69,7 @@ async def _cli_offered_tools(cwd=str(sdk_cwd),env=env,)- async with ClaudeSDKClient(options) as client:+ async with ClaudeSDKClient(launch_options(options)) as client:await client.query("hi")async for message in client.receive_messages():if isinstance(message, SystemMessage) and message.subtype == "init":diff --git a/autogpt_platform/backend/backend/copilot/sdk/cli_environment_e2e_test.py b/autogpt_platform/backend/backend/copilot/sdk/cli_environment_e2e_test.pynew file mode 100644index 0000000000..58ec45e0b4--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sdk/cli_environment_e2e_test.py@@ -0,0 +1,195 @@+"""The Claude Code CLI a run starts holds no backend secret beyond its route's+credential and the network settings it needs.++A copilot turn (``stream_chat_completion_sdk``) and an orchestrator block run in+SDK mode each drive the Claude Code CLI against the billing suite's fake+provider, with secrets in this process's environment. While the CLI waits on+each model request, the provider reads that CLI process's environment as the+operating system holds it, so what is checked is what the CLI was started with.++The Linux SDK wheel bundles the CLI, so without one the tests fail there; on+other platforms, whose wheels ship without it, they skip. CI runs them on Linux.+"""++import platform+from pathlib import Path+from unittest.mock import AsyncMock, MagicMock, patch++import psutil+import pytest+from aiohttp import web+from pydantic import SecretStr++from backend.blocks.orchestrator import OrchestratorBlock+from backend.copilot.billing_e2e.invoice import SONNET, Route+from backend.copilot.billing_e2e.ledger import PlatformLedger+from backend.copilot.billing_e2e.provider import FakeProvider+from backend.copilot.billing_e2e.sdk_turns import SdkTurns+from backend.copilot.config import ChatConfig+from backend.copilot.model import ChatMessage, ChatSession+from backend.data.model import APIKeyCredentials++from . import service as sdk_service+from .cli_openrouter_compat_test import _resolve_cli_path++_SECRET_NAME = "SOME_PLATFORM_SECRET"+_SECRET = "sk-FAKE-platform-secret"+# The deployment's own Anthropic key, which no user's run may hold.+_PLATFORM_KEY = "sk-ant-FAKE-platform-key"+_USER_KEY = "sk-ant-FAKE-the-users-own-key"+++def ledger(monkeypatch: pytest.MonkeyPatch) -> PlatformLedger:+ """Takes the spend, cost-log and credit writes each turn makes."""+ ledger = PlatformLedger()+ ledger.install(monkeypatch)+ return ledger++[email protected](autouse=True)+def _memory_off(monkeypatch: pytest.MonkeyPatch) -> None:+ """Memory is not under test here, and its ingest needs a database."""+ monkeypatch.setattr(+ sdk_service, "_fetch_graphiti_context", AsyncMock(return_value=(False, ""))+ )+++# Its own event loop, like the billing suite: a background task another test+# left on the shared session loop must not run into this one's turns.[email protected](loop_scope="function")+async def test_a_copilot_turns_cli_holds_only_its_routes_credential(+ ledger: PlatformLedger, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ _require_cli()+ monkeypatch.setenv(_SECRET_NAME, _SECRET)+ async with _CliEnvironments() as provider:+ turns = SdkTurns(tmp_path, monkeypatch, provider, _config())+ session = _session()+ session.messages.append(ChatMessage(role="user", content="hello"))+ await turns(session, "hello", new_pod=False)+ await ledger.settle()++ assert provider.seen, "the CLI made no model request"+ for env in provider.seen:+ assert not _holds(env, _SECRET)+ # The direct-Anthropic route's own key, which it carries over.+ assert env["ANTHROPIC_API_KEY"] == "sk-ant-billing-e2e"++[email protected](loop_scope="function")+async def test_an_orchestrator_runs_cli_holds_only_the_users_key(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+):+ cli = _require_cli()+ monkeypatch.setenv(_SECRET_NAME, _SECRET)+ monkeypatch.setenv("ANTHROPIC_API_KEY", _PLATFORM_KEY)+ monkeypatch.setenv("HOME", str(tmp_path / "home"))+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / "home" / ".claude"))+ async with _CliEnvironments() as provider:+ # Where the deployment sends Anthropic traffic; the run keeps that.+ monkeypatch.setenv("ANTHROPIC_BASE_URL", f"{provider.url}/anthropic")+ with patch(+ "backend.blocks.orchestrator.require_verbatim_prompts_cli",+ return_value=str(cli),+ ):+ outputs = [+ output+ async for output in OrchestratorBlock()._execute_tools_sdk_mode(+ input_data=_orchestrator_input(),+ credentials=_user_key(),+ tool_functions=[],+ prompt=[{"role": "user", "content": "hello"}],+ execution_params=MagicMock(graph_exec_id="graph-exec-e2e"),+ execution_processor=MagicMock(),+ )+ ]++ assert not [value for name, value in outputs if name == "error"]+ assert provider.seen, "the CLI made no model request"+ for env in provider.seen:+ assert not _holds(env, _SECRET)+ assert not _holds(env, _PLATFORM_KEY)+ assert env["ANTHROPIC_API_KEY"] == _USER_KEY+++class _CliEnvironments(FakeProvider):+ """The fake provider, reading the environment of each CLI that asks it+ for a reply while that CLI waits."""++ def __init__(self) -> None:+ super().__init__()+ self.seen: list[dict[str, str]] = []++ async def _messages(self, request: web.Request, route: Route) -> web.StreamResponse:+ self.seen += _cli_environments()+ return await super()._messages(request, route)+++def _cli_environments() -> list[dict[str, str]]:+ """The environment of every Claude Code CLI this process has started that+ is still running: the SDK starts each one with ``stream-json`` I/O."""+ environments = []+ for process in psutil.Process().children(recursive=True):+ try:+ if "stream-json" in process.cmdline():+ environments.append(process.environ())+ except psutil.Error:+ continue+ return environments+++def _holds(env: dict[str, str], secret: str) -> bool:+ return any(secret in value for value in env.values())+++def _require_cli() -> Path:+ """The Linux SDK wheel bundles the CLI, so there a missing one fails the+ test instead of skipping it."""+ cli = _resolve_cli_path()+ if cli is not None:+ return cli+ if platform.system() == "Linux":+ pytest.fail("No Claude Code CLI binary: the Linux SDK wheel bundles one")+ pytest.skip("No Claude Code CLI binary: this platform's SDK wheel has none")+++def _config() -> ChatConfig:+ """A direct-Anthropic deployment, pinned so the deployment's own settings+ cannot change the path a turn takes, on the CLI ``_require_cli`` found."""+ cli = _resolve_cli_path()+ return sdk_service.config.model_copy(+ update={+ "use_local": False,+ "use_claude_code_subscription": False,+ "use_e2b_sandbox": False,+ "use_openrouter": False,+ "api_key": "sk-ant-cli-environment-e2e",+ "claude_agent_model": SONNET,+ "claude_agent_fallback_model": None,+ "claude_agent_cli_path": str(cli) if cli else None,+ }+ )+++def _session() -> ChatSession:+ session = ChatSession.new("cli-environment-e2e-user", dry_run=False)+ # A titled chat skips title generation, a separate model call.+ session.title = "CLI environment e2e"+ return session+++def _orchestrator_input() -> MagicMock:+ input_data = MagicMock(sys_prompt="", prompt="hello")+ input_data.model.value = SONNET+ return input_data+++def _user_key() -> APIKeyCredentials:+ return APIKeyCredentials(+ id="cli-environment-e2e-key",+ provider="anthropic",+ api_key=SecretStr(_USER_KEY),+ title="The user's Anthropic key",+ expires_at=None,+ )diff --git a/autogpt_platform/backend/backend/copilot/sdk/cli_prompt_text_test.py b/autogpt_platform/backend/backend/copilot/sdk/cli_prompt_text_test.pyindex 6f7c07bae6..a09d32ba01 100644--- a/autogpt_platform/backend/backend/copilot/sdk/cli_prompt_text_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/cli_prompt_text_test.py@@ -45,6 +45,7 @@ from .env import (cli_prompt_text,cli_user_message,)+from .launch_env import launch_optionsfrom .service import process_cli_restorefrom .tool_adapter import get_copilot_tool_names, get_sdk_disallowed_tools@@ -75,7 +76,11 @@ def cli_path(monkeypatch: pytest.MonkeyPatch) -> str:if override and not Path(override).is_file():pytest.fail(f"The CLI path override {override!r} is not a file")# A run inside Claude Code inherits its CLAUDE_* flags, which change the CLI.- for key in [k for k in os.environ if k.startswith("CLAUDE")]:+ for key in [+ k+ for k in os.environ+ if k.startswith("CLAUDE") and k != "CLAUDE_AGENT_SDK_SKIP_VERSION_CHECK"+ ]:monkeypatch.delenv(key)try:return require_verbatim_prompts_cli(override or None)@@ -252,7 +257,7 @@ async def _run(options: ClaudeAgentOptions, sends: list[Send]) -> dict[str, Any]async def turns() -> None:nonlocal init- async with ClaudeSDKClient(options) as client:+ async with ClaudeSDKClient(launch_options(options)) as client:for send in sends:await send(client)async for message in client.receive_response():diff --git a/autogpt_platform/backend/backend/copilot/sdk/cli_version.py b/autogpt_platform/backend/backend/copilot/sdk/cli_version.pyindex b1b6b1c35f..243323ad21 100644--- a/autogpt_platform/backend/backend/copilot/sdk/cli_version.py+++ b/autogpt_platform/backend/backend/copilot/sdk/cli_version.py@@ -7,6 +7,8 @@ import reimport subprocessfrom pathlib import Path+from backend.copilot.sdk.launch_env import inherited_env+logger = logging.getLogger(__name__)# First CLI release that honours ``client_composed`` on a user message, which@@ -101,6 +103,7 @@ def _probe_version(path: str) -> tuple[int, ...]:result = subprocess.run([path, "-v"],stdin=subprocess.DEVNULL,+ env=inherited_env(),capture_output=True,encoding="utf-8",errors="replace",diff --git a/autogpt_platform/backend/backend/copilot/sdk/codex_compat_cli_test.py b/autogpt_platform/backend/backend/copilot/sdk/codex_compat_cli_test.pyindex f09f3cd4b6..b81ae20f6c 100644--- a/autogpt_platform/backend/backend/copilot/sdk/codex_compat_cli_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/codex_compat_cli_test.py@@ -16,6 +16,7 @@ from claude_agent_sdk import (from backend.copilot.pending_messages import PendingMessage, format_pending_as_followupfrom backend.copilot.sdk.codex_compat_gateway import CodexAnthropicGatewayfrom backend.copilot.sdk.env import build_sdk_env+from backend.copilot.sdk.launch_env import launch_optionsfrom backend.integrations.codex.models import (CodexDynamicToolCall,CodexDynamicToolResult,@@ -138,7 +139,7 @@ async def test_bundled_claude_cli_executes_mcp_tool_through_codex_gateway(),)received = []- async with ClaudeSDKClient(options=options) as client:+ async with ClaudeSDKClient(options=launch_options(options)) as client:await client.query("Call echo with ping, then report completion.")try:async with asyncio.timeout(45):@@ -226,7 +227,7 @@ async def test_bundled_claude_cli_delivers_a_post_tool_use_followup_to_codex(codex_gateway_token=gateway.auth_token,),)- async with ClaudeSDKClient(options=options) as client:+ async with ClaudeSDKClient(options=launch_options(options)) as client:await client.query("Call echo with ping, then report completion.")try:async with asyncio.timeout(45):diff --git a/autogpt_platform/backend/backend/copilot/sdk/env.py b/autogpt_platform/backend/backend/copilot/sdk/env.pyindex 2d6845e3d5..d57fd67cdb 100644--- a/autogpt_platform/backend/backend/copilot/sdk/env.py+++ b/autogpt_platform/backend/backend/copilot/sdk/env.py@@ -12,28 +12,50 @@ import jsonimport osimport refrom typing import Any-from urllib.parse import urlparse+from urllib.parse import urlparse, urlsplit, urlunsplitfrom backend.copilot.config import ChatConfigfrom backend.copilot.llm_attribution import openrouter_attributionfrom backend.copilot.moonshot import is_moonshot_model, moonshot_context_window-from backend.copilot.sdk.subscription import validate_subscription+from backend.copilot.sdk.subscription import host_login_env, validate_subscription# ChatConfig is stateless (reads env vars) — a separate instance is fine.# A singleton would require importing service.py which causes the circular dep# this module was created to avoid.config = ChatConfig()+# Both launch paths check the CLI binary themselves (``cli_version``), from the+# allowlisted environment. The SDK's own check takes no environment, so before+# each launch it would start the CLI with the backend's whole one; an empty+# value would leave it on.+os.environ["CLAUDE_AGENT_SDK_SKIP_VERSION_CHECK"] = "1"+# RFC 7230 §3.2.6 — keep only printable ASCII; strip control chars and non-ASCII._HEADER_SAFE_RE = re.compile(r"[^\x20-\x7e]")_MAX_HEADER_VALUE_LEN = 128_LOOPBACK_NO_PROXY_HOSTS = ("127.0.0.1", "localhost", "::1")+# A direct-Anthropic launch's credential and where it goes, carried over from+# the backend's environment: what the CLI used to inherit along with the rest.+_DIRECT_ANTHROPIC_NAMES = (+ "ANTHROPIC_API_KEY",+ "ANTHROPIC_AUTH_TOKEN",+ "ANTHROPIC_BASE_URL",+)+# CLI flag for ``ClaudeAgentOptions.extra_args``. Every prompt we send is user# or graph text, never a CLI slash command.DISABLE_SLASH_COMMANDS_FLAG = "disable-slash-commands"+def without_url_credentials(url: str) -> str:+ """*url* without a user name and password some deployments embed in it."""+ parts = urlsplit(url)+ if "@" not in parts.netloc:+ return url+ return urlunsplit(parts._replace(netloc=parts.netloc.rpartition("@")[2]))++def cli_prompt_text(text: str) -> str:"""*text* as the CLI must receive it to send it on to the model.@@ -83,11 +105,17 @@ def build_sdk_env() -> dict[str, str]:"""Build env vars for the SDK CLI subprocess.+ A launch keeps nothing else of the backend's environment but what the OS+ and the network need, proxy settings as configured, credentials included+ (``launch_env.py``), so each mode states every credential it uses.+Four modes (checked in order):1. **Codex gateway** — request-scoped loopback Anthropic compatibility.- 2. **Subscription** — clears all keys; CLI uses ``claude login`` auth.- 3. **Direct Anthropic** — subprocess inherits ``ANTHROPIC_API_KEY``- from the parent environment (no overrides needed).+ 2. **Subscription** — clears all keys; CLI uses ``claude login`` auth,+ or the login the host holds in ``CLAUDE_CODE_OAUTH_TOKEN``.+ 3. **Direct Anthropic** — carries the deployment's ``ANTHROPIC_API_KEY``,+ and any auth token or base URL set beside it, over from the backend's+ environment.4. **OpenRouter** (default) — overrides base URL and auth token toroute through the proxy, with the headers and body fields OpenRouterBroadcast attributes generations by (user, chat session,@@ -154,13 +182,19 @@ def build_sdk_env("ANTHROPIC_API_KEY": "","ANTHROPIC_AUTH_TOKEN": "","ANTHROPIC_BASE_URL": "",+ **host_login_env(),}# --- Mode 2: Direct Anthropic (no proxy hop) ---elif not config.openrouter_active:- # Clear OAuth tokens so CLI uses ANTHROPIC_API_KEY from parent env+ # Clear OAuth tokens so CLI uses the deployment's ANTHROPIC_API_KEY# rather than subscription auth if the container has those tokens set.env = {+ **{+ name: value+ for name in _DIRECT_ANTHROPIC_NAMES+ if (value := os.environ.get(name))+ },"CLAUDE_CODE_OAUTH_TOKEN": "","CLAUDE_CODE_REFRESH_TOKEN": "",}diff --git a/autogpt_platform/backend/backend/copilot/sdk/env_test.py b/autogpt_platform/backend/backend/copilot/sdk/env_test.pyindex 463282f0ad..c2dab0398e 100644--- a/autogpt_platform/backend/backend/copilot/sdk/env_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/env_test.py@@ -63,6 +63,22 @@ class TestBuildSdkEnvSubscription:assert result.get("CLAUDE_AUTOCOMPACT_PCT_OVERRIDE") == "50"mock_validate.assert_called_once()+ @patch("backend.copilot.sdk.env.validate_subscription")+ def test_carries_the_login_the_host_holds_in_a_variable(+ self, mock_validate, monkeypatch+ ):+ """The launch keeps nothing else of the backend's environment."""+ monkeypatch.setenv("CLAUDE_CODE_OAUTH_TOKEN", "sk-ant-oat01-host-login")+ monkeypatch.setenv("CLAUDE_CODE_OAUTH_REFRESH_TOKEN", "sk-ant-ort01-host")+ cfg = _make_config(use_claude_code_subscription=True)+ with patch("backend.copilot.sdk.env.config", cfg):+ from backend.copilot.sdk.env import build_sdk_env++ result = build_sdk_env()++ assert result["CLAUDE_CODE_OAUTH_TOKEN"] == "sk-ant-oat01-host-login"+ assert result["CLAUDE_CODE_OAUTH_REFRESH_TOKEN"] == "sk-ant-ort01-host"+@patch("backend.copilot.sdk.env.validate_subscription",side_effect=RuntimeError("CLI not found"),@@ -83,22 +99,54 @@ class TestBuildSdkEnvSubscription:class TestBuildSdkEnvDirectAnthropic:- """When OpenRouter is inactive, no ANTHROPIC_* overrides (inherit parent env)."""+ """When OpenRouter is inactive, the deployment's Anthropic key, and where+ it is sent, are carried over from the parent environment: the launch+ keeps nothing else of it."""++ @pytest.fixture(autouse=True)+ def _deployment_key(self, monkeypatch):+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-deployment-key")+ monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://anthropic-proxy.example")+ monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False)- def test_no_anthropic_key_overrides_when_openrouter_inactive(self):+ def test_carries_the_deployments_key_when_openrouter_inactive(self):cfg = _make_config(use_openrouter=False)with patch("backend.copilot.sdk.env.config", cfg):from backend.copilot.sdk.env import build_sdk_envresult = build_sdk_env()- assert "ANTHROPIC_API_KEY" not in result+ assert result["ANTHROPIC_API_KEY"] == "sk-ant-deployment-key"+ assert result["ANTHROPIC_BASE_URL"] == "https://anthropic-proxy.example"assert "ANTHROPIC_AUTH_TOKEN" not in result- assert "ANTHROPIC_BASE_URL" not in resultassert result.get("CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS") == "1"assert result.get("CLAUDE_AUTOCOMPACT_PCT_OVERRIDE") == "50"- def test_no_anthropic_key_overrides_when_openrouter_flag_true_but_no_key(self):+ def test_carries_an_auth_token_set_beside_the_key(self, monkeypatch):+ """A bearer-authenticated Anthropic proxy keeps working."""+ monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "sk-ant-proxy-bearer")+ cfg = _make_config(use_openrouter=False)+ with patch("backend.copilot.sdk.env.config", cfg):+ from backend.copilot.sdk.env import build_sdk_env++ result = build_sdk_env()++ assert result["ANTHROPIC_AUTH_TOKEN"] == "sk-ant-proxy-bearer"+ assert result["ANTHROPIC_API_KEY"] == "sk-ant-deployment-key"++ def test_sets_no_key_the_parent_does_not_hold(self, monkeypatch):+ monkeypatch.delenv("ANTHROPIC_API_KEY")+ monkeypatch.delenv("ANTHROPIC_BASE_URL")+ cfg = _make_config(use_openrouter=False)+ with patch("backend.copilot.sdk.env.config", cfg):+ from backend.copilot.sdk.env import build_sdk_env++ result = build_sdk_env()++ assert "ANTHROPIC_API_KEY" not in result+ assert "ANTHROPIC_BASE_URL" not in result++ def test_carries_the_deployments_key_when_openrouter_flag_true_but_no_key(self):"""OpenRouter flag is True but no api_key => openrouter_active is False."""cfg = _make_config(use_openrouter=True, base_url="https://openrouter.ai/api/v1")# Force api_key to None after construction (field_validator may pick up env vars)@@ -109,9 +157,9 @@ class TestBuildSdkEnvDirectAnthropic:result = build_sdk_env()- assert "ANTHROPIC_API_KEY" not in result+ assert result["ANTHROPIC_API_KEY"] == "sk-ant-deployment-key"+ assert result["ANTHROPIC_BASE_URL"] == "https://anthropic-proxy.example"assert "ANTHROPIC_AUTH_TOKEN" not in result- assert "ANTHROPIC_BASE_URL" not in resultassert result.get("CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS") == "1"assert result.get("CLAUDE_AUTOCOMPACT_PCT_OVERRIDE") == "50"diff --git a/autogpt_platform/backend/backend/copilot/sdk/launch_env.py b/autogpt_platform/backend/backend/copilot/sdk/launch_env.pynew file mode 100644index 0000000000..3b0981bade--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sdk/launch_env.py@@ -0,0 +1,105 @@+"""The environment a Claude Code CLI launch starts from.++The SDK merges a launch's ``options.env`` over the backend's whole+environment, which holds other routes' keys, integration keys, database+URLs and telemetry credentials. A launch keeps only what the operating+system and the network need from it, plus its own variables: every other+parent variable is blanked in ``options.env``. The blanks are worked out+from ``os.environ`` at each launch, so a variable the backend gains later is+blanked too, without a list of names to keep up to date.++Two things fall outside it: a variable added to ``os.environ`` between+``launch_options`` and the spawn, which the SDK merges in as it spawns, and+the SDK's own ``claude -v`` version check, which takes no environment and so+would run on the parent's; ``env.py`` turns it off in every process that loads+the launch code. The backend writes no secret to ``os.environ`` after import.+"""++from __future__ import annotations++import copy+import os+from collections.abc import Mapping+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from claude_agent_sdk import ClaudeAgentOptions++# The parent variables a launch keeps: the OS runtime, locale, proxies and CA+# bundles, and where the CLI keeps its configuration. Compared upper-cased.+INHERITED_NAMES = frozenset(+ {+ "PATH",+ "PATHEXT",+ "HOME",+ "USERPROFILE",+ "SYSTEMROOT",+ "WINDIR",+ "COMSPEC",+ "APPDATA",+ "LOCALAPPDATA",+ "TEMP",+ "TMP",+ "TMPDIR",+ "SHELL",+ "LANG",+ "LANGUAGE",+ "TZ",+ "HTTP_PROXY",+ "HTTPS_PROXY",+ "NO_PROXY",+ "ALL_PROXY",+ "NODE_EXTRA_CA_CERTS",+ "SSL_CERT_FILE",+ "SSL_CERT_DIR",+ "CLAUDE_CONFIG_DIR",+ }+)+_INHERITED_PREFIXES = ("LC_",)+# Set or dropped by the SDK itself when it spawns the CLI: left alone so its+# own values stand.+SDK_MANAGED_NAMES = frozenset(+ {+ "CLAUDECODE",+ "CLAUDE_CODE_ENTRYPOINT",+ "CLAUDE_AGENT_SDK_VERSION",+ "CLAUDE_CODE_SDK_READS_SESSION_STATE",+ "CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING",+ "PWD",+ "TRACEPARENT",+ "TRACESTATE",+ }+)+++def inherited(name: str) -> bool:+ """Whether a launch keeps the parent's variable *name*."""+ upper = name.upper()+ return upper in INHERITED_NAMES or upper.startswith(_INHERITED_PREFIXES)+++def inherited_env() -> dict[str, str]:+ """The parent variables a launch keeps, for a process started with an+ environment of its own rather than through the SDK."""+ return {name: value for name, value in os.environ.items() if inherited(name)}+++def isolated_launch_env(env: Mapping[str, str]) -> dict[str, str]:+ """*env* as a launch's ``options.env``: with every parent variable the+ launch does not keep blanked."""+ blanked = {+ name: ""+ for name in os.environ+ if name not in env+ and not inherited(name)+ and name.upper() not in SDK_MANAGED_NAMES+ }+ return {**blanked, **env}+++def launch_options(options: ClaudeAgentOptions) -> ClaudeAgentOptions:+ """A copy of *options* with the environment a launch starts from, worked+ out now."""+ launched = copy.copy(options)+ launched.env = isolated_launch_env(options.env)+ return launcheddiff --git a/autogpt_platform/backend/backend/copilot/sdk/launch_env_test.py b/autogpt_platform/backend/backend/copilot/sdk/launch_env_test.pynew file mode 100644index 0000000000..4fe5ba9cc8--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sdk/launch_env_test.py@@ -0,0 +1,370 @@+"""A CLI launch keeps only its own credential, plus the runtime the OS and the+network need, from the backend's environment.++The parent is seeded with the kinds of secret a backend holds, all fake; each+launch's environment is read off the real SDK transport as it spawns the CLI.+"""++import os+import subprocess+import sys+from pathlib import Path+from typing import ClassVar, Self+from unittest.mock import MagicMock, patch++import anyio+import claude_agent_sdk+import pytest+from claude_agent_sdk import ClaudeAgentOptions, CLIConnectionError+from claude_agent_sdk._internal.transport import subprocess_cli+from pydantic import SecretStr++from backend.blocks.orchestrator import OrchestratorBlock+from backend.copilot.config import ChatConfig+from backend.copilot.executor.processor import CoPilotProcessor+from backend.data.model import APIKeyCredentials++from . import cli_version, subscription+from .env import build_sdk_env+from .launch_env import SDK_MANAGED_NAMES, inherited, launch_options++_HOST_LOGIN = "sk-ant-oat01-FAKE-host-login"+# The deployment's own Anthropic key: the direct-Anthropic route's credential,+# and a platform key no user's launch may hold.+_DEPLOYMENT_KEY = "sk-ant-FAKE-deployment"+_PARENT_SECRETS = {+ "CHAT_API_KEY": "sk-or-FAKE-chat-route",+ "OPEN_ROUTER_API_KEY": "sk-or-FAKE-integration",+ "ANTHROPIC_API_KEY": _DEPLOYMENT_KEY,+ "OPENAI_API_KEY": "sk-FAKE-integration",+ "E2B_API_KEY": "e2b_FAKE",+ "DATABASE_URL": "postgresql://app:FAKE-db-password@db:5432/app",+ "REDIS_PASSWORD": "FAKE-redis-password",+ "SUPABASE_SERVICE_ROLE_KEY": "FAKE-service-role",+ "ENCRYPTION_KEY": "FAKE-encryption-key",+ "STRIPE_API_KEY": "sk_live_FAKE",+ "LANGFUSE_SECRET_KEY": "sk-lf-FAKE",+ "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer FAKE-otel",+ "CLAUDE_CODE_OAUTH_TOKEN": _HOST_LOGIN,+}+# What the OS and the network need, kept as configured: a proxy's credentials+# too, since the CLI cannot reach its model without them.+_RUNTIME = {+ "HTTPS_PROXY": "http://proxy-user:[email protected]:3128",+ "NODE_EXTRA_CA_CERTS": "/etc/ssl/corp-ca.pem",+ "LANG": "C.UTF-8",+ "LC_ALL": "C.UTF-8",+}+_ROUTE_KEY = "sk-FAKE-the-routes-own-key"+_CLI = "claude-under-test"+++class _Spawned(Exception):+ pass+++def parent(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ for name, value in {**_PARENT_SECRETS, **_RUNTIME}.items():+ monkeypatch.setenv(name, value)+ for name in ("ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"):+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / "claude"))+ monkeypatch.setattr("backend.copilot.sdk.env.validate_subscription", lambda: None)+++async def _spawned_env(+ monkeypatch: pytest.MonkeyPatch, options: ClaudeAgentOptions+) -> dict[str, str]:+ """The environment the SDK hands the CLI it starts with *options*, which+ is the only process it starts: one started without an environment of its+ own, like the SDK's own version check, gets the backend's whole one."""+ envs: list[dict[str, str] | None] = []++ async def open_process(*_args, **kwargs):+ envs.append(kwargs.get("env"))+ raise _Spawned++ # The SDK's transport spawns through the anyio module.+ monkeypatch.setattr(anyio, "open_process", open_process)+ transport = subprocess_cli.SubprocessCLITransport(prompt="", options=options)+ with pytest.raises(CLIConnectionError):+ await transport.connect()+ [env] = envs+ assert env is not None, "the SDK started the CLI with the whole environment"+ return env+++def _config(**settings) -> ChatConfig:+ defaults = {+ "use_local": False,+ "use_claude_code_subscription": False,+ "use_openrouter": False,+ "thinking_standard_model": "anthropic/claude-sonnet-4-6",+ "thinking_advanced_model": "anthropic/claude-opus-4-7",+ "aux_api_key": "or-aux-key",+ }+ return ChatConfig(**{**defaults, **settings})+++# Each copilot route: the deployment settings, the ``build_sdk_env``+# arguments, and the credential the launch must keep.+_LAUNCHES = {+ "openrouter": (+ {+ "use_openrouter": True,+ "api_key": _ROUTE_KEY,+ "base_url": "https://openrouter.ai/api/v1",+ },+ {},+ "ANTHROPIC_AUTH_TOKEN",+ _ROUTE_KEY,+ ),+ "direct_anthropic": ({}, {}, "ANTHROPIC_API_KEY", _DEPLOYMENT_KEY),+ "subscription": (+ {"use_claude_code_subscription": True},+ {},+ "CLAUDE_CODE_OAUTH_TOKEN",+ _HOST_LOGIN,+ ),+ "codex_gateway": (+ {},+ {"codex_gateway_url": "http://127.0.0.1:1", "codex_gateway_token": _ROUTE_KEY},+ "ANTHROPIC_AUTH_TOKEN",+ _ROUTE_KEY,+ ),+}++[email protected]("launch", sorted(_LAUNCHES))+async def test_a_copilot_launch_keeps_only_its_credential_and_the_runtime(+ launch: str, parent: None, monkeypatch: pytest.MonkeyPatch+):+ settings, arguments, credential_name, credential = _LAUNCHES[launch]+ monkeypatch.setattr("backend.copilot.sdk.env.config", _config(**settings))+ env = build_sdk_env(**arguments)+ options = launch_options(ClaudeAgentOptions(env=env, cli_path=_CLI))++ spawned = await _spawned_env(monkeypatch, options)++ _assert_keeps_only(spawned, env, credential)+ assert spawned[credential_name] == credential+++async def test_a_variable_the_backend_gains_later_is_blanked_too(+ parent: None, monkeypatch: pytest.MonkeyPatch+):+ """Worked out at each launch, not from a list of names."""+ monkeypatch.setattr("backend.copilot.sdk.env.config", _config())+ env = build_sdk_env()+ monkeypatch.setenv("SOME_SERVICE_TOKEN_ADDED_LATER", "FAKE-later")++ spawned = await _spawned_env(+ monkeypatch, launch_options(ClaudeAgentOptions(env=env, cli_path=_CLI))+ )++ assert spawned["SOME_SERVICE_TOKEN_ADDED_LATER"] == ""+++ "provider, credential_name",+ [("anthropic", "ANTHROPIC_API_KEY"), ("open_router", "ANTHROPIC_AUTH_TOKEN")],+)+async def test_an_orchestrator_launch_keeps_only_the_users_key_and_the_runtime(+ provider: str, credential_name: str, parent: None, monkeypatch: pytest.MonkeyPatch+):+ """Read off the options the block starts its CLI with, so a launch that+ skips the allowlist fails here."""+ options = await _orchestrator_launch(provider)++ spawned = await _spawned_env(monkeypatch, options)++ _assert_keeps_only(spawned, options.env, _ROUTE_KEY)+ assert spawned[credential_name] == _ROUTE_KEY+++async def test_an_orchestrator_launch_sends_the_users_key_where_anthropic_is_reached(+ parent: None, monkeypatch: pytest.MonkeyPatch+):+ """A base URL the deployment points Anthropic traffic at still applies,+ without a password embedded in it or the deployment's auth token."""+ monkeypatch.setenv(+ "ANTHROPIC_BASE_URL",+ "https://svc:[email protected]:8443/v",+ )+ monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "FAKE-deployment-bearer")+ options = await _orchestrator_launch("anthropic")++ spawned = await _spawned_env(monkeypatch, options)++ assert spawned["ANTHROPIC_BASE_URL"] == "https://anthropic-proxy.example:8443/v"+ assert spawned["ANTHROPIC_API_KEY"] == _ROUTE_KEY+ assert spawned["ANTHROPIC_AUTH_TOKEN"] == ""+ assert not any("FAKE-gateway-password" in value for value in spawned.values())++[email protected]("preset", [None, ""])+def test_loading_the_launch_code_turns_the_sdks_own_version_check_off(+ preset: str | None,+):+ """The SDK version-checks the CLI by starting it with no environment of+ its own, the backend's whole one, before each launch. It reads the switch+ for truthiness, so an empty value a deployment sets must not leave it on.++ The child gets its environment explicitly: on Windows an empty value set+ through ``os.environ`` removes the variable instead of passing it on."""+ name = "CLAUDE_AGENT_SDK_SKIP_VERSION_CHECK"+ env = {key: value for key, value in os.environ.items() if key != name}+ if preset is not None:+ env[name] = preset+ check = (+ f"import os; print(repr(os.environ.get({name!r}))); "+ f"import backend.copilot.sdk.env; print(repr(os.environ.get({name!r})))"+ )++ result = subprocess.run(+ [sys.executable, "-c", check],+ env=env,+ capture_output=True,+ text=True,+ timeout=120,+ check=False,+ )++ lines = result.stdout.splitlines()+ assert lines[:1] == [repr(preset)], result.stderr[-2000:]+ assert lines[-1:] == ["'1'"], result.stderr[-2000:]+++def test_the_worker_warm_up_starts_the_cli_from_the_allowlist(+ parent: None, monkeypatch: pytest.MonkeyPatch+):+ envs = _record_runs(monkeypatch, "2.1.284")++ CoPilotProcessor.__new__(CoPilotProcessor)._prewarm_cli(cli_path=_CLI)++ [env] = envs+ assert all(inherited(name) for name in env)+ assert not set(_PARENT_SECRETS.values()) & set(env.values())+++def test_the_version_check_starts_the_cli_from_the_allowlist(+ parent: None, monkeypatch: pytest.MonkeyPatch+):+ envs = _record_runs(monkeypatch, "2.1.284 (Claude Code)")++ cli_version._probe_version(_CLI)++ [env] = envs+ assert all(inherited(name) for name in env)+ assert not set(_PARENT_SECRETS.values()) & set(env.values())+++def test_the_subscription_check_starts_the_cli_from_the_allowlist(+ parent: None, monkeypatch: pytest.MonkeyPatch+):+ envs = _record_runs(monkeypatch, "2.1.284", auth='{"loggedIn": true}')+ monkeypatch.setattr(subscription, "find_bundled_cli", lambda: _CLI)+ monkeypatch.setattr(subscription, "provision_credentials_file", lambda: None)++ subscription.validate_subscription.__wrapped__()++ version_env, auth_env = envs+ secrets = set(_PARENT_SECRETS.values())+ assert not secrets & set(version_env.values())+ assert set(auth_env.values()) & secrets == {_HOST_LOGIN}+ assert all(inherited(name) for name in version_env)+++def _assert_keeps_only(+ spawned: dict[str, str], env: dict[str, str], credential: str+) -> None:+ others = {value for value in _PARENT_SECRETS.values() if value != credential}+ assert not {+ name for name, value in spawned.items() if any(s in value for s in others)+ }, "the launch kept another secret of the parent"+ unexpected = {+ name+ for name, value in spawned.items()+ if value+ and name not in env+ and not inherited(name)+ and name.upper() not in SDK_MANAGED_NAMES+ }+ assert not unexpected, f"the launch kept {sorted(unexpected)}"+ for name, value in _RUNTIME.items():+ assert spawned[name] == value+++class _Started(Exception):+ pass+++class _StartingClient:+ """Stands in for ``ClaudeSDKClient``: keeps the options the CLI would+ start with, then stops the run."""++ seen: ClassVar[list[ClaudeAgentOptions]] = []++ def __init__(self, options: ClaudeAgentOptions) -> None:+ self.seen.append(options)++ async def __aenter__(self) -> Self:+ raise _Started++ async def __aexit__(self, *_: object) -> None:+ return None+++async def _orchestrator_launch(provider: str) -> ClaudeAgentOptions:+ """The options the orchestrator block starts its CLI with, on a user's+ *provider* key."""+ input_data = MagicMock(sys_prompt="", prompt="hello")+ input_data.model.value = "claude-sonnet-4-6"+ credentials = APIKeyCredentials(+ id="test-user-key",+ provider=provider,+ api_key=SecretStr(_ROUTE_KEY),+ title="The user's key",+ expires_at=None,+ )+ with (+ patch.object(_StartingClient, "seen", []) as seen,+ patch.object(claude_agent_sdk, "ClaudeSDKClient", _StartingClient),+ patch(+ "backend.blocks.orchestrator.require_verbatim_prompts_cli",+ return_value=_CLI,+ ),+ ):+ async for _ in OrchestratorBlock()._execute_tools_sdk_mode(+ input_data=input_data,+ credentials=credentials,+ tool_functions=[],+ prompt=[{"role": "user", "content": "hello"}],+ execution_params=MagicMock(graph_exec_id="graph-exec-1"),+ execution_processor=MagicMock(),+ ):+ pass+ [options] = seen+ return options+++def _record_runs(+ monkeypatch: pytest.MonkeyPatch, version: str, *, auth: str = ""+) -> list[dict[str, str]]:+ """Stand in for ``subprocess.run``; return the environment of each run."""+ envs: list[dict[str, str]] = []++ def run(args, **kwargs):+ envs.append(kwargs["env"])+ stdout = auth if "auth" in args else version+ if not kwargs.get("text") and not kwargs.get("encoding"):+ return subprocess.CompletedProcess(args, 0, stdout.encode(), b"")+ return subprocess.CompletedProcess(args, 0, stdout, "")++ monkeypatch.setattr(subprocess, "run", run)+ return envsdiff --git a/autogpt_platform/backend/backend/copilot/sdk/p0_guardrails_test.py b/autogpt_platform/backend/backend/copilot/sdk/p0_guardrails_test.pyindex 38fb2eecb3..181e024163 100644--- a/autogpt_platform/backend/backend/copilot/sdk/p0_guardrails_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/p0_guardrails_test.py@@ -278,8 +278,12 @@ class TestBuildSdkEnv:assert env["ANTHROPIC_AUTH_TOKEN"] == ""assert env["ANTHROPIC_BASE_URL"] == ""- def test_direct_anthropic_inherits_api_key(self):- """Mode 2: direct Anthropic doesn't set ANTHROPIC_* keys (inherits from parent)."""+ def test_direct_anthropic_carries_the_parents_api_key(self, monkeypatch):+ """Mode 2: direct Anthropic states the deployment's key, which the+ launch no longer inherits with the rest of the parent's environment."""+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-deployment-key")+ monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False)+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)cfg = _make_config(use_claude_code_subscription=False,use_openrouter=False,@@ -289,7 +293,7 @@ class TestBuildSdkEnv:env = build_sdk_env()- assert "ANTHROPIC_API_KEY" not in env+ assert env["ANTHROPIC_API_KEY"] == "sk-ant-deployment-key"assert "ANTHROPIC_AUTH_TOKEN" not in envassert "ANTHROPIC_BASE_URL" not in env@@ -345,7 +349,7 @@ class TestBuildSdkEnv:assert env["CLAUDE_CODE_REFRESH_TOKEN"] == ""def test_direct_anthropic_clears_oauth_tokens(self):- """Mode 2: OAuth tokens are cleared so CLI uses ANTHROPIC_API_KEY from parent env."""+ """Mode 2: OAuth tokens are cleared so CLI uses the deployment's ANTHROPIC_API_KEY."""cfg = _make_config(use_claude_code_subscription=False,use_openrouter=False,diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex 35839d0a74..2b83248bfd 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -253,6 +253,7 @@ from .compaction import (from .env import DISABLE_SLASH_COMMANDS_FLAG, cli_prompt_text, cli_user_messagefrom .env import build_sdk_env # noqa: F401 — re-export for backward compatfrom .governor import TurnGovernor+from .launch_env import launch_optionsfrom .openrouter_cost import TurnGenerations, record_turn_cost_from_openrouterfrom .response_adapter import SDKResponseAdapterfrom .security_hooks import create_security_hooks@@ -4407,7 +4408,7 @@ async def _run_stream_attempt(read_cli_session_usage, ctx.sdk_cwd, state.options.resume, ctx.log_prefix)state.usage.start_cli_session(baseline)- sdk_client = ClaudeSDKClient(options=state.options)+ sdk_client = ClaudeSDKClient(options=launch_options(state.options))client = await sdk_client.__aenter__()try:logger.info(diff --git a/autogpt_platform/backend/backend/copilot/sdk/subagent_turn_end_test.py b/autogpt_platform/backend/backend/copilot/sdk/subagent_turn_end_test.pyindex aec3d1c422..2ed7838eae 100644--- a/autogpt_platform/backend/backend/copilot/sdk/subagent_turn_end_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/subagent_turn_end_test.py@@ -39,6 +39,7 @@ from claude_agent_sdk import (from backend.copilot.config import ChatConfigfrom backend.copilot.sdk.cli_openrouter_compat_test import _resolve_cli_pathfrom backend.copilot.sdk.env import build_sdk_env+from backend.copilot.sdk.launch_env import launch_options_MAIN_USER_MARKER = "MAIN-USER-7f3a"_SUBAGENT_PROMPT = "SUBAGENT-PROMPT-9c41: report the magic word."@@ -276,7 +277,7 @@ async def run_copilot_style_turn(env=env,stderr=stderr_lines.append,)- sdk_client = ClaudeSDKClient(options=options)+ sdk_client = ClaudeSDKClient(options=launch_options(options))client = await sdk_client.__aenter__()try:await client.query(f"{_MAIN_USER_MARKER} find the magic word")diff --git a/autogpt_platform/backend/backend/copilot/sdk/subscription.py b/autogpt_platform/backend/backend/copilot/sdk/subscription.pyindex 27ed9d65ba..55ec3feab7 100644--- a/autogpt_platform/backend/backend/copilot/sdk/subscription.py+++ b/autogpt_platform/backend/backend/copilot/sdk/subscription.py@@ -11,8 +11,20 @@ import osimport shutilimport subprocess+from backend.copilot.sdk.launch_env import inherited_env+logger = logging.getLogger(__name__)+# The variables a host may hold its Claude login in instead of a+# ``claude login`` credentials file.+HOST_LOGIN_NAMES = ("CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_REFRESH_TOKEN")+++def host_login_env() -> dict[str, str]:+ """The host's Claude login, for a CLI that keeps nothing else of the+ backend's environment (``launch_env.py``)."""+ return {name: value for name in HOST_LOGIN_NAMES if (value := os.environ.get(name))}+def find_bundled_cli() -> str:"""Locate the Claude CLI binary bundled inside ``claude_agent_sdk``.@@ -96,6 +108,7 @@ def validate_subscription() -> None:capture_output=True,text=True,timeout=10,+ env=inherited_env(),)if result.returncode != 0:raise RuntimeError(@@ -113,12 +126,7 @@ def validate_subscription() -> None:capture_output=True,text=True,timeout=10,- env={- **os.environ,- "ANTHROPIC_API_KEY": "",- "ANTHROPIC_AUTH_TOKEN": "",- "ANTHROPIC_BASE_URL": "",- },+ env={**inherited_env(), **host_login_env()},)if auth_result.returncode != 0:raise RuntimeError(diff --git a/autogpt_platform/backend/backend/copilot/sdk/turn_cost_e2e_test.py b/autogpt_platform/backend/backend/copilot/sdk/turn_cost_e2e_test.pyindex 177d2da175..a5e578d677 100644--- a/autogpt_platform/backend/backend/copilot/sdk/turn_cost_e2e_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/turn_cost_e2e_test.py@@ -21,6 +21,7 @@ from backend.copilot.sdk.service import stream_chat_completion_sdkfrom backend.copilot.transcript import TranscriptDownloadfrom .cli_openrouter_compat_test import _resolve_cli_path+from .launch_env import launch_optionsfrom .retry_scenarios_test import _make_sdk_patches_SVC = "backend.copilot.sdk.service"@@ -79,7 +80,7 @@ async def test_second_turn_on_a_new_pod_is_charged_only_its_own_call(options.allowed_tools = []options.disallowed_tools = []options.system_prompt = "Reply ok."- client = ClaudeSDKClient(*args, options=options, **kwargs)+ client = ClaudeSDKClient(*args, options=launch_options(options), **kwargs)receive = client.receive_responseasync def _receive_and_note_totals():