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(backend/copilot): dynamic max_budget_usd for SDK; parity budget hint for baseline (#13002)

Zamil Majdy939774d72640
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.py
index 49fb290689..0c72a3f50a 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py
@@ -58,6 +58,7 @@ from backend.copilot.pending_messages import (
format_pending_as_user_message,
)
from backend.copilot.prompting import SHARED_TOOL_NOTES, get_graphiti_supplement
+from backend.copilot.rate_limit import build_budget_ctx
from backend.copilot.response_model import (
StreamBaseResponse,
StreamError,
@@ -1559,8 +1560,23 @@ async def stream_chat_completion_baseline(
# the very start of the message content.
user_message_for_transcript = message
if should_inject_user_context:
+ # Mirror the SDK path's "model knows about budget" behaviour by
+ # injecting a per-turn ``<budget_context>`` block — the baseline
+ # path has no equivalent of the SDK CLI's native
+ # ``max_budget_usd`` running-cost reminder, so this is the only
+ # signal the model gets about how much USD spend headroom the
+ # user has left.
+ budget_ctx = await build_budget_ctx(
+ user_id=user_id,
+ default_daily_cost_limit=config.daily_cost_limit_microdollars,
+ default_weekly_cost_limit=config.weekly_cost_limit_microdollars,
+ )
prefixed = await inject_user_context(
- understanding, message or "", session_id, session.messages
+ understanding,
+ message or "",
+ session_id,
+ session.messages,
+ budget_ctx=budget_ctx,
)
if prefixed is not None:
# Reverse scan so we update the current turn's user message, not
diff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.py
index 3a29270f28..759a8f6ec2 100644
--- a/autogpt_platform/backend/backend/copilot/rate_limit.py
+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py
@@ -510,6 +510,119 @@ async def get_usage_status(
)
+async def get_remaining_usd_budget(
+ user_id: str,
+ daily_cost_limit: int,
+ weekly_cost_limit: int,
+ floor_usd: float = 0.5,
+) -> float:
+ """Return the user's remaining USD spend cap for the current windows.
+
+ The result is the smaller of ``daily_remaining`` and ``weekly_remaining``
+ expressed in USD. Used to size the SDK's per-query ``max_budget_usd``
+ so the in-CLI "wrap up gracefully" reminder fires earlier when the
+ user is close to their actual cap, and to feed the baseline path's
+ per-turn budget hint via :func:`build_budget_ctx`.
+
+ A limit of ``0`` is treated as unlimited. Both limits unlimited →
+ ``float('inf')``.
+
+ Failure modes:
+ * Both limits unlimited → ``float('inf')`` (no Redis call).
+ * Redis brown-out → ``floor_usd`` (so callers using the value
+ as a soft hint don't pretend the user has unlimited budget;
+ the pre-turn gate has already failed closed at 503 in this
+ case, so we only land here from observability paths).
+
+ Args:
+ user_id: The user's ID.
+ daily_cost_limit: Daily cap in microdollars (0 = unlimited).
+ weekly_cost_limit: Weekly cap in microdollars (0 = unlimited).
+ floor_usd: Lower bound on the returned value (USD). Avoids
+ handing the SDK a degenerate ``$0`` budget that would refuse
+ to start a turn. Set to ``0.0`` when the caller wants a
+ faithful "no remaining budget" signal instead of a floor.
+ """
+ if daily_cost_limit <= 0 and weekly_cost_limit <= 0:
+ return float("inf")
+
+ now = datetime.now(UTC)
+ try:
+ redis = await get_redis_async()
+ daily_raw, weekly_raw = await asyncio.gather(
+ redis.get(_daily_key(user_id, now=now)),
+ redis.get(_weekly_key(user_id, now=now)),
+ )
+ daily_used = int(daily_raw or 0)
+ weekly_used = int(weekly_raw or 0)
+ except (RedisError, RedisClusterException, ConnectionError, OSError, ValueError):
+ logger.warning("Redis unavailable for remaining-budget lookup, returning floor")
+ return floor_usd
+
+ remaining_microdollars = float("inf")
+ if daily_cost_limit > 0:
+ remaining_microdollars = min(
+ remaining_microdollars, max(0, daily_cost_limit - daily_used)
+ )
+ if weekly_cost_limit > 0:
+ remaining_microdollars = min(
+ remaining_microdollars, max(0, weekly_cost_limit - weekly_used)
+ )
+ remaining_usd = (
+ remaining_microdollars / 1_000_000.0
+ if remaining_microdollars != float("inf")
+ else float("inf")
+ )
+ return max(floor_usd, remaining_usd)
+
+
+async def build_budget_ctx(
+ user_id: str | None,
+ default_daily_cost_limit: int,
+ default_weekly_cost_limit: int,
+) -> str:
+ """Build the inner content for an ``<budget_context>`` block.
+
+ Returns the *inner* text — the caller (``inject_user_context``)
+ wraps it in the ``<budget_context>`` tag. Combines the tier-limit
+ lookup (``get_global_rate_limits``) and the remaining-USD lookup
+ (``get_remaining_usd_budget``) so callers don't have to compose
+ them by hand on every turn.
+
+ Returns ``""`` when:
+ * no ``user_id`` is available,
+ * the user's tier limits are unlimited (no cap to surface),
+ * Redis is unavailable (we'd rather emit nothing than a
+ misleading ``$0.00`` hint — the pre-turn gate already fails
+ closed at 503 in that case).
+ """
+ if not user_id:
+ return ""
+ daily_limit, weekly_limit, _tier = await get_global_rate_limits(
+ user_id,
+ default_daily_cost_limit,
+ default_weekly_cost_limit,
+ )
+ if daily_limit <= 0 and weekly_limit <= 0:
+ return ""
+ remaining = await get_remaining_usd_budget(
+ user_id=user_id,
+ daily_cost_limit=daily_limit,
+ weekly_cost_limit=weekly_limit,
+ # 0.0 here is a sentinel meaning "Redis brown-out / no value" —
+ # we map it back to "" below so the model doesn't see a
+ # misleading $0.00 hint when our metrics are degraded.
+ floor_usd=0.0,
+ )
+ if remaining == float("inf") or remaining <= 0.0:
+ return ""
+ return (
+ f"Approximate remaining USD budget for this user: ${remaining:.2f}.\n"
+ "Pace your tool use and reasoning depth so the response stays "
+ "within this envelope."
+ )
+
+
async def check_rate_limit(
user_id: str,
daily_cost_limit: int,
diff --git a/autogpt_platform/backend/backend/copilot/rate_limit_test.py b/autogpt_platform/backend/backend/copilot/rate_limit_test.py
index 019da08088..0bbf64a131 100644
--- a/autogpt_platform/backend/backend/copilot/rate_limit_test.py
+++ b/autogpt_platform/backend/backend/copilot/rate_limit_test.py
@@ -24,9 +24,11 @@ from .rate_limit import (
_weekly_key,
_weekly_reset_time,
acquire_reset_lock,
+ build_budget_ctx,
check_rate_limit,
get_daily_reset_count,
get_global_rate_limits,
+ get_remaining_usd_budget,
get_tier_multipliers,
get_usage_status,
get_user_tier,
@@ -2036,3 +2038,186 @@ class TestWorkspaceStorageLimits:
):
result = await get_workspace_storage_limit_bytes("user-1")
assert result == 250 * 1024 * 1024
+
+
+# ---------------------------------------------------------------------------
+# get_remaining_usd_budget
+# ---------------------------------------------------------------------------
+
+
+class TestGetRemainingUsdBudget:
+ @pytest.mark.asyncio
+ async def test_returns_inf_when_both_limits_unlimited(self):
+ # No Redis call expected — the function short-circuits on 0/0.
+ result = await get_remaining_usd_budget(
+ _USER, daily_cost_limit=0, weekly_cost_limit=0
+ )
+ assert result == float("inf")
+
+ @pytest.mark.asyncio
+ async def test_smaller_of_daily_and_weekly_remaining(self):
+ # daily=$10 used $3 → $7 remaining. weekly=$50 used $48 → $2 remaining.
+ # Returns the smaller (weekly $2).
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(side_effect=["3000000", "48000000"])
+ with patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ return_value=mock_redis,
+ ):
+ result = await get_remaining_usd_budget(
+ _USER,
+ daily_cost_limit=10_000_000,
+ weekly_cost_limit=50_000_000,
+ )
+ assert result == pytest.approx(2.0)
+
+ @pytest.mark.asyncio
+ async def test_floor_applies_when_user_at_or_over_cap(self):
+ # daily=$5 used $5 → 0 remaining → floor returned.
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(side_effect=["5000000", "0"])
+ with patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ return_value=mock_redis,
+ ):
+ result = await get_remaining_usd_budget(
+ _USER,
+ daily_cost_limit=5_000_000,
+ weekly_cost_limit=0,
+ floor_usd=0.5,
+ )
+ assert result == pytest.approx(0.5)
+
+ @pytest.mark.asyncio
+ async def test_returns_floor_on_redis_error(self):
+ with patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ side_effect=RedisError("boom"),
+ ):
+ result = await get_remaining_usd_budget(
+ _USER,
+ daily_cost_limit=10_000_000,
+ weekly_cost_limit=50_000_000,
+ floor_usd=0.5,
+ )
+ assert result == 0.5
+
+ @pytest.mark.asyncio
+ async def test_only_daily_cap_configured(self):
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(side_effect=["1000000", None])
+ with patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ return_value=mock_redis,
+ ):
+ result = await get_remaining_usd_budget(
+ _USER,
+ daily_cost_limit=10_000_000,
+ weekly_cost_limit=0,
+ )
+ assert result == pytest.approx(9.0)
+
+
+# ---------------------------------------------------------------------------
+# build_budget_ctx
+# ---------------------------------------------------------------------------
+
+
+class TestBuildBudgetCtx:
+ """The helper combines ``get_global_rate_limits`` + ``get_remaining_usd_budget``
+ into a single call so callers don't have to compose them by hand on
+ every turn, and returns the *inner* text only — ``inject_user_context``
+ wraps it in the ``<budget_context>`` tag."""
+
+ @pytest.mark.asyncio
+ async def test_returns_empty_without_user_id(self):
+ result = await build_budget_ctx(
+ user_id=None,
+ default_daily_cost_limit=10_000_000,
+ default_weekly_cost_limit=0,
+ )
+ assert result == ""
+
+ @pytest.mark.asyncio
+ async def test_returns_empty_when_unlimited(self):
+ with patch(
+ "backend.copilot.rate_limit.get_global_rate_limits",
+ new=AsyncMock(return_value=(0, 0, DEFAULT_TIER)),
+ ):
+ result = await build_budget_ctx(
+ user_id=_USER,
+ default_daily_cost_limit=10_000_000,
+ default_weekly_cost_limit=50_000_000,
+ )
+ assert result == ""
+
+ @pytest.mark.asyncio
+ async def test_returns_inner_text_with_remaining_in_dollars(self):
+ # daily=$10 used $4.50 → $5.50 remaining.
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(side_effect=["4500000", "0"])
+ with (
+ patch(
+ "backend.copilot.rate_limit.get_global_rate_limits",
+ new=AsyncMock(return_value=(10_000_000, 0, DEFAULT_TIER)),
+ ),
+ patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ return_value=mock_redis,
+ ),
+ ):
+ block = await build_budget_ctx(
+ user_id=_USER,
+ default_daily_cost_limit=10_000_000,
+ default_weekly_cost_limit=0,
+ )
+ # No tag wrap — that's inject_user_context's job.
+ assert "<budget_context>" not in block
+ assert "</budget_context>" not in block
+ assert "$5.50" in block
+
+ @pytest.mark.asyncio
+ async def test_returns_empty_on_redis_brownout(self):
+ """Redis brown-out → empty string, not a misleading ``$0.00`` hint.
+ Pre-turn rate-limit gate has already failed closed at 503 in this
+ case, so the model would never see the hint anyway."""
+ with (
+ patch(
+ "backend.copilot.rate_limit.get_global_rate_limits",
+ new=AsyncMock(return_value=(10_000_000, 0, DEFAULT_TIER)),
+ ),
+ patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ side_effect=RedisError("down"),
+ ),
+ ):
+ block = await build_budget_ctx(
+ user_id=_USER,
+ default_daily_cost_limit=10_000_000,
+ default_weekly_cost_limit=0,
+ )
+ assert block == ""
+
+ @pytest.mark.asyncio
+ async def test_returns_empty_when_remaining_is_zero(self):
+ """At-or-over cap → no hint (the pre-turn gate has already
+ rejected this turn at 429; we only emit a hint when there's
+ actual headroom to communicate)."""
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(side_effect=["10000000", "0"])
+ with (
+ patch(
+ "backend.copilot.rate_limit.get_global_rate_limits",
+ new=AsyncMock(return_value=(10_000_000, 0, DEFAULT_TIER)),
+ ),
+ patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ return_value=mock_redis,
+ ),
+ ):
+ block = await build_budget_ctx(
+ user_id=_USER,
+ default_daily_cost_limit=10_000_000,
+ default_weekly_cost_limit=0,
+ )
+ assert block == ""
diff --git a/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.py b/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.py
index 69e05d98d4..6a0532838a 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.py
@@ -1042,6 +1042,14 @@ def _make_sdk_patches(
),
),
(f"{_SVC}.get_user_tier", dict(new_callable=AsyncMock, return_value=None)),
+ # Bypass dynamic budget resolution — the helper hits Redis via
+ # get_global_rate_limits / get_remaining_usd_budget, which the
+ # retry_scenarios mocks don't stand up. Static cap is fine for
+ # retry-flow assertions (covered directly in service_test).
+ (
+ f"{_SVC}._resolve_dynamic_max_budget_usd",
+ dict(new_callable=AsyncMock, return_value=100.0),
+ ),
# Stub pending-message drain so retry tests don't hit Redis.
# Returns an empty list → no mid-turn injection happens.
(
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index 17d6706f55..e1a1b07bb4 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -81,7 +81,11 @@ from ..pending_messages import (
)
from ..permissions import apply_tool_permissions
from ..prompting import get_graphiti_supplement, get_sdk_supplement
-from ..rate_limit import get_user_tier
+from ..rate_limit import (
+ get_global_rate_limits,
+ get_remaining_usd_budget,
+ get_user_tier,
+)
from ..response_model import (
StreamBaseResponse,
StreamError,
@@ -190,6 +194,50 @@ _CIRCUIT_BREAKER_ERROR_MSG = (
_IDLE_TIMEOUT_SECONDS = 30 * 60
_HUNG_TOOL_CAP_SECONDS = 2 * 60 * 60
+# Floor on the per-query SDK budget — too small and the CLI refuses to
+# start a turn at all. Caller (``_resolve_dynamic_max_budget_usd``) clamps
+# to this so a user near (but not yet at) their cap still gets a chance to
+# wrap up gracefully instead of hitting an immediate hard stop.
+_MAX_BUDGET_USD_FLOOR = 0.5
+
+
+async def _resolve_dynamic_max_budget_usd(user_id: str | None) -> float:
+ """Pick the per-query ``max_budget_usd`` for this user *now*.
+
+ Returns the smaller of:
+ * ``config.claude_agent_max_budget_usd`` (the static per-query cap)
+ * the user's remaining daily/weekly USD cap (from Redis)
+
+ Falls back to the static cap when no ``user_id`` is available (e.g. an
+ internal turn run without auth). Floored at ``_MAX_BUDGET_USD_FLOOR``
+ so a near-capped user still gets enough headroom to surface the
+ "wrap up" reminder rather than failing to dispatch.
+ """
+ static_cap = config.claude_agent_max_budget_usd
+ if not user_id:
+ return static_cap
+ daily_limit, weekly_limit, _ = await get_global_rate_limits(
+ user_id,
+ config.daily_cost_limit_microdollars,
+ config.weekly_cost_limit_microdollars,
+ )
+ # Sentinel ``-1.0`` from ``get_remaining_usd_budget`` means Redis was
+ # unavailable. In that case fall back to the static per-query cap —
+ # we don't actually know the user is near their limit, and clamping
+ # to the floor would shrink every turn to $0.50 while Redis is in a
+ # brown-out. The pre-turn gate already failed closed at 503 in this
+ # branch, so this defensive fallback only matters in edge paths that
+ # bypass the gate.
+ remaining = await get_remaining_usd_budget(
+ user_id=user_id,
+ daily_cost_limit=daily_limit,
+ weekly_cost_limit=weekly_limit,
+ floor_usd=-1.0,
+ )
+ if remaining < 0 or remaining == float("inf"):
+ return static_cap
+ return max(_MAX_BUDGET_USD_FLOOR, min(static_cap, remaining))
+
def _idle_timeout_threshold(adapter: SDKResponseAdapter) -> int:
"""Pick the idle-timeout threshold for the current heartbeat.
@@ -3728,7 +3776,11 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues
# prevent runaway execution from burning budget.
"max_turns": config.agent_max_turns,
# max_budget_usd: per-query spend ceiling enforced by the CLI.
- "max_budget_usd": config.claude_agent_max_budget_usd,
+ # Sized to the smaller of the configured per-query default and
+ # the user's *actual* remaining daily/weekly USD cap so the
+ # CLI's "wrap up gracefully" reminder fires when they're close
+ # to the real limit, not the static $10 default.
+ "max_budget_usd": await _resolve_dynamic_max_budget_usd(user_id),
}
# max_thinking_tokens: cap extended thinking output per LLM call.
# Thinking tokens are billed at output rate ($75/M for Opus) and
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service_test.py b/autogpt_platform/backend/backend/copilot/sdk/service_test.py
index c4b480aed1..d5713fed6c 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service_test.py
@@ -14,12 +14,14 @@ from backend.copilot import config as cfg_mod
from .service import (
_HUNG_TOOL_CAP_SECONDS,
_IDLE_TIMEOUT_SECONDS,
+ _MAX_BUDGET_USD_FLOOR,
_build_system_prompt_value,
_humanise_tool_list,
_idle_timeout_threshold,
_is_sdk_disconnect_error,
_normalize_model_name,
_prepare_file_attachments,
+ _resolve_dynamic_max_budget_usd,
_resolve_sdk_model,
_resolve_sdk_model_for_request,
_safe_close_sdk_client,
@@ -1229,3 +1231,125 @@ class TestIdleTimeoutThreshold:
# The whole point of the two-regime design: pending tools get more
# patience than pure idle.
assert _HUNG_TOOL_CAP_SECONDS > _IDLE_TIMEOUT_SECONDS
+
+
+class TestResolveDynamicMaxBudgetUsd:
+ """The per-query SDK budget is sized to the smaller of the static
+ config cap and the user's *actual* remaining USD spend, so the
+ CLI's "wrap up gracefully" reminder fires on real headroom."""
+
+ @pytest.mark.asyncio
+ async def test_returns_static_cap_without_user_id(self):
+ with patch(
+ "backend.copilot.sdk.service.config.claude_agent_max_budget_usd",
+ 7.5,
+ ):
+ result = await _resolve_dynamic_max_budget_usd(None)
+ assert result == 7.5
+
+ @pytest.mark.asyncio
+ async def test_returns_static_cap_when_unlimited(self):
+ # When tier limits are 0/0 we treat as unlimited and fall back to the
+ # static config cap (the per-query soft ceiling still applies).
+ with (
+ patch(
+ "backend.copilot.sdk.service.get_global_rate_limits",
+ new=AsyncMock(return_value=(0, 0, "FREE")),
+ ),
+ patch(
+ "backend.copilot.sdk.service.get_remaining_usd_budget",
+ new=AsyncMock(return_value=float("inf")),
+ ),
+ patch(
+ "backend.copilot.sdk.service.config.claude_agent_max_budget_usd",
+ 10.0,
+ ),
+ ):
+ result = await _resolve_dynamic_max_budget_usd("u-1")
+ assert result == 10.0
+
+ @pytest.mark.asyncio
+ async def test_uses_remaining_when_smaller_than_static(self):
+ with (
+ patch(
+ "backend.copilot.sdk.service.get_global_rate_limits",
+ new=AsyncMock(return_value=(10_000_000, 50_000_000, "FREE")),
+ ),
+ patch(
+ "backend.copilot.sdk.service.get_remaining_usd_budget",
+ new=AsyncMock(return_value=2.5),
+ ),
+ patch(
+ "backend.copilot.sdk.service.config.claude_agent_max_budget_usd",
+ 10.0,
+ ),
+ ):
+ result = await _resolve_dynamic_max_budget_usd("u-1")
+ assert result == 2.5
+
+ @pytest.mark.asyncio
+ async def test_clamps_to_floor_when_remaining_is_below(self):
+ # A near-capped user still gets enough headroom to dispatch the
+ # turn (and surface the wrap-up reminder) instead of being
+ # blocked at the SDK level.
+ with (
+ patch(
+ "backend.copilot.sdk.service.get_global_rate_limits",
+ new=AsyncMock(return_value=(10_000_000, 0, "FREE")),
+ ),
+ patch(
+ "backend.copilot.sdk.service.get_remaining_usd_budget",
+ new=AsyncMock(return_value=0.05),
+ ),
+ patch(
+ "backend.copilot.sdk.service.config.claude_agent_max_budget_usd",
+ 10.0,
+ ),
+ ):
+ result = await _resolve_dynamic_max_budget_usd("u-1")
+ assert result == _MAX_BUDGET_USD_FLOOR
+
+ @pytest.mark.asyncio
+ async def test_static_cap_wins_when_smaller_than_remaining(self):
+ # User has plenty of headroom — the per-query soft ceiling still
+ # applies so a single chat cannot blow the entire daily budget.
+ with (
+ patch(
+ "backend.copilot.sdk.service.get_global_rate_limits",
+ new=AsyncMock(return_value=(100_000_000, 0, "PRO")),
+ ),
+ patch(
+ "backend.copilot.sdk.service.get_remaining_usd_budget",
+ new=AsyncMock(return_value=80.0),
+ ),
+ patch(
+ "backend.copilot.sdk.service.config.claude_agent_max_budget_usd",
+ 10.0,
+ ),
+ ):
+ result = await _resolve_dynamic_max_budget_usd("u-1")
+ assert result == 10.0
+
+ @pytest.mark.asyncio
+ async def test_redis_brownout_falls_back_to_static_cap(self):
+ """Redis brown-out → ``get_remaining_usd_budget`` returns the
+ ``floor_usd`` we passed. The resolver passes ``-1.0`` as a
+ sentinel and falls back to the static cap when it sees that —
+ otherwise every turn during a Redis outage would shrink to the
+ $0.50 floor instead of the configured per-query cap."""
+ with (
+ patch(
+ "backend.copilot.sdk.service.get_global_rate_limits",
+ new=AsyncMock(return_value=(10_000_000, 50_000_000, "FREE")),
+ ),
+ patch(
+ "backend.copilot.sdk.service.get_remaining_usd_budget",
+ new=AsyncMock(return_value=-1.0),
+ ),
+ patch(
+ "backend.copilot.sdk.service.config.claude_agent_max_budget_usd",
+ 10.0,
+ ),
+ ):
+ result = await _resolve_dynamic_max_budget_usd("u-1")
+ assert result == 10.0
diff --git a/autogpt_platform/backend/backend/copilot/service.py b/autogpt_platform/backend/backend/copilot/service.py
index 061088e788..00460233a7 100644
--- a/autogpt_platform/backend/backend/copilot/service.py
+++ b/autogpt_platform/backend/backend/copilot/service.py
@@ -92,6 +92,12 @@ MEMORY_CONTEXT_TAG = "memory_context"
# without polluting the cacheable system prompt. Server-injected only.
ENV_CONTEXT_TAG = "env_context"
+# Tag name for the per-turn budget hint block (baseline-only — the SDK CLI
+# has its own running-cost reminder via ``max_budget_usd``). Kept as a
+# distinct tag so it does not nest inside ``<env_context>`` and so users
+# cannot spoof a fake budget figure to the model. Server-injected only.
+BUDGET_CONTEXT_TAG = "budget_context"
+
# Builder-binding tag names (``builder_context`` per-turn prefix, and
# ``builder_session`` static system-prompt suffix) are defined in
# ``backend.copilot.builder_context``; the system prompt below refers to
@@ -196,6 +202,14 @@ _ENV_CONTEXT_PREFIX_RE = re.compile(
rf"^<{ENV_CONTEXT_TAG}>.*?</{ENV_CONTEXT_TAG}>\n\n", re.DOTALL
)
+_BUDGET_CONTEXT_ANYWHERE_RE = re.compile(
+ rf"<{BUDGET_CONTEXT_TAG}>.*</{BUDGET_CONTEXT_TAG}>\s*", re.DOTALL
+)
+_BUDGET_CONTEXT_LONE_TAG_RE = re.compile(rf"</?{BUDGET_CONTEXT_TAG}>", re.IGNORECASE)
+_BUDGET_CONTEXT_PREFIX_RE = re.compile(
+ rf"^<{BUDGET_CONTEXT_TAG}>.*?</{BUDGET_CONTEXT_TAG}>\n\n", re.DOTALL
+)
+
def _sanitize_user_context_field(value: str) -> str:
"""Escape any characters that would let user-controlled text break out of
@@ -257,7 +271,11 @@ def sanitize_user_supplied_context(message: str) -> str:
# Strip <env_context> blocks and lone tags — prevents spoofing of working-directory
# context that the SDK service injects server-side.
without_env_ctx = _ENV_CONTEXT_ANYWHERE_RE.sub("", without_mem_ctx)
- return _ENV_CONTEXT_LONE_TAG_RE.sub("", without_env_ctx)
+ without_env_ctx = _ENV_CONTEXT_LONE_TAG_RE.sub("", without_env_ctx)
+ # Strip <budget_context> blocks and lone tags — prevents spoofing of the
+ # server-injected per-turn USD-budget hint.
+ without_budget_ctx = _BUDGET_CONTEXT_ANYWHERE_RE.sub("", without_env_ctx)
+ return _BUDGET_CONTEXT_LONE_TAG_RE.sub("", without_budget_ctx)
def strip_injected_context_for_display(message: str) -> str:
@@ -283,6 +301,7 @@ def strip_injected_context_for_display(message: str) -> str:
result = _USER_CONTEXT_PREFIX_RE.sub("", result)
result = _MEMORY_CONTEXT_PREFIX_RE.sub("", result)
result = _ENV_CONTEXT_PREFIX_RE.sub("", result)
+ result = _BUDGET_CONTEXT_PREFIX_RE.sub("", result)
return result
@@ -374,6 +393,7 @@ async def inject_user_context(
session_messages: list[ChatMessage],
warm_ctx: str = "",
env_ctx: str = "",
+ budget_ctx: str = "",
) -> str | None:
"""Prepend trusted context blocks to the first user message.
@@ -461,6 +481,18 @@ async def inject_user_context(
final_message = (
f"<{ENV_CONTEXT_TAG}>\n{env_ctx}\n</{ENV_CONTEXT_TAG}>\n\n" + final_message
)
+ # Prepend budget context as its own block so the per-turn USD hint does
+ # NOT nest inside ``<env_context>`` (whose system-prompt contract says
+ # it carries the working directory only). Server-injected — sanitised
+ # against user spoofing in ``sanitize_user_supplied_context``. The
+ # cacheable system prompt is intentionally NOT updated to describe this
+ # tag: doing so would invalidate the cross-user prompt cache for an
+ # informational hint with negligible spoof-impact.
+ if budget_ctx:
+ final_message = (
+ f"<{BUDGET_CONTEXT_TAG}>\n{budget_ctx}\n</{BUDGET_CONTEXT_TAG}>\n\n"
+ + final_message
+ )
# Prepend Graphiti warm context as a <memory_context> block AFTER sanitization
# so that the trusted server-injected block is never stripped by
# sanitize_user_supplied_context (which removes attacker-supplied tags).