Skip to content

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(copilot): GitHub CLI support — inject GH_TOKEN and connect_integration tool (#12426)

Zamil Majdy282173be9ddc
diff --git a/autogpt_platform/backend/backend/copilot/integration_creds.py b/autogpt_platform/backend/backend/copilot/integration_creds.py
new file mode 100644
index 0000000000..2da72e2739
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/integration_creds.py
@@ -0,0 +1,173 @@
+"""Integration credential lookup with per-process TTL cache.
+
+Provides token retrieval for connected integrations so that copilot tools
+(e.g. bash_exec) can inject auth tokens into the execution environment without
+hitting the database on every command.
+
+Cache semantics (handled automatically by TTLCache):
+- Token found → cached for _TOKEN_CACHE_TTL (5 min). Avoids repeated DB hits
+ for users who have credentials and are running many bash commands.
+- No credentials found → cached for _NULL_CACHE_TTL (60 s). Avoids a DB hit
+ on every E2B command for users who haven't connected an account yet, while
+ still picking up a newly-connected account within one minute.
+
+Both caches are bounded to _CACHE_MAX_SIZE entries; cachetools evicts the
+least-recently-used entry when the limit is reached.
+
+Multi-worker note: both caches are in-process only. Each worker/replica
+maintains its own independent cache, so a credential fetch may be duplicated
+across processes. This is acceptable for the current goal (reduce DB hits per
+session per-process), but if cache efficiency across replicas becomes important
+a shared cache (e.g. Redis) should be used instead.
+"""
+
+import logging
+from typing import cast
+
+from cachetools import TTLCache
+
+from backend.copilot.providers import SUPPORTED_PROVIDERS
+from backend.data.model import APIKeyCredentials, OAuth2Credentials
+from backend.integrations.creds_manager import (
+ IntegrationCredentialsManager,
+ register_creds_changed_hook,
+)
+
+logger = logging.getLogger(__name__)
+
+# Derived from the single SUPPORTED_PROVIDERS registry for backward compat.
+PROVIDER_ENV_VARS: dict[str, list[str]] = {
+ slug: entry["env_vars"] for slug, entry in SUPPORTED_PROVIDERS.items()
+}
+
+_TOKEN_CACHE_TTL = 300.0 # seconds — for found tokens
+_NULL_CACHE_TTL = 60.0 # seconds — for "not connected" results
+_CACHE_MAX_SIZE = 10_000
+
+# (user_id, provider) → token string. TTLCache handles expiry + eviction.
+# Thread-safety note: TTLCache is NOT thread-safe, but that is acceptable here
+# because all callers (get_provider_token, invalidate_user_provider_cache) run
+# exclusively on the asyncio event loop. There are no await points between a
+# cache read and its corresponding write within any function, so no concurrent
+# coroutine can interleave. If ThreadPoolExecutor workers are ever added to
+# this path, a threading.RLock should be wrapped around these caches.
+_token_cache: TTLCache[tuple[str, str], str] = TTLCache(
+ maxsize=_CACHE_MAX_SIZE, ttl=_TOKEN_CACHE_TTL
+)
+# Separate cache for "no credentials" results with a shorter TTL.
+_null_cache: TTLCache[tuple[str, str], bool] = TTLCache(
+ maxsize=_CACHE_MAX_SIZE, ttl=_NULL_CACHE_TTL
+)
+
+
+def invalidate_user_provider_cache(user_id: str, provider: str) -> None:
+ """Remove the cached entry for *user_id*/*provider* from both caches.
+
+ Call this after storing new credentials so that the next
+ ``get_provider_token()`` call performs a fresh DB lookup instead of
+ serving a stale TTL-cached result.
+ """
+ key = (user_id, provider)
+ _token_cache.pop(key, None)
+ _null_cache.pop(key, None)
+
+
+# Register this module's cache-bust function with the credentials manager so
+# that any create/update/delete operation immediately evicts stale cache
+# entries. This avoids a lazy import inside creds_manager and eliminates the
+# circular-import risk.
+try:
+ register_creds_changed_hook(invalidate_user_provider_cache)
+except RuntimeError:
+ # Hook already registered (e.g. module re-import in tests).
+ pass
+
+# Module-level singleton to avoid re-instantiating IntegrationCredentialsManager
+# on every cache-miss call to get_provider_token().
+_manager = IntegrationCredentialsManager()
+
+
+async def get_provider_token(user_id: str, provider: str) -> str | None:
+ """Return the user's access token for *provider*, or ``None`` if not connected.
+
+ OAuth2 tokens are preferred (refreshed if needed); API keys are the fallback.
+ Found tokens are cached for _TOKEN_CACHE_TTL (5 min). "Not connected" results
+ are cached for _NULL_CACHE_TTL (60 s) to avoid a DB hit on every bash_exec
+ command for users who haven't connected yet, while still picking up a
+ newly-connected account within one minute.
+ """
+ cache_key = (user_id, provider)
+
+ if cache_key in _null_cache:
+ return None
+ if cached := _token_cache.get(cache_key):
+ return cached
+
+ manager = _manager
+ try:
+ creds_list = await manager.store.get_creds_by_provider(user_id, provider)
+ except Exception:
+ logger.warning(
+ "Failed to fetch %s credentials for user %s",
+ provider,
+ user_id,
+ exc_info=True,
+ )
+ return None
+
+ # Pass 1: prefer OAuth2 (carry scope info, refreshable via token endpoint).
+ # Sort so broader-scoped tokens come first: a token with "repo" scope covers
+ # full git access, while a public-data-only token lacks push/pull permission.
+ # lock=False — background injection; not worth a distributed lock acquisition.
+ oauth2_creds = sorted(
+ [c for c in creds_list if c.type == "oauth2"],
+ key=lambda c: 0 if "repo" in (cast(OAuth2Credentials, c).scopes or []) else 1,
+ )
+ for creds in oauth2_creds:
+ if creds.type == "oauth2":
+ try:
+ fresh = await manager.refresh_if_needed(
+ user_id, cast(OAuth2Credentials, creds), lock=False
+ )
+ token = fresh.access_token.get_secret_value()
+ except Exception:
+ logger.warning(
+ "Failed to refresh %s OAuth token for user %s; "
+ "discarding stale token to force re-auth",
+ provider,
+ user_id,
+ exc_info=True,
+ )
+ # Do NOT fall back to the stale token — it is likely expired
+ # or revoked. Returning None forces the caller to re-auth,
+ # preventing the LLM from receiving a non-functional token.
+ continue
+ _token_cache[cache_key] = token
+ return token
+
+ # Pass 2: fall back to API key (no expiry, no refresh needed).
+ for creds in creds_list:
+ if creds.type == "api_key":
+ token = cast(APIKeyCredentials, creds).api_key.get_secret_value()
+ _token_cache[cache_key] = token
+ return token
+
+ # No credentials found — cache to avoid repeated DB hits.
+ _null_cache[cache_key] = True
+ return None
+
+
+async def get_integration_env_vars(user_id: str) -> dict[str, str]:
+ """Return env vars for all providers the user has connected.
+
+ Iterates :data:`PROVIDER_ENV_VARS`, fetches each token, and builds a flat
+ ``{env_var: token}`` dict ready to pass to a subprocess or E2B sandbox.
+ Only providers with a stored credential contribute entries.
+ """
+ env: dict[str, str] = {}
+ for provider, var_names in PROVIDER_ENV_VARS.items():
+ token = await get_provider_token(user_id, provider)
+ if token:
+ for var in var_names:
+ env[var] = token
+ return env
diff --git a/autogpt_platform/backend/backend/copilot/integration_creds_test.py b/autogpt_platform/backend/backend/copilot/integration_creds_test.py
new file mode 100644
index 0000000000..cc2bdb81de
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/integration_creds_test.py
@@ -0,0 +1,195 @@
+"""Tests for integration_creds — TTL cache and token lookup paths."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from pydantic import SecretStr
+
+from backend.copilot.integration_creds import (
+ _NULL_CACHE_TTL,
+ _TOKEN_CACHE_TTL,
+ PROVIDER_ENV_VARS,
+ _null_cache,
+ _token_cache,
+ get_integration_env_vars,
+ get_provider_token,
+ invalidate_user_provider_cache,
+)
+from backend.data.model import APIKeyCredentials, OAuth2Credentials
+
+_USER = "user-integration-creds-test"
+_PROVIDER = "github"
+
+
+def _make_api_key_creds(key: str = "test-api-key") -> APIKeyCredentials:
+ return APIKeyCredentials(
+ id="creds-api-key",
+ provider=_PROVIDER,
+ api_key=SecretStr(key),
+ title="Test API Key",
+ expires_at=None,
+ )
+
+
+def _make_oauth2_creds(token: str = "test-oauth-token") -> OAuth2Credentials:
+ return OAuth2Credentials(
+ id="creds-oauth2",
+ provider=_PROVIDER,
+ title="Test OAuth",
+ access_token=SecretStr(token),
+ refresh_token=SecretStr("test-refresh"),
+ access_token_expires_at=None,
+ refresh_token_expires_at=None,
+ scopes=[],
+ )
+
+
[email protected](autouse=True)
+def clear_caches():
+ """Ensure clean caches before and after every test."""
+ _token_cache.clear()
+ _null_cache.clear()
+ yield
+ _token_cache.clear()
+ _null_cache.clear()
+
+
+class TestInvalidateUserProviderCache:
+ def test_removes_token_entry(self):
+ key = (_USER, _PROVIDER)
+ _token_cache[key] = "tok"
+ invalidate_user_provider_cache(_USER, _PROVIDER)
+ assert key not in _token_cache
+
+ def test_removes_null_entry(self):
+ key = (_USER, _PROVIDER)
+ _null_cache[key] = True
+ invalidate_user_provider_cache(_USER, _PROVIDER)
+ assert key not in _null_cache
+
+ def test_noop_when_key_not_cached(self):
+ # Should not raise even when there is no cache entry.
+ invalidate_user_provider_cache("no-such-user", _PROVIDER)
+
+ def test_only_removes_targeted_key(self):
+ other_key = ("other-user", _PROVIDER)
+ _token_cache[other_key] = "other-tok"
+ invalidate_user_provider_cache(_USER, _PROVIDER)
+ assert other_key in _token_cache
+
+
+class TestGetProviderToken:
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_returns_cached_token_without_db_hit(self):
+ _token_cache[(_USER, _PROVIDER)] = "cached-tok"
+
+ mock_manager = MagicMock()
+ with patch("backend.copilot.integration_creds._manager", mock_manager):
+ result = await get_provider_token(_USER, _PROVIDER)
+
+ assert result == "cached-tok"
+ mock_manager.store.get_creds_by_provider.assert_not_called()
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_returns_none_for_null_cached_provider(self):
+ _null_cache[(_USER, _PROVIDER)] = True
+
+ mock_manager = MagicMock()
+ with patch("backend.copilot.integration_creds._manager", mock_manager):
+ result = await get_provider_token(_USER, _PROVIDER)
+
+ assert result is None
+ mock_manager.store.get_creds_by_provider.assert_not_called()
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_api_key_creds_returned_and_cached(self):
+ api_creds = _make_api_key_creds("my-api-key")
+ mock_manager = MagicMock()
+ mock_manager.store.get_creds_by_provider = AsyncMock(return_value=[api_creds])
+
+ with patch("backend.copilot.integration_creds._manager", mock_manager):
+ result = await get_provider_token(_USER, _PROVIDER)
+
+ assert result == "my-api-key"
+ assert _token_cache.get((_USER, _PROVIDER)) == "my-api-key"
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_oauth2_preferred_over_api_key(self):
+ oauth_creds = _make_oauth2_creds("oauth-tok")
+ api_creds = _make_api_key_creds("api-tok")
+ mock_manager = MagicMock()
+ mock_manager.store.get_creds_by_provider = AsyncMock(
+ return_value=[api_creds, oauth_creds]
+ )
+ mock_manager.refresh_if_needed = AsyncMock(return_value=oauth_creds)
+
+ with patch("backend.copilot.integration_creds._manager", mock_manager):
+ result = await get_provider_token(_USER, _PROVIDER)
+
+ assert result == "oauth-tok"
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_oauth2_refresh_failure_returns_none(self):
+ """On refresh failure, return None instead of caching a stale token."""
+ oauth_creds = _make_oauth2_creds("stale-oauth-tok")
+ mock_manager = MagicMock()
+ mock_manager.store.get_creds_by_provider = AsyncMock(return_value=[oauth_creds])
+ mock_manager.refresh_if_needed = AsyncMock(side_effect=RuntimeError("network"))
+
+ with patch("backend.copilot.integration_creds._manager", mock_manager):
+ result = await get_provider_token(_USER, _PROVIDER)
+
+ # Stale tokens must NOT be returned — forces re-auth.
+ assert result is None
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_no_credentials_caches_null_entry(self):
+ mock_manager = MagicMock()
+ mock_manager.store.get_creds_by_provider = AsyncMock(return_value=[])
+
+ with patch("backend.copilot.integration_creds._manager", mock_manager):
+ result = await get_provider_token(_USER, _PROVIDER)
+
+ assert result is None
+ assert _null_cache.get((_USER, _PROVIDER)) is True
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_db_exception_returns_none_without_caching(self):
+ mock_manager = MagicMock()
+ mock_manager.store.get_creds_by_provider = AsyncMock(
+ side_effect=RuntimeError("db down")
+ )
+
+ with patch("backend.copilot.integration_creds._manager", mock_manager):
+ result = await get_provider_token(_USER, _PROVIDER)
+
+ assert result is None
+ # DB errors are not cached — next call will retry
+ assert (_USER, _PROVIDER) not in _token_cache
+ assert (_USER, _PROVIDER) not in _null_cache
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_null_cache_has_shorter_ttl_than_token_cache(self):
+ """Verify the TTL constants are set correctly for each cache."""
+ assert _null_cache.ttl == _NULL_CACHE_TTL
+ assert _token_cache.ttl == _TOKEN_CACHE_TTL
+ assert _NULL_CACHE_TTL < _TOKEN_CACHE_TTL
+
+
+class TestGetIntegrationEnvVars:
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_injects_all_env_vars_for_provider(self):
+ _token_cache[(_USER, "github")] = "gh-tok"
+
+ result = await get_integration_env_vars(_USER)
+
+ for var in PROVIDER_ENV_VARS["github"]:
+ assert result[var] == "gh-tok"
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_empty_dict_when_no_credentials(self):
+ _null_cache[(_USER, "github")] = True
+
+ result = await get_integration_env_vars(_USER)
+
+ assert result == {}
diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.py
index 8815f4ce33..2ed1c8dac4 100644
--- a/autogpt_platform/backend/backend/copilot/prompting.py
+++ b/autogpt_platform/backend/backend/copilot/prompting.py
@@ -112,6 +112,25 @@ autopilot context, e.g. "research X and write a report" while the
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 = """
+### GitHub CLI (`gh`) and git
+- If the user has connected their GitHub account, both `gh` and `git` are
+ pre-authenticated — use them directly without any manual login step.
+ `git` HTTPS operations (clone, push, pull) work automatically.
+- If the token changes mid-session (e.g. user reconnects with a new token),
+ run `gh auth setup-git` to re-register the credential helper.
+- If `gh` or `git` fails with an authentication error (e.g. "authentication
+ required", "could not read Username", or exit code 128), call
+ `connect_integration(provider="github")` to surface the GitHub credentials
+ setup card so the user can connect their account. Once connected, retry
+ the operation.
+- For operations that need broader access (e.g. private org repos, GitHub
+ Actions), pass the required scopes: e.g.
+ `connect_integration(provider="github", scopes=["repo", "read:org"])`.
+"""
+
# Environment-specific supplement templates
def _build_storage_supplement(
@@ -122,6 +141,7 @@ def _build_storage_supplement(
storage_system_1_persistence: list[str],
file_move_name_1_to_2: str,
file_move_name_2_to_1: str,
+ extra_notes: str = "",
) -> str:
"""Build storage/filesystem supplement for a specific environment.
@@ -136,6 +156,7 @@ def _build_storage_supplement(
storage_system_1_persistence: List of persistence behavior descriptions
file_move_name_1_to_2: Direction label for primary→persistent
file_move_name_2_to_1: Direction label for persistent→primary
+ extra_notes: Environment-specific notes appended after shared notes
"""
# Format lists as bullet points with proper indentation
characteristics = "\n".join(f" - {c}" for c in storage_system_1_characteristics)
@@ -176,12 +197,16 @@ a local file under `~/.claude/projects/.../tool-results/`. To read these files,
always use `read_file` or `Read` (NOT `read_workspace_file`).
`read_workspace_file` reads from cloud workspace storage, where SDK
tool-results are NOT stored.
-{_SHARED_TOOL_NOTES}"""
+{_SHARED_TOOL_NOTES}{extra_notes}"""
# Pre-built supplements for common environments
def _get_local_storage_supplement(cwd: str) -> str:
- """Local ephemeral storage (files lost between turns)."""
+ """Local ephemeral storage (files lost between turns).
+
+ Network is isolated (bubblewrap --unshare-net), so internet-dependent CLIs
+ like gh will not work — no integration env-var notes are included.
+ """
return _build_storage_supplement(
working_dir=cwd,
sandbox_type="in a network-isolated sandbox",
@@ -199,7 +224,11 @@ def _get_local_storage_supplement(cwd: str) -> str:
def _get_cloud_sandbox_supplement() -> str:
- """Cloud persistent sandbox (files survive across turns in session)."""
+ """Cloud persistent sandbox (files survive across turns in session).
+
+ E2B has full internet access, so integration tokens (GH_TOKEN etc.) are
+ injected per command in bash_exec — include the CLI guidance notes.
+ """
return _build_storage_supplement(
working_dir="/home/user",
sandbox_type="in a cloud sandbox with full internet access",
@@ -214,6 +243,7 @@ def _get_cloud_sandbox_supplement() -> str:
],
file_move_name_1_to_2="Sandbox → Persistent",
file_move_name_2_to_1="Persistent → Sandbox",
+ extra_notes=_E2B_TOOL_NOTES,
)
diff --git a/autogpt_platform/backend/backend/copilot/providers.py b/autogpt_platform/backend/backend/copilot/providers.py
new file mode 100644
index 0000000000..decd68ba9e
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/providers.py
@@ -0,0 +1,63 @@
+"""Single source of truth for copilot-supported integration providers.
+
+Both :mod:`~backend.copilot.integration_creds` (env-var injection) and
+:mod:`~backend.copilot.tools.connect_integration` (UI setup card) import from
+here, eliminating the risk of the two registries drifting out of sync.
+"""
+
+from typing import TypedDict
+
+
+class ProviderEntry(TypedDict):
+ """Metadata for a supported integration provider.
+
+ Attributes:
+ name: Human-readable display name (e.g. "GitHub").
+ env_vars: Environment variable names injected when the provider is
+ connected (e.g. ``["GH_TOKEN", "GITHUB_TOKEN"]``).
+ default_scopes: Default OAuth scopes requested when the agent does not
+ specify any.
+ """
+
+ name: str
+ env_vars: list[str]
+ default_scopes: list[str]
+
+
+def _is_github_oauth_configured() -> bool:
+ """Return True if GitHub OAuth env vars are set.
+
+ Uses a lazy import to avoid triggering ``Secrets()`` during module import,
+ which can fail in environments where secrets are not yet loaded (e.g. tests,
+ CLI tooling).
+ """
+ from backend.blocks.github._auth import GITHUB_OAUTH_IS_CONFIGURED
+
+ return GITHUB_OAUTH_IS_CONFIGURED
+
+
+# -- Registry ----------------------------------------------------------------
+# Add new providers here. Both env-var injection and the setup-card tool read
+# from this single registry.
+
+SUPPORTED_PROVIDERS: dict[str, ProviderEntry] = {
+ "github": {
+ "name": "GitHub",
+ "env_vars": ["GH_TOKEN", "GITHUB_TOKEN"],
+ "default_scopes": ["repo"],
+ },
+}
+
+
+def get_provider_auth_types(provider: str) -> list[str]:
+ """Return the supported credential types for *provider* at runtime.
+
+ OAuth types are only offered when the corresponding OAuth client env vars
+ are configured.
+ """
+ if provider == "github":
+ if _is_github_oauth_configured():
+ return ["api_key", "oauth2"]
+ return ["api_key"]
+ # Default for unknown/future providers — API key only.
+ return ["api_key"]
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index 5c1b352eef..b8351e9b89 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -1520,7 +1520,7 @@ async def stream_chat_completion_sdk(
)
return None
try:
- return await get_or_create_sandbox(
+ sandbox = await get_or_create_sandbox(
session_id,
api_key=e2b_api_key,
template=config.e2b_sandbox_template,
@@ -1534,7 +1534,9 @@ async def stream_chat_completion_sdk(
e2b_err,
exc_info=True,
)
- return None
+ return None
+
+ return sandbox
async def _fetch_transcript():
"""Download transcript for --resume if applicable."""
diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.py
index 2a4ab8378a..bde380d1fc 100644
--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py
@@ -12,6 +12,7 @@ from .agent_browser import BrowserActTool, BrowserNavigateTool, BrowserScreensho
from .agent_output import AgentOutputTool
from .base import BaseTool
from .bash_exec import BashExecTool
+from .connect_integration import ConnectIntegrationTool
from .continue_run_block import ContinueRunBlockTool
from .create_agent import CreateAgentTool
from .customize_agent import CustomizeAgentTool
@@ -84,6 +85,7 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
"browser_screenshot": BrowserScreenshotTool(),
# Sandboxed code execution (bubblewrap)
"bash_exec": BashExecTool(),
+ "connect_integration": ConnectIntegrationTool(),
# Persistent workspace tools (cloud storage, survives across sessions)
# Feature request tools
"search_feature_requests": SearchFeatureRequestsTool(),
diff --git a/autogpt_platform/backend/backend/copilot/tools/base.py b/autogpt_platform/backend/backend/copilot/tools/base.py
index 1225d22e18..87820a1bf9 100644
--- a/autogpt_platform/backend/backend/copilot/tools/base.py
+++ b/autogpt_platform/backend/backend/copilot/tools/base.py
@@ -164,8 +164,9 @@ class BaseTool:
"""
if self.requires_auth and not user_id:
- logger.error(
- f"Attempted tool call for {self.name} but user not authenticated"
+ logger.warning(
+ "Attempted tool call for %s but user not authenticated",
+ self.name,
)
return StreamToolOutputAvailable(
toolCallId=tool_call_id,
@@ -196,7 +197,7 @@ class BaseTool:
output=raw_output,
)
except Exception as e:
- logger.error(f"Error in {self.name}: {e}", exc_info=True)
+ logger.warning("Error in %s", self.name, exc_info=True)
return StreamToolOutputAvailable(
toolCallId=tool_call_id,
toolName=self.name,
diff --git a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py b/autogpt_platform/backend/backend/copilot/tools/bash_exec.py
index 1768e97c54..ce7bab5fc2 100644
--- a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py
+++ b/autogpt_platform/backend/backend/copilot/tools/bash_exec.py
@@ -22,6 +22,7 @@ from e2b import AsyncSandbox
from e2b.exceptions import TimeoutException
from backend.copilot.context import E2B_WORKDIR, get_current_sandbox
+from backend.copilot.integration_creds import get_integration_env_vars
from backend.copilot.model import ChatSession
from .base import BaseTool
@@ -74,7 +75,10 @@ class BashExecTool(BaseTool):
@property
def requires_auth(self) -> bool:
- return False
+ # True because _execute_on_e2b injects user tokens (GH_TOKEN etc.)
+ # when user_id is present. Defense-in-depth: ensures only authenticated
+ # users reach the token injection path.
+ return True
async def _execute(
self,
@@ -82,6 +86,14 @@ class BashExecTool(BaseTool):
session: ChatSession,
**kwargs: Any,
) -> ToolResponseBase:
+ """Run a bash command on E2B (if available) or in a bubblewrap sandbox.
+
+ Dispatches to :meth:`_execute_on_e2b` when a sandbox is present in the
+ current execution context, otherwise falls back to the local bubblewrap
+ sandbox. Returns a :class:`BashExecResponse` on success or an
+ :class:`ErrorResponse` when the sandbox is unavailable or the command
+ is empty.
+ """
session_id = session.session_id if session else None
command: str = (kwargs.get("command") or "").strip()
@@ -96,7 +108,9 @@ class BashExecTool(BaseTool):
sandbox = get_current_sandbox()
if sandbox is not None:
- return await self._execute_on_e2b(sandbox, command, timeout, session_id)
+ return await self._execute_on_e2b(
+ sandbox, command, timeout, session_id, user_id
+ )
# Bubblewrap fallback: local isolated execution.
if not has_full_sandbox():
@@ -133,19 +147,42 @@ class BashExecTool(BaseTool):
command: str,
timeout: int,
session_id: str | None,
+ user_id: str | None = None,
) -> ToolResponseBase:
- """Execute *command* on the E2B sandbox via commands.run()."""
+ """Execute *command* on the E2B sandbox via commands.run().
+
+ Integration tokens (e.g. GH_TOKEN) are injected into the sandbox env
+ for any user with connected accounts. E2B has full internet access, so
+ CLI tools like ``gh`` work without manual authentication.
+ """
+ envs: dict[str, str] = {
+ "PATH": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
+ }
+ # Collect injected secret values so we can scrub them from output.
+ secret_values: list[str] = []
+ if user_id is not None:
+ integration_env = await get_integration_env_vars(user_id)
+ secret_values = [v for v in integration_env.values() if v]
+ envs.update(integration_env)
+
try:
result = await sandbox.commands.run(
f"bash -c {shlex.quote(command)}",
cwd=E2B_WORKDIR,
timeout=timeout,
- envs={"PATH": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"},
+ envs=envs,
)
+ stdout = result.stdout or ""
+ stderr = result.stderr or ""
+ # Scrub injected tokens from command output to prevent exfiltration
+ # via `echo $GH_TOKEN`, `env`, `printenv`, etc.
+ for secret in secret_values:
+ stdout = stdout.replace(secret, "[REDACTED]")
+ stderr = stderr.replace(secret, "[REDACTED]")
return BashExecResponse(
message=f"Command executed on E2B (exit {result.exit_code})",
- stdout=result.stdout or "",
- stderr=result.stderr or "",
+ stdout=stdout,
+ stderr=stderr,
exit_code=result.exit_code,
timed_out=False,
session_id=session_id,
diff --git a/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py b/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py
new file mode 100644
index 0000000000..193a7affb4
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/bash_exec_test.py
@@ -0,0 +1,78 @@
+"""Tests for BashExecTool — E2B path with token injection."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from ._test_data import make_session
+from .bash_exec import BashExecTool
+from .models import BashExecResponse
+
+_USER = "user-bash-exec-test"
+
+
+def _make_tool() -> BashExecTool:
+ return BashExecTool()
+
+
+def _make_sandbox(exit_code: int = 0, stdout: str = "", stderr: str = "") -> MagicMock:
+ result = MagicMock()
+ result.exit_code = exit_code
+ result.stdout = stdout
+ result.stderr = stderr
+
+ sandbox = MagicMock()
+ sandbox.commands.run = AsyncMock(return_value=result)
+ return sandbox
+
+
+class TestBashExecE2BTokenInjection:
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_token_injected_when_user_id_set(self):
+ """When user_id is provided, integration env vars are merged into sandbox envs."""
+ tool = _make_tool()
+ session = make_session(user_id=_USER)
+ sandbox = _make_sandbox(stdout="ok")
+ env_vars = {"GH_TOKEN": "gh-secret", "GITHUB_TOKEN": "gh-secret"}
+
+ with patch(
+ "backend.copilot.tools.bash_exec.get_integration_env_vars",
+ new=AsyncMock(return_value=env_vars),
+ ) as mock_get_env:
+ result = await tool._execute_on_e2b(
+ sandbox=sandbox,
+ command="echo hi",
+ timeout=10,
+ session_id=session.session_id,
+ user_id=_USER,
+ )
+
+ mock_get_env.assert_awaited_once_with(_USER)
+ call_kwargs = sandbox.commands.run.call_args[1]
+ assert call_kwargs["envs"]["GH_TOKEN"] == "gh-secret"
+ assert call_kwargs["envs"]["GITHUB_TOKEN"] == "gh-secret"
+ assert isinstance(result, BashExecResponse)
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_no_token_injection_when_user_id_is_none(self):
+ """When user_id is None, get_integration_env_vars must NOT be called."""
+ tool = _make_tool()
+ session = make_session(user_id=_USER)
+ sandbox = _make_sandbox(stdout="ok")
+
+ with patch(
+ "backend.copilot.tools.bash_exec.get_integration_env_vars",
+ new=AsyncMock(return_value={"GH_TOKEN": "should-not-appear"}),
+ ) as mock_get_env:
+ result = await tool._execute_on_e2b(
+ sandbox=sandbox,
+ command="echo hi",
+ timeout=10,
+ session_id=session.session_id,
+ user_id=None,
+ )
+
+ mock_get_env.assert_not_called()
+ call_kwargs = sandbox.commands.run.call_args[1]
+ assert "GH_TOKEN" not in call_kwargs["envs"]
+ assert isinstance(result, BashExecResponse)
diff --git a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py b/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
new file mode 100644
index 0000000000..88f68b7eee
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
@@ -0,0 +1,196 @@
+"""Tool for prompting the user to connect a required integration.
+
+When the copilot encounters an authentication failure (e.g. `gh` CLI returns
+"authentication required"), it calls this tool to surface the credentials
+setup card in the chat — the same UI that appears when a GitHub block runs
+without configured credentials.
+"""
+
+from typing import Any, TypedDict
+
+from backend.copilot.model import ChatSession
+from backend.copilot.providers import SUPPORTED_PROVIDERS, get_provider_auth_types
+from backend.copilot.tools.models import (
+ ErrorResponse,
+ ResponseType,
+ SetupInfo,
+ SetupRequirementsResponse,
+ ToolResponseBase,
+ UserReadiness,
+)
+
+from .base import BaseTool
+
+
+class _CredentialEntry(TypedDict):
+ """Shape of each entry inside SetupRequirementsResponse.user_readiness.missing_credentials.
+
+ Partially overlaps with :class:`~backend.data.model.CredentialsMetaInput`
+ (``id``, ``title``, ``provider``) but carries extra UI-facing fields
+ (``types``, ``scopes``) that the frontend ``SetupRequirementsCard`` needs
+ to render the inline credential setup card.
+
+ Display name is derived from :data:`SUPPORTED_PROVIDERS` at build time
+ rather than stored here — eliminates the old ``provider_name`` field.
+ ``types`` replaces the old singular ``type`` field; the frontend already
+ prefers ``types`` and only fell back to ``type`` for compatibility.
+ """
+
+ id: str
+ title: str
+ # Slug used as the credential key (e.g. "github").
+ provider: str
+ # All supported credential types the user can choose from (e.g. ["api_key", "oauth2"]).
+ # The first element is the default/primary type.
+ types: list[str]
+ scopes: list[str]
+
+
+class ConnectIntegrationTool(BaseTool):
+ """Surface the credentials setup UI when an integration is not connected."""
+
+ @property
+ def name(self) -> str:
+ return "connect_integration"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Prompt the user to connect a required integration (e.g. GitHub). "
+ "Call this when an external CLI or API call fails because the user "
+ "has not connected the relevant account. "
+ "The tool surfaces a credentials setup card in the chat so the user "
+ "can authenticate without leaving the page. "
+ "After the user connects the account, retry the operation. "
+ "In E2B/cloud sandbox mode the token (GH_TOKEN/GITHUB_TOKEN) is "
+ "automatically injected per-command in bash_exec — no manual export needed. "
+ "In local bubblewrap mode network is isolated so GitHub CLI commands "
+ "will still fail after connecting; inform the user of this limitation."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "provider": {
+ "type": "string",
+ "description": (
+ "Integration provider slug, e.g. 'github'. "
+ "Must be one of the supported providers."
+ ),
+ "enum": list(SUPPORTED_PROVIDERS.keys()),
+ },
+ "reason": {
+ "type": "string",
+ "description": (
+ "Brief explanation of why the integration is needed, "
+ "shown to the user in the setup card."
+ ),
+ "maxLength": 500,
+ },
+ "scopes": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "OAuth scopes to request. Omit to use the provider default. "
+ "Add extra scopes when you need more access — e.g. for GitHub: "
+ "'repo' (clone/push/pull), 'read:org' (org membership), "
+ "'workflow' (GitHub Actions). "
+ "Requesting only the scopes you actually need is best practice."
+ ),
+ },
+ },
+ "required": ["provider"],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ # Require auth so only authenticated users can trigger the setup card.
+ # The card itself is user-agnostic (no per-user data needed), so
+ # user_id is intentionally unused in _execute.
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ **kwargs: Any,
+ ) -> ToolResponseBase:
+ """Build and return a :class:`SetupRequirementsResponse` for the requested provider.
+
+ Validates the *provider* slug against the known registry, merges any
+ agent-requested OAuth *scopes* with the provider defaults, and constructs
+ the credential setup card payload that the frontend renders as an inline
+ authentication prompt.
+
+ Returns an :class:`ErrorResponse` if *provider* is unknown.
+ """
+ _ = user_id # setup card is user-agnostic; auth is enforced via requires_auth
+ session_id = session.session_id if session else None
+ provider: str = (kwargs.get("provider") or "").strip().lower()
+ reason: str = (kwargs.get("reason") or "").strip()[
+ :500
+ ] # cap LLM-controlled text
+ extra_scopes: list[str] = [
+ str(s).strip() for s in (kwargs.get("scopes") or []) if str(s).strip()
+ ]
+
+ entry = SUPPORTED_PROVIDERS.get(provider)
+ if not entry:
+ supported = ", ".join(f"'{p}'" for p in SUPPORTED_PROVIDERS)
+ return ErrorResponse(
+ message=(
+ f"Unknown provider '{provider}'. "
+ f"Supported providers: {supported}."
+ ),
+ error="unknown_provider",
+ session_id=session_id,
+ )
+
+ display_name: str = entry["name"]
+ supported_types: list[str] = get_provider_auth_types(provider)
+ # Merge agent-requested scopes with provider defaults (deduplicated, order preserved).
+ default_scopes: list[str] = entry["default_scopes"]
+ seen: set[str] = set()
+ scopes: list[str] = []
+ for s in default_scopes + extra_scopes:
+ if s not in seen:
+ seen.add(s)
+ scopes.append(s)
+ field_key = f"{provider}_credentials"
+
+ message_parts = [
+ f"To continue, please connect your {display_name} account.",
+ ]
+ if reason:
+ message_parts.append(reason)
+
+ credential_entry: _CredentialEntry = {
+ "id": field_key,
+ "title": f"{display_name} Credentials",
+ "provider": provider,
+ "types": supported_types,
+ "scopes": scopes,
+ }
+ missing_credentials: dict[str, _CredentialEntry] = {field_key: credential_entry}
+
+ return SetupRequirementsResponse(
+ type=ResponseType.SETUP_REQUIREMENTS,
+ message=" ".join(message_parts),
+ session_id=session_id,
+ setup_info=SetupInfo(
+ agent_id=f"connect_{provider}",
+ agent_name=display_name,
+ user_readiness=UserReadiness(
+ has_all_credentials=False,
+ missing_credentials=missing_credentials,
+ ready_to_run=False,
+ ),
+ requirements={
+ "credentials": [missing_credentials[field_key]],
+ "inputs": [],
+ "execution_modes": [],
+ },
+ ),
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/connect_integration_test.py b/autogpt_platform/backend/backend/copilot/tools/connect_integration_test.py
new file mode 100644
index 0000000000..cf17f4cc79
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/connect_integration_test.py
@@ -0,0 +1,135 @@
+"""Tests for ConnectIntegrationTool."""
+
+import pytest
+
+from ._test_data import make_session
+from .connect_integration import ConnectIntegrationTool
+from .models import ErrorResponse, SetupRequirementsResponse
+
+_TEST_USER_ID = "test-user-connect-integration"
+
+
+class TestConnectIntegrationTool:
+ def _make_tool(self) -> ConnectIntegrationTool:
+ return ConnectIntegrationTool()
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_unknown_provider_returns_error(self):
+ tool = self._make_tool()
+ session = make_session(user_id=_TEST_USER_ID)
+ result = await tool._execute(
+ user_id=_TEST_USER_ID, session=session, provider="nonexistent"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "unknown_provider"
+ assert "nonexistent" in result.message
+ assert "github" in result.message
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_empty_provider_returns_error(self):
+ tool = self._make_tool()
+ session = make_session(user_id=_TEST_USER_ID)
+ result = await tool._execute(
+ user_id=_TEST_USER_ID, session=session, provider=""
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "unknown_provider"
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_github_provider_returns_setup_response(self):
+ tool = self._make_tool()
+ session = make_session(user_id=_TEST_USER_ID)
+ result = await tool._execute(
+ user_id=_TEST_USER_ID, session=session, provider="github"
+ )
+ assert isinstance(result, SetupRequirementsResponse)
+ assert result.setup_info.agent_name == "GitHub"
+ assert result.setup_info.agent_id == "connect_github"
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_github_has_missing_credentials_in_readiness(self):
+ tool = self._make_tool()
+ session = make_session(user_id=_TEST_USER_ID)
+ result = await tool._execute(
+ user_id=_TEST_USER_ID, session=session, provider="github"
+ )
+ assert isinstance(result, SetupRequirementsResponse)
+ readiness = result.setup_info.user_readiness
+ assert readiness.has_all_credentials is False
+ assert readiness.ready_to_run is False
+ assert "github_credentials" in readiness.missing_credentials
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_github_requirements_include_credential_entry(self):
+ tool = self._make_tool()
+ session = make_session(user_id=_TEST_USER_ID)
+ result = await tool._execute(
+ user_id=_TEST_USER_ID, session=session, provider="github"
+ )
+ assert isinstance(result, SetupRequirementsResponse)
+ creds = result.setup_info.requirements["credentials"]
+ assert len(creds) == 1
+ assert creds[0]["provider"] == "github"
+ assert creds[0]["id"] == "github_credentials"
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_reason_appears_in_message(self):
+ tool = self._make_tool()
+ session = make_session(user_id=_TEST_USER_ID)
+ reason = "Needed to create a pull request."
+ result = await tool._execute(
+ user_id=_TEST_USER_ID, session=session, provider="github", reason=reason
+ )
+ assert isinstance(result, SetupRequirementsResponse)
+ assert reason in result.message
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_session_id_propagated(self):
+ tool = self._make_tool()
+ session = make_session(user_id=_TEST_USER_ID)
+ result = await tool._execute(
+ user_id=_TEST_USER_ID, session=session, provider="github"
+ )
+ assert isinstance(result, SetupRequirementsResponse)
+ assert result.session_id == session.session_id
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_provider_case_insensitive(self):
+ """Provider slug is normalised to lowercase before lookup."""
+ tool = self._make_tool()
+ session = make_session(user_id=_TEST_USER_ID)
+ result = await tool._execute(
+ user_id=_TEST_USER_ID, session=session, provider="GitHub"
+ )
+ assert isinstance(result, SetupRequirementsResponse)
+
+ def test_tool_name(self):
+ assert ConnectIntegrationTool().name == "connect_integration"
+
+ def test_requires_auth(self):
+ assert ConnectIntegrationTool().requires_auth is True
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_unauthenticated_user_gets_need_login_response(self):
+ """execute() with user_id=None must return NeedLoginResponse, not the setup card.
+
+ This verifies that the requires_auth guard in BaseTool.execute() fires
+ before _execute() is called, so unauthenticated callers cannot probe
+ which integrations are configured.
+ """
+ import json
+
+ tool = self._make_tool()
+ # Session still needs a user_id string; the None is passed to execute()
+ # to simulate an unauthenticated call.
+ session = make_session(user_id=_TEST_USER_ID)
+ result = await tool.execute(
+ user_id=None,
+ session=session,
+ tool_call_id="test-call-id",
+ provider="github",
+ )
+ raw = result.output
+ output = json.loads(raw) if isinstance(raw, str) else raw
+ assert output.get("type") == "need_login"
+ assert result.success is False
diff --git a/autogpt_platform/backend/backend/integrations/creds_manager.py b/autogpt_platform/backend/backend/integrations/creds_manager.py
index 5634dd73b6..6e404aca7e 100644
--- a/autogpt_platform/backend/backend/integrations/creds_manager.py
+++ b/autogpt_platform/backend/backend/integrations/creds_manager.py
@@ -25,6 +25,53 @@ logger = logging.getLogger(__name__)
settings = Settings()
+_on_creds_changed: Callable[[str, str], None] | None = None
+
+
+def register_creds_changed_hook(hook: Callable[[str, str], None]) -> None:
+ """Register a callback invoked after any credential is created/updated/deleted.
+
+ The callback receives ``(user_id, provider)`` and should be idempotent.
+ Only one hook can be registered at a time. Intended to be called once at
+ application startup (e.g. by the copilot module) without creating an
+ import cycle.
+
+ Raises:
+ RuntimeError: If a hook is already registered. Call
+ :func:`unregister_creds_changed_hook` first if replacement is needed.
+ """
+ global _on_creds_changed
+ if _on_creds_changed is not None:
+ raise RuntimeError(
+ "A creds_changed hook is already registered. "
+ "Call unregister_creds_changed_hook() before registering a new one."
+ )
+ _on_creds_changed = hook
+
+
+def unregister_creds_changed_hook() -> None:
+ """Remove the currently registered creds-changed hook (if any).
+
+ Primarily useful in tests to reset global state between test cases.
+ """
+ global _on_creds_changed
+ _on_creds_changed = None
+
+
+def _invoke_creds_changed_hook(user_id: str, provider: str) -> None:
+ """Invoke the registered creds-changed hook (if any)."""
+ if _on_creds_changed is not None:
+ try:
+ _on_creds_changed(user_id, provider)
+ except Exception:
+ logger.warning(
+ "Credential-change hook failed for user=%s provider=%s",
+ user_id,
+ provider,
+ exc_info=True,
+ )
+
+
class IntegrationCredentialsManager:
"""
Handles the lifecycle of integration credentials.
@@ -69,7 +116,10 @@ class IntegrationCredentialsManager:
return self._locks
async def create(self, user_id: str, credentials: Credentials) -> None:
- return await self.store.add_creds(user_id, credentials)
+ result = await self.store.add_creds(user_id, credentials)
+ # Notify listeners so downstream caches are invalidated immediately.
+ _invoke_creds_changed_hook(user_id, credentials.provider)
+ return result
async def exists(self, user_id: str, credentials_id: str) -> bool:
return (await self.store.get_creds_by_id(user_id, credentials_id)) is not None
@@ -146,8 +196,7 @@ class IntegrationCredentialsManager:
oauth_handler = await _get_provider_oauth_handler(credentials.provider)
if oauth_handler.needs_refresh(credentials):
logger.debug(
- f"Refreshing '{credentials.provider}' "
- f"credentials #{credentials.id}"
+ f"Refreshing '{credentials.provider}' credentials #{credentials.id}"
)
_lock = None
if lock:
@@ -156,11 +205,16 @@ class IntegrationCredentialsManager:
fresh_credentials = await oauth_handler.refresh_tokens(credentials)
await self.store.update_creds(user_id, fresh_credentials)
+ # Notify listeners so the refreshed token is picked up immediately.
+ _invoke_creds_changed_hook(user_id, fresh_credentials.provider)
if _lock and (await _lock.locked()) and (await _lock.owned()):
try:
await _lock.release()
- except Exception as e:
- logger.warning(f"Failed to release OAuth refresh lock: {e}")
+ except Exception:
+ logger.warning(
+ "Failed to release OAuth refresh lock",
+ exc_info=True,
+ )
credentials = fresh_credentials
return credentials
@@ -168,10 +222,17 @@ class IntegrationCredentialsManager:
async def update(self, user_id: str, updated: Credentials) -> None:
async with self._locked(user_id, updated.id):
await self.store.update_creds(user_id, updated)
+ # Notify listeners so the updated credential is picked up immediately.
+ _invoke_creds_changed_hook(user_id, updated.provider)
async def delete(self, user_id: str, credentials_id: str) -> None:
async with self._locked(user_id, credentials_id):
+ # Read inside the lock to avoid TOCTOU — another coroutine could
+ # delete the same credential between the read and the delete.
+ creds = await self.store.get_creds_by_id(user_id, credentials_id)
await self.store.delete_creds_by_id(user_id, credentials_id)
+ if creds:
+ _invoke_creds_changed_hook(user_id, creds.provider)
# -- Locking utilities -- #
@@ -195,8 +256,11 @@ class IntegrationCredentialsManager:
if (await lock.locked()) and (await lock.owned()):
try:
await lock.release()
- except Exception as e:
- logger.warning(f"Failed to release credentials lock: {e}")
+ except Exception:
+ logger.warning(
+ "Failed to release credentials lock",
+ exc_info=True,
+ )
async def release_all_locks(self):
"""Call this on process termination to ensure all locks are released"""
diff --git a/autogpt_platform/backend/backend/integrations/creds_manager_test.py b/autogpt_platform/backend/backend/integrations/creds_manager_test.py
new file mode 100644
index 0000000000..68665bd731
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/creds_manager_test.py
@@ -0,0 +1,60 @@
+"""Tests for creds_manager hook system: register, invoke, and CRUD integration."""
+
+import pytest
+
+from backend.integrations.creds_manager import (
+ _invoke_creds_changed_hook,
+ register_creds_changed_hook,
+ unregister_creds_changed_hook,
+)
+
+
[email protected](autouse=True)
+def _reset_hook():
+ """Ensure global hook state is clean before and after every test."""
+ unregister_creds_changed_hook()
+ yield
+ unregister_creds_changed_hook()
+
+
+class TestRegisterCredsChangedHook:
+ def test_register_and_invoke(self):
+ calls: list[tuple[str, str]] = []
+ register_creds_changed_hook(lambda u, p: calls.append((u, p)))
+
+ _invoke_creds_changed_hook("user-1", "github")
+ assert calls == [("user-1", "github")]
+
+ def test_double_register_raises(self):
+ register_creds_changed_hook(lambda u, p: None)
+ with pytest.raises(RuntimeError, match="already registered"):
+ register_creds_changed_hook(lambda u, p: None)
+
+ def test_unregister_then_reregister(self):
+ register_creds_changed_hook(lambda u, p: None)
+ unregister_creds_changed_hook()
+ # Should not raise after unregister.
+ register_creds_changed_hook(lambda u, p: None)
+
+
+class TestInvokeCredsChangedHook:
+ def test_noop_when_no_hook_registered(self):
+ # Must not raise even when no hook is registered.
+ _invoke_creds_changed_hook("user-1", "github")
+
+ def test_hook_exception_is_swallowed(self):
+ def bad_hook(user_id: str, provider: str) -> None:
+ raise ValueError("boom")
+
+ register_creds_changed_hook(bad_hook)
+ # Must not propagate the exception.
+ _invoke_creds_changed_hook("user-1", "github")
+
+ def test_hook_receives_correct_args(self):
+ calls: list[tuple[str, str]] = []
+ register_creds_changed_hook(lambda u, p: calls.append((u, p)))
+
+ _invoke_creds_changed_hook("user-a", "github")
+ _invoke_creds_changed_hook("user-b", "slack")
+
+ assert calls == [("user-a", "github"), ("user-b", "slack")]
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
index 50381f5b38..8eadc3e8f8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
@@ -3,6 +3,7 @@ import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
import { ExclamationMarkIcon } from "@phosphor-icons/react";
import { ToolUIPart, UIDataTypes, UIMessage, UITools } from "ai";
import { useState } from "react";
+import { ConnectIntegrationTool } from "../../../tools/ConnectIntegrationTool/ConnectIntegrationTool";
import { CreateAgentTool } from "../../../tools/CreateAgent/CreateAgent";
import { EditAgentTool } from "../../../tools/EditAgent/EditAgent";
import {
@@ -136,6 +137,8 @@ export function MessagePartRenderer({
case "tool-search_docs":
case "tool-get_doc_page":
return <SearchDocsTool key={key} part={part as ToolUIPart} />;
+ case "tool-connect_integration":
+ return <ConnectIntegrationTool key={key} part={part as ToolUIPart} />;
case "tool-run_block":
case "tool-continue_run_block":
return <RunBlockTool key={key} part={part as ToolUIPart} />;
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsx
new file mode 100644
index 0000000000..1be760e2f0
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ConnectIntegrationTool/ConnectIntegrationTool.tsx
@@ -0,0 +1,104 @@
+"use client";
+
+import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";
+import type { ToolUIPart } from "ai";
+import { useState } from "react";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import { ContentMessage } from "../../components/ToolAccordion/AccordionContent";
+import { SetupRequirementsCard } from "../RunBlock/components/SetupRequirementsCard/SetupRequirementsCard";
+
+type Props = {
+ part: ToolUIPart;
+};
+
+function parseJson(raw: unknown): unknown {
+ if (typeof raw === "string") {
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ }
+ return raw;
+}
+
+function parseOutput(raw: unknown): SetupRequirementsResponse | null {
+ const parsed = parseJson(raw);
+ if (parsed && typeof parsed === "object" && "setup_info" in parsed) {
+ return parsed as SetupRequirementsResponse;
+ }
+ return null;
+}
+
+function parseError(raw: unknown): string | null {
+ const parsed = parseJson(raw);
+ if (parsed && typeof parsed === "object" && "message" in parsed) {
+ return String((parsed as { message: unknown }).message);
+ }
+ return null;
+}
+
+export function ConnectIntegrationTool({ part }: Props) {
+ // Persist dismissed state here so SetupRequirementsCard remounts don't re-enable Proceed.
+ const [isDismissed, setIsDismissed] = useState(false);
+
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+ const isError = part.state === "output-error";
+
+ const output =
+ part.state === "output-available"
+ ? parseOutput((part as { output?: unknown }).output)
+ : null;
+
+ const errorMessage = isError
+ ? (parseError((part as { output?: unknown }).output) ??
+ "Failed to connect integration")
+ : null;
+
+ const rawProvider =
+ (part as { input?: { provider?: string } }).input?.provider ?? "";
+ const providerName =
+ output?.setup_info?.agent_name ??
+ // Sanitize LLM-controlled provider slug: trim and cap at 64 chars to
+ // prevent runaway text in the DOM.
+ (rawProvider ? rawProvider.trim().slice(0, 64) : "integration");
+
+ const label = isStreaming
+ ? `Connecting ${providerName}…`
+ : isError
+ ? `Failed to connect ${providerName}`
+ : output
+ ? `Connect ${output.setup_info?.agent_name ?? providerName}`
+ : `Connect ${providerName}`;
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <MorphingTextAnimation
+ text={label}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {isError && errorMessage && (
+ <p className="mt-1 text-sm text-red-500">{errorMessage}</p>
+ )}
+
+ {output && (
+ <div className="mt-2">
+ {isDismissed ? (
+ <ContentMessage>Connected. Continuing…</ContentMessage>
+ ) : (
+ <SetupRequirementsCard
+ output={output}
+ credentialsLabel={`${output.setup_info?.agent_name ?? providerName} credentials`}
+ retryInstruction="I've connected my account. Please continue."
+ onComplete={() => setIsDismissed(true)}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/helpers.ts
index 6bb10751f0..0d94b80095 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/helpers.ts
@@ -35,11 +35,7 @@ export function coerceCredentialFields(rawMissingCredentials: unknown): {
if (!provider) return;
const types =
- Array.isArray(cred.types) && cred.types.length > 0
- ? cred.types
- : typeof cred.type === "string"
- ? [cred.type]
- : [];
+ Array.isArray(cred.types) && cred.types.length > 0 ? cred.types : [];
const credentialTypes = types
.map((t) => (typeof t === "string" ? t.trim() : ""))
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx
index 34aa1358a8..9c1c2a464a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx
@@ -23,12 +23,16 @@ interface Props {
/** Override the label shown above the credentials section.
* Defaults to "Credentials". */
credentialsLabel?: string;
+ /** Called after Proceed is clicked so the parent can persist the dismissed state
+ * across remounts (avoids re-enabling the Proceed button on remount). */
+ onComplete?: () => void;
}
export function SetupRequirementsCard({
output,
retryInstruction,
credentialsLabel,
+ onComplete,
}: Props) {
const { onSend } = useCopilotChatActions();
@@ -68,13 +72,17 @@ export function SetupRequirementsCard({
return v !== undefined && v !== null && v !== "";
});
+ if (hasSent) {
+ return <ContentMessage>Connected. Continuing…</ContentMessage>;
+ }
+
const canRun =
- !hasSent &&
(!needsCredentials || isAllCredentialsComplete) &&
(!needsInputs || isAllInputsComplete);
function handleRun() {
setHasSent(true);
+ onComplete?.();
const parts: string[] = [];
if (needsCredentials) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/helpers.ts
index bacc0bac55..035f471cf0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/helpers.ts
@@ -29,11 +29,7 @@ export function coerceCredentialFields(rawMissingCredentials: unknown): {
if (!provider) return;
const types =
- Array.isArray(cred.types) && cred.types.length > 0
- ? cred.types
- : typeof cred.type === "string"
- ? [cred.type]
- : [];
+ Array.isArray(cred.types) && cred.types.length > 0 ? cred.types : [];
const credentialTypes = types
.map((t) => (typeof t === "string" ? t.trim() : ""))
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
index 60ac72304c..2e2a5d586f 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
@@ -125,9 +125,9 @@ export function useCredentialsInput({
if (hasAttemptedAutoSelect.current) return;
hasAttemptedAutoSelect.current = true;
- // Auto-select if exactly one credential matches.
- // For optional fields with multiple options, let the user choose.
- if (isOptional && savedCreds.length > 1) return;
+ // Auto-select only when there is exactly one saved credential.
+ // With multiple options the user must choose — regardless of optional/required.
+ if (savedCreds.length > 1) return;
const cred = savedCreds[0];
onSelectCredential({