> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cycls.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Plans and quotas

> Read the subscription tier from context.user.plan, meter usage on the workspace volume, set up the plans window, and verify Apple in-app purchases offline.

This page is for developers adding paid tiers to an agent. It covers reading the
plan claim, enforcing a quota, the plans window, and accepting an Apple in-app
purchase as proof of entitlement.

**Prerequisites:** an auth provider configured with
[`cycls.Web().auth(...)`](https://docs.cycls.com/web/auth), and a volume at `/workspace`.

## Read the plan

`context.user.plan` is whatever your identity provider puts in the JWT claim. The
Cycls-hosted Clerk application emits:

| Value | Meaning |
| - | - |
| `u:free_user` | free individual |
| `o:free_org` | free organization |
| `cycls_pass` | paid subscriber |

```python theme={null}
if context.user.plan == "cycls_pass":
    yield "Premium features are enabled."
else:
    yield "Upgrade for full access."
    yield {"type": "ui", "action": "open_plan_modal"}
```

`{"type": "ui", "action": "open_plan_modal"}` opens the [plans window](#the-plans-window).
The client selects user plans or organization plans based on the active
organization.

## Meter usage per user

Store the counter in `cycls.DB`, which writes to the `/workspace` volume. Keying
by month means history accumulates and resets happen without a scheduled job.
Report the count to the chat with a `usage` event on every reply of a limited plan.

```python theme={null}
from datetime import datetime, timezone
import cycls

LIMITS = {"u:free_user": 14}   # messages a month per plan; a plan not listed has no limit


def next_month(now):
    return f"{now.year + 1}-01-01" if now.month == 12 else f"{now.year}-{now.month + 1:02d}-01"


@cycls.agent(image=image, web=web, volumes={"/workspace": cycls.Volume("my-agent")})
async def my_agent(context):
    user = context.user
    exempt = not context.prod                      # local runs are never blocked

    if user.plan == "o:free_org" and not exempt:
        cycls.log("cap_hit", user=user, chat_id=context.chat_id, kind="org_free")
        yield {"type": "callout", "callout": "This workspace needs a paid plan.", "style": "error"}
        yield {"type": "ui", "action": "open_plan_modal"}
        return

    db = cycls.DB(context.workspace)
    now = datetime.now(timezone.utc)
    month = now.strftime("%Y-%m")
    entry = await db.get(f"usage/{month}", {"count": 0})
    limit = None if exempt else LIMITS.get(user.plan)
    usage = lambda n: {"type": "usage", "used": n, "limit": limit, "per": "month", "resets": next_month(now)}

    if limit and entry["count"] >= limit:
        cycls.log("cap_hit", user=user, chat_id=context.chat_id,
                  kind="user_free_monthly", count=entry["count"])
        yield usage(entry["count"])
        yield {"type": "ui", "action": "open_plan_modal", "reason": "limit"}
        return

    entry["count"] += 1
    await db.put(f"usage/{month}", entry)
    if limit:
        yield usage(entry["count"])

    async for ev in llm.run(context=context):
        yield ev
```

Expected behavior: from a free user's 11th message in a month, a line above the
composer counts what is left. The 14th is answered, and the plans window opens
as that reply ends, once that month on each device. The 15th gets a note in place
of a reply that thanks the person by the agent's name and offers the plans, and
the model is never called. The mobile app shows its own alert.

| `usage` key | Meaning |
| - | - |
| `used` | messages used this period |
| `limit` | messages the plan allows per period |
| `per` | `month` or `quarter`, for the note's wording |
| `resets` | the ISO date the messages come back |

> [!WARNING]
>
> `cycls.DB` writes are atomic per key, not transactional across keys. Two requests
> racing on the same counter can both read the same value. For strict enforcement,
> check the counter again after incrementing, or accept a small overshoot.

## The plans window

The plans window shows your Clerk plans. One button leads, for the plan on offer,
already chosen: the first paid plan the person does not have. Under it come the
price, a local amount and "cancel anytime", then the ways to pay, the choice of
plan and billing period with the yearly saving, and the plan's features. Opened
by a limit, it thanks the person first. **Not now** closes it.

```python theme={null}
web = cycls.Web().plans(
    pay=("apple_pay", "google_pay", "visa", "mastercard"),
    currency=("SAR", 3.75),
    words={
        "pro": {"ar": {"name": "برو", "description": "لمن يستخدم الذكاء الاصطناعي كل يوم."}},
        "memory": {"ar": {"name": "الذاكرة"}},
    },
)
```

| Argument | Effect |
| - | - |
| `pay` | the ways your checkout takes payment, shown under the button as each brand's official mark: `apple_pay`, `google_pay`, `visa`, `mastercard`. List only what checkout takes |
| `currency` | a currency code and a fixed rate, such as `("SAR", 3.75)`, to show each price also in that currency. Checkout still charges the plan's own currency |
| `words` | plan and feature names and one-liners in other languages, keyed by the Clerk slug of each plan and feature. Without them the window uses Clerk's own words |

## Track spend

Set token prices so every turn logs its cost:

```python theme={null}
llm = cycls.LLM().price(input=3, output=15, cache_read=0.30, cache_write=6)
```

Prices are USD per million tokens. Query the result with
[`cycls cost` and `cycls sql`](https://docs.cycls.com/ship/observability). Without `.price()`, costs
are logged as zero.

## Apple in-app purchase

Use this when an iOS client sells the subscription and the agent has to trust it
without calling Apple on every request.

```python theme={null}
iap = cycls.AppleIAP(
    bundle_id="com.example.app",
    products={"com.example.app.pro.monthly": "u:pro"},
    namespace="00000000-0000-0000-0000-000000000000",
)

web = cycls.Web().auth(cycls.Clerk()).iap(iap)
```

| Argument | Required | Meaning |
| - | - | - |
| `bundle_id` | yes | the app's bundle identifier, checked against the transaction |
| `products` | yes | a set of product ids, or a mapping of product id to plan value |
| `namespace` | yes | UUIDv5 namespace the client also uses to derive `appAccountToken` |
| `plan` | no | plan value for set-form products, default `u:iap` |
| `header` | no | request header carrying the JWS, default `x-apple-entitlement` |
| `root_cert` | no | override the bundled Apple Root CA G3 |

How verification works: the iOS client sends its current StoreKit 2 signed
transaction in the header. Cycls validates the certificate chain against the
bundled Apple Root CA G3, checks the product and expiry, and confirms that the
purchase's `appAccountToken` derives from the authenticated user id under your
namespace. A valid entitlement raises `user.plan` for that request only.

The `appAccountToken` binding is what stops a valid receipt from one account
being replayed by another. Both client and server must derive it with the same
UUIDv5 namespace.

## Affiliate tracking

```python theme={null}
web = cycls.Web().affiliate(os.environ["REWARDFUL_KEY"])
```

The key is injected into the page config. The client loads the tracker and
reports conversions at checkout.

## Next

> [card] [Local and remote builds](https://docs.cycls.com/ship/builds.md)
>
> Where a build happens, and which code it contains.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.