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): add session-level dry_run flag to autopilot sessions (#12582)

Zamil Majdy3e25488b2d36
diff --git a/autogpt_platform/backend/backend/api/external/v1/tools.py b/autogpt_platform/backend/backend/api/external/v1/tools.py
index 7b8b327919..c4e1b26c70 100644
--- a/autogpt_platform/backend/backend/api/external/v1/tools.py
+++ b/autogpt_platform/backend/backend/api/external/v1/tools.py
@@ -72,7 +72,7 @@ class RunAgentRequest(BaseModel):
def _create_ephemeral_session(user_id: str) -> ChatSession:
"""Create an ephemeral session for stateless API requests."""
- return ChatSession.new(user_id)
+ return ChatSession.new(user_id, dry_run=False)
@tools_router.post(
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index daf52d1247..38246191ef 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -11,7 +11,7 @@ from autogpt_libs import auth
from fastapi import APIRouter, HTTPException, Query, Response, Security
from fastapi.responses import StreamingResponse
from prisma.models import UserWorkspaceFile
-from pydantic import BaseModel, Field, field_validator
+from pydantic import BaseModel, ConfigDict, Field, field_validator
from backend.copilot import service as chat_service
from backend.copilot import stream_registry
@@ -20,6 +20,7 @@ from backend.copilot.executor.utils import enqueue_cancel_task, enqueue_copilot_
from backend.copilot.model import (
ChatMessage,
ChatSession,
+ ChatSessionMetadata,
append_and_save_message,
create_chat_session,
delete_chat_session,
@@ -112,12 +113,25 @@ class StreamChatRequest(BaseModel):
) # Workspace file IDs attached to this message
+class CreateSessionRequest(BaseModel):
+ """Request model for creating a new chat session.
+
+ ``dry_run`` is a **top-level** field — do not nest it inside ``metadata``.
+ Extra/unknown fields are rejected (422) to prevent silent mis-use.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ dry_run: bool = False
+
+
class CreateSessionResponse(BaseModel):
"""Response model containing information on a newly created chat session."""
id: str
created_at: str
user_id: str | None
+ metadata: ChatSessionMetadata = ChatSessionMetadata()
class ActiveStreamInfo(BaseModel):
@@ -138,6 +152,7 @@ class SessionDetailResponse(BaseModel):
active_stream: ActiveStreamInfo | None = None # Present if stream is still active
total_prompt_tokens: int = 0
total_completion_tokens: int = 0
+ metadata: ChatSessionMetadata = ChatSessionMetadata()
class SessionSummaryResponse(BaseModel):
@@ -248,6 +263,7 @@ async def list_sessions(
)
async def create_session(
user_id: Annotated[str, Security(auth.get_user_id)],
+ request: CreateSessionRequest | None = None,
) -> CreateSessionResponse:
"""
Create a new chat session.
@@ -256,22 +272,28 @@ async def create_session(
Args:
user_id: The authenticated user ID parsed from the JWT (required).
+ request: Optional request body. When provided, ``dry_run=True``
+ forces run_block and run_agent calls to use dry-run simulation.
Returns:
CreateSessionResponse: Details of the created session.
"""
+ dry_run = request.dry_run if request else False
+
logger.info(
f"Creating session with user_id: "
f"...{user_id[-8:] if len(user_id) > 8 else '<redacted>'}"
+ f"{', dry_run=True' if dry_run else ''}"
)
- session = await create_chat_session(user_id)
+ session = await create_chat_session(user_id, dry_run=dry_run)
return CreateSessionResponse(
id=session.session_id,
created_at=session.started_at.isoformat(),
user_id=session.user_id,
+ metadata=session.metadata,
)
@@ -420,6 +442,7 @@ async def get_session(
active_stream=active_stream_info,
total_prompt_tokens=total_prompt,
total_completion_tokens=total_completion,
+ metadata=session.metadata,
)
@@ -1174,7 +1197,7 @@ async def health_check() -> dict:
)
# Create and retrieve session to verify full data layer
- session = await create_chat_session(health_check_user_id)
+ session = await create_chat_session(health_check_user_id, dry_run=False)
await get_chat_session(session.session_id, health_check_user_id)
return {
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
index 95818407d3..b710bf7c57 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -469,3 +469,60 @@ def test_suggested_prompts_empty_prompts(
assert response.status_code == 200
assert response.json() == {"themes": []}
+
+
+# ─── Create session: dry_run contract ─────────────────────────────────
+
+
+def _mock_create_chat_session(mocker: pytest_mock.MockerFixture):
+ """Mock create_chat_session to return a fake session."""
+ from backend.copilot.model import ChatSession
+
+ async def _fake_create(user_id: str, *, dry_run: bool):
+ return ChatSession.new(user_id, dry_run=dry_run)
+
+ return mocker.patch(
+ "backend.api.features.chat.routes.create_chat_session",
+ new_callable=AsyncMock,
+ side_effect=_fake_create,
+ )
+
+
+def test_create_session_dry_run_true(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ """Sending ``{"dry_run": true}`` sets metadata.dry_run to True."""
+ _mock_create_chat_session(mocker)
+
+ response = client.post("/sessions", json={"dry_run": True})
+
+ assert response.status_code == 200
+ assert response.json()["metadata"]["dry_run"] is True
+
+
+def test_create_session_dry_run_default_false(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ """Empty body defaults dry_run to False."""
+ _mock_create_chat_session(mocker)
+
+ response = client.post("/sessions")
+
+ assert response.status_code == 200
+ assert response.json()["metadata"]["dry_run"] is False
+
+
+def test_create_session_rejects_nested_metadata(
+ test_user_id: str,
+) -> None:
+ """Sending ``{"metadata": {"dry_run": true}}`` must return 422, not silently
+ default to ``dry_run=False``. This guards against the common mistake of
+ nesting dry_run inside metadata instead of providing it at the top level."""
+ response = client.post(
+ "/sessions",
+ json={"metadata": {"dry_run": True}},
+ )
+
+ assert response.status_code == 422
diff --git a/autogpt_platform/backend/backend/blocks/autopilot.py b/autogpt_platform/backend/backend/blocks/autopilot.py
index 27765f6744..d479169c94 100644
--- a/autogpt_platform/backend/backend/blocks/autopilot.py
+++ b/autogpt_platform/backend/backend/blocks/autopilot.py
@@ -146,6 +146,21 @@ class AutoPilotBlock(Block):
advanced=True,
)
+ dry_run: bool = SchemaField(
+ description=(
+ "When enabled, run_block and run_agent tool calls in this "
+ "autopilot session are forced to use dry-run simulation mode. "
+ "No real API calls, side effects, or credits are consumed "
+ "by those tools. Useful for testing agent wiring and "
+ "previewing outputs. "
+ "Only applies when creating a new session (session_id is empty). "
+ "When reusing an existing session_id, the session's original "
+ "dry_run setting is preserved."
+ ),
+ default=False,
+ advanced=True,
+ )
+
# timeout_seconds removed: the SDK manages its own heartbeat-based
# timeouts internally; wrapping with asyncio.timeout corrupts the
# SDK's internal stream (see service.py CRITICAL comment).
@@ -232,11 +247,11 @@ class AutoPilotBlock(Block):
},
)
- async def create_session(self, user_id: str) -> str:
+ async def create_session(self, user_id: str, *, dry_run: bool) -> str:
"""Create a new chat session and return its ID (mockable for tests)."""
from backend.copilot.model import create_chat_session # avoid circular import
- session = await create_chat_session(user_id)
+ session = await create_chat_session(user_id, dry_run=dry_run)
return session.session_id
async def execute_copilot(
@@ -367,7 +382,9 @@ class AutoPilotBlock(Block):
# even if the downstream stream fails (avoids orphaned sessions).
sid = input_data.session_id
if not sid:
- sid = await self.create_session(execution_context.user_id)
+ sid = await self.create_session(
+ execution_context.user_id, dry_run=input_data.dry_run
+ )
# NOTE: No asyncio.timeout() here — the SDK manages its own
# heartbeat-based timeouts internally. Wrapping with asyncio.timeout
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.py
index e2eb67b207..379686b64d 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py
@@ -18,6 +18,7 @@ import orjson
from langfuse import propagate_attributes
from openai.types.chat import ChatCompletionMessageParam, ChatCompletionToolParam
+from backend.copilot.context import set_execution_context
from backend.copilot.model import (
ChatMessage,
ChatSession,
@@ -457,6 +458,9 @@ async def stream_chat_completion_baseline(
tools = get_available_tools()
+ # Propagate execution context so tool handlers can read session-level flags.
+ set_execution_context(user_id, session)
+
yield StreamStart(messageId=message_id, sessionId=session_id)
# Propagate user/session context to Langfuse so all LLM calls within
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service_test.py b/autogpt_platform/backend/backend/copilot/baseline/service_test.py
index a68be3f909..46cc0a40cc 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service_test.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service_test.py
@@ -31,7 +31,7 @@ async def test_baseline_multi_turn(setup_test_user, test_user_id):
if not api_key:
return pytest.skip("OPEN_ROUTER_API_KEY is not set, skipping test")
- session = await create_chat_session(test_user_id)
+ session = await create_chat_session(test_user_id, dry_run=False)
session = await upsert_chat_session(session)
# --- Turn 1: send a message with a unique keyword ---
diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.py
index 74a030888d..6bdd22094a 100644
--- a/autogpt_platform/backend/backend/copilot/db.py
+++ b/autogpt_platform/backend/backend/copilot/db.py
@@ -18,7 +18,13 @@ from prisma.types import (
from backend.data import db
from backend.util.json import SafeJson, sanitize_string
-from .model import ChatMessage, ChatSession, ChatSessionInfo, invalidate_session_cache
+from .model import (
+ ChatMessage,
+ ChatSession,
+ ChatSessionInfo,
+ ChatSessionMetadata,
+ invalidate_session_cache,
+)
logger = logging.getLogger(__name__)
@@ -35,6 +41,7 @@ async def get_chat_session(session_id: str) -> ChatSession | None:
async def create_chat_session(
session_id: str,
user_id: str,
+ metadata: ChatSessionMetadata | None = None,
) -> ChatSessionInfo:
"""Create a new chat session in the database."""
data = ChatSessionCreateInput(
@@ -43,6 +50,7 @@ async def create_chat_session(
credentials=SafeJson({}),
successfulAgentRuns=SafeJson({}),
successfulAgentSchedules=SafeJson({}),
+ metadata=SafeJson((metadata or ChatSessionMetadata()).model_dump()),
)
prisma_session = await PrismaChatSession.prisma().create(data=data)
return ChatSessionInfo.from_db(prisma_session)
@@ -57,7 +65,12 @@ async def update_chat_session(
total_completion_tokens: int | None = None,
title: str | None = None,
) -> ChatSession | None:
- """Update a chat session's metadata."""
+ """Update a chat session's mutable fields.
+
+ Note: ``metadata`` (which includes ``dry_run``) is intentionally omitted —
+ it is set once at creation time and treated as immutable for the lifetime
+ of the session.
+ """
data: ChatSessionUpdateInput = {"updatedAt": datetime.now(UTC)}
if credentials is not None:
diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.py
index c96b027e20..9afc380d68 100644
--- a/autogpt_platform/backend/backend/copilot/model.py
+++ b/autogpt_platform/backend/backend/copilot/model.py
@@ -46,6 +46,16 @@ def _get_session_cache_key(session_id: str) -> str:
# ===================== Chat data models ===================== #
+class ChatSessionMetadata(BaseModel):
+ """Typed metadata stored in the ``metadata`` JSON column of ChatSession.
+
+ Add new session-level flags here instead of adding DB columns —
+ no migration required for new fields as long as a default is provided.
+ """
+
+ dry_run: bool = False
+
+
class ChatMessage(BaseModel):
role: str
content: str | None = None
@@ -90,6 +100,12 @@ class ChatSessionInfo(BaseModel):
updated_at: datetime
successful_agent_runs: dict[str, int] = {}
successful_agent_schedules: dict[str, int] = {}
+ metadata: ChatSessionMetadata = ChatSessionMetadata()
+
+ @property
+ def dry_run(self) -> bool:
+ """Convenience accessor for ``metadata.dry_run``."""
+ return self.metadata.dry_run
@classmethod
def from_db(cls, prisma_session: PrismaChatSession) -> Self:
@@ -103,6 +119,10 @@ class ChatSessionInfo(BaseModel):
prisma_session.successfulAgentSchedules, default={}
)
+ # Parse typed metadata from the JSON column.
+ raw_metadata = _parse_json_field(prisma_session.metadata, default={})
+ metadata = ChatSessionMetadata.model_validate(raw_metadata)
+
# Calculate usage from token counts.
# NOTE: Per-turn cache_read_tokens / cache_creation_tokens breakdown
# is lost after persistence — the DB only stores aggregate prompt and
@@ -128,6 +148,7 @@ class ChatSessionInfo(BaseModel):
updated_at=prisma_session.updatedAt,
successful_agent_runs=successful_agent_runs,
successful_agent_schedules=successful_agent_schedules,
+ metadata=metadata,
)
@@ -135,7 +156,7 @@ class ChatSession(ChatSessionInfo):
messages: list[ChatMessage]
@classmethod
- def new(cls, user_id: str) -> Self:
+ def new(cls, user_id: str, *, dry_run: bool) -> Self:
return cls(
session_id=str(uuid.uuid4()),
user_id=user_id,
@@ -145,6 +166,7 @@ class ChatSession(ChatSessionInfo):
credentials={},
started_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
+ metadata=ChatSessionMetadata(dry_run=dry_run),
)
@classmethod
@@ -532,6 +554,7 @@ async def _save_session_to_db(
await db.create_chat_session(
session_id=session.session_id,
user_id=session.user_id,
+ metadata=session.metadata,
)
existing_message_count = 0
@@ -609,21 +632,27 @@ async def append_and_save_message(session_id: str, message: ChatMessage) -> Chat
return session
-async def create_chat_session(user_id: str) -> ChatSession:
+async def create_chat_session(user_id: str, *, dry_run: bool) -> ChatSession:
"""Create a new chat session and persist it.
+ Args:
+ user_id: The authenticated user ID.
+ dry_run: When True, run_block and run_agent tool calls in this
+ session are forced to use dry-run simulation mode.
+
Raises:
DatabaseError: If the database write fails. We fail fast to ensure
callers never receive a non-persisted session that only exists
in cache (which would be lost when the cache expires).
"""
- session = ChatSession.new(user_id)
+ session = ChatSession.new(user_id, dry_run=dry_run)
# Create in database first - fail fast if this fails
try:
await chat_db().create_chat_session(
session_id=session.session_id,
user_id=user_id,
+ metadata=session.metadata,
)
except Exception as e:
logger.error(f"Failed to create session {session.session_id} in database: {e}")
diff --git a/autogpt_platform/backend/backend/copilot/model_test.py b/autogpt_platform/backend/backend/copilot/model_test.py
index edd39351fa..6e748d9c6d 100644
--- a/autogpt_platform/backend/backend/copilot/model_test.py
+++ b/autogpt_platform/backend/backend/copilot/model_test.py
@@ -46,7 +46,7 @@ messages = [
@pytest.mark.asyncio(loop_scope="session")
async def test_chatsession_serialization_deserialization():
- s = ChatSession.new(user_id="abc123")
+ s = ChatSession.new(user_id="abc123", dry_run=False)
s.messages = messages
s.usage = [Usage(prompt_tokens=100, completion_tokens=200, total_tokens=300)]
serialized = s.model_dump_json()
@@ -57,7 +57,7 @@ async def test_chatsession_serialization_deserialization():
@pytest.mark.asyncio(loop_scope="session")
async def test_chatsession_redis_storage(setup_test_user, test_user_id):
- s = ChatSession.new(user_id=test_user_id)
+ s = ChatSession.new(user_id=test_user_id, dry_run=False)
s.messages = messages
s = await upsert_chat_session(s)
@@ -75,7 +75,7 @@ async def test_chatsession_redis_storage_user_id_mismatch(
setup_test_user, test_user_id
):
- s = ChatSession.new(user_id=test_user_id)
+ s = ChatSession.new(user_id=test_user_id, dry_run=False)
s.messages = messages
s = await upsert_chat_session(s)
@@ -90,7 +90,7 @@ async def test_chatsession_db_storage(setup_test_user, test_user_id):
from backend.data.redis_client import get_redis_async
# Create session with messages including assistant message
- s = ChatSession.new(user_id=test_user_id)
+ s = ChatSession.new(user_id=test_user_id, dry_run=False)
s.messages = messages # Contains user, assistant, and tool messages
assert s.session_id is not None, "Session id is not set"
# Upsert to save to both cache and DB
@@ -241,7 +241,7 @@ _raw_tc2 = {
def test_add_tool_call_appends_to_existing_assistant():
"""When the last assistant is from the current turn, tool_call is added to it."""
- session = ChatSession.new(user_id="u")
+ session = ChatSession.new(user_id="u", dry_run=False)
session.messages = [
ChatMessage(role="user", content="hi"),
ChatMessage(role="assistant", content="working on it"),
@@ -254,7 +254,7 @@ def test_add_tool_call_appends_to_existing_assistant():
def test_add_tool_call_creates_assistant_when_none_exists():
"""When there's no current-turn assistant, a new one is created."""
- session = ChatSession.new(user_id="u")
+ session = ChatSession.new(user_id="u", dry_run=False)
session.messages = [
ChatMessage(role="user", content="hi"),
]
@@ -267,7 +267,7 @@ def test_add_tool_call_creates_assistant_when_none_exists():
def test_add_tool_call_does_not_cross_user_boundary():
"""A user message acts as a boundary — previous assistant is not modified."""
- session = ChatSession.new(user_id="u")
+ session = ChatSession.new(user_id="u", dry_run=False)
session.messages = [
ChatMessage(role="assistant", content="old turn"),
ChatMessage(role="user", content="new message"),
@@ -282,7 +282,7 @@ def test_add_tool_call_does_not_cross_user_boundary():
def test_add_tool_call_multiple_times():
"""Multiple long-running tool calls accumulate on the same assistant."""
- session = ChatSession.new(user_id="u")
+ session = ChatSession.new(user_id="u", dry_run=False)
session.messages = [
ChatMessage(role="user", content="hi"),
ChatMessage(role="assistant", content="doing stuff"),
@@ -300,7 +300,7 @@ def test_add_tool_call_multiple_times():
def test_to_openai_messages_merges_split_assistants():
"""End-to-end: session with split assistants produces valid OpenAI messages."""
- session = ChatSession.new(user_id="u")
+ session = ChatSession.new(user_id="u", dry_run=False)
session.messages = [
ChatMessage(role="user", content="build agent"),
ChatMessage(role="assistant", content="Let me build that"),
@@ -352,7 +352,7 @@ async def test_concurrent_saves_collision_detection(setup_test_user, test_user_i
import asyncio
# Create a session with initial messages
- session = ChatSession.new(user_id=test_user_id)
+ session = ChatSession.new(user_id=test_user_id, dry_run=False)
for i in range(3):
session.messages.append(
ChatMessage(
diff --git a/autogpt_platform/backend/backend/copilot/sdk/compaction_test.py b/autogpt_platform/backend/backend/copilot/sdk/compaction_test.py
index 7c7d056d70..04d842c653 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/compaction_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/compaction_test.py
@@ -25,7 +25,7 @@ from backend.copilot.sdk.compaction import (
def _make_session() -> ChatSession:
- return ChatSession.new(user_id="test-user")
+ return ChatSession.new(user_id="test-user", dry_run=False)
# ---------------------------------------------------------------------------
diff --git a/autogpt_platform/backend/backend/copilot/sdk/e2e_compaction_test.py b/autogpt_platform/backend/backend/copilot/sdk/e2e_compaction_test.py
index 11d0f8a1f5..0fad2aef77 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/e2e_compaction_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/e2e_compaction_test.py
@@ -275,7 +275,7 @@ class TestCompactionE2E:
# --- Step 7: CompactionTracker receives PreCompact hook ---
tracker = CompactionTracker()
- session = ChatSession.new(user_id="test-user")
+ session = ChatSession.new(user_id="test-user", dry_run=False)
tracker.on_compact(str(session_file))
# --- Step 8: Next SDK message arrives → emit_start ---
@@ -376,7 +376,7 @@ class TestCompactionE2E:
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(config_dir))
tracker = CompactionTracker()
- session = ChatSession.new(user_id="test")
+ session = ChatSession.new(user_id="test", dry_run=False)
builder = TranscriptBuilder()
# --- First query with compaction ---
diff --git a/autogpt_platform/backend/backend/copilot/service_test.py b/autogpt_platform/backend/backend/copilot/service_test.py
index 10d29f3fbf..d65b356f4a 100644
--- a/autogpt_platform/backend/backend/copilot/service_test.py
+++ b/autogpt_platform/backend/backend/copilot/service_test.py
@@ -30,7 +30,7 @@ async def test_sdk_resume_multi_turn(setup_test_user, test_user_id):
if not cfg.claude_agent_use_resume:
return pytest.skip("CLAUDE_AGENT_USE_RESUME is not enabled, skipping test")
- session = await create_chat_session(test_user_id)
+ session = await create_chat_session(test_user_id, dry_run=False)
session = await upsert_chat_session(session)
# --- Turn 1: send a message with a unique keyword ---
diff --git a/autogpt_platform/backend/backend/copilot/tools/add_understanding.py b/autogpt_platform/backend/backend/copilot/tools/add_understanding.py
index a5ef7caabf..1a5c6241d6 100644
--- a/autogpt_platform/backend/backend/copilot/tools/add_understanding.py
+++ b/autogpt_platform/backend/backend/copilot/tools/add_understanding.py
@@ -68,6 +68,9 @@ class AddUnderstandingTool(BaseTool):
Each call merges new data with existing understanding:
- String fields are overwritten if provided
- List fields are appended (with deduplication)
+
+ Note: This tool accepts **kwargs because its parameters are derived
+ dynamically from the BusinessUnderstandingInput model schema.
"""
session_id = session.session_id
@@ -77,23 +80,21 @@ class AddUnderstandingTool(BaseTool):
session_id=session_id,
)
+ # Build input model from kwargs (only include fields defined in the model)
+ valid_fields = set(BusinessUnderstandingInput.model_fields.keys())
+ filtered = {k: v for k, v in kwargs.items() if k in valid_fields}
+
# Check if any data was provided
- if not any(v is not None for v in kwargs.values()):
+ if not any(v is not None for v in filtered.values()):
return ErrorResponse(
message="Please provide at least one field to update.",
session_id=session_id,
)
- # Build input model from kwargs (only include fields defined in the model)
- valid_fields = set(BusinessUnderstandingInput.model_fields.keys())
- input_data = BusinessUnderstandingInput(
- **{k: v for k, v in kwargs.items() if k in valid_fields}
- )
+ input_data = BusinessUnderstandingInput(**filtered)
# Track which fields were updated
- updated_fields = [
- k for k, v in kwargs.items() if k in valid_fields and v is not None
- ]
+ updated_fields = [k for k, v in filtered.items() if v is not None]
# Upsert with merge
understanding = await understanding_db().upsert_business_understanding(
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_browser.py b/autogpt_platform/backend/backend/copilot/tools/agent_browser.py
index 5bc39c724f..8951843484 100644
--- a/autogpt_platform/backend/backend/copilot/tools/agent_browser.py
+++ b/autogpt_platform/backend/backend/copilot/tools/agent_browser.py
@@ -180,12 +180,14 @@ async def _save_browser_state(
"""
try:
# Gather state in parallel
- (rc_url, url_out, _), (rc_ck, ck_out, _), (rc_ls, ls_out, _) = (
- await asyncio.gather(
- _run(session_name, "get", "url", timeout=10),
- _run(session_name, "cookies", "get", "--json", timeout=10),
- _run(session_name, "storage", "local", "--json", timeout=10),
- )
+ (
+ (rc_url, url_out, _),
+ (rc_ck, ck_out, _),
+ (rc_ls, ls_out, _),
+ ) = await asyncio.gather(
+ _run(session_name, "get", "url", timeout=10),
+ _run(session_name, "cookies", "get", "--json", timeout=10),
+ _run(session_name, "storage", "local", "--json", timeout=10),
)
state = {
@@ -448,6 +450,8 @@ class BrowserNavigateTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ url: str = "",
+ wait_for: str = "networkidle",
**kwargs: Any,
) -> ToolResponseBase:
"""Navigate to *url*, wait for the page to settle, and return a snapshot.
@@ -456,8 +460,8 @@ class BrowserNavigateTool(BaseTool):
Note: for slow SPAs that never fully idle, the snapshot may reflect a
partially-loaded state (the wait is best-effort).
"""
- url: str = (kwargs.get("url") or "").strip()
- wait_for: str = kwargs.get("wait_for") or "networkidle"
+ url = url.strip()
+ wait_for = wait_for or "networkidle"
session_name = session.session_id
if not url:
@@ -612,6 +616,10 @@ class BrowserActTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ action: str = "",
+ target: str = "",
+ value: str = "",
+ direction: str = "down",
**kwargs: Any,
) -> ToolResponseBase:
"""Perform a browser action and return an updated page snapshot.
@@ -620,10 +628,10 @@ class BrowserActTool(BaseTool):
``agent-browser``, waits for the page to settle, and returns the
accessibility-tree snapshot so the LLM can plan the next step.
"""
- action: str = (kwargs.get("action") or "").strip()
- target: str = (kwargs.get("target") or "").strip()
- value: str = (kwargs.get("value") or "").strip()
- direction: str = (kwargs.get("direction") or "down").strip()
+ action = action.strip()
+ target = target.strip()
+ value = value.strip()
+ direction = direction.strip()
session_name = session.session_id
if not action:
@@ -777,6 +785,8 @@ class BrowserScreenshotTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ annotate: bool | str = True,
+ filename: str = "screenshot.png",
**kwargs: Any,
) -> ToolResponseBase:
"""Capture a PNG screenshot and upload it to the workspace.
@@ -786,12 +796,12 @@ class BrowserScreenshotTool(BaseTool):
Returns a :class:`BrowserScreenshotResponse` with the workspace
``file_id`` the LLM should pass to ``read_workspace_file``.
"""
- raw_annotate = kwargs.get("annotate", True)
+ raw_annotate = annotate
if isinstance(raw_annotate, str):
annotate = raw_annotate.strip().lower() in {"1", "true", "yes", "on"}
else:
annotate = bool(raw_annotate)
- filename: str = (kwargs.get("filename") or "screenshot.png").strip()
+ filename = filename.strip()
session_name = session.session_id
# Restore browser state from cloud if this is a different pod
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_output.py b/autogpt_platform/backend/backend/copilot/tools/agent_output.py
index 88033052fe..f0aedb9fb3 100644
--- a/autogpt_platform/backend/backend/copilot/tools/agent_output.py
+++ b/autogpt_platform/backend/backend/copilot/tools/agent_output.py
@@ -411,7 +411,12 @@ class AgentOutputTool(BaseTool):
session: ChatSession,
**kwargs,
) -> ToolResponseBase:
- """Execute the agent_output tool."""
+ """Execute the agent_output tool.
+
+ Note: This tool accepts **kwargs and delegates to AgentOutputInput
+ for validation because the parameter set has cross-field validators
+ defined in the Pydantic model.
+ """
session_id = session.session_id
# Parse and validate input
diff --git a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py b/autogpt_platform/backend/backend/copilot/tools/bash_exec.py
index 3f4c59a8bf..be0471ac98 100644
--- a/autogpt_platform/backend/backend/copilot/tools/bash_exec.py
+++ b/autogpt_platform/backend/backend/copilot/tools/bash_exec.py
@@ -76,6 +76,8 @@ class BashExecTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ command: str = "",
+ timeout: int = 30,
**kwargs: Any,
) -> ToolResponseBase:
"""Run a bash command on E2B (if available) or in a bubblewrap sandbox.
@@ -88,8 +90,8 @@ class BashExecTool(BaseTool):
"""
session_id = session.session_id if session else None
- command: str = (kwargs.get("command") or "").strip()
- timeout: int = int(kwargs.get("timeout", 30))
+ command = command.strip()
+ timeout = int(timeout)
if not command:
return ErrorResponse(
diff --git a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py b/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
index 88f68b7eee..6ebef104bc 100644
--- a/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
+++ b/autogpt_platform/backend/backend/copilot/tools/connect_integration.py
@@ -115,6 +115,9 @@ class ConnectIntegrationTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ provider: str = "",
+ reason: str = "",
+ scopes: list[str] | None = None,
**kwargs: Any,
) -> ToolResponseBase:
"""Build and return a :class:`SetupRequirementsResponse` for the requested provider.
@@ -128,12 +131,10 @@ class ConnectIntegrationTool(BaseTool):
"""
_ = 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
+ provider = (provider or "").strip().lower()
+ reason = (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()
+ str(s).strip() for s in (scopes or []) if str(s).strip()
]
entry = SUPPORTED_PROVIDERS.get(provider)
@@ -141,8 +142,7 @@ class ConnectIntegrationTool(BaseTool):
supported = ", ".join(f"'{p}'" for p in SUPPORTED_PROVIDERS)
return ErrorResponse(
message=(
- f"Unknown provider '{provider}'. "
- f"Supported providers: {supported}."
+ f"Unknown provider '{provider}'. Supported providers: {supported}."
),
error="unknown_provider",
session_id=session_id,
@@ -153,11 +153,11 @@ class ConnectIntegrationTool(BaseTool):
# Merge agent-requested scopes with provider defaults (deduplicated, order preserved).
default_scopes: list[str] = entry["default_scopes"]
seen: set[str] = set()
- scopes: list[str] = []
+ merged_scopes: list[str] = []
for s in default_scopes + extra_scopes:
if s not in seen:
seen.add(s)
- scopes.append(s)
+ merged_scopes.append(s)
field_key = f"{provider}_credentials"
message_parts = [
@@ -171,7 +171,7 @@ class ConnectIntegrationTool(BaseTool):
"title": f"{display_name} Credentials",
"provider": provider,
"types": supported_types,
- "scopes": scopes,
+ "scopes": merged_scopes,
}
missing_credentials: dict[str, _CredentialEntry] = {field_key: credential_entry}
diff --git a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
index f459bf38e1..2daacaa2e1 100644
--- a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
@@ -53,11 +53,10 @@ class ContinueRunBlockTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ review_id: str = "",
**kwargs,
) -> ToolResponseBase:
- review_id = (
- kwargs.get("review_id", "").strip() if kwargs.get("review_id") else ""
- )
+ review_id = review_id.strip() if review_id else ""
session_id = session.session_id
if not review_id:
diff --git a/autogpt_platform/backend/backend/copilot/tools/create_agent.py b/autogpt_platform/backend/backend/copilot/tools/create_agent.py
index decdf9ef1f..5c00f555c8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/create_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/create_agent.py
@@ -62,9 +62,12 @@ class CreateAgentTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ agent_json: dict[str, Any] | None = None,
+ save: bool = True,
+ library_agent_ids: list[str] | None = None,
+ folder_id: str | None = None,
**kwargs,
) -> ToolResponseBase:
- agent_json: dict[str, Any] | None = kwargs.get("agent_json")
session_id = session.session_id if session else None
if not agent_json:
@@ -77,9 +80,8 @@ class CreateAgentTool(BaseTool):
session_id=session_id,
)
- save = kwargs.get("save", True)
- library_agent_ids = kwargs.get("library_agent_ids", [])
- folder_id: str | None = kwargs.get("folder_id")
+ if library_agent_ids is None:
+ library_agent_ids = []
nodes = agent_json.get("nodes", [])
if not nodes:
diff --git a/autogpt_platform/backend/backend/copilot/tools/customize_agent.py b/autogpt_platform/backend/backend/copilot/tools/customize_agent.py
index e869696d6e..d4c7a36930 100644
--- a/autogpt_platform/backend/backend/copilot/tools/customize_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/customize_agent.py
@@ -61,9 +61,12 @@ class CustomizeAgentTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ agent_json: dict[str, Any] | None = None,
+ save: bool = True,
+ library_agent_ids: list[str] | None = None,
+ folder_id: str | None = None,
**kwargs,
) -> ToolResponseBase:
- agent_json: dict[str, Any] | None = kwargs.get("agent_json")
session_id = session.session_id if session else None
if not agent_json:
@@ -75,9 +78,8 @@ class CustomizeAgentTool(BaseTool):
session_id=session_id,
)
- save = kwargs.get("save", True)
- library_agent_ids = kwargs.get("library_agent_ids", [])
- folder_id: str | None = kwargs.get("folder_id")
+ if library_agent_ids is None:
+ library_agent_ids = []
nodes = agent_json.get("nodes", [])
if not nodes:
diff --git a/autogpt_platform/backend/backend/copilot/tools/edit_agent.py b/autogpt_platform/backend/backend/copilot/tools/edit_agent.py
index 0ad2d10606..59081b1527 100644
--- a/autogpt_platform/backend/backend/copilot/tools/edit_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/edit_agent.py
@@ -62,10 +62,15 @@ class EditAgentTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ agent_id: str = "",
+ agent_json: dict[str, Any] | None = None,
+ save: bool = True,
+ library_agent_ids: list[str] | None = None,
**kwargs,
) -> ToolResponseBase:
- agent_id = kwargs.get("agent_id", "").strip()
- agent_json: dict[str, Any] | None = kwargs.get("agent_json")
+ agent_id = agent_id.strip()
+ if library_agent_ids is None:
+ library_agent_ids = []
session_id = session.session_id if session else None
if not agent_id:
@@ -84,9 +89,6 @@ class EditAgentTool(BaseTool):
session_id=session_id,
)
- save = kwargs.get("save", True)
- library_agent_ids = kwargs.get("library_agent_ids", [])
-
nodes = agent_json.get("nodes", [])
if not nodes:
return ErrorResponse(
diff --git a/autogpt_platform/backend/backend/copilot/tools/feature_requests.py b/autogpt_platform/backend/backend/copilot/tools/feature_requests.py
index d296cea110..b2d128c690 100644
--- a/autogpt_platform/backend/backend/copilot/tools/feature_requests.py
+++ b/autogpt_platform/backend/backend/copilot/tools/feature_requests.py
@@ -157,9 +157,10 @@ class SearchFeatureRequestsTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ query: str = "",
**kwargs,
) -> ToolResponseBase:
- query = kwargs.get("query", "").strip()
+ query = (query or "").strip()
session_id = session.session_id if session else None
if not query:
@@ -288,11 +289,13 @@ class CreateFeatureRequestTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ title: str = "",
+ description: str = "",
+ existing_issue_id: str | None = None,
**kwargs,
) -> ToolResponseBase:
- title = kwargs.get("title", "").strip()
- description = kwargs.get("description", "").strip()
- existing_issue_id = kwargs.get("existing_issue_id")
+ title = (title or "").strip()
+ description = (description or "").strip()
session_id = session.session_id if session else None
if not title or not description:
diff --git a/autogpt_platform/backend/backend/copilot/tools/find_agent.py b/autogpt_platform/backend/backend/copilot/tools/find_agent.py
index a3cd3155d8..a7747bcc25 100644
--- a/autogpt_platform/backend/backend/copilot/tools/find_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/find_agent.py
@@ -34,11 +34,15 @@ class FindAgentTool(BaseTool):
}
async def _execute(
- self, user_id: str | None, session: ChatSession, **kwargs
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ query: str = "",
+ **kwargs,
) -> ToolResponseBase:
"""Search marketplace for agents matching the query."""
return await search_agents(
- query=kwargs.get("query", "").strip(),
+ query=query.strip(),
source="marketplace",
session_id=session.session_id,
user_id=user_id,
diff --git a/autogpt_platform/backend/backend/copilot/tools/find_block.py b/autogpt_platform/backend/backend/copilot/tools/find_block.py
index 5bba308a37..0cbc3ba047 100644
--- a/autogpt_platform/backend/backend/copilot/tools/find_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/find_block.py
@@ -86,6 +86,8 @@ class FindBlockTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ query: str = "",
+ include_schemas: bool = False,
**kwargs,
) -> ToolResponseBase:
"""Search for blocks matching the query.
@@ -94,14 +96,14 @@ class FindBlockTool(BaseTool):
user_id: User ID (required)
session: Chat session
query: Search query
+ include_schemas: Whether to include block schemas in results
Returns:
BlockListResponse: List of matching blocks
NoResultsResponse: No blocks found
ErrorResponse: Error message
"""
- query = kwargs.get("query", "").strip()
- include_schemas = kwargs.get("include_schemas", False)
+ query = (query or "").strip()
session_id = session.session_id
if not query:
diff --git a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py
index 724676f8c5..6b0d2ace2a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/find_library_agent.py
@@ -41,10 +41,14 @@ class FindLibraryAgentTool(BaseTool):
return True
async def _execute(
- self, user_id: str | None, session: ChatSession, **kwargs
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ query: str = "",
+ **kwargs,
) -> ToolResponseBase:
return await search_agents(
- query=(kwargs.get("query") or "").strip(),
+ query=query.strip(),
source="library",
session_id=session.session_id,
user_id=user_id,
diff --git a/autogpt_platform/backend/backend/copilot/tools/fix_agent.py b/autogpt_platform/backend/backend/copilot/tools/fix_agent.py
index 817f9b4069..81f36e8a7d 100644
--- a/autogpt_platform/backend/backend/copilot/tools/fix_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/fix_agent.py
@@ -51,9 +51,9 @@ class FixAgentGraphTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ agent_json: dict | None = None,
**kwargs,
) -> ToolResponseBase:
- agent_json = kwargs.get("agent_json")
session_id = session.session_id if session else None
if not agent_json or not isinstance(agent_json, dict):
@@ -98,8 +98,7 @@ class FixAgentGraphTool(BaseTool):
if is_valid:
return FixResultResponse(
message=(
- f"Applied {len(fixes_applied)} fix(es). "
- "Agent graph is now valid!"
+ f"Applied {len(fixes_applied)} fix(es). Agent graph is now valid!"
),
fixed_agent_json=fixed_agent,
fixes_applied=fixes_applied,
diff --git a/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide.py b/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide.py
index a2dfc86eff..2fc733ceb2 100644
--- a/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide.py
+++ b/autogpt_platform/backend/backend/copilot/tools/get_agent_building_guide.py
@@ -60,7 +60,7 @@ class GetAgentBuildingGuideTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
- **kwargs,
+ **kwargs, # no tool-specific params; accepts kwargs for forward-compat
) -> ToolResponseBase:
session_id = session.session_id if session else None
try:
diff --git a/autogpt_platform/backend/backend/copilot/tools/get_doc_page.py b/autogpt_platform/backend/backend/copilot/tools/get_doc_page.py
index 3ae7505a23..6d4a2b53bc 100644
--- a/autogpt_platform/backend/backend/copilot/tools/get_doc_page.py
+++ b/autogpt_platform/backend/backend/copilot/tools/get_doc_page.py
@@ -68,6 +68,7 @@ class GetDocPageTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ path: str = "",
**kwargs,
) -> ToolResponseBase:
"""Fetch full content of a documentation page.
@@ -81,7 +82,7 @@ class GetDocPageTool(BaseTool):
DocPageResponse: Full document content
ErrorResponse: Error message
"""
- path = kwargs.get("path", "").strip()
+ path = path.strip()
session_id = session.session_id if session else None
if not path:
diff --git a/autogpt_platform/backend/backend/copilot/tools/get_mcp_guide.py b/autogpt_platform/backend/backend/copilot/tools/get_mcp_guide.py
index 5171166acc..7afd3e808c 100644
--- a/autogpt_platform/backend/backend/copilot/tools/get_mcp_guide.py
+++ b/autogpt_platform/backend/backend/copilot/tools/get_mcp_guide.py
@@ -56,7 +56,7 @@ class GetMCPGuideTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
- **kwargs,
+ **kwargs, # no tool-specific params; accepts kwargs for forward-compat
) -> ToolResponseBase:
session_id = session.session_id if session else None
try:
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index 066f280a8f..f6597f041a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -81,7 +81,7 @@ async def execute_block(
node_exec_id: str,
matched_credentials: dict[str, CredentialsMetaInput],
sensitive_action_safe_mode: bool = False,
- dry_run: bool = False,
+ dry_run: bool,
) -> ToolResponseBase:
"""Execute a block with full context setup, credential injection, and error handling.
@@ -115,10 +115,7 @@ async def execute_block(
session_id=session_id,
)
return BlockOutputResponse(
- message=(
- f"[DRY RUN] Block '{block.name}' simulated successfully "
- "— no real execution occurred."
- ),
+ message=f"Block '{block.name}' executed successfully",
block_id=block_id,
block_name=block.name,
outputs=dict(outputs),
@@ -337,7 +334,7 @@ async def prepare_block_for_execution(
user_id: str,
session: ChatSession,
session_id: str,
- dry_run: bool = False,
+ dry_run: bool,
) -> "BlockPreparation | ToolResponseBase":
"""Validate and prepare a block for execution.
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
index 011c771f1e..f0634b0c13 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
@@ -102,6 +102,7 @@ class TestExecuteBlockCreditCharging:
session_id=_SESSION,
node_exec_id="exec-1",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(result, BlockOutputResponse)
@@ -132,6 +133,7 @@ class TestExecuteBlockCreditCharging:
session_id=_SESSION,
node_exec_id="exec-1",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(result, ErrorResponse)
@@ -158,6 +160,7 @@ class TestExecuteBlockCreditCharging:
session_id=_SESSION,
node_exec_id="exec-1",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(result, BlockOutputResponse)
@@ -194,6 +197,7 @@ class TestExecuteBlockCreditCharging:
session_id=_SESSION,
node_exec_id="exec-1",
matched_credentials={},
+ dry_run=False,
)
# Block already executed (with side effects), so output is returned
@@ -277,6 +281,7 @@ async def test_coerce_json_string_to_nested_list():
session_id=_TEST_SESSION_ID,
node_exec_id="exec-1",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
@@ -317,6 +322,7 @@ async def test_coerce_json_string_to_list():
session_id=_TEST_SESSION_ID,
node_exec_id="exec-2",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
@@ -349,6 +355,7 @@ async def test_coerce_json_string_to_dict():
session_id=_TEST_SESSION_ID,
node_exec_id="exec-3",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
@@ -382,6 +389,7 @@ async def test_no_coercion_when_type_matches():
session_id=_TEST_SESSION_ID,
node_exec_id="exec-4",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
@@ -415,6 +423,7 @@ async def test_coerce_string_to_int():
session_id=_TEST_SESSION_ID,
node_exec_id="exec-5",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
@@ -448,6 +457,7 @@ async def test_coerce_skips_none_values():
session_id=_TEST_SESSION_ID,
node_exec_id="exec-6",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
@@ -481,6 +491,7 @@ async def test_coerce_union_type_preserves_valid_member():
session_id=_TEST_SESSION_ID,
node_exec_id="exec-7",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
@@ -516,6 +527,7 @@ async def test_coerce_inner_elements_of_generic():
session_id=_TEST_SESSION_ID,
node_exec_id="exec-8",
matched_credentials={},
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
@@ -592,6 +604,7 @@ async def test_prepare_block_not_found() -> None:
user_id=_PREP_USER,
session=_make_prep_session(),
session_id=_PREP_SESSION,
+ dry_run=False,
)
assert isinstance(result, ErrorResponse)
assert "not found" in result.message
@@ -612,6 +625,7 @@ async def test_prepare_block_disabled() -> None:
user_id=_PREP_USER,
session=_make_prep_session(),
session_id=_PREP_SESSION,
+ dry_run=False,
)
assert isinstance(result, ErrorResponse)
assert "disabled" in result.message
@@ -640,6 +654,7 @@ async def test_prepare_block_unrecognized_fields() -> None:
user_id=_PREP_USER,
session=_make_prep_session(),
session_id=_PREP_SESSION,
+ dry_run=False,
)
assert isinstance(result, InputValidationErrorResponse)
assert "unknown_field" in result.unrecognized_fields
@@ -669,6 +684,7 @@ async def test_prepare_block_missing_credentials() -> None:
user_id=_PREP_USER,
session=_make_prep_session(),
session_id=_PREP_SESSION,
+ dry_run=False,
)
assert isinstance(result, SetupRequirementsResponse)
@@ -698,6 +714,7 @@ async def test_prepare_block_success_returns_preparation() -> None:
user_id=_PREP_USER,
session=_make_prep_session(),
session_id=_PREP_SESSION,
+ dry_run=False,
)
assert isinstance(result, BlockPreparation)
assert result.required_non_credential_keys == {"text"}
@@ -802,6 +819,7 @@ async def test_prepare_block_excluded_by_type() -> None:
user_id=_PREP_USER,
session=_make_prep_session(),
session_id=_PREP_SESSION,
+ dry_run=False,
)
assert isinstance(result, ErrorResponse)
assert "cannot be run directly" in result.message
@@ -824,6 +842,7 @@ async def test_prepare_block_excluded_by_id() -> None:
user_id=_PREP_USER,
session=_make_prep_session(),
session_id=_PREP_SESSION,
+ dry_run=False,
)
assert isinstance(result, ErrorResponse)
assert "cannot be run directly" in result.message
@@ -857,6 +876,7 @@ async def test_prepare_block_file_ref_expansion_error() -> None:
user_id=_PREP_USER,
session=_make_prep_session(),
session_id=_PREP_SESSION,
+ dry_run=False,
)
assert isinstance(result, ErrorResponse)
assert "file reference" in result.message.lower()
diff --git a/autogpt_platform/backend/backend/copilot/tools/http_credentials_test.py b/autogpt_platform/backend/backend/copilot/tools/http_credentials_test.py
index 8a6345d186..30254df80b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/http_credentials_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/http_credentials_test.py
@@ -866,6 +866,7 @@ class TestRunBlockToolAuthenticatedHttp:
session=session,
block_id=block.id,
input_data={"url": "https://api.example.com/data", "method": "GET"},
+ dry_run=False,
)
assert isinstance(response, SetupRequirementsResponse)
@@ -907,6 +908,7 @@ class TestRunBlockToolAuthenticatedHttp:
session=session,
block_id=block.id,
input_data={},
+ dry_run=False,
)
assert isinstance(response, BlockDetailsResponse)
diff --git a/autogpt_platform/backend/backend/copilot/tools/manage_folders.py b/autogpt_platform/backend/backend/copilot/tools/manage_folders.py
index 16f97e0001..0a30093e2c 100644
--- a/autogpt_platform/backend/backend/copilot/tools/manage_folders.py
+++ b/autogpt_platform/backend/backend/copilot/tools/manage_folders.py
@@ -120,14 +120,18 @@ class CreateFolderTool(BaseTool):
}
async def _execute(
- self, user_id: str | None, session: ChatSession, **kwargs
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ name: str = "",
+ parent_id: str | None = None,
+ icon: str | None = None,
+ color: str | None = None,
+ **kwargs,
) -> ToolResponseBase:
"""Create a folder with the given name and optional parent/icon/color."""
assert user_id is not None # guaranteed by requires_auth
- name = (kwargs.get("name") or "").strip()
- parent_id = kwargs.get("parent_id")
- icon = kwargs.get("icon")
- color = kwargs.get("color")
+ name = (name or "").strip()
session_id = session.session_id if session else None
if not name:
@@ -196,12 +200,15 @@ class ListFoldersTool(BaseTool):
}
async def _execute(
- self, user_id: str | None, session: ChatSession, **kwargs
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ parent_id: str | None = None,
+ include_agents: bool = False,
+ **kwargs,
) -> ToolResponseBase:
"""List folders as a flat list (by parent) or full tree."""
assert user_id is not None # guaranteed by requires_auth
- parent_id = kwargs.get("parent_id")
- include_agents = kwargs.get("include_agents", False)
session_id = session.session_id if session else None
try:
@@ -293,14 +300,18 @@ class UpdateFolderTool(BaseTool):
}
async def _execute(
- self, user_id: str | None, session: ChatSession, **kwargs
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ folder_id: str = "",
+ name: str | None = None,
+ icon: str | None = None,
+ color: str | None = None,
+ **kwargs,
) -> ToolResponseBase:
"""Update a folder's name, icon, or color."""
assert user_id is not None # guaranteed by requires_auth
- folder_id = (kwargs.get("folder_id") or "").strip()
- name = kwargs.get("name")
- icon = kwargs.get("icon")
- color = kwargs.get("color")
+ folder_id = (folder_id or "").strip()
session_id = session.session_id if session else None
if not folder_id:
@@ -365,12 +376,16 @@ class MoveFolderTool(BaseTool):
}
async def _execute(
- self, user_id: str | None, session: ChatSession, **kwargs
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ folder_id: str = "",
+ target_parent_id: str | None = None,
+ **kwargs,
) -> ToolResponseBase:
"""Move a folder to a new parent or to root level."""
assert user_id is not None # guaranteed by requires_auth
- folder_id = (kwargs.get("folder_id") or "").strip()
- target_parent_id = kwargs.get("target_parent_id")
+ folder_id = (folder_id or "").strip()
session_id = session.session_id if session else None
if not folder_id:
@@ -431,11 +446,15 @@ class DeleteFolderTool(BaseTool):
}
async def _execute(
- self, user_id: str | None, session: ChatSession, **kwargs
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ folder_id: str = "",
+ **kwargs,
) -> ToolResponseBase:
"""Soft-delete a folder; agents inside are moved to root level."""
assert user_id is not None # guaranteed by requires_auth
- folder_id = (kwargs.get("folder_id") or "").strip()
+ folder_id = (folder_id or "").strip()
session_id = session.session_id if session else None
if not folder_id:
@@ -499,12 +518,17 @@ class MoveAgentsToFolderTool(BaseTool):
}
async def _execute(
- self, user_id: str | None, session: ChatSession, **kwargs
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ agent_ids: list[str] | None = None,
+ folder_id: str | None = None,
+ **kwargs,
) -> ToolResponseBase:
"""Move one or more agents to a folder or to root level."""
assert user_id is not None # guaranteed by requires_auth
- agent_ids = kwargs.get("agent_ids", [])
- folder_id = kwargs.get("folder_id")
+ if agent_ids is None:
+ agent_ids = []
session_id = session.session_id if session else None
if not agent_ids:
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.py
index 479bb4e36d..d07e0c4d51 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py
@@ -71,7 +71,7 @@ class RunAgentInput(BaseModel):
cron: str = ""
timezone: str = "UTC"
wait_for_result: int = Field(default=0, ge=0, le=300)
- dry_run: bool = False
+ dry_run: bool
@field_validator(
"username_agent_slug",
@@ -153,14 +153,10 @@ class RunAgentTool(BaseTool):
},
"dry_run": {
"type": "boolean",
- "description": (
- "When true, simulates the entire agent execution using an LLM "
- "for each block — no real API calls, no credentials needed, "
- "no credits charged. Useful for testing agent wiring end-to-end."
- ),
+ "description": "Execute in preview mode.",
},
},
- "required": [],
+ "required": ["dry_run"],
}
@property
@@ -174,8 +170,16 @@ class RunAgentTool(BaseTool):
session: ChatSession,
**kwargs,
) -> ToolResponseBase:
- """Execute the tool with automatic state detection."""
+ """Execute the tool with automatic state detection.
+
+ Note: This tool accepts **kwargs and delegates to RunAgentInput for
+ validation because the parameter set is complex with cross-field
+ validators defined in the Pydantic model.
+ """
params = RunAgentInput(**kwargs)
+ # Session-level dry_run forces all tool calls to use dry-run mode.
+ if session.dry_run:
+ params.dry_run = True
session_id = session.session_id
# Validate at least one identifier is provided
@@ -201,6 +205,18 @@ class RunAgentTool(BaseTool):
# Determine if this is a schedule request
is_schedule = bool(params.schedule_name or params.cron)
+ # Session-level dry-run blocks scheduling — schedules create real
+ # side effects that cannot be simulated.
+ if params.dry_run and is_schedule:
+ return ErrorResponse(
+ message=(
+ "Scheduling is disabled in dry-run mode because it creates "
+ "real side effects. Remove cron/schedule_name to simulate "
+ "a run, or disable dry-run to create a real schedule."
+ ),
+ session_id=session_id,
+ )
+
try:
# Step 1: Fetch agent details
graph: GraphModel | None = None
@@ -458,8 +474,8 @@ class RunAgentTool(BaseTool):
graph: GraphModel,
graph_credentials: dict[str, CredentialsMetaInput],
inputs: dict[str, Any],
+ dry_run: bool,
wait_for_result: int = 0,
- dry_run: bool = False,
) -> ToolResponseBase:
"""Execute an agent immediately, optionally waiting for completion."""
session_id = session.session_id
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
index d5da394fa6..efb1e32ab9 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
@@ -53,6 +53,7 @@ async def test_run_agent(setup_test_data):
tool_call_id=str(uuid.uuid4()),
username_agent_slug=agent_marketplace_id,
inputs={"test_input": "Hello World"},
+ dry_run=False,
session=session,
)
@@ -93,6 +94,7 @@ async def test_run_agent_missing_inputs(setup_test_data):
tool_call_id=str(uuid.uuid4()),
username_agent_slug=agent_marketplace_id,
inputs={}, # Missing required input
+ dry_run=False,
session=session,
)
@@ -125,6 +127,7 @@ async def test_run_agent_invalid_agent_id(setup_test_data):
tool_call_id=str(uuid.uuid4()),
username_agent_slug="invalid/agent-id",
inputs={"test_input": "Hello World"},
+ dry_run=False,
session=session,
)
@@ -165,6 +168,7 @@ async def test_run_agent_with_llm_credentials(setup_llm_test_data):
tool_call_id=str(uuid.uuid4()),
username_agent_slug=agent_marketplace_id,
inputs={"user_prompt": "What is 2+2?"},
+ dry_run=False,
session=session,
)
@@ -203,6 +207,7 @@ async def test_run_agent_shows_available_inputs_when_none_provided(setup_test_da
username_agent_slug=agent_marketplace_id,
inputs={},
use_defaults=False,
+ dry_run=False,
session=session,
)
@@ -238,6 +243,7 @@ async def test_run_agent_with_use_defaults(setup_test_data):
username_agent_slug=agent_marketplace_id,
inputs={},
use_defaults=True,
+ dry_run=False,
session=session,
)
@@ -268,6 +274,7 @@ async def test_run_agent_missing_credentials(setup_firecrawl_test_data):
tool_call_id=str(uuid.uuid4()),
username_agent_slug=agent_marketplace_id,
inputs={"url": "https://example.com"},
+ dry_run=False,
session=session,
)
@@ -300,6 +307,7 @@ async def test_run_agent_invalid_slug_format(setup_test_data):
tool_call_id=str(uuid.uuid4()),
username_agent_slug="no-slash-here",
inputs={},
+ dry_run=False,
session=session,
)
@@ -327,6 +335,7 @@ async def test_run_agent_unauthenticated():
tool_call_id=str(uuid.uuid4()),
username_agent_slug="test/test-agent",
inputs={},
+ dry_run=False,
session=session,
)
@@ -359,6 +368,7 @@ async def test_run_agent_schedule_without_cron(setup_test_data):
inputs={"test_input": "test"},
schedule_name="My Schedule",
cron="", # Empty cron
+ dry_run=False,
session=session,
)
@@ -391,6 +401,7 @@ async def test_run_agent_schedule_without_name(setup_test_data):
inputs={"test_input": "test"},
schedule_name="", # Empty name
cron="0 9 * * *",
+ dry_run=False,
session=session,
)
@@ -424,6 +435,7 @@ async def test_run_agent_rejects_unknown_input_fields(setup_test_data):
"unknown_field": "some value",
"another_unknown": "another value",
},
+ dry_run=False,
session=session,
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block.py b/autogpt_platform/backend/backend/copilot/tools/run_block.py
index a21f9fd23b..90a75284cc 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block.py
@@ -51,14 +51,10 @@ class RunBlockTool(BaseTool):
},
"dry_run": {
"type": "boolean",
- "description": (
- "When true, simulates block execution using an LLM without making any "
- "real API calls or producing side effects. Useful for testing agent "
- "wiring and previewing outputs. Default: false."
- ),
+ "description": "Execute in preview mode.",
},
},
- "required": ["block_id", "input_data"],
+ "required": ["block_id", "input_data", "dry_run"],
}
@property
@@ -69,6 +65,10 @@ class RunBlockTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ *,
+ block_id: str = "",
+ input_data: dict | None = None,
+ dry_run: bool,
**kwargs,
) -> ToolResponseBase:
"""Execute a block with the given input data.
@@ -78,15 +78,19 @@ class RunBlockTool(BaseTool):
session: Chat session
block_id: Block UUID to execute
input_data: Input values for the block
+ dry_run: If True, simulate execution without side effects
Returns:
BlockOutputResponse: Block execution outputs
SetupRequirementsResponse: Missing credentials
ErrorResponse: Error message
"""
- block_id = kwargs.get("block_id", "").strip()
- input_data = kwargs.get("input_data", {})
- dry_run = bool(kwargs.get("dry_run", False))
+ block_id = block_id.strip()
+ if input_data is None:
+ input_data = {}
+ # Session-level dry_run forces all tool calls to use dry-run mode.
+ if session.dry_run:
+ dry_run = True
session_id = session.session_id
if not block_id:
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
index 7b31c2d6a5..98edc2315b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
@@ -103,6 +103,7 @@ class TestRunBlockFiltering:
session=session,
block_id="input-block-id",
input_data={},
+ dry_run=False,
)
assert isinstance(response, ErrorResponse)
@@ -129,6 +130,7 @@ class TestRunBlockFiltering:
session=session,
block_id=orchestrator_id,
input_data={},
+ dry_run=False,
)
assert isinstance(response, ErrorResponse)
@@ -154,6 +156,7 @@ class TestRunBlockFiltering:
session=session,
block_id=block_id,
input_data={},
+ dry_run=False,
)
finally:
_current_permissions.reset(token)
@@ -187,6 +190,7 @@ class TestRunBlockFiltering:
session=session,
block_id=block_id,
input_data={},
+ dry_run=False,
)
finally:
_current_permissions.reset(token)
@@ -222,6 +226,7 @@ class TestRunBlockFiltering:
session=session,
block_id="standard-id",
input_data={},
+ dry_run=False,
)
# Should NOT be an ErrorResponse about CoPilot exclusion
@@ -282,6 +287,7 @@ class TestRunBlockInputValidation:
"prompt": "Write a haiku about coding",
"LLM_Model": "claude-opus-4-6",
},
+ dry_run=False,
)
assert isinstance(response, InputValidationErrorResponse)
@@ -327,6 +333,7 @@ class TestRunBlockInputValidation:
"system_prompt": "Be helpful",
"retries": 5,
},
+ dry_run=False,
)
assert isinstance(response, InputValidationErrorResponse)
@@ -370,6 +377,7 @@ class TestRunBlockInputValidation:
input_data={
"LLM_Model": "claude-opus-4-6",
},
+ dry_run=False,
)
assert isinstance(response, InputValidationErrorResponse)
@@ -424,6 +432,7 @@ class TestRunBlockInputValidation:
"prompt": "Write a haiku",
"model": "gpt-4o-mini",
},
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
@@ -463,6 +472,7 @@ class TestRunBlockInputValidation:
input_data={
"model": "gpt-4o-mini",
},
+ dry_run=False,
)
assert isinstance(response, BlockDetailsResponse)
@@ -514,6 +524,7 @@ class TestRunBlockSensitiveAction:
session=session,
block_id="delete-branch-id",
input_data=input_data,
+ dry_run=False,
)
assert isinstance(response, ReviewRequiredResponse)
@@ -574,6 +585,7 @@ class TestRunBlockSensitiveAction:
session=session,
block_id="delete-branch-id",
input_data=input_data,
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
@@ -628,6 +640,7 @@ class TestRunBlockSensitiveAction:
session=session,
block_id="http-request-id",
input_data=input_data,
+ dry_run=False,
)
assert isinstance(response, BlockOutputResponse)
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
index eb7a23143f..61a64709cc 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_mcp_tool.py
@@ -91,21 +91,40 @@ class RunMCPToolTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ server_url: str = "",
+ tool_name: str = "",
+ tool_arguments: dict[str, Any] | None = None,
**kwargs,
) -> ToolResponseBase:
- server_url: str = (kwargs.get("server_url") or "").strip()
- tool_name: str = (kwargs.get("tool_name") or "").strip()
- raw_tool_arguments = kwargs.get("tool_arguments")
- tool_arguments: dict[str, Any] = (
- raw_tool_arguments if isinstance(raw_tool_arguments, dict) else {}
- )
+ server_url = server_url.strip()
+ tool_name = tool_name.strip()
session_id = session.session_id
- if raw_tool_arguments is not None and not isinstance(raw_tool_arguments, dict):
+ # Session-level dry_run prevents real MCP tool execution.
+ # Discovery (no tool_name) is still allowed so the agent can inspect
+ # available tools, but actual execution is blocked.
+ if session.dry_run and tool_name:
+ return MCPToolOutputResponse(
+ message=(
+ f"[dry-run] MCP tool '{tool_name}' on "
+ f"{server_host(server_url)} was not executed "
+ "because the session is in dry-run mode."
+ ),
+ server_url=server_url,
+ tool_name=tool_name,
+ result=None,
+ success=True,
+ session_id=session_id,
+ )
+
+ if tool_arguments is not None and not isinstance(tool_arguments, dict):
return ErrorResponse(
message="tool_arguments must be a JSON object.",
session_id=session_id,
)
+ resolved_tool_arguments: dict[str, Any] = (
+ tool_arguments if isinstance(tool_arguments, dict) else {}
+ )
if not server_url:
return ErrorResponse(
@@ -167,7 +186,7 @@ class RunMCPToolTool(BaseTool):
else:
# Stage 2: Execute the selected tool
return await self._execute_tool(
- client, server_url, tool_name, tool_arguments, session_id
+ client, server_url, tool_name, resolved_tool_arguments, session_id
)
except HTTPClientError as e:
diff --git a/autogpt_platform/backend/backend/copilot/tools/search_docs.py b/autogpt_platform/backend/backend/copilot/tools/search_docs.py
index 8f08cef8d0..b0d787f681 100644
--- a/autogpt_platform/backend/backend/copilot/tools/search_docs.py
+++ b/autogpt_platform/backend/backend/copilot/tools/search_docs.py
@@ -85,6 +85,7 @@ class SearchDocsTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ query: str = "",
**kwargs,
) -> ToolResponseBase:
"""Search documentation and return relevant sections.
@@ -99,7 +100,7 @@ class SearchDocsTool(BaseTool):
NoResultsResponse: No results found
ErrorResponse: Error message
"""
- query = kwargs.get("query", "").strip()
+ query = query.strip()
session_id = session.session_id if session else None
if not query:
diff --git a/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py b/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py
index aea123c005..a1d97d32ca 100644
--- a/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py
+++ b/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py
@@ -238,7 +238,7 @@ async def test_execute_block_dry_run_skips_real_execution():
@pytest.mark.asyncio
async def test_execute_block_dry_run_response_format():
- """Dry-run response should contain [DRY RUN] in message and success=True."""
+ """Dry-run response should match real execution message format and have success=True."""
mock_block = make_mock_block()
async def fake_simulate(block, input_data):
@@ -259,7 +259,8 @@ async def test_execute_block_dry_run_response_format():
)
assert isinstance(response, BlockOutputResponse)
- assert "[DRY RUN]" in response.message
+ assert "executed successfully" in response.message
+ assert "[DRY RUN]" not in response.message # must not leak to LLM context
assert response.success is True
assert response.outputs == {"result": ["simulated"]}
@@ -307,23 +308,24 @@ async def test_execute_block_real_execution_unchanged():
def test_run_block_tool_dry_run_param():
- """RunBlockTool parameters should include 'dry_run'."""
+ """RunBlockTool parameters should include 'dry_run' as a required field."""
tool = RunBlockTool()
params = tool.parameters
assert "dry_run" in params["properties"]
assert params["properties"]["dry_run"]["type"] == "boolean"
+ assert "dry_run" in params["required"]
def test_run_block_tool_dry_run_calls_execute():
- """RunBlockTool._execute extracts dry_run from kwargs correctly.
+ """RunBlockTool._execute accepts dry_run as a typed parameter.
- We verify the extraction logic directly by inspecting the source, then confirm
- the kwarg is forwarded in the execute_block call site.
+ We verify the parameter exists in the signature and is forwarded to
+ execute_block.
"""
source = inspect.getsource(run_block_module.RunBlockTool._execute)
- # Verify dry_run is extracted from kwargs
+ # Verify dry_run is a typed parameter (not extracted from kwargs)
assert "dry_run" in source
- assert 'kwargs.get("dry_run"' in source
+ assert "dry_run: bool" in source
# Scope to _execute method source only — module-wide search is brittle
# and can match unrelated text/comments.
@@ -338,7 +340,10 @@ async def test_execute_block_dry_run_simulator_error_returns_error_response():
mock_block = make_mock_block()
async def fake_simulate_error(block, input_data):
- yield "error", "[SIMULATOR ERROR — NOT A BLOCK FAILURE] No LLM client available (missing OpenAI/OpenRouter API key)."
+ yield (
+ "error",
+ "[SIMULATOR ERROR — NOT A BLOCK FAILURE] No LLM client available (missing OpenAI/OpenRouter API key).",
+ )
with patch(
"backend.copilot.tools.helpers.simulate_block", side_effect=fake_simulate_error
diff --git a/autogpt_platform/backend/backend/copilot/tools/test_run_block_details.py b/autogpt_platform/backend/backend/copilot/tools/test_run_block_details.py
index 153f163644..8216ec45d8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/test_run_block_details.py
+++ b/autogpt_platform/backend/backend/copilot/tools/test_run_block_details.py
@@ -76,6 +76,7 @@ async def test_run_block_returns_details_when_no_input_provided():
session=session,
block_id="http-block-id",
input_data={}, # Empty input data
+ dry_run=False,
)
# Should return BlockDetailsResponse showing the schema
@@ -143,6 +144,7 @@ async def test_run_block_returns_details_when_only_credentials_provided():
session=session,
block_id="api-block-id",
input_data={"credentials": {"some": "cred"}}, # Only credential
+ dry_run=False,
)
# Should return details because no non-credential inputs provided
diff --git a/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py b/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
index 493b78a230..e831772b64 100644
--- a/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
+++ b/autogpt_platform/backend/backend/copilot/tools/test_run_mcp_tool.py
@@ -151,7 +151,7 @@ async def test_non_dict_tool_arguments_returns_error():
session=session,
server_url=_SERVER_URL,
tool_name="fetch",
- tool_arguments=["this", "is", "a", "list"], # wrong type
+ tool_arguments=["this", "is", "a", "list"], # type: ignore[arg-type] # intentionally wrong type to test validation
)
assert isinstance(response, ErrorResponse)
diff --git a/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.py b/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.py
new file mode 100644
index 0000000000..5f8e72a6f3
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.py
@@ -0,0 +1,499 @@
+"""Tests for session-level dry_run flag propagation.
+
+Verifies that when a session has dry_run=True, run_block, run_agent, and
+run_mcp_tool calls are forced to use dry-run mode, regardless of what the
+individual tool call specifies. The single source of truth is
+``session.dry_run``.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.models import ErrorResponse, MCPToolOutputResponse
+from backend.copilot.tools.run_agent import RunAgentInput, RunAgentTool
+from backend.copilot.tools.run_block import RunBlockTool
+from backend.copilot.tools.run_mcp_tool import RunMCPToolTool
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_session(dry_run: bool = False) -> ChatSession:
+ """Create a minimal ChatSession for testing."""
+ session = ChatSession.new("test-user", dry_run=dry_run)
+ return session
+
+
+def _make_mock_block(name: str = "TestBlock"):
+ """Create a minimal mock block with jsonschema() methods."""
+ block = MagicMock()
+ block.name = name
+ block.description = "A test block"
+ block.disabled = False
+ block.block_type = "STANDARD"
+ block.id = "test-block-id"
+
+ block.input_schema = MagicMock()
+ block.input_schema.jsonschema.return_value = {
+ "type": "object",
+ "properties": {"query": {"type": "string"}},
+ "required": ["query"],
+ }
+ block.input_schema.get_credentials_fields.return_value = {}
+ block.input_schema.get_credentials_fields_info.return_value = {}
+
+ block.output_schema = MagicMock()
+ block.output_schema.jsonschema.return_value = {
+ "type": "object",
+ "properties": {"result": {"type": "string"}},
+ "required": ["result"],
+ }
+
+ return block
+
+
+# ---------------------------------------------------------------------------
+# RunBlockTool tests
+# ---------------------------------------------------------------------------
+
+
+class TestRunBlockToolSessionDryRun:
+ """Test that RunBlockTool respects session-level dry_run."""
+
+ @pytest.mark.asyncio
+ async def test_session_dry_run_forces_block_dry_run(self):
+ """When session dry_run is True, run_block should force dry_run=True."""
+ tool = RunBlockTool()
+ session = _make_session(dry_run=True)
+
+ mock_block = _make_mock_block()
+
+ with (
+ patch(
+ "backend.copilot.tools.run_block.prepare_block_for_execution"
+ ) as mock_prep,
+ patch("backend.copilot.tools.run_block.execute_block") as mock_exec,
+ patch(
+ "backend.copilot.tools.run_block.get_current_permissions",
+ return_value=None,
+ ),
+ ):
+ # Set up prepare_block_for_execution to return a mock prep
+ mock_prep_result = MagicMock()
+ mock_prep_result.block = mock_block
+ mock_prep_result.input_data = {"query": "test"}
+ mock_prep_result.matched_credentials = {}
+ mock_prep_result.synthetic_node_id = "node-1"
+ mock_prep.return_value = mock_prep_result
+
+ # Set up execute_block to return a success
+ mock_exec.return_value = MagicMock(
+ message="Block 'TestBlock' executed successfully",
+ success=True,
+ )
+
+ await tool._execute(
+ user_id="test-user",
+ session=session,
+ block_id="test-block-id",
+ input_data={"query": "test"},
+ dry_run=False, # User passed False, but session overrides
+ )
+
+ # Verify execute_block was called with dry_run=True
+ mock_exec.assert_called_once()
+ call_kwargs = mock_exec.call_args
+ assert call_kwargs.kwargs.get("dry_run") is True
+
+ @pytest.mark.asyncio
+ async def test_no_session_dry_run_respects_tool_param(self):
+ """When session dry_run is False, tool-level dry_run should be respected."""
+ tool = RunBlockTool()
+ session = _make_session(dry_run=False)
+
+ mock_block = _make_mock_block()
+
+ with (
+ patch(
+ "backend.copilot.tools.run_block.prepare_block_for_execution"
+ ) as mock_prep,
+ patch("backend.copilot.tools.run_block.execute_block") as mock_exec,
+ patch(
+ "backend.copilot.tools.run_block.get_current_permissions",
+ return_value=None,
+ ),
+ patch("backend.copilot.tools.run_block.check_hitl_review") as mock_hitl,
+ ):
+ mock_prep_result = MagicMock()
+ mock_prep_result.block = mock_block
+ mock_prep_result.input_data = {"query": "test"}
+ mock_prep_result.matched_credentials = {}
+ mock_prep_result.synthetic_node_id = "node-1"
+ mock_prep_result.required_non_credential_keys = {"query"}
+ mock_prep_result.provided_input_keys = {"query"}
+ mock_prep.return_value = mock_prep_result
+
+ mock_hitl.return_value = ("node-exec-1", {"query": "test"})
+
+ mock_exec.return_value = MagicMock(
+ message="Block executed",
+ success=True,
+ )
+
+ await tool._execute(
+ user_id="test-user",
+ session=session,
+ block_id="test-block-id",
+ input_data={"query": "test"},
+ dry_run=False,
+ )
+
+ # Verify execute_block was called with dry_run=False
+ mock_exec.assert_called_once()
+ call_kwargs = mock_exec.call_args
+ assert call_kwargs.kwargs.get("dry_run") is False
+
+
+# ---------------------------------------------------------------------------
+# RunAgentTool tests
+# ---------------------------------------------------------------------------
+
+
+class TestRunAgentToolSessionDryRun:
+ """Test that RunAgentTool respects session-level dry_run."""
+
+ @pytest.mark.asyncio
+ async def test_session_dry_run_forces_agent_dry_run(self):
+ """When session dry_run is True, run_agent params.dry_run should be forced True."""
+ tool = RunAgentTool()
+ session = _make_session(dry_run=True)
+
+ # Mock the graph and dependencies
+ mock_graph = MagicMock()
+ mock_graph.id = "graph-1"
+ mock_graph.name = "Test Agent"
+ mock_graph.description = "A test agent"
+ mock_graph.input_schema = {"properties": {}, "required": []}
+ mock_graph.trigger_setup_info = None
+
+ mock_library_agent = MagicMock()
+ mock_library_agent.id = "lib-1"
+ mock_library_agent.graph_id = "graph-1"
+ mock_library_agent.graph_version = 1
+ mock_library_agent.name = "Test Agent"
+
+ mock_execution = MagicMock()
+ mock_execution.id = "exec-1"
+
+ with (
+ patch("backend.copilot.tools.run_agent.graph_db"),
+ patch("backend.copilot.tools.run_agent.library_db"),
+ patch(
+ "backend.copilot.tools.run_agent.fetch_graph_from_store_slug",
+ return_value=(mock_graph, None),
+ ),
+ patch(
+ "backend.copilot.tools.run_agent.match_user_credentials_to_graph",
+ return_value=({}, []),
+ ),
+ patch(
+ "backend.copilot.tools.run_agent.get_or_create_library_agent",
+ return_value=mock_library_agent,
+ ),
+ patch("backend.copilot.tools.run_agent.execution_utils") as mock_exec_utils,
+ patch("backend.copilot.tools.run_agent.track_agent_run_success"),
+ ):
+ mock_exec_utils.add_graph_execution = AsyncMock(return_value=mock_execution)
+
+ await tool._execute(
+ user_id="test-user",
+ session=session,
+ username_agent_slug="user/test-agent",
+ dry_run=False, # User passed False, but session overrides
+ use_defaults=True,
+ )
+
+ # Verify add_graph_execution was called with dry_run=True
+ mock_exec_utils.add_graph_execution.assert_called_once()
+ call_kwargs = mock_exec_utils.add_graph_execution.call_args
+ assert call_kwargs.kwargs.get("dry_run") is True
+
+ @pytest.mark.asyncio
+ async def test_session_dry_run_blocks_scheduling(self):
+ """When session dry_run is True, scheduling requests should be rejected."""
+ tool = RunAgentTool()
+ session = _make_session(dry_run=True)
+
+ result = await tool._execute(
+ user_id="test-user",
+ session=session,
+ username_agent_slug="user/test-agent",
+ schedule_name="daily-run",
+ cron="0 9 * * *",
+ dry_run=False, # Session overrides to True
+ )
+
+ assert isinstance(result, ErrorResponse)
+ assert "dry-run" in result.message.lower()
+ assert (
+ "scheduling" in result.message.lower()
+ or "schedule" in result.message.lower()
+ )
+
+
+# ---------------------------------------------------------------------------
+# ChatSession model tests
+# ---------------------------------------------------------------------------
+
+
+class TestChatSessionDryRun:
+ """Test the dry_run field on ChatSession model."""
+
+ def test_new_session_default_dry_run_false(self):
+ session = ChatSession.new("test-user", dry_run=False)
+ assert session.dry_run is False
+
+ def test_new_session_dry_run_true(self):
+ session = ChatSession.new("test-user", dry_run=True)
+ assert session.dry_run is True
+
+ def test_new_session_dry_run_false_explicit(self):
+ session = ChatSession.new("test-user", dry_run=False)
+ assert session.dry_run is False
+
+
+# ---------------------------------------------------------------------------
+# RunAgentInput tests
+# ---------------------------------------------------------------------------
+
+
+class TestRunAgentInputDryRunOverride:
+ """Test that RunAgentInput.dry_run can be mutated by session-level override."""
+
+ def test_explicit_dry_run_false(self):
+ params = RunAgentInput(username_agent_slug="user/agent", dry_run=False)
+ assert params.dry_run is False
+
+ def test_session_override(self):
+ params = RunAgentInput(username_agent_slug="user/agent", dry_run=False)
+ # Simulate session-level override
+ params.dry_run = True
+ assert params.dry_run is True
+
+
+# ---------------------------------------------------------------------------
+# RunMCPToolTool tests
+# ---------------------------------------------------------------------------
+
+
+class TestRunMCPToolToolSessionDryRun:
+ """Test that RunMCPToolTool respects session-level dry_run."""
+
+ @pytest.mark.asyncio
+ async def test_session_dry_run_blocks_mcp_execution(self):
+ """When session dry_run is True, MCP tool execution should be skipped."""
+ tool = RunMCPToolTool()
+ session = _make_session(dry_run=True)
+
+ result = await tool._execute(
+ user_id="test-user",
+ session=session,
+ server_url="https://mcp.example.com/sse",
+ tool_name="some_tool",
+ tool_arguments={"key": "value"},
+ )
+
+ assert isinstance(result, MCPToolOutputResponse)
+ assert result.success is True
+ assert "dry-run" in result.message
+ assert result.tool_name == "some_tool"
+ assert result.result is None
+
+ @pytest.mark.asyncio
+ async def test_session_dry_run_allows_discovery(self):
+ """When session dry_run is True, tool discovery (no tool_name) should still work."""
+ tool = RunMCPToolTool()
+ session = _make_session(dry_run=True)
+
+ # Discovery requires a network call, so we mock the client
+ with (
+ patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ return_value=None,
+ ),
+ patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host",
+ return_value=None,
+ ),
+ patch("backend.copilot.tools.run_mcp_tool.MCPClient") as mock_client_cls,
+ ):
+ mock_client = AsyncMock()
+ mock_client_cls.return_value = mock_client
+
+ mock_tool = MagicMock()
+ mock_tool.name = "test_tool"
+ mock_tool.description = "A test tool"
+ mock_tool.input_schema = {"type": "object", "properties": {}}
+ mock_client.list_tools.return_value = [mock_tool]
+
+ result = await tool._execute(
+ user_id="test-user",
+ session=session,
+ server_url="https://mcp.example.com/sse",
+ tool_name="", # Discovery mode
+ )
+
+ # Discovery should proceed normally
+ mock_client.initialize.assert_called_once()
+ mock_client.list_tools.assert_called_once()
+ assert "Discovered" in result.message
+
+ @pytest.mark.asyncio
+ async def test_no_session_dry_run_allows_execution(self):
+ """When session dry_run is False, MCP tool execution should proceed."""
+ tool = RunMCPToolTool()
+ session = _make_session(dry_run=False)
+
+ with (
+ patch(
+ "backend.copilot.tools.run_mcp_tool.auto_lookup_mcp_credential",
+ return_value=None,
+ ),
+ patch(
+ "backend.copilot.tools.run_mcp_tool.validate_url_host",
+ return_value=None,
+ ),
+ patch("backend.copilot.tools.run_mcp_tool.MCPClient") as mock_client_cls,
+ ):
+ mock_client = AsyncMock()
+ mock_client_cls.return_value = mock_client
+
+ mock_result = MagicMock()
+ mock_result.is_error = False
+ mock_result.content = [{"type": "text", "text": "hello"}]
+ mock_client.call_tool.return_value = mock_result
+
+ result = await tool._execute(
+ user_id="test-user",
+ session=session,
+ server_url="https://mcp.example.com/sse",
+ tool_name="some_tool",
+ tool_arguments={"key": "value"},
+ )
+
+ # Execution should proceed
+ mock_client.initialize.assert_called_once()
+ mock_client.call_tool.assert_called_once_with("some_tool", {"key": "value"})
+ assert isinstance(result, MCPToolOutputResponse)
+ assert result.success is True
+
+
+# ---------------------------------------------------------------------------
+# Backward-compatibility tests for ChatSessionMetadata deserialization
+# ---------------------------------------------------------------------------
+
+
+class TestChatSessionMetadataBackwardCompat:
+ """Verify that sessions created before the dry_run field existed still load.
+
+ The ``metadata`` JSON column in the DB may contain ``{}``, ``null``, or a
+ dict without the ``dry_run`` key for sessions created before the flag was
+ introduced. These must deserialize without errors and default to
+ ``dry_run=False``.
+ """
+
+ def test_metadata_default_construction(self):
+ """ChatSessionMetadata() with no args should default dry_run=False."""
+ from backend.copilot.model import ChatSessionMetadata
+
+ meta = ChatSessionMetadata()
+ assert meta.dry_run is False
+
+ def test_metadata_from_empty_dict(self):
+ """Deserializing an empty dict (old-format metadata) should succeed."""
+ from backend.copilot.model import ChatSessionMetadata
+
+ meta = ChatSessionMetadata.model_validate({})
+ assert meta.dry_run is False
+
+ def test_metadata_from_dict_without_dry_run_key(self):
+ """A metadata dict with other keys but no dry_run should still work."""
+ from backend.copilot.model import ChatSessionMetadata
+
+ meta = ChatSessionMetadata.model_validate({"some_future_field": 42})
+ # dry_run should fall back to default
+ assert meta.dry_run is False
+
+ def test_metadata_round_trip_with_dry_run_false(self):
+ """Serialize then deserialize with dry_run=False."""
+ from backend.copilot.model import ChatSessionMetadata
+
+ original = ChatSessionMetadata(dry_run=False)
+ raw = original.model_dump()
+ restored = ChatSessionMetadata.model_validate(raw)
+ assert restored.dry_run is False
+
+ def test_metadata_round_trip_with_dry_run_true(self):
+ """Serialize then deserialize with dry_run=True."""
+ from backend.copilot.model import ChatSessionMetadata
+
+ original = ChatSessionMetadata(dry_run=True)
+ raw = original.model_dump()
+ restored = ChatSessionMetadata.model_validate(raw)
+ assert restored.dry_run is True
+
+ def test_metadata_json_round_trip(self):
+ """Serialize to JSON string and back, simulating Redis cache flow."""
+ from backend.copilot.model import ChatSessionMetadata
+
+ original = ChatSessionMetadata(dry_run=True)
+ json_str = original.model_dump_json()
+ restored = ChatSessionMetadata.model_validate_json(json_str)
+ assert restored.dry_run is True
+
+ def test_session_dry_run_property_with_default_metadata(self):
+ """ChatSession.dry_run returns False when metadata has no dry_run."""
+ from backend.copilot.model import ChatSessionMetadata
+
+ # Simulate building a session with metadata deserialized from an old row
+ meta = ChatSessionMetadata.model_validate({})
+ session = _make_session(dry_run=False)
+ session.metadata = meta
+ assert session.dry_run is False
+
+ def test_session_info_dry_run_property_with_default_metadata(self):
+ """ChatSessionInfo.dry_run returns False when metadata is default."""
+ from datetime import UTC, datetime
+
+ from backend.copilot.model import ChatSessionInfo, ChatSessionMetadata
+
+ info = ChatSessionInfo(
+ session_id="old-session-id",
+ user_id="test-user",
+ usage=[],
+ started_at=datetime.now(UTC),
+ updated_at=datetime.now(UTC),
+ metadata=ChatSessionMetadata.model_validate({}),
+ )
+ assert info.dry_run is False
+
+ def test_session_full_json_round_trip_without_dry_run(self):
+ """A full ChatSession JSON round-trip preserves dry_run default."""
+ session = _make_session(dry_run=False)
+ json_bytes = session.model_dump_json()
+ restored = ChatSession.model_validate_json(json_bytes)
+ assert restored.dry_run is False
+ assert restored.metadata.dry_run is False
+
+ def test_session_full_json_round_trip_with_dry_run(self):
+ """A full ChatSession JSON round-trip preserves dry_run=True."""
+ session = _make_session(dry_run=True)
+ json_bytes = session.model_dump_json()
+ restored = ChatSession.model_validate_json(json_bytes)
+ assert restored.dry_run is True
+ assert restored.metadata.dry_run is True
diff --git a/autogpt_platform/backend/backend/copilot/tools/validate_agent.py b/autogpt_platform/backend/backend/copilot/tools/validate_agent.py
index ebcd049136..fe329af7b0 100644
--- a/autogpt_platform/backend/backend/copilot/tools/validate_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/validate_agent.py
@@ -48,9 +48,9 @@ class ValidateAgentGraphTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ agent_json: dict | None = None,
**kwargs,
) -> ToolResponseBase:
- agent_json = kwargs.get("agent_json")
session_id = session.session_id if session else None
if not agent_json or not isinstance(agent_json, dict):
diff --git a/autogpt_platform/backend/backend/copilot/tools/web_fetch.py b/autogpt_platform/backend/backend/copilot/tools/web_fetch.py
index 6c11f02054..79cc05dfa6 100644
--- a/autogpt_platform/backend/backend/copilot/tools/web_fetch.py
+++ b/autogpt_platform/backend/backend/copilot/tools/web_fetch.py
@@ -87,10 +87,11 @@ class WebFetchTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ url: str = "",
+ extract_text: bool = True,
**kwargs: Any,
) -> ToolResponseBase:
- url: str = (kwargs.get("url") or "").strip()
- extract_text: bool = kwargs.get("extract_text", True)
+ url = url.strip()
session_id = session.session_id if session else None
if not url:
diff --git a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py b/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
index a5884d63b2..b0459378ad 100644
--- a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
+++ b/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
@@ -450,6 +450,9 @@ class ListWorkspaceFilesTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ path_prefix: Optional[str] = None,
+ limit: int = 50,
+ include_all_sessions: bool = False,
**kwargs,
) -> ToolResponseBase:
session_id = session.session_id
@@ -458,9 +461,7 @@ class ListWorkspaceFilesTool(BaseTool):
message="Authentication required", session_id=session_id
)
- path_prefix: Optional[str] = kwargs.get("path_prefix")
- limit = min(kwargs.get("limit", 50), 100)
- include_all_sessions: bool = kwargs.get("include_all_sessions", False)
+ limit = min(limit, 100)
try:
manager = await get_workspace_manager(user_id, session_id)
@@ -567,6 +568,12 @@ class ReadWorkspaceFileTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ file_id: Optional[str] = None,
+ path: Optional[str] = None,
+ save_to_path: Optional[str] = None,
+ force_download_url: bool = False,
+ offset: int = 0,
+ length: Optional[int] = None,
**kwargs,
) -> ToolResponseBase:
session_id = session.session_id
@@ -575,12 +582,8 @@ class ReadWorkspaceFileTool(BaseTool):
message="Authentication required", session_id=session_id
)
- file_id: Optional[str] = kwargs.get("file_id")
- path: Optional[str] = kwargs.get("path")
- save_to_path: Optional[str] = kwargs.get("save_to_path")
- force_download_url: bool = kwargs.get("force_download_url", False)
- char_offset: int = max(0, kwargs.get("offset", 0))
- char_length: Optional[int] = kwargs.get("length")
+ char_offset: int = max(0, offset)
+ char_length: Optional[int] = length
if not file_id and not path:
return ErrorResponse(
@@ -770,6 +773,13 @@ class WriteWorkspaceFileTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ filename: str = "",
+ source_path: str | None = None,
+ content: str | None = None,
+ content_base64: str | None = None,
+ path: str | None = None,
+ mime_type: str | None = None,
+ overwrite: bool = False,
**kwargs,
) -> ToolResponseBase:
session_id = session.session_id
@@ -778,15 +788,14 @@ class WriteWorkspaceFileTool(BaseTool):
message="Authentication required", session_id=session_id
)
- filename: str = kwargs.get("filename", "")
if not filename:
return ErrorResponse(
message="Please provide a filename", session_id=session_id
)
- source_path_arg: str | None = kwargs.get("source_path")
- content_text: str | None = kwargs.get("content")
- content_b64: str | None = kwargs.get("content_base64")
+ source_path_arg: str | None = source_path
+ content_text: str | None = content
+ content_b64: str | None = content_base64
resolved = await _resolve_write_content(
content_text,
@@ -796,24 +805,24 @@ class WriteWorkspaceFileTool(BaseTool):
)
if isinstance(resolved, ErrorResponse):
return resolved
- content: bytes = resolved
+ content_bytes: bytes = resolved
max_size = _MAX_FILE_SIZE_MB * 1024 * 1024
- if len(content) > max_size:
+ if len(content_bytes) > max_size:
return ErrorResponse(
message=f"File too large. Maximum size is {_MAX_FILE_SIZE_MB}MB",
session_id=session_id,
)
try:
- await scan_content_safe(content, filename=filename)
+ await scan_content_safe(content_bytes, filename=filename)
manager = await get_workspace_manager(user_id, session_id)
rec = await manager.write_file(
- content=content,
+ content=content_bytes,
filename=filename,
- path=kwargs.get("path"),
- mime_type=kwargs.get("mime_type"),
- overwrite=kwargs.get("overwrite", False),
+ path=path,
+ mime_type=mime_type,
+ overwrite=overwrite,
)
# Build informative source label and message.
@@ -837,8 +846,8 @@ class WriteWorkspaceFileTool(BaseTool):
preview: str | None = None
if _is_text_mime(rec.mime_type):
try:
- preview = content[:200].decode("utf-8", errors="replace")
- if len(content) > 200:
+ preview = content_bytes[:200].decode("utf-8", errors="replace")
+ if len(content_bytes) > 200:
preview += "..."
except Exception:
pass
@@ -910,6 +919,8 @@ class DeleteWorkspaceFileTool(BaseTool):
self,
user_id: str | None,
session: ChatSession,
+ file_id: Optional[str] = None,
+ path: Optional[str] = None,
**kwargs,
) -> ToolResponseBase:
session_id = session.session_id
@@ -917,9 +928,6 @@ class DeleteWorkspaceFileTool(BaseTool):
return ErrorResponse(
message="Authentication required", session_id=session_id
)
-
- file_id: Optional[str] = kwargs.get("file_id")
- path: Optional[str] = kwargs.get("path")
if not file_id and not path:
return ErrorResponse(
message="Please provide either file_id or path", session_id=session_id
diff --git a/autogpt_platform/backend/migrations/20260326120000_add_metadata_to_chat_session/migration.sql b/autogpt_platform/backend/migrations/20260326120000_add_metadata_to_chat_session/migration.sql
new file mode 100644
index 0000000000..2907f511fe
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260326120000_add_metadata_to_chat_session/migration.sql
@@ -0,0 +1,4 @@
+-- Add extensible metadata JSONB column to ChatSession.
+-- New session-level flags (e.g. dry_run) live inside this JSON
+-- so future additions need no extra migrations.
+ALTER TABLE "ChatSession" ADD COLUMN "metadata" JSONB NOT NULL DEFAULT '{}';
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index e84c3b79ba..2656cef8f2 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -220,6 +220,10 @@ model ChatSession {
successfulAgentRuns Json @default("{}") // Map of graph_id -> count
successfulAgentSchedules Json @default("{}") // Map of graph_id -> count
+ // Extensible session metadata (typed via ChatSessionMetadata in Python).
+ // Avoids DB migrations for each new flag (e.g. dry_run, future fields).
+ metadata Json @default("{}")
+
// Usage tracking
totalPromptTokens Int @default(0)
totalCompletionTokens Int @default(0)
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
index 52b3ffa6c8..db3f0341a8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
@@ -95,7 +95,7 @@ export function useChatSession() {
async function createSession() {
if (sessionId) return sessionId;
try {
- const response = await createSessionMutation();
+ const response = await createSessionMutation({ data: null });
if (response.status !== 200 || !response.data?.id) {
const error = new Error("Failed to create session");
Sentry.captureException(error, {
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 44c69a1817..187d3e5c5c 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -1059,9 +1059,22 @@
"post": {
"tags": ["v2", "chat", "chat"],
"summary": "Create Session",
- "description": "Create a new chat session.\n\nInitiates a new chat session for the authenticated user.\n\nArgs:\n user_id: The authenticated user ID parsed from the JWT (required).\n\nReturns:\n CreateSessionResponse: Details of the created session.",
+ "description": "Create a new chat session.\n\nInitiates a new chat session for the authenticated user.\n\nArgs:\n user_id: The authenticated user ID parsed from the JWT (required).\n request: Optional request body. When provided, ``dry_run=True``\n forces run_block and run_agent calls to use dry-run simulation.\n\nReturns:\n CreateSessionResponse: Details of the created session.",
"operationId": "postV2CreateSession",
"security": [{ "HTTPBearerJWT": [] }],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "anyOf": [
+ { "$ref": "#/components/schemas/CreateSessionRequest" },
+ { "type": "null" }
+ ],
+ "title": "Request"
+ }
+ }
+ }
+ },
"responses": {
"200": {
"description": "Successful Response",
@@ -1075,6 +1088,14 @@
},
"401": {
"$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
}
}
}
@@ -8385,6 +8406,14 @@
"required": ["query", "conversation_history", "message_id"],
"title": "ChatRequest"
},
+ "ChatSessionMetadata": {
+ "properties": {
+ "dry_run": { "type": "boolean", "title": "Dry Run", "default": false }
+ },
+ "type": "object",
+ "title": "ChatSessionMetadata",
+ "description": "Typed metadata stored in the ``metadata`` JSON column of ChatSession.\n\nAdd new session-level flags here instead of adding DB columns —\nno migration required for new fields as long as a default is provided."
+ },
"ClarificationNeededResponse": {
"properties": {
"type": {
@@ -8514,6 +8543,15 @@
"required": ["graph"],
"title": "CreateGraph"
},
+ "CreateSessionRequest": {
+ "properties": {
+ "dry_run": { "type": "boolean", "title": "Dry Run", "default": false }
+ },
+ "additionalProperties": false,
+ "type": "object",
+ "title": "CreateSessionRequest",
+ "description": "Request model for creating a new chat session.\n\n``dry_run`` is a **top-level** field — do not nest it inside ``metadata``.\nExtra/unknown fields are rejected (422) to prevent silent mis-use."
+ },
"CreateSessionResponse": {
"properties": {
"id": { "type": "string", "title": "Id" },
@@ -8521,6 +8559,10 @@
"user_id": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "User Id"
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/ChatSessionMetadata",
+ "default": { "dry_run": false }
}
},
"type": "object",
@@ -12139,6 +12181,10 @@
"type": "integer",
"title": "Total Completion Tokens",
"default": 0
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/ChatSessionMetadata",
+ "default": { "dry_run": false }
}
},
"type": "object",
diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.md
index 30f6aaf499..7d60c93ae6 100644
--- a/docs/integrations/block-integrations/misc.md
+++ b/docs/integrations/block-integrations/misc.md
@@ -62,6 +62,7 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run
| tools_exclude | Controls how the 'tools' list is interpreted. True (default): 'tools' is a deny-list — listed tools are blocked, all others are allowed. An empty 'tools' list means allow everything. False: 'tools' is an allow-list — only listed tools are permitted. | bool | No |
| blocks | Block identifiers to filter when the copilot uses run_block. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No |
| blocks_exclude | Controls how the 'blocks' list is interpreted. True (default): 'blocks' is a deny-list — listed blocks are blocked, all others are allowed. An empty 'blocks' list means allow everything. False: 'blocks' is an allow-list — only listed blocks are permitted. | bool | No |
+| dry_run | When enabled, run_block and run_agent tool calls in this autopilot session are forced to use dry-run simulation mode. No real API calls, side effects, or credits are consumed by those tools. Useful for testing agent wiring and previewing outputs. Only applies when creating a new session (session_id is empty). When reusing an existing session_id, the session's original dry_run setting is preserved. | bool | No |
### Outputs