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(platform): edit expert Soul from chat with confirm gate (#14028)

Abhimanyu Yadav566700c09716
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 25fbdb0a42..8895630fd6 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -100,6 +100,7 @@ from backend.copilot.tools.models import (
DocSearchResultsResponse,
ErrorResponse,
ExecutionStartedResponse,
+ ExpertSoulUpdatedResponse,
InputValidationErrorResponse,
MCPToolOutputResponse,
MCPToolsDiscoveredResponse,
@@ -2030,6 +2031,7 @@ ToolResponseUnion = (
| MemoryForgetCandidatesResponse
| MemoryForgetConfirmResponse
| TodoWriteResponse
+ | ExpertSoulUpdatedResponse
)
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 b3d0d9f106..30a47e65dc 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -1,6 +1,7 @@
"""Tests for chat API routes: session title update, file attachment validation, usage, and rate limiting."""
from datetime import UTC, datetime, timedelta
+from typing import get_args
from unittest.mock import AsyncMock, MagicMock
import fastapi
@@ -13,6 +14,7 @@ from backend.api.features.chat import routes as chat_routes
from backend.api.features.chat.routes import _strip_injected_context
from backend.copilot.config import CopilotLlmAuthProvider
from backend.copilot.rate_limit import SubscriptionTier
+from backend.copilot.tools.models import ExpertSoulUpdatedResponse
from backend.data.model import OAuth2Credentials
from backend.integrations.codex.auth_bundle import (
CodexAuthBundleV1,
@@ -49,6 +51,10 @@ VALID_CODEX_PROVIDER_STATE = encode_provider_state(
)
+def test_tool_response_union_exports_expert_soul_response() -> None:
+ assert ExpertSoulUpdatedResponse in get_args(chat_routes.ToolResponseUnion)
+
+
@pytest.fixture(autouse=True)
def setup_app_auth(mock_jwt_user, mocker: pytest_mock.MockerFixture):
"""Setup auth overrides for all tests in this module"""
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
index 85363ec6a3..1764ae6cbe 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -2,11 +2,13 @@ import logging
import prisma.errors
import prisma.models
+import prisma.types
from backend.api.features.experts import scheduling
from backend.api.features.experts.models import (
PROTECTED_SOUL_RULES,
Expert,
+ ExpertSoulFieldsPatch,
ExpertSoulUpdate,
ExpertWorkflowRef,
HireResult,
@@ -251,6 +253,111 @@ async def update_soul(user_id: str, expert_id: str, soul: ExpertSoulUpdate) -> E
return expert
+def _soul_field_update_data(
+ *,
+ identity: str | None,
+ voice_preferences: str | None,
+ boundaries: str | None,
+) -> prisma.types.ExpertUpdateManyMutationInput:
+ patch = ExpertSoulFieldsPatch(
+ identity=identity,
+ voice_preferences=voice_preferences,
+ boundaries=boundaries,
+ )
+ data: prisma.types.ExpertUpdateManyMutationInput = {}
+ if patch.identity is not None:
+ data["identity"] = patch.identity
+ if patch.voice_preferences is not None:
+ data["voicePreferences"] = patch.voice_preferences
+ if patch.boundaries is not None:
+ data["boundaries"] = patch.boundaries
+ if not data:
+ raise ValueError("At least one Soul field must be provided")
+ return data
+
+
+async def update_soul_fields(
+ user_id: str,
+ expert_id: str,
+ *,
+ identity: str | None = None,
+ voice_preferences: str | None = None,
+ boundaries: str | None = None,
+) -> Expert:
+ """Patch only the supplied Soul fields in one scoped write.
+
+ Backs the copilot Soul-edit tools, which edit identity / voice /
+ boundaries but never rename the expert. A single ``update_many`` writes
+ only the supplied columns, so concurrent edits to disjoint fields cannot
+ clobber each other; per-field validation mirrors ``update_soul`` via
+ ``ExpertSoulFieldsPatch``.
+ """
+ data = _soul_field_update_data(
+ identity=identity,
+ voice_preferences=voice_preferences,
+ boundaries=boundaries,
+ )
+
+ updated = await prisma.models.Expert.prisma().update_many(
+ where={
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ },
+ data=data,
+ )
+ if updated == 0:
+ raise ExpertNotFoundError(expert_id)
+
+ expert = await get_expert(user_id, expert_id, include_workflows=False)
+ if expert is None:
+ raise ExpertNotFoundError(expert_id)
+ return expert
+
+
+async def update_soul_fields_if_current(
+ user_id: str,
+ expert_id: str,
+ *,
+ identity: str | None = None,
+ voice_preferences: str | None = None,
+ boundaries: str | None = None,
+ expected_identity: str | None = None,
+ expected_voice_preferences: str | None = None,
+ expected_boundaries: str | None = None,
+) -> bool:
+ """Atomically patch Soul fields only when their previewed values still match."""
+ data = _soul_field_update_data(
+ identity=identity,
+ voice_preferences=voice_preferences,
+ boundaries=boundaries,
+ )
+ comparisons: dict[str, str] = {}
+ for field, value, expected in (
+ ("identity", identity, expected_identity),
+ ("voicePreferences", voice_preferences, expected_voice_preferences),
+ ("boundaries", boundaries, expected_boundaries),
+ ):
+ if value is None:
+ continue
+ if expected is None:
+ raise ValueError(f"Expected value required for {field}")
+ comparisons[field] = expected
+
+ updated = await prisma.models.Expert.prisma().update_many(
+ where={
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ **comparisons,
+ },
+ data=data,
+ )
+ return updated == 1
+
+
async def _install_preloads(
expert_id: str, user_id: str, preloads: list[prisma.models.ExpertWorkflow]
) -> list[str]:
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
index f98553cd55..bdb13b8075 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
@@ -1,14 +1,16 @@
+import asyncio
import uuid
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import prisma.enums
import prisma.models
+import pydantic
import pytest
import backend.api.features.store.model as store_model
from backend.api.features.experts import experts_db, scheduling, seed
-from backend.api.features.experts.models import ExpertSoulUpdate
+from backend.api.features.experts.models import ExpertSoulFieldsPatch, ExpertSoulUpdate
from backend.api.model import CreateGraph
from backend.blocks.io import AgentInputBlock
from backend.data.graph import Graph, Node
@@ -709,3 +711,144 @@ async def test_seed_backfills_presentation_fields_onto_hired_copies(
assert refreshed.skills == ["Content strategy", "SEO writing"]
# A user's rename of their own hire survives the refresh.
assert refreshed.name == "My Maria"
+
+
[email protected](loop_scope="session")
+async def test_update_soul_fields_patches_subset_only(
+ server: SpinTestServer, test_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ updated = await experts_db.update_soul_fields(
+ test_user.id,
+ hired.expert.id,
+ voice_preferences="Warm and concise.",
+ )
+
+ assert updated.voice_preferences == "Warm and concise."
+ # Untouched fields (including the name) are preserved.
+ assert updated.identity == hired.expert.identity
+ assert updated.name == hired.expert.name
+ assert updated.boundaries == hired.expert.boundaries
+
+
[email protected](loop_scope="session")
+async def test_update_soul_fields_scopes_by_owner(
+ server: SpinTestServer, test_user, other_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ with pytest.raises(experts_db.ExpertNotFoundError):
+ await experts_db.update_soul_fields(
+ other_user.id, hired.expert.id, identity="Hijacked identity."
+ )
+
+
[email protected](loop_scope="session")
+async def test_update_soul_fields_concurrent_disjoint_edits_both_persist(
+ server: SpinTestServer, test_user
+):
+ """Each call writes only its own column, so neither edit is clobbered."""
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ await asyncio.gather(
+ experts_db.update_soul_fields(
+ test_user.id, hired.expert.id, voice_preferences="Warm and concise."
+ ),
+ experts_db.update_soul_fields(
+ test_user.id, hired.expert.id, boundaries="Never email externally."
+ ),
+ )
+
+ fetched = await experts_db.get_expert(test_user.id, hired.expert.id)
+ assert fetched is not None
+ assert fetched.voice_preferences == "Warm and concise."
+ assert fetched.boundaries == "Never email externally."
+
+
[email protected](loop_scope="session")
+async def test_update_soul_fields_rejects_empty_patch():
+ with pytest.raises(ValueError, match="At least one Soul field"):
+ await experts_db.update_soul_fields("user-1", "expert-1")
+
+
[email protected](loop_scope="session")
+async def test_update_soul_fields_if_current_requires_expected_value():
+ with pytest.raises(ValueError, match="Expected value required"):
+ await experts_db.update_soul_fields_if_current(
+ "user-1", "expert-1", identity="New identity."
+ )
+
+
[email protected](loop_scope="session")
+async def test_update_soul_fields_if_current_is_atomic(
+ server: SpinTestServer, test_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ before = hired.expert.voice_preferences
+
+ applied = await experts_db.update_soul_fields_if_current(
+ test_user.id,
+ hired.expert.id,
+ voice_preferences="Warm and concise.",
+ expected_voice_preferences=before,
+ )
+ stale_apply = await experts_db.update_soul_fields_if_current(
+ test_user.id,
+ hired.expert.id,
+ voice_preferences="Stale overwrite.",
+ expected_voice_preferences=before,
+ )
+
+ fetched = await experts_db.get_expert(test_user.id, hired.expert.id)
+ assert applied is True
+ assert stale_apply is False
+ assert fetched is not None
+ assert fetched.voice_preferences == "Warm and concise."
+
+
[email protected](loop_scope="session")
+async def test_update_soul_fields_if_current_scopes_by_owner(
+ server: SpinTestServer, test_user, other_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ applied = await experts_db.update_soul_fields_if_current(
+ other_user.id,
+ hired.expert.id,
+ identity="Hijacked identity.",
+ expected_identity=hired.expert.identity,
+ )
+
+ fetched = await experts_db.get_expert(test_user.id, hired.expert.id)
+ assert applied is False
+ assert fetched is not None
+ assert fetched.identity == hired.expert.identity
+
+
+def test_expert_soul_fields_patch_rejects_blank_identity():
+ with pytest.raises(pydantic.ValidationError):
+ ExpertSoulFieldsPatch(identity=" ")
+
+
+def test_expert_soul_fields_patch_enforces_length_caps():
+ with pytest.raises(pydantic.ValidationError):
+ ExpertSoulFieldsPatch(identity="x" * 10_001)
+ with pytest.raises(pydantic.ValidationError):
+ ExpertSoulFieldsPatch(voice_preferences="x" * 4_001)
+ with pytest.raises(pydantic.ValidationError):
+ ExpertSoulFieldsPatch(boundaries="x" * 4_001)
+
+
+def test_expert_soul_fields_patch_strips_and_preserves_none():
+ patch = ExpertSoulFieldsPatch(
+ voice_preferences=" ", boundaries=" Keep it short. "
+ )
+ assert patch.voice_preferences == ""
+ assert patch.boundaries == "Keep it short."
+ assert patch.identity is None
diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.py
index fb130dcedc..d0fa07534e 100644
--- a/autogpt_platform/backend/backend/api/features/experts/models.py
+++ b/autogpt_platform/backend/backend/api/features/experts/models.py
@@ -6,6 +6,21 @@ AI_DISCLOSURE_RULE = "The expert discloses that it is AI when acting externally.
EXTERNAL_ACTION_APPROVAL_RULE = "External actions require approval."
PROTECTED_SOUL_RULES = (AI_DISCLOSURE_RULE, EXTERNAL_ACTION_APPROVAL_RULE)
+_EXPERT_NAME_MAX_LENGTH = 100
+_EXPERT_IDENTITY_MAX_LENGTH = 10_000
+_EXPERT_SOUL_TEXT_MAX_LENGTH = 4_000
+
+
+def _strip_required_soul_field(value: str) -> str:
+ stripped = value.strip()
+ if not stripped:
+ raise ValueError("Field must not be blank")
+ return stripped
+
+
+def _strip_optional_soul_field(value: str) -> str:
+ return value.strip()
+
class ExpertWorkflowRef(BaseModel):
id: str
@@ -61,22 +76,48 @@ class HireResult(BaseModel):
class ExpertSoulUpdate(BaseModel):
- name: str = Field(min_length=1, max_length=100)
- identity: str = Field(min_length=1, max_length=10_000)
- voice_preferences: str = Field(max_length=4_000)
- boundaries: str = Field(max_length=4_000)
+ name: str = Field(min_length=1, max_length=_EXPERT_NAME_MAX_LENGTH)
+ identity: str = Field(min_length=1, max_length=_EXPERT_IDENTITY_MAX_LENGTH)
+ voice_preferences: str = Field(max_length=_EXPERT_SOUL_TEXT_MAX_LENGTH)
+ boundaries: str = Field(max_length=_EXPERT_SOUL_TEXT_MAX_LENGTH)
@field_validator("name", "identity")
@classmethod
def strip_required_fields(cls, value: str) -> str:
- stripped = value.strip()
- if not stripped:
- raise ValueError("Field must not be blank")
- return stripped
+ return _strip_required_soul_field(value)
@field_validator("voice_preferences", "boundaries")
@classmethod
def strip_optional_fields(cls, value: str) -> str:
- # Whitespace-only input must collapse to "" so prompt rendering falls
- # back to "Not specified." instead of emitting a blank section.
- return value.strip()
+ return _strip_optional_soul_field(value)
+
+
+class ExpertSoulFieldsPatch(BaseModel):
+ """Partial Soul edit: only supplied fields are validated and written.
+
+ Mirrors ``ExpertSoulUpdate``'s per-field rules (lengths, blank handling)
+ but leaves ``None`` fields untouched so disjoint concurrent edits cannot
+ clobber each other.
+ """
+
+ identity: str | None = Field(
+ default=None, min_length=1, max_length=_EXPERT_IDENTITY_MAX_LENGTH
+ )
+ voice_preferences: str | None = Field(
+ default=None, max_length=_EXPERT_SOUL_TEXT_MAX_LENGTH
+ )
+ boundaries: str | None = Field(
+ default=None, max_length=_EXPERT_SOUL_TEXT_MAX_LENGTH
+ )
+
+ @field_validator("identity")
+ @classmethod
+ def strip_required_fields(cls, value: str | None) -> str | None:
+ if value is None:
+ return None
+ return _strip_required_soul_field(value)
+
+ @field_validator("voice_preferences", "boundaries")
+ @classmethod
+ def strip_optional_fields(cls, value: str | None) -> str | None:
+ return None if value is None else _strip_optional_soul_field(value)
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.py
index e0aef56b2f..9770f881f5 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py
@@ -2035,6 +2035,8 @@ async def stream_chat_completion_baseline(
disabled_tool_groups: list[ToolGroup] = []
if not graphiti_enabled:
disabled_tool_groups.append("graphiti")
+ if not session.expert_id:
+ disabled_tool_groups.append("experts")
tools = get_available_tools(disabled_groups=disabled_tool_groups)
# --- Permission filtering ---
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.py
index b22d1d5f43..ebc9dda38b 100644
--- a/autogpt_platform/backend/backend/copilot/permissions.py
+++ b/autogpt_platform/backend/backend/copilot/permissions.py
@@ -75,6 +75,7 @@ ToolName = Literal[
"browser_act",
"browser_navigate",
"browser_screenshot",
+ "confirm_expert_soul_update",
"connect_integration",
"continue_run_block",
"create_agent",
@@ -123,6 +124,7 @@ ToolName = Literal[
"search_feature_requests",
"setup_agent_webhook_trigger",
"store_skill",
+ "update_expert_soul",
"update_folder",
"update_preset",
"validate_agent_graph",
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index 2e64139f39..50ce36ce2c 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -4341,6 +4341,8 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues
disabled_tool_groups: list[ToolGroup] = []
if not graphiti_enabled:
disabled_tool_groups.append("graphiti")
+ if not session.expert_id:
+ disabled_tool_groups.append("experts")
# Hide both permission-denied tools AND group-disabled tools at
# registration. ``allowed_tools`` filtering alone routes group-
diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.py
index be19067cd5..e852c1e19a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py
@@ -54,6 +54,7 @@ from .search_docs import SearchDocsTool
from .setup_agent_webhook_trigger import SetupAgentWebhookTriggerTool
from .skills import DeleteSkillTool, ListSkillsTool, ReadSkillTool, StoreSkillTool
from .todo_write import TodoWriteTool
+from .update_soul import ConfirmExpertSoulUpdateTool, UpdateExpertSoulTool
from .validate_agent import ValidateAgentGraphTool
from .web_fetch import WebFetchTool
from .web_search import WebSearchTool
@@ -151,6 +152,9 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
"read_workspace_file": ReadWorkspaceFileTool(),
"write_workspace_file": WriteWorkspaceFileTool(),
"delete_workspace_file": DeleteWorkspaceFileTool(),
+ # Expert Soul edits from chat (expert sessions only): preview + confirm
+ "update_expert_soul": UpdateExpertSoulTool(),
+ "confirm_expert_soul_update": ConfirmExpertSoulUpdateTool(),
}
# Export individual tool instances for backwards compatibility
@@ -164,13 +168,17 @@ run_agent_tool = TOOL_REGISTRY["run_agent"]
# for tools whose backend is off and then hit opaque runtime errors. Add
# a new group by extending ``ToolGroup`` and registering its members in
# ``TOOL_GROUPS`` below.
-ToolGroup = Literal["graphiti"]
+ToolGroup = Literal["graphiti", "experts"]
TOOL_GROUPS: dict[str, ToolGroup] = {
"memory_store": "graphiti",
"memory_search": "graphiti",
"memory_forget_search": "graphiti",
"memory_forget_confirm": "graphiti",
+ # Soul edits only make sense in an expert-scoped session; the engines
+ # disable this group when the session has no expert_id.
+ "update_expert_soul": "experts",
+ "confirm_expert_soul_update": "experts",
}
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index 8dfba90b7d..3413070415 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -123,6 +123,9 @@ class ResponseType(str, Enum):
SKILL_DELETED = "skill_deleted"
SKILL_LIST = "skill_list"
+ # Experts (soul edits)
+ EXPERT_SOUL_UPDATED = "expert_soul_updated"
+
# Base response model
class ToolResponseBase(BaseModel):
@@ -486,6 +489,32 @@ class UnderstandingUpdatedResponse(ToolResponseBase):
current_understanding: dict[str, Any] = Field(default_factory=dict)
+SoulFieldName = Literal["identity", "voice_preferences", "boundaries"]
+
+
+class SoulFieldChange(BaseModel):
+ """One field's before/after values for an expert soul edit."""
+
+ field: SoulFieldName
+ before: str
+ after: str
+
+
+class ExpertSoulUpdatedResponse(ToolResponseBase):
+ """Response for the two-step Soul edit tools.
+
+ Carries the diff so the model must surface exactly what changed. ``applied``
+ is False for the update_expert_soul preview (nothing written yet; the
+ one-time ``confirmation_id`` references the stored proposal) and True once
+ confirm_expert_soul_update saves the edit.
+ """
+
+ type: ResponseType = ResponseType.EXPERT_SOUL_UPDATED
+ applied: bool = False
+ changes: list[SoulFieldChange] = Field(default_factory=list)
+ confirmation_id: str | None = None
+
+
# Agent generation models
class ClarifyingQuestion(BaseModel):
"""A question that needs user clarification."""
diff --git a/autogpt_platform/backend/backend/copilot/tools/soul_proposal.py b/autogpt_platform/backend/backend/copilot/tools/soul_proposal.py
new file mode 100644
index 0000000000..e757a07c7a
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/soul_proposal.py
@@ -0,0 +1,132 @@
+"""Server-side storage and atomic application for expert Soul proposals."""
+
+import logging
+
+from pydantic import BaseModel, Field, ValidationError
+
+from backend.copilot.model import ChatSession
+from backend.data.db_accessors import experts_db
+from backend.data.redis_client import AsyncRedisClient
+
+from .models import (
+ ErrorResponse,
+ ExpertSoulUpdatedResponse,
+ SoulFieldChange,
+ ToolResponseBase,
+)
+
+logger = logging.getLogger(__name__)
+
+PROPOSAL_TTL_SECONDS = 15 * 60
+_PROPOSAL_KEY_PREFIX = "copilot:soul_edit_proposal:"
+_LOG_ID_PREFIX_LENGTH = 12
+
+
+class SoulEditProposal(BaseModel):
+ """The exact pending edit stored between preview and confirm."""
+
+ user_id: str
+ session_id: str
+ expert_id: str
+ changes: list[SoulFieldChange] = Field(min_length=1)
+
+
+def proposal_key(confirmation_id: str) -> str:
+ return f"{_PROPOSAL_KEY_PREFIX}{confirmation_id}"
+
+
+def _stale_preview_error(session_id: str) -> ErrorResponse:
+ return ErrorResponse(
+ message=(
+ "This confirmation_id is unknown, expired, or already used. "
+ "Call update_expert_soul again for a fresh preview."
+ ),
+ session_id=session_id,
+ )
+
+
+async def load_bound_proposal(
+ redis: AsyncRedisClient,
+ confirmation_id: str,
+ user_id: str,
+ session: ChatSession,
+) -> SoulEditProposal | ErrorResponse:
+ key = proposal_key(confirmation_id)
+ raw = await redis.get(key)
+ if raw is None:
+ return _stale_preview_error(session.session_id)
+
+ try:
+ proposal = SoulEditProposal.model_validate_json(raw)
+ except ValidationError:
+ await redis.delete(key)
+ logger.warning(
+ "Discarding malformed soul-edit proposal for user %s",
+ user_id[:_LOG_ID_PREFIX_LENGTH],
+ )
+ return _stale_preview_error(session.session_id)
+
+ if (
+ proposal.user_id != user_id
+ or proposal.expert_id != session.expert_id
+ or proposal.session_id != session.session_id
+ ):
+ return ErrorResponse(
+ message="This confirmation_id belongs to a different chat or expert.",
+ session_id=session.session_id,
+ )
+
+ # GET and DEL are intentionally separate: binding must be checked before
+ # consumption so a mismatched caller cannot invalidate a legitimate proposal.
+ if await redis.delete(key) == 0:
+ return _stale_preview_error(session.session_id)
+ return proposal
+
+
+async def apply_proposal(
+ user_id: str,
+ expert_id: str,
+ session_id: str,
+ proposal: SoulEditProposal,
+) -> ToolResponseBase:
+ update_args: dict[str, str] = {}
+ for change in proposal.changes:
+ update_args[change.field] = change.after
+ update_args[f"expected_{change.field}"] = change.before
+
+ try:
+ applied = await experts_db().update_soul_fields_if_current(
+ user_id,
+ expert_id,
+ **update_args,
+ )
+ except Exception:
+ logger.warning(
+ "Soul edit apply failed for user %s",
+ user_id[:_LOG_ID_PREFIX_LENGTH],
+ exc_info=True,
+ )
+ return ErrorResponse(
+ message=(
+ "Couldn't apply the Soul edit — the proposal has been "
+ "discarded. Call update_expert_soul again to re-preview "
+ "and retry."
+ ),
+ session_id=session_id,
+ )
+
+ if not applied:
+ return ErrorResponse(
+ message=(
+ "The expert is no longer available or its Soul changed since "
+ "this preview, so the proposal was discarded. Call "
+ "update_expert_soul again to preview the current Soul."
+ ),
+ session_id=session_id,
+ )
+ return ExpertSoulUpdatedResponse(
+ message="Soul updated. Tell the user exactly what changed.",
+ session_id=session_id,
+ applied=True,
+ changes=proposal.changes,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
index 98b14c0adb..93303adf22 100644
--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
@@ -97,7 +97,10 @@ from backend.copilot.tools import TOOL_REGISTRY
# ``{}`` and dropping it; nested props are kept type-only to minimise the spend.
# Merged registry measures 50915 chars (incl. find_library_agent's
# write_graph_to); ~580 headroom for wording tweaks.
-_CHAR_BUDGET = 51_500
+# Includes the two-step Soul edit flow (update_expert_soul preview +
+# confirm_expert_soul_update); registry measures ~52.2k chars locally, with
+# ~800 headroom for CI env deltas and wording tweaks.
+_CHAR_BUDGET = 53_000
@pytest.fixture(scope="module")
diff --git a/autogpt_platform/backend/backend/copilot/tools/update_soul.py b/autogpt_platform/backend/backend/copilot/tools/update_soul.py
new file mode 100644
index 0000000000..0a01e906f0
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/update_soul.py
@@ -0,0 +1,276 @@
+"""Two-step tools for editing the current expert's Soul.
+
+Step 1 (update_expert_soul): compute the before/after diff, store the exact
+proposal server-side, and return a one-time confirmation_id — nothing written.
+Step 2 (confirm_expert_soul_update): after the user approves the diff, apply
+exactly the stored proposal by confirmation_id. New field values are rejected
+at this step, the id is single-use, and a Soul that changed since the preview
+aborts the apply. Mirrors the memory_forget_search -> memory_forget_confirm
+flow in graphiti_forget.py.
+"""
+
+import uuid
+from typing import Any
+
+from pydantic import ValidationError
+
+from backend.api.features.experts.models import Expert, ExpertSoulFieldsPatch
+from backend.copilot.model import ChatSession
+from backend.data.db_accessors import experts_db
+from backend.data.redis_client import get_redis_async
+
+from .base import BaseTool
+from .models import (
+ ErrorResponse,
+ ExpertSoulUpdatedResponse,
+ SoulFieldChange,
+ SoulFieldName,
+ ToolResponseBase,
+)
+from .soul_proposal import (
+ PROPOSAL_TTL_SECONDS,
+ SoulEditProposal,
+ apply_proposal,
+ load_bound_proposal,
+ proposal_key,
+)
+
+_PLAIN_SESSION_REFUSAL = (
+ "I can only edit an expert's Soul inside that expert's chat. Open a thread "
+ "with a hired expert to change their identity, voice, or boundaries."
+)
+
+_EDITABLE_FIELDS: tuple[SoulFieldName, ...] = (
+ "identity",
+ "voice_preferences",
+ "boundaries",
+)
+
+
+def _soul_snapshot(expert: Expert) -> dict[SoulFieldName, str]:
+ return {
+ "identity": expert.identity,
+ "voice_preferences": expert.voice_preferences,
+ "boundaries": expert.boundaries,
+ }
+
+
+def _session_guard(user_id: str | None, session: ChatSession) -> ErrorResponse | None:
+ if not user_id:
+ return ErrorResponse(
+ message="Please sign in to edit an expert's Soul.",
+ session_id=session.session_id,
+ )
+ if not session.expert_id:
+ return ErrorResponse(
+ message=_PLAIN_SESSION_REFUSAL,
+ session_id=session.session_id,
+ )
+ return None
+
+
+class UpdateExpertSoulTool(BaseTool):
+ """Preview a Soul edit for the current session's expert (never writes)."""
+
+ @property
+ def name(self) -> str:
+ return "update_expert_soul"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Propose an edit to this expert's Soul — identity/personality, "
+ "voice preferences, or boundaries. Never writes: it returns the "
+ "before/after diff plus a one-time confirmation_id. Show the user "
+ "the diff and, only after they explicitly approve, call "
+ "confirm_expert_soul_update with that confirmation_id."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "identity": {
+ "type": "string",
+ "description": "New identity/personality text; omit to leave unchanged.",
+ },
+ "voice_preferences": {
+ "type": "string",
+ "description": "New voice/tone preferences; omit to leave unchanged.",
+ },
+ "boundaries": {
+ "type": "string",
+ "description": "New boundaries; omit to leave unchanged.",
+ },
+ },
+ "required": [],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id
+ if error := _session_guard(user_id, session):
+ return error
+ assert user_id is not None
+ assert session.expert_id is not None
+
+ supplied = {
+ field: kwargs[field]
+ for field in _EDITABLE_FIELDS
+ if isinstance(kwargs.get(field), str)
+ }
+ if not supplied:
+ return ErrorResponse(
+ message="Provide at least one of identity, voice_preferences, or boundaries.",
+ session_id=session_id,
+ )
+ try:
+ patch = ExpertSoulFieldsPatch(**supplied)
+ except ValidationError as e:
+ detail = "; ".join(
+ f"{'.'.join(str(loc) for loc in err['loc'])}: {err['msg']}"
+ for err in e.errors()
+ )
+ return ErrorResponse(
+ message=f"Invalid Soul edit — {detail}",
+ session_id=session_id,
+ )
+ edits = {
+ field: value
+ for field in _EDITABLE_FIELDS
+ if (value := getattr(patch, field)) is not None
+ }
+
+ expert = await experts_db().get_expert(
+ user_id, session.expert_id, include_workflows=False
+ )
+ if expert is None:
+ return ErrorResponse(
+ message="This expert no longer exists.",
+ session_id=session_id,
+ )
+
+ before = _soul_snapshot(expert)
+ changes = [
+ SoulFieldChange(field=field, before=before[field], after=edits[field])
+ for field in _EDITABLE_FIELDS
+ if field in edits and edits[field] != before[field]
+ ]
+ if not changes:
+ return ErrorResponse(
+ message="Those values match the current Soul — nothing to change.",
+ session_id=session_id,
+ )
+
+ confirmation_id = str(uuid.uuid4())
+ proposal = SoulEditProposal(
+ user_id=user_id,
+ session_id=session_id,
+ expert_id=session.expert_id,
+ changes=changes,
+ )
+ redis = await get_redis_async()
+ await redis.setex(
+ proposal_key(confirmation_id),
+ PROPOSAL_TTL_SECONDS,
+ proposal.model_dump_json(),
+ )
+ return ExpertSoulUpdatedResponse(
+ message=(
+ "Nothing saved yet. Show the user this before/after diff and ask "
+ "them to approve. Only after they explicitly approve, call "
+ "confirm_expert_soul_update with this confirmation_id."
+ ),
+ session_id=session_id,
+ applied=False,
+ changes=changes,
+ confirmation_id=confirmation_id,
+ )
+
+
+class ConfirmExpertSoulUpdateTool(BaseTool):
+ """Apply a previewed Soul edit by its one-time confirmation_id."""
+
+ @property
+ def name(self) -> str:
+ return "confirm_expert_soul_update"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Apply a Soul edit previously proposed by update_expert_soul, after "
+ "the user has approved the diff. Takes only the confirmation_id "
+ "from that preview and applies the stored proposal exactly as "
+ "previewed; the id is single-use."
+ )
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "confirmation_id": {
+ "type": "string",
+ "description": "The confirmation_id returned by update_expert_soul.",
+ },
+ },
+ "required": ["confirmation_id"],
+ }
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ *,
+ confirmation_id: str = "",
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id
+ if error := _session_guard(user_id, session):
+ return error
+ assert user_id is not None
+ assert session.expert_id is not None
+
+ if any(field in kwargs for field in _EDITABLE_FIELDS):
+ return ErrorResponse(
+ message=(
+ "confirm_expert_soul_update applies exactly the previewed "
+ "proposal and does not accept field values. Call "
+ "update_expert_soul to propose a different edit."
+ ),
+ session_id=session_id,
+ )
+ if not confirmation_id:
+ return ErrorResponse(
+ message="A confirmation_id from update_expert_soul is required.",
+ session_id=session_id,
+ )
+
+ redis = await get_redis_async()
+ proposal = await load_bound_proposal(
+ redis,
+ confirmation_id,
+ user_id,
+ session,
+ )
+ if isinstance(proposal, ErrorResponse):
+ return proposal
+ return await apply_proposal(
+ user_id,
+ session.expert_id,
+ session_id,
+ proposal,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/update_soul_test.py b/autogpt_platform/backend/backend/copilot/tools/update_soul_test.py
new file mode 100644
index 0000000000..758d4a4787
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/update_soul_test.py
@@ -0,0 +1,399 @@
+"""Tests for the two-step Soul edit flow (preview + confirm-by-id)."""
+
+import asyncio
+from contextlib import contextmanager
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from ._test_data import make_session
+from .models import ErrorResponse, ExpertSoulUpdatedResponse
+from .soul_proposal import proposal_key
+from .update_soul import ConfirmExpertSoulUpdateTool, UpdateExpertSoulTool
+
+_TEST_USER_ID = "test-user-update-soul"
+_MODULE = "backend.copilot.tools.update_soul"
+_PROPOSAL_MODULE = "backend.copilot.tools.soul_proposal"
+
+
+class _FakeRedis:
+ """Minimal async Redis: just the setex/get/delete surface the tools use."""
+
+ def __init__(self):
+ self.store: dict[str, str] = {}
+
+ async def setex(self, key, ttl, value):
+ self.store[key] = value
+
+ async def get(self, key):
+ value = self.store.get(key)
+ return value.encode() if value is not None else None
+
+ async def delete(self, key):
+ return 1 if self.store.pop(key, None) is not None else 0
+
+
+class _ConcurrentReadRedis(_FakeRedis):
+ """Hold both GETs until they have read the same proposal."""
+
+ def __init__(self):
+ super().__init__()
+ self.readers = 0
+ self.both_read = asyncio.Event()
+
+ async def get(self, key):
+ value = await super().get(key)
+ self.readers += 1
+ if self.readers == 2:
+ self.both_read.set()
+ await asyncio.wait_for(self.both_read.wait(), timeout=5)
+ return value
+
+
+def _current_expert():
+ return SimpleNamespace(
+ identity="Old identity.",
+ voice_preferences="Old voice.",
+ boundaries="Old boundaries.",
+ )
+
+
+@contextmanager
+def _patch_databases(mock_db):
+ with (
+ patch(f"{_MODULE}.experts_db", MagicMock(return_value=mock_db)),
+ patch(f"{_PROPOSAL_MODULE}.experts_db", MagicMock(return_value=mock_db)),
+ ):
+ yield
+
+
+def _mock_env(*, expert=None, applied=True, redis=None):
+ mock_db = MagicMock()
+ mock_db.get_expert = AsyncMock(return_value=expert)
+ mock_db.update_soul_fields_if_current = AsyncMock(return_value=applied)
+ patchers = [
+ _patch_databases(mock_db),
+ patch(
+ f"{_MODULE}.get_redis_async",
+ AsyncMock(return_value=redis or _FakeRedis()),
+ ),
+ ]
+ return mock_db, patchers
+
+
+async def _preview(session, **fields):
+ return await UpdateExpertSoulTool()._execute(
+ user_id=_TEST_USER_ID, session=session, **fields
+ )
+
+
+async def _confirm(session, **kwargs):
+ return await ConfirmExpertSoulUpdateTool()._execute(
+ user_id=_TEST_USER_ID, session=session, **kwargs
+ )
+
+
[email protected](loop_scope="session")
+async def test_preview_never_writes_even_with_confirm_true():
+ """A model-supplied confirm flag must be inert: the preview tool has no
+ write path, so nothing it is called with can cause a write."""
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ resp = await _preview(session, voice_preferences="New voice.", confirm=True)
+ assert isinstance(resp, ExpertSoulUpdatedResponse)
+ assert resp.applied is False
+ assert resp.confirmation_id
+ assert [(c.field, c.before, c.after) for c in resp.changes] == [
+ ("voice_preferences", "Old voice.", "New voice.")
+ ]
+ mock_db.update_soul_fields_if_current.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_confirm_applies_exact_previewed_proposal():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await _preview(session, voice_preferences="New voice.")
+ assert isinstance(preview, ExpertSoulUpdatedResponse)
+ resp = await _confirm(session, confirmation_id=preview.confirmation_id)
+ assert isinstance(resp, ExpertSoulUpdatedResponse)
+ assert resp.applied is True
+ assert [(c.field, c.before, c.after) for c in resp.changes] == [
+ ("voice_preferences", "Old voice.", "New voice.")
+ ]
+ mock_db.update_soul_fields_if_current.assert_awaited_once_with(
+ _TEST_USER_ID,
+ "exp-1",
+ voice_preferences="New voice.",
+ expected_voice_preferences="Old voice.",
+ )
+
+
[email protected](loop_scope="session")
+async def test_confirm_rejects_field_values():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await _preview(session, voice_preferences="New voice.")
+ assert isinstance(preview, ExpertSoulUpdatedResponse)
+ resp = await _confirm(
+ session,
+ confirmation_id=preview.confirmation_id,
+ identity="Sneaky replacement.",
+ )
+ assert isinstance(resp, ErrorResponse)
+ mock_db.update_soul_fields_if_current.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_confirmation_id_is_single_use():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await _preview(session, voice_preferences="New voice.")
+ assert isinstance(preview, ExpertSoulUpdatedResponse)
+ first = await _confirm(session, confirmation_id=preview.confirmation_id)
+ second = await _confirm(session, confirmation_id=preview.confirmation_id)
+ assert isinstance(first, ExpertSoulUpdatedResponse) and first.applied is True
+ assert isinstance(second, ErrorResponse)
+ mock_db.update_soul_fields_if_current.assert_awaited_once()
+
+
[email protected](loop_scope="session")
+async def test_concurrent_confirms_apply_exactly_once():
+ redis = _ConcurrentReadRedis()
+ mock_db, patchers = _mock_env(expert=_current_expert(), redis=redis)
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await _preview(session, voice_preferences="New voice.")
+ assert isinstance(preview, ExpertSoulUpdatedResponse)
+ results = await asyncio.gather(
+ _confirm(session, confirmation_id=preview.confirmation_id),
+ _confirm(session, confirmation_id=preview.confirmation_id),
+ )
+
+ assert sum(isinstance(result, ExpertSoulUpdatedResponse) for result in results) == 1
+ assert sum(isinstance(result, ErrorResponse) for result in results) == 1
+ mock_db.update_soul_fields_if_current.assert_awaited_once()
+
+
[email protected](loop_scope="session")
+async def test_confirm_rejects_stale_before_state():
+ """A Soul that changed between preview and confirm discards the proposal."""
+ mock_db, patchers = _mock_env(expert=_current_expert(), applied=False)
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await _preview(session, voice_preferences="New voice.")
+ assert isinstance(preview, ExpertSoulUpdatedResponse)
+ resp = await _confirm(session, confirmation_id=preview.confirmation_id)
+ assert isinstance(resp, ErrorResponse)
+ assert "changed since" in resp.message
+ mock_db.update_soul_fields_if_current.assert_awaited_once_with(
+ _TEST_USER_ID,
+ "exp-1",
+ voice_preferences="New voice.",
+ expected_voice_preferences="Old voice.",
+ )
+
+
[email protected](loop_scope="session")
+async def test_confirm_rejects_unknown_id():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ resp = await _confirm(session, confirmation_id="never-issued")
+ assert isinstance(resp, ErrorResponse)
+ mock_db.update_soul_fields_if_current.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_confirm_rejects_proposal_from_other_session():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session_a = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await _preview(session_a, voice_preferences="New voice.")
+ assert isinstance(preview, ExpertSoulUpdatedResponse)
+ session_b = make_session(_TEST_USER_ID, expert_id="exp-1")
+ rejected = await _confirm(session_b, confirmation_id=preview.confirmation_id)
+ accepted = await _confirm(session_a, confirmation_id=preview.confirmation_id)
+ assert isinstance(rejected, ErrorResponse)
+ assert isinstance(accepted, ExpertSoulUpdatedResponse)
+ mock_db.update_soul_fields_if_current.assert_awaited_once()
+
+
[email protected](loop_scope="session")
+async def test_preview_plain_session_refuses():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID) # no expert_id
+ resp = await _preview(session, identity="x")
+ assert isinstance(resp, ErrorResponse)
+ mock_db.get_expert.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_confirm_plain_session_refuses():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID) # no expert_id
+ resp = await _confirm(session, confirmation_id="anything")
+ assert isinstance(resp, ErrorResponse)
+ mock_db.update_soul_fields_if_current.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_preview_no_fields_rejected():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ resp = await _preview(session)
+ assert isinstance(resp, ErrorResponse)
+ mock_db.update_soul_fields_if_current.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_preview_noop_when_values_match_current():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ resp = await _preview(session, voice_preferences="Old voice.")
+ assert isinstance(resp, ErrorResponse)
+ mock_db.update_soul_fields_if_current.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_preview_missing_expert_errors():
+ mock_db, patchers = _mock_env(expert=None)
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ resp = await _preview(session, identity="x")
+ assert isinstance(resp, ErrorResponse)
+ mock_db.update_soul_fields_if_current.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_both_tools_require_authentication():
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await UpdateExpertSoulTool()._execute(
+ user_id=None, session=session, identity="x"
+ )
+ confirm = await ConfirmExpertSoulUpdateTool()._execute(
+ user_id=None, session=session, confirmation_id="anything"
+ )
+ assert isinstance(preview, ErrorResponse)
+ assert isinstance(confirm, ErrorResponse)
+
+
[email protected](loop_scope="session")
+async def test_preview_rejects_blank_identity_before_storing():
+ """Invalid input must die at preview — never become a stored proposal
+ that explodes after the user has already approved the diff."""
+ fake_redis = _FakeRedis()
+ mock_db, patchers = _mock_env(expert=_current_expert(), redis=fake_redis)
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ resp = await _preview(session, identity=" ")
+ assert isinstance(resp, ErrorResponse)
+ assert "identity" in resp.message
+ assert fake_redis.store == {}
+ mock_db.update_soul_fields_if_current.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_preview_rejects_overlong_field():
+ fake_redis = _FakeRedis()
+ mock_db, patchers = _mock_env(expert=_current_expert(), redis=fake_redis)
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ resp = await _preview(session, voice_preferences="x" * 4_001)
+ assert isinstance(resp, ErrorResponse)
+ assert fake_redis.store == {}
+ mock_db.update_soul_fields_if_current.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_preview_strips_whitespace_so_diff_matches_persisted():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await _preview(session, voice_preferences=" New voice. ")
+ assert isinstance(preview, ExpertSoulUpdatedResponse)
+ assert [(c.field, c.after) for c in preview.changes] == [
+ ("voice_preferences", "New voice.")
+ ]
+ resp = await _confirm(session, confirmation_id=preview.confirmation_id)
+ assert isinstance(resp, ExpertSoulUpdatedResponse) and resp.applied is True
+ mock_db.update_soul_fields_if_current.assert_awaited_once_with(
+ _TEST_USER_ID,
+ "exp-1",
+ voice_preferences="New voice.",
+ expected_voice_preferences="Old voice.",
+ )
+
+
[email protected](loop_scope="session")
+async def test_confirm_rejects_other_user():
+ """The proposal.user_id binding is the core authz boundary: an id issued
+ to one user must be useless to any other."""
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await _preview(session, voice_preferences="New voice.")
+ assert isinstance(preview, ExpertSoulUpdatedResponse)
+ resp = await ConfirmExpertSoulUpdateTool()._execute(
+ user_id="some-other-user",
+ session=session,
+ confirmation_id=preview.confirmation_id,
+ )
+ accepted = await _confirm(session, confirmation_id=preview.confirmation_id)
+ assert isinstance(resp, ErrorResponse)
+ assert isinstance(accepted, ExpertSoulUpdatedResponse)
+ mock_db.update_soul_fields_if_current.assert_awaited_once()
+
+
[email protected](loop_scope="session")
+async def test_confirm_rejects_other_expert():
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ with patchers[0], patchers[1]:
+ session_a = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await _preview(session_a, voice_preferences="New voice.")
+ assert isinstance(preview, ExpertSoulUpdatedResponse)
+ session_b = make_session(_TEST_USER_ID, expert_id="exp-2")
+ resp = await _confirm(session_b, confirmation_id=preview.confirmation_id)
+ accepted = await _confirm(session_a, confirmation_id=preview.confirmation_id)
+ assert isinstance(resp, ErrorResponse)
+ assert isinstance(accepted, ExpertSoulUpdatedResponse)
+ mock_db.update_soul_fields_if_current.assert_awaited_once()
+
+
[email protected](loop_scope="session")
+async def test_confirm_recovers_from_corrupt_stored_proposal():
+ fake_redis = _FakeRedis()
+ fake_redis.store[proposal_key("corrupt-id")] = "{not valid json"
+ mock_db, patchers = _mock_env(expert=_current_expert(), redis=fake_redis)
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ resp = await _confirm(session, confirmation_id="corrupt-id")
+ assert isinstance(resp, ErrorResponse)
+ assert "fresh preview" in resp.message
+ mock_db.update_soul_fields_if_current.assert_not_called()
+
+
[email protected](loop_scope="session")
+async def test_apply_failure_returns_recoverable_error():
+ """The id is already consumed when the write runs, so a surprise failure
+ must come back as guidance to re-preview, not an uncaught exception."""
+ mock_db, patchers = _mock_env(expert=_current_expert())
+ mock_db.update_soul_fields_if_current.side_effect = RuntimeError(
+ "db transport down"
+ )
+ with patchers[0], patchers[1]:
+ session = make_session(_TEST_USER_ID, expert_id="exp-1")
+ preview = await _preview(session, voice_preferences="New voice.")
+ assert isinstance(preview, ExpertSoulUpdatedResponse)
+ resp = await _confirm(session, confirmation_id=preview.confirmation_id)
+ assert isinstance(resp, ErrorResponse)
+ assert "re-preview" in resp.message
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index ad704a432f..c9245d8cc8 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -499,6 +499,8 @@ class DatabaseManager(AppService):
get_expert = _(experts_db.get_expert)
list_experts = _(experts_db.list_experts)
enforce_expert_run_budget = _(experts_scheduling.enforce_expert_run_budget)
+ update_soul_fields = _(experts_db.update_soul_fields)
+ update_soul_fields_if_current = _(experts_db.update_soul_fields_if_current)
# ============ CoPilot Chat Sessions ============ #
# NOTE: no eager-load `get_chat_session` here — callers go through
@@ -819,6 +821,8 @@ class DatabaseManagerAsyncClient(AppServiceClient):
get_expert = d.get_expert
list_experts = d.list_experts
enforce_expert_run_budget = d.enforce_expert_run_budget
+ update_soul_fields = d.update_soul_fields
+ update_soul_fields_if_current = d.update_soul_fields_if_current
# ============ CoPilot Chat Sessions ============ #
get_chat_session_metadata = d.get_chat_session_metadata
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index cb3707e0f3..2abdaa1b21 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -3353,7 +3353,8 @@
{
"$ref": "#/components/schemas/MemoryForgetConfirmResponse"
},
- { "$ref": "#/components/schemas/TodoWriteResponse" }
+ { "$ref": "#/components/schemas/TodoWriteResponse" },
+ { "$ref": "#/components/schemas/ExpertSoulUpdatedResponse" }
],
"title": "Response Getv2[Dummy] Tool Response Type Export For Codegen"
}
@@ -17797,6 +17798,37 @@
"required": ["name", "identity", "voice_preferences", "boundaries"],
"title": "ExpertSoulUpdate"
},
+ "ExpertSoulUpdatedResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "expert_soul_updated"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "applied": {
+ "type": "boolean",
+ "title": "Applied",
+ "default": false
+ },
+ "changes": {
+ "items": { "$ref": "#/components/schemas/SoulFieldChange" },
+ "type": "array",
+ "title": "Changes"
+ },
+ "confirmation_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Confirmation Id"
+ }
+ },
+ "type": "object",
+ "required": ["message"],
+ "title": "ExpertSoulUpdatedResponse",
+ "description": "Response for the two-step Soul edit tools.\n\nCarries the diff so the model must surface exactly what changed. ``applied``\nis False for the update_expert_soul preview (nothing written yet; the\none-time ``confirmation_id`` references the stored proposal) and True once\nconfirm_expert_soul_update saves the edit."
+ },
"ExpertWorkflowRef": {
"properties": {
"id": { "type": "string", "title": "Id" },
@@ -22847,7 +22879,8 @@
"skill_stored",
"skill_loaded",
"skill_deleted",
- "skill_list"
+ "skill_list",
+ "expert_soul_updated"
],
"title": "ResponseType",
"description": "Types of tool responses."
@@ -23750,6 +23783,21 @@
"title": "SkippedWebhookPreset",
"description": "A webhook preset that was left pinned to its old version because the\nnewly activated version swaps or reconfigures the trigger block. The user\nneeds to reconfigure the trigger on the new version for it to fire."
},
+ "SoulFieldChange": {
+ "properties": {
+ "field": {
+ "type": "string",
+ "enum": ["identity", "voice_preferences", "boundaries"],
+ "title": "Field"
+ },
+ "before": { "type": "string", "title": "Before" },
+ "after": { "type": "string", "title": "After" }
+ },
+ "type": "object",
+ "required": ["field", "before", "after"],
+ "title": "SoulFieldChange",
+ "description": "One field's before/after values for an expert soul edit."
+ },
"Stats": {
"properties": {
"cost": {