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.

fix(platform): disable CoPilot spend caps for self-hosted installs (#14517)

Nicholas Tindle6a1f87cb5a99
diff --git a/autogpt_platform/backend/backend/copilot/config.py b/autogpt_platform/backend/backend/copilot/config.py
index 66698b0526..2b63e486ea 100644
--- a/autogpt_platform/backend/backend/copilot/config.py
+++ b/autogpt_platform/backend/backend/copilot/config.py
@@ -358,15 +358,24 @@ class ChatConfig(BaseSettings):
#
# These defaults act as the ceiling when LaunchDarkly is unreachable;
# the live per-tier values come from the COPILOT_*_COST_LIMIT flags.
+ #
+ # A negative value disables that window's cap. Self-hosted distributions
+ # (the single-container image and the unraid template) export -1 for both
+ # because the operator pays the model provider directly and, without
+ # LaunchDarkly, every account resolves to NO_TIER → BASIC multiplier and
+ # would otherwise inherit these cloud ceilings. The defaults here stay
+ # positive so a LaunchDarkly outage on cloud never removes the cap.
daily_cost_limit_microdollars: int = Field(
default=2_500_000,
description="Max cost per day in microdollars, resets at midnight UTC. "
- "0 means no spend allowed (will block); there is no unlimited tier.",
+ "0 means no spend allowed (will block); a negative value disables the "
+ "daily cap (the self-hosted default).",
)
weekly_cost_limit_microdollars: int = Field(
default=5_000_000,
description="Max cost per week in microdollars, resets Monday 00:00 UTC. "
- "0 means no spend allowed (will block); there is no unlimited tier.",
+ "0 means no spend allowed (will block); a negative value disables the "
+ "weekly cap (the self-hosted default).",
)
# Cost (in credits / cents) to reset the daily rate limit using credits.
diff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.py
index a50a374e8a..a9117a81c1 100644
--- a/autogpt_platform/backend/backend/copilot/rate_limit.py
+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py
@@ -342,9 +342,9 @@ class UsageWindow(BaseModel):
used: int
limit: int = Field(
description="Maximum microdollars of spend allowed in this window. "
- "0 means no spend allowed (the user is over-cap immediately); there "
- "is no unlimited tier — the public model uses ``None`` for "
- "no-cap-configured."
+ "0 means no spend allowed (the user is over-cap immediately); a "
+ "negative value means no cap is configured for this window (the "
+ "self-hosted default) and projects to ``None`` in the public model."
)
resets_at: datetime
@@ -406,9 +406,9 @@ class CoPilotUsagePublic(BaseModel):
def window(w: UsageWindow) -> UsageWindowPublic | None:
if w.limit < 0:
- # Defensive: nothing produces a negative limit today, but
- # treat it as "no cap configured" → hide the window from
- # the UI rather than divide-by-negative.
+ # Negative limit = no cap configured for this window (the
+ # self-hosted default, see ChatConfig) → hide the window
+ # from the UI rather than divide-by-negative.
return None
if w.limit == 0:
# Limit of 0 means "no spend allowed" — surface as fully
@@ -540,8 +540,9 @@ async def get_remaining_usd_budget(
per-turn budget hint via :func:`build_budget_ctx`.
A limit of ``0`` is treated as "no spend allowed" — remaining = 0
- on that window. There is no real-world unlimited tier; callers
- should not pass 0 expecting it to mean "no cap".
+ on that window; callers should not pass 0 expecting it to mean "no
+ cap". A negative limit means that window has no cap (the self-hosted
+ default); when both windows are uncapped the result is ``inf``.
Failure modes:
* Redis brown-out → ``floor_usd`` (so callers using the value
@@ -552,9 +553,9 @@ async def get_remaining_usd_budget(
Args:
user_id: The user's ID.
daily_cost_limit: Daily cap in microdollars. 0 = no spend allowed
- on this window.
+ on this window; negative = no cap on this window.
weekly_cost_limit: Weekly cap in microdollars. 0 = no spend allowed
- on this window.
+ on this window; negative = no cap on this window.
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
@@ -579,8 +580,9 @@ async def get_remaining_usd_budget(
return 0.0 if trial else floor_usd
# ``>= 0`` (not ``> 0``): a limit of 0 is "no spend allowed", so the
- # remaining is 0 on that window. Mirrors check_rate_limit's semantics
- # — there is no unlimited tier, so we never short-circuit to float(inf).
+ # remaining is 0 on that window. Mirrors check_rate_limit's semantics:
+ # only an explicitly negative limit (the self-hosted "no cap" sentinel)
+ # skips a window, so an uncapped deployment resolves to float(inf).
remaining_microdollars = float("inf")
if daily_cost_limit >= 0:
remaining_microdollars = min(
@@ -663,8 +665,10 @@ async def check_rate_limit(
caller must fail closed (HTTP 503) — the daily/weekly USD caps are
real money and cannot be bypassed by a Redis brown-out.
- A limit of ``0`` means "no spend allowed", not "unlimited" — there is
- no real-world unlimited tier. Routes that want to skip rate-limiting
+ A limit of ``0`` means "no spend allowed", not "unlimited". A negative
+ limit disables that window's check entirely — the explicit "no cap"
+ sentinel that self-hosted distributions export (see ChatConfig) — so
+ an uncapped window never raises. Routes that want to skip rate-limiting
entirely should not call this function. Entitlement (``NO_TIER`` +
``ENABLE_PLATFORM_PAYMENT``) is enforced upstream by the route
dependency :func:`enforce_payment_paywall`, so this function is
@@ -688,6 +692,8 @@ async def check_rate_limit(
raise RateLimitExceeded("trial", now)
if trial.cost_microdollars >= trial.offer.total_cost_limit:
raise RateLimitExceeded("trial", trial.ends_at or now)
+ if (skip_daily or daily_cost_limit < 0) and weekly_cost_limit < 0:
+ return
try:
redis = await get_redis_async()
daily_raw, weekly_raw = await asyncio.gather(
@@ -717,7 +723,8 @@ async def check_rate_limit(
# any usage at or above 0 is over-cap. The previous ``> 0`` check
# silently treated 0 as unlimited, which collided with the multiplier-
# collapse semantics of :func:`get_global_rate_limits` and produced
- # the autopilot paywall bypass.
+ # the autopilot paywall bypass. Only an explicitly negative limit — the
+ # self-hosted "no cap" sentinel — skips a window.
if not skip_daily and daily_cost_limit >= 0 and daily_used >= daily_cost_limit:
raise RateLimitExceeded("daily", _daily_reset_time(now=now))
@@ -1216,8 +1223,8 @@ async def get_global_rate_limits(
# Cast back to int to preserve the microdollar integer contract
# downstream — fractional LD multipliers (e.g. 8.5×) truncate at the
# last microdollar, which is well below any meaningful precision.
- daily = int(daily * multiplier)
- weekly = int(weekly * multiplier)
+ daily = int(daily * multiplier) if daily >= 0 else daily
+ weekly = int(weekly * multiplier) if weekly >= 0 else weekly
return daily, weekly, tier
diff --git a/autogpt_platform/backend/backend/copilot/rate_limit_test.py b/autogpt_platform/backend/backend/copilot/rate_limit_test.py
index c0aa697f16..b36469b698 100644
--- a/autogpt_platform/backend/backend/copilot/rate_limit_test.py
+++ b/autogpt_platform/backend/backend/copilot/rate_limit_test.py
@@ -360,6 +360,34 @@ class TestCheckRateLimit:
await check_rate_limit(_USER, daily_cost_limit=0, weekly_cost_limit=0)
assert exc_info.value.window == "daily"
+ @pytest.mark.asyncio
+ async def test_negative_limit_disables_the_window(self):
+ """A negative limit is the explicit "no cap" sentinel that self-hosted
+ distributions export (the single-container image sets -1 for both
+ windows). Unlike 0 it must never raise, however much was spent."""
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(side_effect=["999000000", "999000000"])
+ with patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ return_value=mock_redis,
+ ):
+ await check_rate_limit(_USER, daily_cost_limit=-1, weekly_cost_limit=-1)
+
+ @pytest.mark.asyncio
+ async def test_negative_daily_limit_still_enforces_weekly(self):
+ """Disabling one window must not disable the other."""
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(side_effect=["999000000", "5000000"])
+ with patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ return_value=mock_redis,
+ ):
+ with pytest.raises(RateLimitExceeded) as exc_info:
+ await check_rate_limit(
+ _USER, daily_cost_limit=-1, weekly_cost_limit=5_000_000
+ )
+ assert exc_info.value.window == "weekly"
+
class TestCoPilotUsagePublicFromStatus:
"""Public-shape projection must surface a 0-limit window as fully
@@ -393,6 +421,14 @@ class TestCoPilotUsagePublicFromStatus:
assert public.weekly is not None
assert public.weekly.percent_used == 100.0
+ def test_negative_limit_hides_the_window(self):
+ """A negative limit means "no cap configured" (the self-hosted
+ default) and must project to ``None`` so the UI hides the meter
+ instead of rendering a negative percentage."""
+ public = CoPilotUsagePublic.from_status(self._status(-1, -1))
+ assert public.daily is None
+ assert public.weekly is None
+
def test_positive_limit_renders_normally(self):
# daily limit $10, used $0 → 0% used
from .rate_limit import UsageWindow
@@ -2766,6 +2802,35 @@ class TestGetRemainingUsdBudget:
)
assert result == 0.5
+ @pytest.mark.asyncio
+ async def test_negative_limits_mean_unlimited_budget(self):
+ """Self-hosted installs export -1 for both windows; SDK budget sizing
+ must see an unbounded budget rather than the floor."""
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(side_effect=["999000000", "999000000"])
+ with patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ return_value=mock_redis,
+ ):
+ result = await get_remaining_usd_budget(
+ _USER, daily_cost_limit=-1, weekly_cost_limit=-1
+ )
+ assert result == float("inf")
+
+ @pytest.mark.asyncio
+ async def test_negative_daily_limit_defers_to_weekly_remaining(self):
+ # daily uncapped; weekly=$50 used $48 → $2 remaining drives the result.
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(side_effect=["999000000", "48000000"])
+ with patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ return_value=mock_redis,
+ ):
+ result = await get_remaining_usd_budget(
+ _USER, daily_cost_limit=-1, weekly_cost_limit=50_000_000
+ )
+ assert result == pytest.approx(2.0)
+
@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.
diff --git a/autogpt_platform/backend/backend/copilot/rate_limit_unlimited_test.py b/autogpt_platform/backend/backend/copilot/rate_limit_unlimited_test.py
new file mode 100644
index 0000000000..9f16c08b5f
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/rate_limit_unlimited_test.py
@@ -0,0 +1,127 @@
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.rate_limit import (
+ RateLimitExceeded,
+ RateLimitUnavailable,
+ SubscriptionTier,
+ check_rate_limit,
+ get_global_rate_limits,
+)
+from backend.data.subscription_trial import TrialState
+
+
+ "multiplier,config_daily,config_weekly,expected_daily,expected_weekly",
+ [
+ (0.5, -1, -1, -1, -1),
+ (0.5, -1, 200, -1, 100),
+ (0.5, 100, -1, 50, -1),
+ (2.0, -1, -1, -1, -1),
+ (0.5, 0, 200, 0, 100),
+ (0.5, 100, 200, 50, 100),
+ ],
+)
+async def test_tier_scaling_preserves_unlimited_windows(
+ multiplier: float,
+ config_daily: int,
+ config_weekly: int,
+ expected_daily: int,
+ expected_weekly: int,
+):
+ with (
+ patch(
+ "backend.copilot.rate_limit._fetch_cost_limits_flag",
+ new=AsyncMock(return_value=None),
+ ),
+ patch(
+ "backend.copilot.rate_limit.get_user_tier",
+ new=AsyncMock(return_value=SubscriptionTier.NO_TIER),
+ ),
+ patch(
+ "backend.copilot.rate_limit.get_tier_multipliers",
+ new=AsyncMock(
+ return_value={
+ SubscriptionTier.NO_TIER.value: 0.0,
+ SubscriptionTier.BASIC.value: multiplier,
+ }
+ ),
+ ),
+ patch(
+ "backend.copilot.rate_limit.is_feature_enabled",
+ new=AsyncMock(return_value=False),
+ ),
+ ):
+ daily, weekly, tier = await get_global_rate_limits(
+ "unlimited-user", config_daily, config_weekly
+ )
+
+ assert (daily, weekly, tier) == (
+ expected_daily,
+ expected_weekly,
+ SubscriptionTier.NO_TIER,
+ )
+
+
[email protected]("daily,skip_daily", [(-1, False), (0, True), (100, True)])
+async def test_uncapped_windows_do_not_require_redis(daily: int, skip_daily: bool):
+ with (
+ patch(
+ "backend.copilot.rate_limit._fetch_user_tier",
+ new=AsyncMock(return_value=SubscriptionTier.NO_TIER),
+ ),
+ patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ new=AsyncMock(side_effect=ConnectionError("Redis unavailable")),
+ ) as redis,
+ ):
+ await check_rate_limit("unlimited-user", daily, -1, skip_daily=skip_daily)
+
+ redis.assert_not_awaited()
+
+
[email protected]("daily,weekly,skip_daily", [(0, -1, False), (-1, 0, True)])
+async def test_active_window_still_fails_closed_without_redis(
+ daily: int, weekly: int, skip_daily: bool
+):
+ with (
+ patch(
+ "backend.copilot.rate_limit._fetch_user_tier",
+ new=AsyncMock(return_value=SubscriptionTier.NO_TIER),
+ ),
+ patch(
+ "backend.copilot.rate_limit.get_redis_async",
+ new=AsyncMock(side_effect=ConnectionError("Redis unavailable")),
+ ),
+ pytest.raises(RateLimitUnavailable),
+ ):
+ await check_rate_limit("limited-user", daily, weekly, skip_daily=skip_daily)
+
+
[email protected]("active,cost", [(False, 0), (True, 100)])
+async def test_uncapped_windows_preserve_trial_enforcement(active: bool, cost: int):
+ trial = MagicMock(spec=TrialState)
+ trial.active = active
+ trial.cost_microdollars = cost
+ trial.offer = MagicMock(total_cost_limit=100)
+ trial.ends_at = None
+ store = MagicMock()
+ store.get_subscription_trial = AsyncMock(return_value=trial)
+ with (
+ patch(
+ "backend.copilot.rate_limit._fetch_user_tier",
+ new=AsyncMock(return_value=SubscriptionTier.TRIAL),
+ ),
+ patch("backend.copilot.rate_limit.credit_db", return_value=store),
+ patch("backend.copilot.rate_limit.get_redis_async", new=AsyncMock()) as redis,
+ pytest.raises(RateLimitExceeded) as exc,
+ ):
+ await check_rate_limit("trial-user", -1, -1)
+
+ assert exc.value.window == "trial"
+ redis.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/copilot/tree.py b/autogpt_platform/backend/backend/copilot/tree.py
index b8ed4ed1da..b15e21b9aa 100644
--- a/autogpt_platform/backend/backend/copilot/tree.py
+++ b/autogpt_platform/backend/backend/copilot/tree.py
@@ -390,6 +390,10 @@ async def resolve_root_ceiling_microdollars(user_id: str | None) -> int:
may not spawn either. The floor keeps a modest daily limit from
producing a tree too small to fund one real turn; the cap keeps a
generous one from handing a single tree the whole day.
+
+ A negative daily limit is the self-hosted "no cap" sentinel (see
+ ChatConfig). There is no tier daily to scale from, so the absolute cap
+ alone bounds one tree — it must not collapse to 0 and refuse spawns.
"""
cap = config.tree_ceiling_microdollars
if not user_id:
@@ -403,11 +407,7 @@ async def resolve_root_ceiling_microdollars(user_id: str | None) -> int:
config.weekly_cost_limit_microdollars,
)
# ``daily`` is already tier-scaled by get_global_rate_limits.
- scaled = int(config.tree_ceiling_fraction_of_daily * daily)
- # A zero tier allowance means no spend at all; the floor must not
- # resurrect it, so it only applies to a tier that may spend.
- allowance = max(scaled, config.tree_ceiling_floor_microdollars) if daily > 0 else 0
- ceiling = min(allowance, cap)
+ ceiling = min(_tree_allowance_microdollars(daily, cap), cap)
remaining_usd = await get_remaining_usd_budget(
user_id=user_id, daily_cost_limit=daily, weekly_cost_limit=weekly, floor_usd=0.0
@@ -418,6 +418,25 @@ async def resolve_root_ceiling_microdollars(user_id: str | None) -> int:
return max(0, min(remaining, ceiling))
+def _tree_allowance_microdollars(daily: int, cap: int) -> int:
+ """Tier-scaled share of the daily limit one tree may spend, before the
+ remaining-budget clamp.
+
+ * negative ``daily`` — uncapped (self-hosted): the absolute cap is the
+ only bound, so hand it out rather than scaling a sentinel to nothing.
+ * ``daily == 0`` — a tier that may not spend at all; the floor must not
+ resurrect it.
+ * ``daily > 0`` — fraction of the daily limit, floored so a small tier
+ still affords one real turn.
+ """
+ if daily < 0:
+ return cap
+ if daily == 0:
+ return 0
+ scaled = int(config.tree_ceiling_fraction_of_daily * daily)
+ return max(scaled, config.tree_ceiling_floor_microdollars)
+
+
async def admit_turn(
envelope: TurnEnvelope, *, user_id: str | None, ledger: TreeLedger | None = None
) -> None:
diff --git a/autogpt_platform/backend/backend/copilot/tree_test.py b/autogpt_platform/backend/backend/copilot/tree_test.py
index f2b7b8233c..f3a7a838a7 100644
--- a/autogpt_platform/backend/backend/copilot/tree_test.py
+++ b/autogpt_platform/backend/backend/copilot/tree_test.py
@@ -391,11 +391,14 @@ def test_all_tool_names_cover_the_denied_set() -> None:
# ── ceiling formula (finding 3) ────────────────────────────────────────
-def _ceiling(daily: int, remaining_usd: float, monkeypatch) -> int:
+def _ceiling(
+ daily: int, remaining_usd: float, monkeypatch, *, weekly: int | None = None
+) -> int:
"""Drive resolve_root_ceiling_microdollars with a fixed tier + balance."""
+ weekly_limit = daily * 5 if weekly is None else weekly
async def _limits(_uid, _d, _w):
- return daily, daily * 5, "TIER"
+ return daily, weekly_limit, "TIER"
async def _remaining(**_kw):
return remaining_usd
@@ -443,6 +446,26 @@ def test_remaining_budget_clamps_the_ceiling(monkeypatch) -> None:
assert _ceiling(8_000_000, 0.75, monkeypatch) == 750_000
+def test_uncapped_daily_limit_yields_the_absolute_cap(monkeypatch) -> None:
+ """A negative daily limit is the self-hosted "no cap" sentinel. There is
+ no tier daily to scale from, so the absolute cap alone bounds a tree —
+ scaling the sentinel would collapse it to 0 and refuse every spawn."""
+ monkeypatch.setattr(tree.config, "tree_ceiling_fraction_of_daily", 0.5)
+ monkeypatch.setattr(tree.config, "tree_ceiling_floor_microdollars", 500_000)
+ monkeypatch.setattr(tree.config, "tree_ceiling_microdollars", 10_000_000)
+ assert _ceiling(-1, float("inf"), monkeypatch) == 10_000_000
+
+
+def test_uncapped_daily_limit_still_respects_remaining_weekly_budget(
+ monkeypatch,
+) -> None:
+ # Daily off, weekly on with $0.75 left: the weekly remainder still clamps.
+ monkeypatch.setattr(tree.config, "tree_ceiling_fraction_of_daily", 0.5)
+ monkeypatch.setattr(tree.config, "tree_ceiling_floor_microdollars", 500_000)
+ monkeypatch.setattr(tree.config, "tree_ceiling_microdollars", 10_000_000)
+ assert _ceiling(-1, 0.75, monkeypatch, weekly=50_000_000) == 750_000
+
+
def test_isolate_denied_names_are_real_tools() -> None:
# DESCENT and SPAWN are asserted above; ISOLATE was the gap.
assert ISOLATE_DENIED_TOOLS <= ALL_TOOL_NAMES
diff --git a/autogpt_platform/single-container/entrypoint.sh b/autogpt_platform/single-container/entrypoint.sh
index cd53bb577d..5137a7ec4a 100755
--- a/autogpt_platform/single-container/entrypoint.sh
+++ b/autogpt_platform/single-container/entrypoint.sh
@@ -179,6 +179,17 @@ configure_environment() {
# MUST set BEHAVE_AS=cloud, or every user gets every gated capability.
export APP_ENV=dev BEHAVE_AS="${BEHAVE_AS:-local}" ENABLE_AUTH=true
+ # AutoPilot's daily/weekly USD spend caps are tuned for AutoGPT Cloud
+ # tiers. Without LaunchDarkly every account resolves to NO_TIER, which
+ # falls back to the BASIC multiplier and would inherit the cloud ceilings
+ # from ChatConfig. A self-hosted operator pays the model provider directly,
+ # so both caps are off unless the operator sets them. -1 is the "no cap"
+ # sentinel; a positive microdollar amount (1 USD = 1000000) re-enables a
+ # spend guard for that window. An empty value also means "unset" so a
+ # blank template field never reaches Pydantic as a non-integer.
+ export CHAT_DAILY_COST_LIMIT_MICRODOLLARS="${CHAT_DAILY_COST_LIMIT_MICRODOLLARS:--1}"
+ export CHAT_WEEKLY_COST_LIMIT_MICRODOLLARS="${CHAT_WEEKLY_COST_LIMIT_MICRODOLLARS:--1}"
+
export BETTER_AUTH_URL="${AUTOGPT_PUBLIC_URL}"
export BETTER_AUTH_INTERNAL_URL=http://127.0.0.1:3001
export JWT_JWKS_URL=http://127.0.0.1:3001/api/auth/jwks
diff --git a/autogpt_platform/single-container/tests/test_entrypoint.py b/autogpt_platform/single-container/tests/test_entrypoint.py
index f241b5ad47..79747b4308 100644
--- a/autogpt_platform/single-container/tests/test_entrypoint.py
+++ b/autogpt_platform/single-container/tests/test_entrypoint.py
@@ -137,7 +137,29 @@ class EnvironmentPolicyTest(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.splitlines()[-1], "cloud")
- def _configure(self, **overrides: str) -> subprocess.CompletedProcess[str]:
+ def test_disables_copilot_spend_caps_by_default(self) -> None:
+ # Self-hosted operators pay the provider directly, so the cloud
+ # daily/weekly USD caps must not apply unless explicitly configured.
+ result = self._configure(output=_COPILOT_SPEND_CAPS)
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout.splitlines()[-1], "-1 -1")
+
+ def test_preserves_operator_copilot_spend_caps(self) -> None:
+ # A blank template field arrives as an empty string and must fall
+ # back to the sentinel rather than reach Pydantic as a non-integer.
+ result = self._configure(
+ output=_COPILOT_SPEND_CAPS,
+ CHAT_DAILY_COST_LIMIT_MICRODOLLARS="2500000",
+ CHAT_WEEKLY_COST_LIMIT_MICRODOLLARS="",
+ )
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout.splitlines()[-1], "2500000 -1")
+
+ def _configure(
+ self, *, output: str = "$BEHAVE_AS", **overrides: str
+ ) -> subprocess.CompletedProcess[str]:
environment = {
"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
"AUTOGPT_ASSET_DIR": str(ASSET_DIR),
@@ -164,7 +186,7 @@ class EnvironmentPolicyTest(unittest.TestCase):
"pipefail",
"-c",
'source "$1"; write_nginx_public_url_config() { :; }; '
- 'configure_environment; printf "%s\\n" "$BEHAVE_AS"',
+ f'configure_environment; printf "%s\\n" "{output}"',
"bash",
str(ENTRYPOINT_PATH),
],
@@ -175,6 +197,11 @@ class EnvironmentPolicyTest(unittest.TestCase):
)
+_COPILOT_SPEND_CAPS = (
+ "$CHAT_DAILY_COST_LIMIT_MICRODOLLARS $CHAT_WEEKLY_COST_LIMIT_MICRODOLLARS"
+)
+
+
class PublicOriginConfigurationTest(unittest.TestCase):
def test_backend_cors_uses_the_validated_public_origin(self) -> None:
result = subprocess.run(
diff --git a/docs/platform/single-container.md b/docs/platform/single-container.md
index 438b229b8b..8bb96cec15 100644
--- a/docs/platform/single-container.md
+++ b/docs/platform/single-container.md
@@ -446,6 +446,27 @@ provider client secrets, `OPENAI_API_KEY`, `TRANSCRIPTION_API_KEY`, and the
legacy `SUPABASE_JWT_SECRET`. These values remain server-side process
environment and are not baked into the browser bundle.
+### AutoPilot spend caps
+
+AutoGPT Cloud limits each account's AutoPilot spend per day and per week,
+measured from the provider-reported cost of every chat turn. This image
+disables both caps by default because you pay the model provider directly:
+`CHAT_DAILY_COST_LIMIT_MICRODOLLARS` and `CHAT_WEEKLY_COST_LIMIT_MICRODOLLARS`
+are set to `-1` unless you provide a value. To guard an OpenRouter or
+Anthropic bill, set either variable to a positive amount in microdollars
+(1 USD = `1000000`):
+
+```dotenv
+CHAT_DAILY_COST_LIMIT_MICRODOLLARS=5000000
+CHAT_WEEKLY_COST_LIMIT_MICRODOLLARS=20000000
+```
+
+The daily window resets at midnight UTC and the weekly window at Monday
+00:00 UTC. Once a window is exhausted, further AutoPilot turns are refused
+with HTTP 429 until it resets. The caps only meter the platform-routed chat
+transport: ChatGPT/Codex subscription turns are exempt, and local
+OpenAI-compatible servers report no cost, so they never count against a cap.
+
### Database connection tuning
`DB_CONNECTION_LIMIT` controls each backend role's Prisma connection pool and