AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(backend): pause expert work for approval once her spend reaches the threshold (#14420)
Reinier van der Leer051d6b811039
diff --git a/autogpt_platform/backend/backend/api/features/experts/scheduling.py b/autogpt_platform/backend/backend/api/features/experts/scheduling.pyindex 0d999e1cc8..c61d23cb78 100644--- a/autogpt_platform/backend/backend/api/features/experts/scheduling.py+++ b/autogpt_platform/backend/backend/api/features/experts/scheduling.py@@ -309,8 +309,9 @@ async def resume_expert_schedules(user_id: str, expert_id: str) -> bool:async def enforce_expert_run_budget(user_id: str, expert_id: str) -> None:- """Run-start gate for expert-attributed executions (schedules and- triggers; chat runs never carry an expert_id and are never gated).+ """Run-start gate for expert-attributed executions: schedules, triggers,+ and agent runs launched from an expert's chat (``run_agent`` passes the+ session's expert_id). Chat turns and ``run_block`` are not executions.Raises ExpertRunPausedError when the expert is archived, paused, or hashit her weekly credit budget — breaching pauses her and posts andiff --git a/autogpt_platform/backend/backend/api/features/experts/spend_approval.py b/autogpt_platform/backend/backend/api/features/experts/spend_approval.pynew file mode 100644index 0000000000..652fca64d7--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/spend_approval.py@@ -0,0 +1,251 @@+"""Spend-approval gate for expert work (SECRT-2599).++The weekly budget (``scheduling.enforce_expert_run_budget``) is the hard stop+that pauses an expert's schedules. This is the softer line below it: once her+credit spend in the window reaches the approval threshold, new work is parked+as a ``PendingHumanReview`` row — the row Home's "Needs You" list, the run+page and the chat card already render and decide — and proceeds once the+user approves. One approval unlocks the rest of the window.+"""++import logging+import uuid++import prisma.models+from prisma.enums import ResourceVisibility, ReviewStatus+from pydantic import BaseModel++from backend.copilot import db as chat_db+from backend.copilot.constants import (+ COPILOT_NODE_EXEC_ID_SEPARATOR,+ COPILOT_NODE_PREFIX,+ COPILOT_SESSION_PREFIX,+)+from backend.data import human_review+from backend.data.execution import ExecutionStatus, update_graph_execution_stats+from backend.data.expert_spend import SpendWindow, get_spend, window_start+from backend.util.feature_flag import Flag, is_feature_enabled+from backend.util.settings import Settings++logger = logging.getLogger(__name__)+settings = Settings()++# Present in every spend-approval review id, on both the graph-execution and+# the chat shape, so one ``contains`` lookup finds an expert's decisions.+SPEND_REVIEW_MARKER = "expert-spend:"+_POST_NAMESPACE = uuid.UUID("2b7d1c4e-5a6f-4e8b-9c0d-1e2f3a4b5c6d")+++class SpendApprovalParkFailed(Exception):+ """The execution could not be held, so it must not be allowed to run."""+++class SpendApprovalNeeded(BaseModel):+ expert_id: str+ expert_name: str+ spent: int+ threshold: int+ window: SpendWindow++ @property+ def period(self) -> str:+ return "this week" if self.window == "week" else "today"++ @property+ def headline(self) -> str:+ return (+ f"{self.expert_name} has used {self.spent} of {self.threshold} credits "+ f"{self.period} and needs your approval to keep spending"+ )+++def approval_threshold() -> int | None:+ """Credits per window before work waits for approval; None = disabled."""+ value = settings.config.expert_spend_approval_threshold_default+ return value if value > 0 else None+++def approval_window() -> SpendWindow:+ return settings.config.expert_spend_approval_window+++def is_spend_review(node_exec_id: str) -> bool:+ return SPEND_REVIEW_MARKER in node_exec_id+++def spend_review_id(expert_id: str, graph_exec_id: str) -> str:+ return f"{SPEND_REVIEW_MARKER}{expert_id}:{graph_exec_id}"+++async def spend_approval_required(+ user_id: str, expert_id: str+) -> SpendApprovalNeeded | None:+ """What the user must approve before this expert spends more, or None+ when she may proceed: check disabled, spend below the threshold, or an+ approval already given in the current window.++ Like the weekly gate, the spend read is a snapshot: concurrent starts can+ each pass before any of them meters, bounded by their own cost."""+ threshold = approval_threshold()+ if threshold is None:+ return None+ if not await is_feature_enabled(Flag.EXPERT_SPEND_APPROVAL, user_id):+ return None+ window = approval_window()+ spent = await get_spend(expert_id, window)+ if spent < threshold:+ return None+ if await _approved_in_window(user_id, expert_id, window):+ return None+ expert = await prisma.models.Expert.prisma().find_first(+ where={+ "id": expert_id,+ "ownerUserId": user_id,+ "isTemplate": False,+ "visibility": ResourceVisibility.PRIVATE,+ }+ )+ return SpendApprovalNeeded(+ expert_id=expert_id,+ expert_name=expert.name if expert else "Your expert",+ spent=spent,+ threshold=threshold,+ window=window,+ )+++async def _approved_in_window(+ user_id: str, expert_id: str, window: SpendWindow+) -> bool:+ row = await prisma.models.PendingHumanReview.prisma().find_first(+ where={+ "userId": user_id,+ "nodeExecId": {"contains": f"{SPEND_REVIEW_MARKER}{expert_id}:"},+ "status": ReviewStatus.APPROVED,+ "reviewedAt": {"gte": window_start(window)},+ }+ )+ return row is not None+++async def park_execution_for_spend_approval(+ user_id: str,+ graph_exec_id: str,+ graph_id: str,+ graph_version: int,+ needed: SpendApprovalNeeded,+ organization_id: str | None = None,+ team_id: str | None = None,+) -> None:+ """Hold a just-created, unpublished execution: one review row keyed on+ it, status REVIEW so the run page shows the approval, and one message in+ the expert's thread per window."""+ review_id = spend_review_id(needed.expert_id, graph_exec_id)+ await human_review.get_or_create_human_review(+ user_id=user_id,+ node_exec_id=review_id,+ graph_exec_id=graph_exec_id,+ graph_id=graph_id,+ graph_version=graph_version,+ input_data=_review_payload(needed),+ message=needed.headline,+ editable=False,+ organization_id=organization_id,+ team_id=team_id,+ )+ if (+ await update_graph_execution_stats(+ graph_exec_id=graph_exec_id, status=ExecutionStatus.REVIEW+ )+ is None+ ):+ # The resume gate reads the durable status, so a waiting review over an+ # execution left in another status is worse than no gate: the run+ # requeues unapproved while the card still asks. Undo and fail instead.+ await human_review.delete_review_by_node_exec_id(review_id, user_id)+ raise SpendApprovalParkFailed(+ f"Execution #{graph_exec_id} could not be set to REVIEW"+ )+ await _post_thread_message(user_id, needed)+++async def parked_spend_decision(+ user_id: str, expert_id: str, graph_exec_id: str+) -> ReviewStatus | None:+ """The user's decision on a parked execution; None when it was never parked."""+ review_id = spend_review_id(expert_id, graph_exec_id)+ reviews = await human_review.get_reviews_by_node_exec_ids([review_id], user_id)+ review = reviews.get(review_id)+ return review.status if review else None+++async def open_chat_spend_review(+ user_id: str,+ session_id: str,+ needed: SpendApprovalNeeded,+ block_name: str,+ organization_id: str | None = None,+ team_id: str | None = None,+) -> str:+ """Park a paid ``run_block`` on the session's review rails and return the+ review id. An open row for the same expert is reused so a model retry+ does not stack cards."""+ synthetic_graph_id = f"{COPILOT_SESSION_PREFIX}{session_id}"+ node_id = f"{COPILOT_NODE_PREFIX}{SPEND_REVIEW_MARKER}{needed.expert_id}"+ for review in await human_review.get_pending_reviews_for_execution(+ synthetic_graph_id, user_id+ ):+ if review.node_id == node_id:+ return review.node_exec_id+ review_id = f"{node_id}{COPILOT_NODE_EXEC_ID_SEPARATOR}{uuid.uuid4().hex[:8]}"+ await human_review.get_or_create_human_review(+ user_id=user_id,+ node_exec_id=review_id,+ graph_exec_id=synthetic_graph_id,+ graph_id=synthetic_graph_id,+ graph_version=1,+ input_data=_review_payload(needed, block=block_name),+ message=needed.headline,+ editable=False,+ organization_id=organization_id,+ team_id=team_id,+ )+ return review_id+++def _review_payload(needed: SpendApprovalNeeded, block: str | None = None) -> dict:+ payload: dict = {+ "expert": needed.expert_name,+ "spent_credits": needed.spent,+ "threshold_credits": needed.threshold,+ "window": needed.window,+ }+ if block:+ payload["block"] = block+ return payload+++async def _post_thread_message(user_id: str, needed: SpendApprovalNeeded) -> None:+ """Once per expert per window, deduplicated by message id. Never raises —+ a failed post must not affect the park."""+ bucket = window_start(needed.window).date().isoformat()+ message_id = str(+ uuid.uuid5(_POST_NAMESPACE, f"spend-approval:{needed.expert_id}:{bucket}")+ )+ content = (+ f"I've used {needed.spent} of my {needed.threshold} credits "+ f"{needed.period}, so I'm holding new work until you approve more "+ "spending — it's waiting under Needs You on your Home page."+ )+ try:+ await chat_db.append_expert_run_message(+ user_id=user_id,+ expert_id=needed.expert_id,+ content=content,+ message_id=message_id,+ )+ except Exception as e:+ logger.warning(+ f"Failed to post spend-approval message for expert "+ f"#{needed.expert_id}: {type(e).__name__}: {e}"+ )diff --git a/autogpt_platform/backend/backend/api/features/experts/spend_approval_routes_test.py b/autogpt_platform/backend/backend/api/features/experts/spend_approval_routes_test.pynew file mode 100644index 0000000000..38b6a44334--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/spend_approval_routes_test.py@@ -0,0 +1,159 @@+"""Every route that starts expert work reaches the same spend-approval seam+(SECRT-2599): with the expert at her threshold, the run is created, parked+unpublished, and nothing else happens. Chat's ``run_block`` path is covered in+``copilot/tools/run_block_test.py``; ``delegate_to_expert`` and scheduled+copilot turns open a session scoped to the expert (their own tests pin that)+and then spend through these same seams."""++from unittest.mock import AsyncMock, MagicMock++import pytest++from backend.executor.utils_test import (+ _mock_add_graph_execution_create_path,+ _mock_expert_personal_tenancy,+ _mock_spend_gate,+ _spend_needed,+)+++def parked(mocker):+ """Seam A armed at the threshold; yields (park, queue, create)."""+ mock_edb, _ = _mock_add_graph_execution_create_path(mocker)+ _mock_expert_personal_tenancy(mocker)+ _, park, queue = _mock_spend_gate(mocker, _spend_needed())+ return park, queue, mock_edb.create_graph_execution+++def _assert_parked(park, queue, create, *, expert_id: str = "expert-1") -> None:+ park.assert_awaited_once()+ assert park.await_args.kwargs["graph_exec_id"] == "exec-id"+ assert create.await_args.kwargs["expert_id"] == expert_id+ queue.publish_message.assert_not_awaited()+++async def test_schedule_fire_is_parked(mocker, parked) -> None:+ from backend.executor import scheduler++ park, queue, create = parked+ mocker.patch.object(+ scheduler,+ "get_database_manager_async_client",+ return_value=MagicMock(increment_onboarding_runs=AsyncMock()),+ )+ args = scheduler.GraphExecutionJobArgs(+ user_id="owner",+ graph_id="g",+ graph_version=1,+ cron="0 9 * * *",+ input_data={},+ organization_id="org",+ team_id="team",+ expert_id="expert-1",+ schedule_id="sched-1",+ )++ await scheduler._execute_graph(**args.model_dump())++ _assert_parked(park, queue, create)+++async def test_webhook_trigger_is_parked(mocker, parked) -> None:+ from backend.api.features.integrations import router as ingress++ park, queue, create = parked+ mocker.patch.object(+ ingress,+ "experts_db",+ return_value=MagicMock(+ resolve_private_expert_tenancy=AsyncMock(return_value=("org", "team"))+ ),+ )+ trigger_node = MagicMock(id="node-1")+ trigger_node.block.is_triggered_by_event_type.return_value = True+ mocker.patch.object(+ ingress,+ "get_graph",+ AsyncMock(return_value=MagicMock(webhook_input_node=trigger_node)),+ )+ preset = MagicMock(+ id="preset-1",+ user_id="owner",+ is_active=True,+ expert_id="expert-1",+ graph_id="g",+ graph_version=1,+ inputs={},+ credentials={},+ )+ webhook = MagicMock(id="wh-1", user_id="owner")++ await ingress._execute_webhook_preset_trigger(preset, webhook, "wh-1", "push", {})++ _assert_parked(park, queue, create)+++async def test_preset_api_run_is_parked(mocker, parked) -> None:+ from backend.api.features.library.routes import presets as presets_routes++ park, queue, create = parked+ preset = MagicMock(+ graph_id="g",+ graph_version=1,+ inputs={},+ credentials={},+ expert_id="expert-1",+ organization_id="org",+ team_id="team",+ )+ mocker.patch.object(presets_routes.db, "get_preset", AsyncMock(return_value=preset))++ result = await presets_routes.execute_preset(+ preset_id="preset-1",+ user_id="owner",+ ctx=MagicMock(org_id="org", team_id="team"),+ inputs={},+ credential_inputs={},+ )++ assert result.status.value == "REVIEW"+ _assert_parked(park, queue, create)+++async def test_run_agent_from_expert_chat_is_parked_and_says_so(mocker, parked) -> None:+ from backend.copilot.tools import run_agent as run_agent_mod+ from backend.copilot.tools._test_data import make_session+ from backend.copilot.tools.models import ExecutionStartedResponse++ park, queue, create = parked+ library_agent = MagicMock(id="lib-1", graph_id="g")+ library_agent.name = "Weekly report"+ mocker.patch.object(+ run_agent_mod,+ "get_or_create_library_agent",+ AsyncMock(return_value=library_agent),+ )+ mocker.patch.object(run_agent_mod, "emit_tool_display_name")+ mocker.patch.object(run_agent_mod, "track_agent_run_success")+ mocker.patch.object(run_agent_mod, "_safe_link_to_chat_share", AsyncMock())+ session = make_session(user_id="owner", expert_id="expert-1")++ response = await run_agent_mod.RunAgentTool()._run_agent(+ user_id="owner",+ session=session,+ graph=MagicMock(id="g"),+ graph_credentials={},+ inputs={},+ dry_run=False,+ )++ assert isinstance(response, ExecutionStartedResponse)+ assert response.status == "REVIEW"+ assert "approval" in response.message+ _assert_parked(park, queue, create)+ assert session.successful_agent_runs.get("g", 0) == 0diff --git a/autogpt_platform/backend/backend/api/features/experts/spend_approval_test.py b/autogpt_platform/backend/backend/api/features/experts/spend_approval_test.pynew file mode 100644index 0000000000..feac321475--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/spend_approval_test.py@@ -0,0 +1,241 @@+from unittest.mock import AsyncMock, MagicMock++import prisma.models+import pytest+from prisma.enums import ReviewStatus++from backend.api.features.experts import spend_approval as sa+from backend.data.expert_spend import window_start+from backend.util.settings import Config++NEEDED = sa.SpendApprovalNeeded(+ expert_id="e-1", expert_name="Ada", spent=250, threshold=250, window="week"+)+++def _arm(+ mocker,+ *,+ spent: int,+ threshold: int | None = 250,+ window: str = "week",+ flag: bool = True,+ approved: bool = False,+):+ mocker.patch.object(sa, "approval_threshold", return_value=threshold)+ mocker.patch.object(sa, "approval_window", return_value=window)+ mocker.patch.object(sa, "is_feature_enabled", AsyncMock(return_value=flag))+ get_spend = mocker.patch.object(sa, "get_spend", AsyncMock(return_value=spent))+ reviews = MagicMock(+ find_first=AsyncMock(return_value=MagicMock() if approved else None)+ )+ mocker.patch.object(+ prisma.models.PendingHumanReview, "prisma", return_value=reviews+ )+ expert = MagicMock()+ expert.name = "Ada"+ mocker.patch.object(+ prisma.models.Expert,+ "prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=expert)),+ )+ return get_spend, reviews++[email protected]("spent,expected", [(249, None), (250, NEEDED)])+async def test_check_fires_at_the_threshold_not_below(mocker, spent, expected) -> None:+ _arm(mocker, spent=spent)++ assert await sa.spend_approval_required("owner", "e-1") == expected++[email protected]("threshold,flag", [(None, True), (250, False)])+async def test_disabled_check_reads_no_spend(mocker, threshold, flag) -> None:+ get_spend, _ = _arm(mocker, spent=1_000, threshold=threshold, flag=flag)++ assert await sa.spend_approval_required("owner", "e-1") is None+ get_spend.assert_not_awaited()++[email protected]("window", ["week", "day"])+async def test_an_approval_in_the_window_unlocks_it(mocker, window) -> None:+ get_spend, reviews = _arm(mocker, spent=999, window=window, approved=True)++ assert await sa.spend_approval_required("owner", "e-1") is None++ get_spend.assert_awaited_once_with("e-1", window)+ where = reviews.find_first.call_args.kwargs["where"]+ assert where["userId"] == "owner"+ assert where["nodeExecId"] == {"contains": "expert-spend:e-1:"}+ assert where["status"] == ReviewStatus.APPROVED+ assert where["reviewedAt"] == {"gte": window_start(window)}+++def test_headline_names_the_expert_and_avoids_the_card_discriminator() -> None:+ assert NEEDED.headline == (+ "Ada has used 250 of 250 credits this week and needs your approval "+ "to keep spending"+ )+ # PendingReviewCard drops any instructions containing "Block".+ assert "Block" not in NEEDED.headline+++def test_defaults_are_250_credits_per_iso_week() -> None:+ fields = Config.model_fields+ assert fields["expert_spend_approval_threshold_default"].default == 250+ assert fields["expert_spend_approval_window"].default == "week"+++def test_spend_review_ids_are_recognised_on_both_rails() -> None:+ assert sa.is_spend_review(sa.spend_review_id("e-1", "exec-9"))+ assert sa.is_spend_review("copilot-node-expert-spend:e-1:abcd1234")+ assert not sa.is_spend_review("3f1a0c2e-node-exec")+++def _park_mocks(mocker):+ create = mocker.patch.object(+ sa.human_review, "get_or_create_human_review", AsyncMock(return_value=None)+ )+ status = mocker.patch.object(+ sa, "update_graph_execution_stats", AsyncMock(return_value=MagicMock())+ )+ post = mocker.patch.object(+ sa.chat_db, "append_expert_run_message", AsyncMock(return_value="msg")+ )+ return create, status, post+++async def test_park_opens_a_review_on_the_run_and_sets_review_status(mocker) -> None:+ create, status, post = _park_mocks(mocker)++ await sa.park_execution_for_spend_approval(+ user_id="owner",+ graph_exec_id="exec-9",+ graph_id="graph",+ graph_version=3,+ needed=NEEDED,+ organization_id="org",+ team_id="team",+ )++ kwargs = create.await_args.kwargs+ assert kwargs["node_exec_id"] == "expert-spend:e-1:exec-9"+ assert kwargs["graph_exec_id"] == "exec-9"+ assert kwargs["message"] == NEEDED.headline+ assert kwargs["editable"] is False+ assert kwargs["input_data"]["spent_credits"] == 250+ assert kwargs["organization_id"] == "org"+ status.assert_awaited_once_with(+ graph_exec_id="exec-9", status=sa.ExecutionStatus.REVIEW+ )+ assert post.await_args.kwargs["expert_id"] == "e-1"+++async def test_a_park_that_cannot_hold_the_run_undoes_its_review_and_raises(+ mocker,+) -> None:+ """A waiting card over an execution that is not in REVIEW is worse than no+ gate: the resume path reads the durable status, so it would skip the check+ and requeue unapproved."""+ _, status, post = _park_mocks(mocker)+ status.return_value = None+ delete = mocker.patch.object(+ sa.human_review, "delete_review_by_node_exec_id", AsyncMock(return_value=1)+ )++ with pytest.raises(sa.SpendApprovalParkFailed):+ await sa.park_execution_for_spend_approval(+ user_id="owner",+ graph_exec_id="exec-9",+ graph_id="graph",+ graph_version=3,+ needed=NEEDED,+ )++ delete.assert_awaited_once_with("expert-spend:e-1:exec-9", "owner")+ post.assert_not_awaited()+++async def test_thread_message_is_posted_once_per_window(mocker) -> None:+ _, _, post = _park_mocks(mocker)++ for exec_id in ("exec-1", "exec-2"):+ await sa.park_execution_for_spend_approval(+ user_id="owner",+ graph_exec_id=exec_id,+ graph_id="graph",+ graph_version=1,+ needed=NEEDED,+ )++ ids = {c.kwargs["message_id"] for c in post.await_args_list}+ assert len(ids) == 1+++async def test_parked_decision_reads_the_run_review(mocker) -> None:+ review_id = sa.spend_review_id("e-1", "exec-9")+ lookup = mocker.patch.object(+ sa.human_review,+ "get_reviews_by_node_exec_ids",+ AsyncMock(return_value={review_id: MagicMock(status=ReviewStatus.REJECTED)}),+ )++ assert (+ await sa.parked_spend_decision("owner", "e-1", "exec-9")+ == ReviewStatus.REJECTED+ )+ lookup.assert_awaited_once_with([review_id], "owner")++ lookup.return_value = {}+ assert await sa.parked_spend_decision("owner", "e-1", "exec-9") is None+++async def test_chat_review_reuses_the_open_row_for_the_expert(mocker) -> None:+ existing = MagicMock(+ node_id="copilot-node-expert-spend:e-1",+ node_exec_id="copilot-node-expert-spend:e-1:abcd1234",+ )+ mocker.patch.object(+ sa.human_review,+ "get_pending_reviews_for_execution",+ AsyncMock(return_value=[existing]),+ )+ create = mocker.patch.object(+ sa.human_review, "get_or_create_human_review", AsyncMock()+ )++ review_id = await sa.open_chat_spend_review(+ user_id="owner", session_id="s-1", needed=NEEDED, block_name="Send Email"+ )++ assert review_id == existing.node_exec_id+ create.assert_not_awaited()+++async def test_chat_review_opens_on_the_session_rails(mocker) -> None:+ mocker.patch.object(+ sa.human_review, "get_pending_reviews_for_execution", AsyncMock(return_value=[])+ )+ create = mocker.patch.object(+ sa.human_review, "get_or_create_human_review", AsyncMock()+ )++ review_id = await sa.open_chat_spend_review(+ user_id="owner", session_id="s-1", needed=NEEDED, block_name="Send Email"+ )++ kwargs = create.await_args.kwargs+ assert review_id == kwargs["node_exec_id"]+ assert review_id.startswith("copilot-node-expert-spend:e-1:")+ assert kwargs["graph_exec_id"] == "copilot-session-s-1"+ assert kwargs["editable"] is False+ assert kwargs["input_data"]["block"] == "Send Email"diff --git a/autogpt_platform/backend/backend/api/features/home/attention.py b/autogpt_platform/backend/backend/api/features/home/attention.pyindex 4604defd47..9be0e37c1b 100644--- a/autogpt_platform/backend/backend/api/features/home/attention.py+++ b/autogpt_platform/backend/backend/api/features/home/attention.py@@ -4,6 +4,7 @@ from urllib.parse import quotefrom backend.api.features.executions.review.model import PendingHumanReviewModelfrom backend.api.features.experts.models import Expert+from backend.api.features.experts.spend_approval import is_spend_reviewfrom backend.copilot.briefing.outcome import as_utc, run_linkfrom backend.copilot.model import ChatSessionInfo, PendingQuestionfrom backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo@@ -44,13 +45,19 @@ def _review_attention() -> HomeAttentionItem:title = review.instructions or review.agent_name or "Review an agent decision"created_at = as_utc(review.created_at)+ if is_spend_review(review.node_exec_id):+ description = "Spending threshold reached; this work is on hold."+ why_it_matters = "It runs once you approve; declining cancels it."+ else:+ description = "Your agent paused before taking an external action."+ why_it_matters = "The task cannot continue until you approve or decline it."return HomeAttentionItem(id=f"approval-{review.node_exec_id}",kind="approval",priority=("high" if now - created_at > timedelta(hours=24) else "normal"),title=title,- description="Your agent paused before taking an external action.",- why_it_matters="The task cannot continue until you approve or decline it.",+ description=description,+ why_it_matters=why_it_matters,expert=_review_expert(review),agent_name=review.agent_name,created_at=created_at,diff --git a/autogpt_platform/backend/backend/api/features/home/attention_test.py b/autogpt_platform/backend/backend/api/features/home/attention_test.pyindex 4c3901392f..0e076afc00 100644--- a/autogpt_platform/backend/backend/api/features/home/attention_test.py+++ b/autogpt_platform/backend/backend/api/features/home/attention_test.py@@ -406,3 +406,17 @@ def test_one_session_asking_twice_yields_one_item() -> None:assert len(items) == 1assert items[0].description == "latest question only"+++def test_spend_hold_is_described_as_such() -> None:+ items = compose_attention_items(+ now=NOW,+ experts=[],+ reviews=[_review(NOW, node_exec_id="expert-spend:expert:exec-9")],+ schedules=[],+ credits_balance=100,+ )++ assert [item.kind for item in items] == ["approval"]+ assert items[0].title == "Send the prepared message"+ assert items[0].description == "Spending threshold reached; this work is on hold."diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.pyindex 5f57bfb406..8d76e91528 100644--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py@@ -24,8 +24,15 @@ from backend.copilot.sdk.env import config as chat_configfrom backend.copilot.sdk.file_ref import FileRefExpansionError, expand_file_refs_in_argsfrom backend.copilot.tool_display import emit_tool_display_namefrom backend.data.credit import UsageTransactionMetadata-from backend.data.db_accessors import credit_db, review_db, user_db, workspace_db+from backend.data.db_accessors import (+ credit_db,+ review_db,+ spend_approval_db,+ user_db,+ workspace_db,+)from backend.data.execution import ExecutionContext+from backend.data.expert_spend import add_weekly_spendfrom backend.data.model import CredentialsFieldInfo, CredentialsMetaInputfrom backend.executor.auto_credentials import (MissingAutoCredentialsError,@@ -39,6 +46,7 @@ from backend.integrations.credentials_store import provider_matchesfrom backend.integrations.creds_manager import IntegrationCredentialsManagerfrom backend.integrations.providers import ProviderNamefrom backend.util.exceptions import BlockError, InsufficientBalanceError+from backend.util.feature_flag import Flag, is_feature_enabledfrom backend.util.timezone_utils import get_user_timezone_or_utcfrom backend.util.type import coerce_inputs_to_schema@@ -149,12 +157,14 @@ async def _charge_block_credits(cost_filter: dict[str, Any],synthetic_graph_id: str,synthetic_node_id: str,+ expert_id: str | None = None,) -> None:"""Charge credits for a block execution and log any billing leak.Centralised so the normal-path charge and the cancellation-recovery charge(see ``execute_block``'s finally) use the same metadata and the same- leak-logging contract.+ leak-logging contract. ``expert_id`` also meters the charge on the+ expert's spend counters."""try:await _credit_db.spend_credits(@@ -171,6 +181,8 @@ async def _charge_block_credits(reason="copilot_block_execution",),)+ if expert_id:+ await add_weekly_spend(expert_id, cost)except Exception as e:# Block already executed (with possible side effects). Never# return ErrorResponse here — the user received output and@@ -503,6 +515,7 @@ async def execute_block(cost_filter=cost_filter,synthetic_graph_id=synthetic_graph_id,synthetic_node_id=synthetic_node_id,+ expert_id=await metered_expert_id(user_id, expert_id),))@@ -562,6 +575,7 @@ async def execute_block(cost_filter=cost_filter,synthetic_graph_id=synthetic_graph_id,synthetic_node_id=synthetic_node_id,+ expert_id=await metered_expert_id(user_id, expert_id),))finally:@@ -1044,6 +1058,59 @@ async def check_hitl_review(return synthetic_node_exec_id, input_data+async def check_spend_approval(+ prep: BlockPreparation, user_id: str, session: ChatSession+) -> "ReviewRequiredResponse | None":+ """Park a paid block once the session's expert has reached her spend+ threshold (SECRT-2599). None means the block may run."""+ if session.expert_id is None:+ return None+ cost, _ = block_usage_cost(+ prep.block, prep.input_data, use_preflight_estimate=False+ )+ if cost <= 0:+ return None+ needed = await spend_approval_db().spend_approval_required(+ user_id, session.expert_id+ )+ if needed is None:+ return None+ review_id = await spend_approval_db().open_chat_spend_review(+ user_id=user_id,+ session_id=session.session_id,+ needed=needed,+ block_name=prep.block.name,+ organization_id=session.organization_id,+ team_id=session.team_id,+ )+ return ReviewRequiredResponse(+ message=(+ f"{needed.headline}. Tell the user, and after they approve "+ "call run_block again with the same input."+ ),+ session_id=session.session_id,+ block_id=prep.block_id,+ block_name=prep.block.name,+ review_id=review_id,+ graph_exec_id=prep.synthetic_graph_id,+ input_data=prep.input_data,+ )+++async def metered_expert_id(user_id: str, expert_id: str | None) -> str | None:+ """The expert whose spend counters a chat block charge lands on; None+ keeps the pre-SECRT-2599 behaviour of not counting chat block spend.++ Narrower than the scope id ``execute_block`` takes: the flag gates who+ gets metered, never whose file scope a ``workspace://`` input resolves in.+ """+ if expert_id is None:+ return None+ if not await is_feature_enabled(Flag.EXPERT_SPEND_APPROVAL, user_id):+ return None+ return expert_id++def _resolve_discriminated_credentials(block: AnyBlockSchema,input_data: dict[str, Any],diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.pyindex 973bb48f8a..0bd6fef1bb 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py@@ -931,6 +931,26 @@ class RunAgentTool(BaseTool):inputs=inputs,)+ library_agent_link = f"/library/agents/{library_agent.id}"+ if execution.status == ExecutionStatus.REVIEW:+ # Parked for spend approval (SECRT-2599): it runs once the user+ # approves it on Home or the run page. Not a successful run yet.+ return ExecutionStartedResponse(+ message=(+ f"Agent '{library_agent.name}' is waiting for the user's "+ "approval to spend more credits (spend threshold reached). "+ f"It runs once they approve it on Home or at "+ f"{library_agent_link}. {MSG_DO_NOT_RUN_AGAIN}"+ ),+ session_id=session_id,+ execution_id=execution.id,+ graph_id=library_agent.graph_id,+ graph_name=library_agent.name,+ library_agent_id=library_agent.id,+ library_agent_link=library_agent_link,+ status=ExecutionStatus.REVIEW.value,+ )+# Track successful run (dry runs don't count against the session limit)if not dry_run:session.successful_agent_runs[library_agent.graph_id] = (@@ -947,8 +967,6 @@ class RunAgentTool(BaseTool):library_agent_id=library_agent.id,)- library_agent_link = f"/library/agents/{library_agent.id}"-# If wait_for_result is requested, wait for execution to completeif wait_for_result > 0:logger.info(diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block.py b/autogpt_platform/backend/backend/copilot/tools/run_block.pyindex f0b6c3c8aa..cf09a86f1a 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_block.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_block.py@@ -15,6 +15,7 @@ from .base import BaseToolfrom .helpers import (BlockPreparation,check_hitl_review,+ check_spend_approval,execute_block,prepare_block_for_execution,)@@ -281,6 +282,11 @@ class RunBlockTool(BaseTool):user_authenticated=True,)+ if not dry_run:+ spend_gate = await check_spend_approval(prep, user_id, session)+ if spend_gate is not None:+ return spend_gate+hitl_or_err = await check_hitl_review(prep,user_id,diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.pyindex e5773b9833..1eb76820c6 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py@@ -1546,3 +1546,146 @@ class _StubCreditDB:async def spend_credits(self, **kwargs):return None+++class TestSpendApproval:+ """Seam B of SECRT-2599: a paid block in an expert's chat waits for the+ user once she has reached her spend threshold."""++ @staticmethod+ def _needed():+ from backend.api.features.experts.spend_approval import SpendApprovalNeeded++ return SpendApprovalNeeded(+ expert_id="expert-1",+ expert_name="Ada",+ spent=250,+ threshold=250,+ window="week",+ )++ @staticmethod+ def _paid_block():+ block = make_mock_block_with_schema(+ block_id="paid-block",+ name="Paid Block",+ input_properties={"prompt": {"type": "string"}},+ required_fields=["prompt"],+ )+ block.executed = False++ async def execute(input_data, **kwargs):+ block.executed = True+ yield "response", "ok"++ block.execute = execute+ return block++ @staticmethod+ def _patches(block, gate, *, cost: int = 5, flag: bool = True):+ credit = MagicMock(+ get_credits=AsyncMock(return_value=1_000), spend_credits=AsyncMock()+ )+ workspace = MagicMock(+ get_or_create_workspace=AsyncMock(return_value=MagicMock(id="ws"))+ )+ return [+ patch("backend.copilot.tools.helpers.get_block", return_value=block),+ patch(+ "backend.copilot.tools.helpers.match_credentials_to_requirements",+ return_value=({}, []),+ ),+ patch(+ "backend.copilot.tools.helpers.block_usage_cost",+ return_value=(cost, {}),+ ),+ patch("backend.copilot.tools.helpers.spend_approval_db", return_value=gate),+ patch("backend.copilot.tools.helpers.credit_db", return_value=credit),+ patch("backend.copilot.tools.helpers.workspace_db", return_value=workspace),+ patch(+ "backend.copilot.tools.helpers.is_feature_enabled",+ AsyncMock(return_value=flag),+ ),+ ]++ async def _run(self, session, block, gate, **kw):+ from contextlib import ExitStack++ with ExitStack() as stack:+ for p in self._patches(block, gate, **kw):+ stack.enter_context(p)+ return await RunBlockTool()._execute(+ user_id=_TEST_USER_ID,+ session=session,+ block_id="paid-block",+ input_data={"prompt": "hi"},+ dry_run=False,+ )++ @pytest.mark.asyncio(loop_scope="session")+ async def test_expert_at_threshold_parks_a_paid_block(self):+ session = make_session(user_id=_TEST_USER_ID, expert_id="expert-1")+ block = self._paid_block()+ gate = MagicMock(+ spend_approval_required=AsyncMock(return_value=self._needed()),+ open_chat_spend_review=AsyncMock(+ return_value="copilot-node-expert-spend:expert-1:abcd1234"+ ),+ )++ response = await self._run(session, block, gate)++ assert isinstance(response, ReviewRequiredResponse)+ assert response.review_id == "copilot-node-expert-spend:expert-1:abcd1234"+ assert response.graph_exec_id.startswith("copilot-session-")+ assert not block.executed+ gate.spend_approval_required.assert_awaited_once_with(_TEST_USER_ID, "expert-1")+ assert (+ gate.open_chat_spend_review.await_args.kwargs["block_name"] == "Paid Block"+ )++ @pytest.mark.asyncio(loop_scope="session")+ @pytest.mark.parametrize("expert_id,cost", [(None, 5), ("expert-1", 0)])+ async def test_plain_sessions_and_free_blocks_are_not_gated(self, expert_id, cost):+ session = make_session(user_id=_TEST_USER_ID, expert_id=expert_id)+ block = self._paid_block()+ gate = MagicMock(spend_approval_required=AsyncMock(return_value=self._needed()))++ response = await self._run(session, block, gate, cost=cost)++ assert isinstance(response, BlockOutputResponse)+ assert block.executed+ gate.spend_approval_required.assert_not_awaited()++ @pytest.mark.asyncio(loop_scope="session")+ @pytest.mark.parametrize("flag", [True, False])+ async def test_below_threshold_meters_only_with_the_flag_but_always_scopes(+ self, flag+ ):+ """The flag gates who is metered, never whose file scope the block+ runs in — ``workspace://`` inputs resolve against the session's expert+ either way."""+ session = make_session(user_id=_TEST_USER_ID, expert_id="expert-1")+ block = self._paid_block()+ captured: dict[str, object] = {}++ async def execute(input_data, **kwargs):+ block.executed = True+ captured["ctx"] = kwargs["execution_context"]+ yield "response", "ok"++ block.execute = execute+ gate = MagicMock(spend_approval_required=AsyncMock(return_value=None))++ with patch(+ "backend.copilot.tools.helpers.add_weekly_spend", AsyncMock()+ ) as add_spend:+ response = await self._run(session, block, gate, flag=flag)++ assert isinstance(response, BlockOutputResponse)+ assert block.executed+ assert captured["ctx"].expert_id == "expert-1"+ if flag:+ add_spend.assert_awaited_once_with("expert-1", 5)+ else:+ add_spend.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/data/db_accessors.py b/autogpt_platform/backend/backend/data/db_accessors.pyindex e64685e351..b2603e87b8 100644--- a/autogpt_platform/backend/backend/data/db_accessors.py+++ b/autogpt_platform/backend/backend/data/db_accessors.py@@ -27,6 +27,19 @@ def experts_db():return experts_db+def spend_approval_db():+ if db.is_connected():+ from backend.api.features.experts import spend_approval as _spend_approval++ spend_approval_db = _spend_approval+ else:+ from backend.util.clients import get_database_manager_async_client++ spend_approval_db = get_database_manager_async_client()++ return spend_approval_db++def graph_db():if db.is_connected():from backend.data import graph as _graph_dbdiff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex 9e38dabad2..333de4d3e1 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Callable, Concatenate, ParamSpec, TypeVar, casfrom backend.api.features.experts import credentials as expert_credentialsfrom backend.api.features.experts import experts_dbfrom backend.api.features.experts import scheduling as experts_scheduling+from backend.api.features.experts import spend_approval as experts_spend_approvalfrom backend.api.features.library.db import (add_store_agent_to_library,bulk_move_agents_to_folder,@@ -531,6 +532,12 @@ class DatabaseManager(AppService):list_experts = _(experts_db.list_experts)resolve_private_expert_tenancy = _(experts_db.resolve_private_expert_tenancy)enforce_expert_run_budget = _(experts_scheduling.enforce_expert_run_budget)+ spend_approval_required = _(experts_spend_approval.spend_approval_required)+ park_execution_for_spend_approval = _(+ experts_spend_approval.park_execution_for_spend_approval+ )+ parked_spend_decision = _(experts_spend_approval.parked_spend_decision)+ open_chat_spend_review = _(experts_spend_approval.open_chat_spend_review)expert_allowed_credential_ids = _(expert_credentials.expert_allowed_credential_ids)update_soul = _(experts_db.update_soul)update_soul_if_current = _(experts_db.update_soul_if_current)@@ -916,6 +923,10 @@ class DatabaseManagerAsyncClient(AppServiceClient):list_experts = d.list_expertsresolve_private_expert_tenancy = d.resolve_private_expert_tenancyenforce_expert_run_budget = d.enforce_expert_run_budget+ spend_approval_required = d.spend_approval_required+ park_execution_for_spend_approval = d.park_execution_for_spend_approval+ parked_spend_decision = d.parked_spend_decision+ open_chat_spend_review = d.open_chat_spend_reviewexpert_allowed_credential_ids = d.expert_allowed_credential_idsupdate_soul = d.update_soulupdate_soul_if_current = d.update_soul_if_currentdiff --git a/autogpt_platform/backend/backend/data/execution.py b/autogpt_platform/backend/backend/data/execution.pyindex 57ed323b8b..18122ce1f6 100644--- a/autogpt_platform/backend/backend/data/execution.py+++ b/autogpt_platform/backend/backend/data/execution.py@@ -180,6 +180,7 @@ VALID_STATUS_TRANSITIONS = {],ExecutionStatus.REVIEW: [ExecutionStatus.RUNNING,+ ExecutionStatus.INCOMPLETE, # Parked for spend approval, never published],}diff --git a/autogpt_platform/backend/backend/data/expert_spend.py b/autogpt_platform/backend/backend/data/expert_spend.pyindex 53ce400059..140426f646 100644--- a/autogpt_platform/backend/backend/data/expert_spend.py+++ b/autogpt_platform/backend/backend/data/expert_spend.py@@ -1,45 +1,68 @@-"""Per-expert weekly credit spend counters (issue #13717).+"""Per-expert credit spend counters (issue #13717, SECRT-2599).Redis is the hot-path store: billing increments on every charge that carriesan expert-attributed execution context, and the budget gate reads it beforestarting a scheduled/triggered run. The durable source of truth remainsCreditTransaction joined through AgentGraphExecution.expertId — these-counters are a cache, safe to lose (a lost key under-counts one week's+counters are a cache, safe to lose (a lost key under-counts one window'sspend, which only ever errs in the user's favor).++Every charge lands in two buckets, the ISO week the weekly budget enforces+and the UTC day, so the spend-approval window can switch between them+without losing data."""import logging-from datetime import datetime, timezone+from datetime import datetime, timedelta, timezone+from typing import Literalfrom backend.data.redis_client import get_redis, get_redis_asynclogger = logging.getLogger(__name__)-# Keys outlive the week they track so a just-rolled-over week is still-# readable for display; two weeks is plenty.-_KEY_TTL_SECONDS = 14 * 24 * 3600+SpendWindow = Literal["week", "day"]++# Keys outlive the window they track so a just-rolled-over one is still+# readable for display.+_KEY_TTL_SECONDS = {"week": 14 * 24 * 3600, "day": 2 * 24 * 3600}def weekly_spend_key(expert_id: str, now: datetime | None = None) -> str:+ return spend_key(expert_id, "week", now)+++def spend_key(expert_id: str, window: SpendWindow, now: datetime | None = None) -> str:now = now or datetime.now(timezone.utc)+ if window == "day":+ return f"expert-spend:{expert_id}:{now:%Y-%m-%d}"year, week, _ = now.isocalendar()return f"expert-spend:{expert_id}:{year}-W{week:02d}"+def window_start(window: SpendWindow, now: datetime | None = None) -> datetime:+ """First instant of the bucket ``now`` falls in (UTC)."""+ now = now or datetime.now(timezone.utc)+ day = now.replace(hour=0, minute=0, second=0, microsecond=0)+ if window == "day":+ return day+ return day - timedelta(days=day.weekday())++async def add_weekly_spend(expert_id: str, amount: int) -> None:"""Add *amount* credits (may be negative for refund reconciliation) to- the expert's current-week counter. Never raises — a metering failure- must not fail the charge that triggered it."""+ the expert's current week and day counters. Never raises — a metering+ failure must not fail the charge that triggered it."""if amount == 0:returntry:redis = await get_redis_async()- key = weekly_spend_key(expert_id)- await redis.incrby(key, amount)- await redis.expire(key, _KEY_TTL_SECONDS)+ for window in ("week", "day"):+ key = spend_key(expert_id, window)+ await redis.incrby(key, amount)+ await redis.expire(key, _KEY_TTL_SECONDS[window])except Exception as e:logger.warning(- f"Failed to record weekly spend for expert #{expert_id}: "+ f"Failed to record spend for expert #{expert_id}: "f"{type(e).__name__}: {e}")@@ -51,44 +74,48 @@ def add_weekly_spend_sync(expert_id: str, amount: int) -> None:returntry:redis = get_redis()- key = weekly_spend_key(expert_id)- redis.incrby(key, amount)- redis.expire(key, _KEY_TTL_SECONDS)+ for window in ("week", "day"):+ key = spend_key(expert_id, window)+ redis.incrby(key, amount)+ redis.expire(key, _KEY_TTL_SECONDS[window])except Exception as e:logger.warning(- f"Failed to record weekly spend for expert #{expert_id}: "+ f"Failed to record spend for expert #{expert_id}: "f"{type(e).__name__}: {e}")async def reset_weekly_spend(expert_id: str) -> None:- """Zero the current-week counter. Called when the user resumes a paused+ """Zero the current counters. Called when the user resumes a pausedexpert: keeping the count would re-pause her on the next gate check,making Resume a no-op until the ISO week rolls over. Billing is- unaffected — only the guardrail's counter restarts. Never raises; on+ unaffected — only the guardrail's counters restart. Never raises; onfailure the user can simply resume again."""try:redis = await get_redis_async()- await redis.delete(weekly_spend_key(expert_id))+ await redis.delete(spend_key(expert_id, "week"), spend_key(expert_id, "day"))except Exception as e:logger.warning(- f"Failed to reset weekly spend for expert #{expert_id}: "+ f"Failed to reset spend for expert #{expert_id}: "f"{type(e).__name__}: {e}")async def get_weekly_spend(expert_id: str) -> int:- """Current-week spend in credits; 0 on any read failure (errs open —- the budget gate must not block runs because Redis hiccuped). Clamped to- non-negative: a refund reconciled in a later ISO week than its charge- decrements the new week's counter and could otherwise go below zero."""+ return await get_spend(expert_id, "week")+++async def get_spend(expert_id: str, window: SpendWindow) -> int:+ """Current-window spend in credits; 0 on any read failure (errs open —+ a gate must not block runs because Redis hiccuped). Clamped to+ non-negative: a refund reconciled in a later window than its charge+ decrements the new counter and could otherwise go below zero."""try:redis = await get_redis_async()- value = await redis.get(weekly_spend_key(expert_id))+ value = await redis.get(spend_key(expert_id, window))return max(0, int(value)) if value is not None else 0except Exception as e:logger.warning(- f"Failed to read weekly spend for expert #{expert_id}: "- f"{type(e).__name__}: {e}"+ f"Failed to read spend for expert #{expert_id}: " f"{type(e).__name__}: {e}")return 0diff --git a/autogpt_platform/backend/backend/data/expert_spend_test.py b/autogpt_platform/backend/backend/data/expert_spend_test.pynew file mode 100644index 0000000000..bd6325595a--- /dev/null+++ b/autogpt_platform/backend/backend/data/expert_spend_test.py@@ -0,0 +1,59 @@+from datetime import datetime, timezone+from unittest.mock import AsyncMock, MagicMock++import pytest++from backend.data import expert_spend++# A Wednesday in ISO week 37; that week starts on Monday 2026-09-07.+WEDNESDAY = datetime(2026, 9, 9, 15, 30, tzinfo=timezone.utc)+++def test_keys_bucket_by_window() -> None:+ assert expert_spend.spend_key("e", "week", WEDNESDAY) == "expert-spend:e:2026-W37"+ assert expert_spend.spend_key("e", "day", WEDNESDAY) == "expert-spend:e:2026-09-09"+ assert expert_spend.weekly_spend_key("e", WEDNESDAY) == "expert-spend:e:2026-W37"+++def test_window_start_is_monday_or_midnight() -> None:+ assert expert_spend.window_start("week", WEDNESDAY) == datetime(+ 2026, 9, 7, tzinfo=timezone.utc+ )+ assert expert_spend.window_start("day", WEDNESDAY) == datetime(+ 2026, 9, 9, tzinfo=timezone.utc+ )+++async def test_add_spend_feeds_both_windows(mocker) -> None:+ redis = MagicMock(incrby=AsyncMock(), expire=AsyncMock())+ mocker.patch.object(expert_spend, "get_redis_async", AsyncMock(return_value=redis))++ await expert_spend.add_weekly_spend("e", 7)++ assert [c.args for c in redis.incrby.await_args_list] == [+ (expert_spend.spend_key("e", "week"), 7),+ (expert_spend.spend_key("e", "day"), 7),+ ]+++async def test_reset_clears_both_windows(mocker) -> None:+ redis = MagicMock(delete=AsyncMock())+ mocker.patch.object(expert_spend, "get_redis_async", AsyncMock(return_value=redis))++ await expert_spend.reset_weekly_spend("e")++ redis.delete.assert_awaited_once_with(+ expert_spend.spend_key("e", "week"), expert_spend.spend_key("e", "day")+ )+++async def test_get_spend_reads_the_requested_window_and_clamps(mocker) -> None:+ redis = MagicMock(get=AsyncMock(return_value=b"-3"))+ mocker.patch.object(expert_spend, "get_redis_async", AsyncMock(return_value=redis))++ assert await expert_spend.get_spend("e", "day") == 0++ redis.get.assert_awaited_once_with(expert_spend.spend_key("e", "day"))diff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.pyindex c84267287c..9d83af1cef 100644--- a/autogpt_platform/backend/backend/executor/utils.py+++ b/autogpt_platform/backend/backend/executor/utils.py@@ -7,6 +7,7 @@ from collections import defaultdictfrom concurrent.futures import Futurefrom typing import Literal, Mapping, Optional, cast+from prisma.enums import ReviewStatusfrom pydantic import BaseModel, JsonValue, ValidationErrorfrom backend.api.features.experts import scheduling as experts_scheduling@@ -27,6 +28,7 @@ from backend.data.block_preflight_estimates import get_preflight_estimatefrom backend.data.credit import UsageTransactionMetadata, get_user_credit_modelfrom backend.data.db import prismafrom backend.data.db_accessors import experts_db as get_experts_db+from backend.data.db_accessors import spend_approval_dbfrom backend.data.dynamic_fields import merge_execution_inputfrom backend.data.execution import (ExecutionContext,@@ -1421,6 +1423,26 @@ async def _add_graph_execution(team_id = graph_exec.team_idif not bypass_paywall:await _enforce_expert_run_budget(user_id, expert_id)+ if graph_exec.status == ExecutionStatus.REVIEW:+ decision = await _parked_spend_decision(+ user_id, expert_id, graph_exec.id+ )+ if decision == ReviewStatus.WAITING:+ return graph_exec+ if decision == ReviewStatus.REJECTED:+ await edb.update_node_execution_status_batch(+ [ne.node_exec_id for ne in graph_exec.node_executions],+ ExecutionStatus.TERMINATED,+ )+ await edb.update_graph_execution_stats(+ graph_exec_id=graph_exec.id,+ status=ExecutionStatus.TERMINATED,+ stats=GraphExecutionStats(+ error="Additional spending declined by the user"+ ),+ )+ graph_exec.status = ExecutionStatus.TERMINATED+ return graph_exec# Use existing execution's compiled input maskscompiled_nodes_input_masks = graph_exec.nodes_input_masks or {}@@ -1521,6 +1543,23 @@ async def _add_graph_execution(f"#{graph_id} with {len(starting_nodes_input)} starting nodes")+ # Spend approval (SECRT-2599): once the expert has reached her+ # threshold the run is held, unpublished, until the user approves it.+ # Nested runs were gated with their parent; admin requeues are exempt.+ if expert_id and not dry_run and parent_exec_id is None and not bypass_paywall:+ if needed := await _spend_approval_required(user_id, expert_id):+ await _park_for_spend_approval(+ user_id=user_id,+ graph_exec_id=graph_exec.id,+ graph_id=graph_id,+ graph_version=graph_exec.graph_version,+ needed=needed,+ organization_id=organization_id,+ team_id=team_id,+ )+ graph_exec.status = ExecutionStatus.REVIEW+ return graph_exec+# Generate execution context if it's not providedif execution_context is None:user = await udb.get_user_by_id(user_id)@@ -1670,6 +1709,22 @@ async def _add_graph_execution(return graph_exec+async def _spend_approval_required(user_id: str, expert_id: str):+ return await spend_approval_db().spend_approval_required(user_id, expert_id)+++async def _park_for_spend_approval(**kwargs) -> None:+ await spend_approval_db().park_execution_for_spend_approval(**kwargs)+++async def _parked_spend_decision(+ user_id: str, expert_id: str, graph_exec_id: str+) -> ReviewStatus | None:+ return await spend_approval_db().parked_spend_decision(+ user_id, expert_id, graph_exec_id+ )++# ============ Execution Output Helpers ============ #diff --git a/autogpt_platform/backend/backend/executor/utils_test.py b/autogpt_platform/backend/backend/executor/utils_test.pyindex 9472014ba9..35eb0d08d2 100644--- a/autogpt_platform/backend/backend/executor/utils_test.py+++ b/autogpt_platform/backend/backend/executor/utils_test.py@@ -2,10 +2,15 @@ from datetime import datetime, timezonefrom typing import castimport pytest+from prisma.enums import ReviewStatusfrom pytest_mock import MockerFixturefrom backend.data.dynamic_fields import merge_execution_input, parse_execution_output-from backend.data.execution import ExecutionStatus, GraphExecutionWithNodes+from backend.data.execution import (+ ExecutionContext,+ ExecutionStatus,+ GraphExecutionWithNodes,+)from backend.data.model import Userfrom backend.executor.utils import (CRED_ERR_INVALID_PREFIX,@@ -2774,3 +2779,154 @@ async def test_add_graph_execution_records_outcome(mocker):verr + 1,err + 1,)+++# ============ Spend approval (SECRT-2599) ============ #+++def _spend_needed():+ from backend.api.features.experts.spend_approval import SpendApprovalNeeded++ return SpendApprovalNeeded(+ expert_id="expert-1", expert_name="Ada", spent=250, threshold=250, window="week"+ )+++def _mock_spend_gate(mocker: MockerFixture, needed):+ required = mocker.patch(+ "backend.executor.utils._spend_approval_required",+ new=mocker.AsyncMock(return_value=needed),+ )+ park = mocker.patch(+ "backend.executor.utils._park_for_spend_approval", new=mocker.AsyncMock()+ )+ queue = mocker.AsyncMock()+ mocker.patch("backend.executor.utils.get_async_execution_queue", return_value=queue)+ return required, park, queue+++async def test_expert_execution_at_threshold_is_parked_unpublished(+ mocker: MockerFixture,+):+ mock_edb, _ = _mock_add_graph_execution_create_path(mocker)+ _mock_expert_personal_tenancy(mocker)+ needed = _spend_needed()+ required, park, queue = _mock_spend_gate(mocker, needed)++ result = await add_graph_execution(+ graph_id="g", user_id="owner", expert_id="expert-1"+ )++ required.assert_awaited_once_with("owner", "expert-1")+ assert result.status == ExecutionStatus.REVIEW+ park_kwargs = park.await_args.kwargs+ assert park_kwargs["graph_exec_id"] == "exec-id"+ assert park_kwargs["needed"] is needed+ mock_edb.update_graph_execution_stats.assert_not_awaited()+ queue.publish_message.assert_not_awaited()+++async def test_expert_execution_below_threshold_publishes(mocker: MockerFixture):+ mock_edb, _ = _mock_add_graph_execution_create_path(mocker)+ _mock_expert_personal_tenancy(mocker)+ _, park, queue = _mock_spend_gate(mocker, None)++ result = await add_graph_execution(+ graph_id="g", user_id="owner", expert_id="expert-1"+ )++ park.assert_not_awaited()+ assert mock_edb.update_graph_execution_stats.await_args.kwargs["status"] == (+ ExecutionStatus.QUEUED+ )+ queue.publish_message.assert_awaited_once()+ assert result.status == ExecutionStatus.QUEUED+++ "extra",+ [+ {"dry_run": True},+ {"bypass_paywall": True},+ {"execution_context": ExecutionContext(parent_execution_id="parent-exec")},+ ],+ ids=["dry_run", "admin_bypass", "nested_sub_graph"],+)+async def test_spend_gate_skips_dry_admin_and_nested_runs(+ mocker: MockerFixture, extra: dict+):+ _mock_add_graph_execution_create_path(mocker)+ _mock_expert_personal_tenancy(mocker)+ required, park, queue = _mock_spend_gate(mocker, _spend_needed())++ await add_graph_execution(+ graph_id="g", user_id="owner", expert_id="expert-1", **extra+ )++ required.assert_not_awaited()+ park.assert_not_awaited()+ queue.publish_message.assert_awaited_once()+++def _mock_parked_resume(mocker: MockerFixture, decision):+ graph_exec, store, queue, _ = _mock_add_graph_execution_requeue_path(+ mocker, expert_id="expert-1", organization_id="org", team_id="team"+ )+ graph_exec.status = ExecutionStatus.REVIEW+ store.update_graph_execution_stats = mocker.AsyncMock(+ return_value=mocker.MagicMock(status=ExecutionStatus.QUEUED)+ )+ _mock_expert_personal_tenancy(mocker)+ mocker.patch(+ "backend.executor.utils._parked_spend_decision",+ new=mocker.AsyncMock(return_value=decision),+ )+ return graph_exec, store, queue+++async def test_parked_execution_stays_parked_while_waiting(mocker: MockerFixture):+ graph_exec, store, queue = _mock_parked_resume(mocker, ReviewStatus.WAITING)++ result = await add_graph_execution(+ graph_id="g", user_id="owner", graph_exec_id="existing-execution"+ )++ assert result is graph_exec+ store.update_graph_execution_stats.assert_not_awaited()+ queue.publish_message.assert_not_awaited()+++async def test_declined_execution_is_terminated_not_run(mocker: MockerFixture):+ graph_exec, store, queue = _mock_parked_resume(mocker, ReviewStatus.REJECTED)++ result = await add_graph_execution(+ graph_id="g", user_id="owner", graph_exec_id="existing-execution"+ )++ assert result.status == ExecutionStatus.TERMINATED+ assert store.update_graph_execution_stats.await_args.kwargs["status"] == (+ ExecutionStatus.TERMINATED+ )+ queue.publish_message.assert_not_awaited()+++ "decision", [ReviewStatus.APPROVED, None], ids=["approved", "hitl"]+)+async def test_approved_or_hitl_review_resumes(mocker: MockerFixture, decision):+ _, store, queue = _mock_parked_resume(mocker, decision)++ await add_graph_execution(+ graph_id="g", user_id="owner", graph_exec_id="existing-execution"+ )++ assert store.update_graph_execution_stats.await_args.kwargs["status"] == (+ ExecutionStatus.QUEUED+ )+ queue.publish_message.assert_awaited_once()diff --git a/autogpt_platform/backend/backend/util/exceptions.py b/autogpt_platform/backend/backend/util/exceptions.pyindex 951cebfccc..f46ffaf749 100644--- a/autogpt_platform/backend/backend/util/exceptions.py+++ b/autogpt_platform/backend/backend/util/exceptions.py@@ -337,9 +337,9 @@ class WebhookSetupUnavailableError(Exception):class ExpertRunPausedError(ValueError):- """An expert-attributed scheduled/triggered run was refused because the- expert's schedules are paused (weekly credit budget reached or archive).- Chat-initiated runs are never gated by this."""+ """An expert-attributed run (schedule, trigger, or ``run_agent`` from her+ chat) was refused because the expert's schedules are paused (weekly credit+ budget reached or archive)."""def __init__(self, message: str, expert_id: str):super().__init__(message)diff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.pyindex 026fe1c94a..d0bdc6608a 100644--- a/autogpt_platform/backend/backend/util/feature_flag.py+++ b/autogpt_platform/backend/backend/util/feature_flag.py@@ -82,6 +82,10 @@ class Flag(str, Enum):# retrieval-relevance benefit is measured.GRAPHITI_COMMUNITIES_ENABLED = "graphiti-communities-enabled"+ # Parks expert work for the user's approval once her credit spend in the+ # window reaches the approval threshold (SECRT-2599). Off by default.+ EXPERT_SPEND_APPROVAL = "expert-spend-approval"+# --- Dream-system gates (P0) ---## No "enabled-users list" flag — LD's per-flag targeting nativelydiff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex 6525172850..1343ca1b70 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -2,7 +2,7 @@ import jsonimport osimport refrom enum import Enum-from typing import Any, Dict, Generic, List, Set, Tuple, Type, TypeVar+from typing import Any, Dict, Generic, List, Literal, Set, Tuple, Type, TypeVarfrom pydantic import (AliasChoices,@@ -225,6 +225,15 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):ge=0,description="Default weekly credit budget per hired expert when the expert has no explicit budget (100 = $1). 0 disables the guardrail.",)+ expert_spend_approval_threshold_default: int = Field(+ default=250,+ ge=0,+ description="Credits an expert may spend per window on her own; at this amount new work waits for the user's approval (100 = $1). 0 disables the check.",+ )+ expert_spend_approval_window: Literal["week", "day"] = Field(+ default="week",+ description="Accounting window for the spend-approval threshold: the ISO week the weekly budget also uses, or the UTC day.",+ )refund_notification_email: str = Field(default="[email protected]",description="Email address to send refund notifications to.",