# 14 — Billing, credits and plans

**Status:** Draft. Written 2026-11-07. Prices are placeholders modelled on Keiki's preview
pricing and must be validated against LatAm purchasing power. **[DECISION NEEDED]** on final
numbers.

## 1. Model

Customers pay for creating and operating agents across personal, team, business and embedded
use cases. The commercial model is platform subscription plus metered execution and
capabilities. WhatsApp number and message fees are channel-specific items. Templates are
entry points into the platform; the marketplace and white-label remain later roadmap items.
Individuals use an organization as their workspace and billing boundary.

Commercial validation should cover hosted agents and connecting an existing agent through
the planned external harness. Keep the subscription/usage structure; validate willingness to
pay and infrastructure effort saved for each path. External execution must distinguish
customer-paid model usage from Charla-provided services before pricing; do not assume hosted
model-token revenue applies to every deployment. This adds no new price or entitlement.
Agency interviews include their own lead research and client setup as well as resale.
See [21](21-product-validation.md) for pilot baselines and cost per verified completion.

Two meters, like Keiki:

1. **Subscription** (monthly, in local currency where possible) that grants a monthly **credit**
   allowance and unlocks features.
2. **Credits** consumed by what agents do: model tokens, STT seconds, TTS characters, sandbox
   minutes, browser minutes, scraping pages, image renders, voice minutes, and **platform
   surcharge on WhatsApp template messages** when we relay payment (Later). Overage is bought in
   packs or auto-topped up.

Not credits: Meta's own per-message fees, phone numbers, payment processing fees (Mercado Pago /
Stripe charge the merchant directly).

**WhatsApp costs under the BSP model (decided 2026-11-07):**
- **BSP per-number fee** (Kapso: ≈ $5–10 per extra number on Platform/Pro; 360dialog:
  €15–49 per channel) is absorbed into the plan's included numbers and charged at **$15/mo per
  extra number** (vs Keiki's $99–300 iMessage lines).
- **Meta per-message fees**: the tenant chooses at connect time between paying Meta directly
  (card on the WABA) or **managed billing** through our BSP credits, re-billed as credits at
  Meta's rate plus the BSP's 5% managed-billing fee plus our 10% margin, itemised on the invoice.
  Service messages inside the 24 h window are mostly free (Meta's 1,000 free per number per
  month, then charged) so an agent's cost is dominated by templates.

## 2. Plans (placeholder)

| | Gratis | Starter | Pro | Max | Enterprise |
|---|---|---|---|---|---|
| Price | $0 | $19/mo (first 3 months $1) | $99/mo | $499/mo | custom |
| Monthly credits | $5 (test number only) | $20 | $100 (+$50 first month) | $500 (+$150 first month) | committed |
| Agents | 1 | 3 | 20 | unlimited | unlimited |
| Channels | shared test number, API | WhatsApp (own WABA via BSP), Telegram, API | + Instagram, Messenger, email | + voice, Slack/Teams | all |
| WhatsApp numbers included | 0 (shared) | 1 (+$15/mo each) | 3 (+$15/mo each) | 10 (+$10/mo each) | custom |
| Eval runs | 3/mo | 10/mo | unlimited | unlimited | unlimited |
| Concurrent turns | 1 | 5 | 25 | 100 | custom |
| API requests per key (T-124) | 600/min | 600/min | 1,200/min | 3,000/min | 6,000/min (custom) |
| BYOK | – | – | ✓ | ✓ | ✓ |
| Trace retention | 7 d | 14 d | 30 d | 90 d | custom |
| Audit export | – | – | – | ✓ | ✓ |
| SSO | – | – | – | – | ✓ |
| Data region choice | – | – | ✓ | ✓ | ✓ + dedicated |
| Voice numbers | – | – | $25/mo each | $15/mo each | custom |
| Support | docs | email | chat | priority | dedicated, SLA |

Regional pricing: USD list price; display and, where the processor allows, charge in EUR (ES,
PT, IT), MXN, BRL, ARS, COP, CLP, PEN, UYU; other footprint currencies displayed with USD
settlement. Local taxes (IVA/ICMS/ISS/IGV) handled by the processor; consider PPP-adjusted tiers
for AR, CO and Tier B countries **[DECISION NEEDED]**.

Country-specific pass-throughs: where Meta charges per AI reply (Italy, possibly the EEA
**[VERIFY]**), the delivery service tags each outbound message with its charge class and the
ledger bills it at cost plus margin, itemised separately from credits. T-105: the class is on
`messages.charge_class`; costed ones are `usage_events` rows (`provider: meta`, one per message)
and `UsageEventsRepo.chargesByClass` gives the month's line per class (messages, cost at Meta's
price, rows still unpriced). Rates: `packages/domain/src/billing/meta-charges.ts`, versioned by
`validFrom`, every figure `TODO verify` (Italy's AI-reply price included).

Gating (T-103): `PLAN_CATALOG[plan].entitlements` in `packages/domain/src/billing/plans.ts` is
this table in code (limits, features, channels); Enterprise uses Max's numbers until contracts
carry their own (`TODO price`). `packages/domain/src/billing/entitlements.ts` is the only way to
read it: `createEntitlements(...).can(org, feature)` / `.limit(org, key)` / `.channel(org, type)`
with the org's plan cached 30 s per process, and `PlanGuards` for quotas checked in the
transaction that creates the row, under a per-org advisory lock (`AgentsRepo.create` → `agents`;
eval run start → `eval_runs_per_month`, UTC calendar month; `assertChannel` → channels and
WhatsApp numbers, where a number beyond the included ones returns `included: false`, an add-on
the caller charges, not a refusal). A refusal is `PlanRequiredError` → `402 plan_required`
(`docs/10` §1). `concurrent_turns` is enforced by the `steer` worker (`docs/07` §10) and
`trace_retention_days` is read by the retention jobs (T-141).

## 3. Credit pricing

`credits = Σ usage_events.quantity × unit_price(provider, feature) × (1 + margin)`.

| Feature | Unit | Basis |
|---|---|---|
| Model tokens | per 1k in / out, by model | Provider list price × 1.3 margin; BYOK → 0 credits, small platform fee per turn |
| Auto model routing | — | Priced at the model actually used |
| STT (voice notes) | per second | Provider price × 1.3 |
| TTS | per 1k chars | same |
| Sandbox / browser | per minute | same |
| Scrape / search | per page / query | same |
| Voice call | per minute | carrier + STT/TTS + margin |
| Template relay (Later) | per message | Meta price + margin |
| Steered / test / eval turns | — | eval runs billed as runs per plan; steers free |

Balances in `credit_ledger`; usage computed when a turn settles; low-balance alerts at 20% and
0%; hard stop at 0 with a grace reserve for in-flight turns; auto top-up optional.

## 4. Payment collection (our billing)

- **Stripe Billing** for ES, PT, IT, US, MX, BR (cards, SEPA, Multibanco and MB WAY [VERIFY],
  PayPal and Satispay in IT [VERIFY], OXXO, Pix via Stripe) with tax ids (NIF in PT, Codice
  Fiscale / Partita IVA in IT).
- **Pan-LatAm aggregator** (dLocal or EBANX, contract after written country list) for our own
  billing in Tier B countries where Stripe and Mercado Pago are unavailable; PayPal as fallback.
- **Mercado Pago** subscriptions for AR, CL, CO, PE, UY (and as an alternative in MX/BR) where
  Stripe is unavailable or local methods dominate. Both integrate via webhooks into
  `credit_ledger`.
- Invoices with local tax fields (RFC + CFDI in MX is a notable burden → use a local invoicing
  provider such as Facturapi **[VERIFY]**; NF-e in BR via provider; CUIT/factura electrónica in
  AR).

Implemented (T-102, Stripe): `BillingProvider` (`packages/domain/src/billing/provider.ts`:
`createCheckout`, `createPortalSession`, `handleWebhook`, `recordUsage`) with the Stripe
implementation in `packages/domain/src/billing/stripe.ts`; Mercado Pago and the aggregator plug
in behind it in Phase 2. Plans, packs and prices are coded in `packages/domain/src/billing/plans.ts`
(the §2 placeholders; local prices in EUR, MXN and BRL are rounded conversions, other currencies
pay in USD; packs of 10, 50 and 200 credits at list price, **[DECISION NEEDED]** on both) and
`pnpm billing:sync-products` creates them in Stripe (products, monthly prices with
`currency_options` found by lookup key `charla_plan_<plan>_monthly` / `charla_pack_<n>`,
Starter's $1-for-3-months coupon, the `charla_credits` meter, the Billing Portal configuration).

- **Checkout** (`POST /api/webapp/billing/checkout`, owners and admins; UI in T-137): one Stripe
  customer per org (`organizations.billing_customer_id`), `tax_id_collection` and
  `customer_update` so the NIF/CIF, Partita IVA, NIF PT, RFC or CNPJ is on the customer and every
  invoice, required billing address, `automatic_tax` behind `STRIPE_AUTOMATIC_TAX`, the org's
  currency when priced, and no payment method list: Checkout shows what the dashboard enables
  per country (cards, SEPA, OXXO, Pix, Multibanco, MB WAY). Packs are one-off payments with an
  invoice. Creating a checkout changes neither the plan nor the credits.
- **Portal** (`POST /api/webapp/billing/portal`): card, plan change, cancellation at period end,
  invoices and tax ids.
- **Webhooks** (`POST /webhooks/stripe`, signature over the raw body): `checkout.session.completed`
  and `.async_payment_succeeded`, `invoice.paid`, `invoice.payment_failed`,
  `customer.subscription.updated` and `.deleted`. `BillingService.apply` claims the event id in
  `billing_events` inside the transaction that applies it; the ledger's unique index on the
  invoice or checkout is the second guard. A paid subscription checkout or invoice sets the plan;
  `invoice.paid` grants the month's credits (`subscription_create`: plus the first-month bonus,
  as a separate entry; `subscription_cycle`: the unused part of the previous grant expires first,
  unless `settings.billing.grantRollover`; `subscription_update` grants nothing, the new
  allowance comes with the next renewal); a paid pack checkout adds a `purchase`. A failed
  payment publishes `billing.payment_failed` and marks the org `past_due`; the hourly
  `billing-grace` task moves it to `free` seven days after the first failure, and a later paid
  invoice restores the plan. A price that maps to no plan answers `500` so Stripe retries.
  `invoice.paid` of an auto top-up invoice (metadata `charla_topup`, T-104) adds its pack as a
  `purchase` unless the runtime already did (same invoice ref).
- `recordUsage` sends meter events; the hourly overage batch of §6 is not wired (credits are
  prepaid, overage is bought in packs).
- Locally: `stripe listen --forward-to localhost:3000/webhooks/stripe` and its `whsec_` in
  `STRIPE_WEBHOOK_SECRET`; `packages/domain/src/billing/stripe.live.test.ts` runs against test
  mode on demand. Not included: Mercado Pago, the aggregator, CFDI/NF-e.

## 5. Payments *by agents* (tenant collects from its customers)

Decided in [ADR-0019](adr/0019-agent-payments.md) (2026-11-16); built by #426–#435. This is not
§4: the money goes straight to the business's own Mercado Pago or Stripe account, Charla never
holds it and takes no fee at GA (E3). The code lives in `packages/domain/src/payments/` behind a
`PaymentProvider` port of its own, with its own keys and webhook endpoints, never in
`packages/domain/src/billing/`.

### 5.1 Providers and connection

| Org country | Provider | Connection |
|---|---|---|
| AR, CL, CO, PE, UY | Mercado Pago | OAuth of Charla's application (authorization code + PKCE); tokens in the secrets service, kind `payment`, refreshed before their 180-day expiry |
| MX, BR | Mercado Pago by default, Stripe as the alternative | As above / as below |
| ES, PT, IT | Stripe Connect | Accounts v2 with `dashboard: full` (Standard equivalent), hosted onboarding; direct charges on the connected account, no `application_fee_amount`, no stored token |
| Tier B | None until #434; proposed: dLocal Go through 0 % split-payment collaborations ([ADR-0021](adr/0021-tier-b-payment-aggregator.md), Propuesta) | — |

Connecting a provider and setting the limits are done by an owner or admin in the dashboard
(#431); `payments_onboard_business` and `payments_request_limit` are not agent tools at GA.

**Mercado Pago adapter** (#428, `packages/domain/src/payments/mercadopago.ts`, subpath
`@charla/domain/payments/mercadopago`; a minimal `fetch` client, no SDK):

- *Connect:* an owner or admin calls `POST /api/webapp/payments/mercadopago/connect` and opens
  the returned `https://auth.mercadopago.com/authorization` URL (`platform_id=mp`, PKCE S256).
  The `state` is `<payload>.<HMAC>` (org, nonce, `redirect_uri`, 15-minute expiry) under a key
  derived from the client secret, and the PKCE verifier is an HMAC of its nonce: nothing to
  store, and only the org that started it can finish it. Mercado Pago redirects to
  `GET /api/webapp/payments/mercadopago/callback` (register `<PUBLIC_BASE_URL>` plus that path as
  the application's Redirect URL and enable PKCE in its details); it exchanges the code at
  `/oauth/token` with the verifier and seals the tokens as the `payment` secret. The URL holds
  the code and is never logged; the browser goes back to `/settings/payments?mercadopago=<outcome>`
  (the page is #431's).
- *Requests:* a Checkout Pro preference with the seller's token: one item, `external_reference`
  = request id, `expires: true`, `expiration_date_from/to`, no `marketplace_fee`, and
  `notification_url` = `<PUBLIC_BASE_URL>/webhooks/payments/mercadopago?source_news=webhooks&charla_request=<id>`
  (the runtime's `PUBLIC_BASE_URL`; without it the application's configured URL is used).
  Preferences take no idempotency key, so a retry first searches by `external_reference`.
- *Status:* the payments searched by `external_reference`: one `approved`, `refunded`,
  `charged_back` or `in_mediation` → `paid` (refunded amount from `transaction_amount_refunded`);
  one `pending`, `in_process` or `authorized` → `pending`; none → `expired` once the preference's
  `expiration_date_to` passed. Cancel sets `expiration_date_to` to now. Refunds:
  `POST /v1/payments/{id}/refunds` with `X-Idempotency-Key` = the action id.
- *Webhook:* `x-signature` HMAC-SHA256 over `id:<data.id>;request-id:<x-request-id>;ts:<ts>;`
  with `PAYMENTS_MERCADOPAGO_WEBHOOK_SECRET`; routed by `user_id`; the request id comes from the
  `charla_request` query parameter we set.
- *Unlinking* (#455): enable the topic «Application linking» (`mp-connect`) in the
  application's Webhooks settings, on `<PUBLIC_BASE_URL>/webhooks/payments/mercadopago`. Its
  notices are signed like the rest (`data.id` is the seller, and the body's `user_id` must be
  that signed id or the notice is refused); the adapter reports `application.deauthorized` as
  `connection.deauthorized` and `application.authorized` as `connection.authorized`, with no
  request. The `payments-webhook` worker takes the org's `active` connection of that account
  to `error` (`last_error` says the seller unlinked it), audits
  `payment_connection.deauthorized` and emails the owner (`reconnectEmail`, "unlinked" text)
  under the refresh's key `payment-reconnect:<connection>:<token expiry>`, so the same grant
  never sends two emails; only then is the event processed. A link, an unknown account or a
  connection already out of service change nothing.
- *Tokens:* 180 days. The `maintenance` task `payment-token-refresh` (daily 04:40 UTC) refreshes
  those expiring within 30 days (both tokens rotate); a refused refresh leaves the connection in
  `error` with its reason and emails `settings.notifications.ownerEmail` once. Mercado Pago has
  no revoke endpoint: `disconnect` sends nothing and the secret is deleted; the seller unlinks
  the application in their account.
- *Sandbox:* `PAYMENTS_MERCADOPAGO_SANDBOX=true` asks for test credentials (`test_token`).
- *Tests:* the shared contract suite (`@charla/domain/testing/payment-contract`) against a fake
  Mercado Pago over HTTP with answers recorded from the API reference
  (`@charla/domain/testing/mercadopago`), signature vectors from the official SDK, the service and
  the refresh on Postgres (`apps/runtime` `mercadopago.int.test.ts`) and, opt-in, the test
  accounts (`MP_LIVE=1`, `mercadopago.live.test.ts`).

**Stripe Connect adapter** (#429, `packages/domain/src/payments/stripe.ts`, subpath
`@charla/domain/payments/stripe`; the `stripe` SDK only there and in `billing/stripe.ts`):

- *Onboarding:* `startConnection` creates a v2 account (`dashboard: full`, `merchant` with
  `card_payments` requested, `fees_collector` and `losses_collector` `stripe`, the org's country
  and currency, `charla_org_id` metadata; `Idempotency-Key` `charla-connect-<connection id>`)
  and an Account Link whose `return_url` is the caller's URL plus `?code=<acct_…>&state=<…>`
  (`refresh_url` adds `refresh=1`: start again). The pending connection keeps the `acct_…`, so a
  restart continues that account. `state` is an HMAC of org and account keyed by the platform
  key. `completeConnection` checks it, that the account's metadata names the org, and that
  `card_payments` is `active`; otherwise `StripeOnboardingIncompleteError` and it stays pending.
- *Requests:* a Checkout Session on the connected account (`Stripe-Account`), `mode: payment`,
  one `price_data` line, `client_reference_id` and metadata `charla_payment_request_id`, no
  `application_fee_amount`, `expires_at` between 30 min and 24 h, `success_url`
  `PAYMENTS_STRIPE_SUCCESS_URL` (runtime, required with the key); `Idempotency-Key`
  `charla-pay-<request id>`, so a retry returns the same session. Status: `complete` and paid →
  `paid` (refunded amount from the latest charge), `expired` before its `expires_at` →
  `cancelled` (Charla expired it), after → `expired`, otherwise `pending`. Cancel expires an
  open session; refunds go to the payment intent with `charla-refund-<action id>`.
- *Webhook:* the endpoint is a Connect one (scope «Connected accounts») with its own `whsec_`
  (`PAYMENTS_STRIPE_WEBHOOK_SECRET`) and the events `checkout.session.completed`,
  `checkout.session.async_payment_succeeded`, `checkout.session.async_payment_failed`,
  `checkout.session.expired`, `charge.refunded`, `refund.updated`, `refund.failed`. An event
  without `account` (a platform or billing event) is refused with `400`; billing's secret fails
  its signature (`401`), and this endpoint's secret fails at `/webhooks/stripe`.
- *Account status* (#452): v2 thin events (scope «Your account») go to an event destination on
  `<PUBLIC_BASE_URL>/webhooks/payments/stripe-accounts` with its own `whsec_`
  (`PAYMENTS_STRIPE_ACCOUNTS_WEBHOOK_SECRET`, web only, optional: unset, the route answers
  `404`), subscribed to `v2.core.account[configuration.merchant].capability_status_updated`,
  `v2.core.account.closed` and `v2.core.account.updated` (`STRIPE_ACCOUNT_EVENTS`). The
  verifier (`createStripeAccountEventsVerifier`, `parseEventNotification`) stores each as
  `connection.account_updated` routed by `related_object.id`; a v1 event signed with that
  secret is `400`, the Connect secret `401`. The `payments-webhook` worker reads the account
  (`fetchAccountStatus`: `closed`, then `card_payments`) and moves the connection: `active` →
  activates a pending one or one in `error` by a restriction (`payment_connection.activated`);
  `restricted` → `error` only if it was active; `rejected`/`unsupported` → `error` if active or
  pending (`payment_connection.restricted`, `last_error` `restricted: …`); closed → `revoked`
  (`payment_connection.closed`, `last_error` `closed: …`), and the next `startConnection` opens
  a new account (`Idempotency-Key` `charla-connect-<connection>-after-<closed acct>`). An
  outage emails the owner (`reconnectEmail`, "restricted"/"closed" text) under
  `payment-outage:<connection>:<event>`; a retried job finds its own outage by the audit entry.
  `payments_request` sees `not_connected` meanwhile; the dashboard shows "reconnect" (`error`)
  or "connect" (`revoked`).
- *Disconnect:* `PaymentsService.disconnect` revokes the row, deletes its secret and audits;
  Stripe's adapter calls nothing (the account and its dashboard are the business's).
- *Tests:* contract suite against a fake Stripe over HTTP (`@charla/domain/testing/stripe-connect`),
  the service against Postgres (`stripe.int.test.ts`), the endpoint (`apps/web`
  `payments-stripe.int.test.ts`) and, opt-in, the sandbox (`STRIPE_CONNECT_LIVE=1`,
  `stripe.live.test.ts`).

### 5.2 Tables

| Table | Holds |
|---|---|
| `payment_connections` | One per org and provider: `status` (`pending | active | error | revoked`), `external_account_id` (Mercado Pago `user_id`, Stripe `acct_…`, unique per provider), country, currency, `secret_id` (Mercado Pago), `token_expires_at`, limits `max_request_minor` and `daily_total_minor`. |
| `payment_requests` | One per link: `id` (sent as `external_reference`), `amount_minor` (`bigint`, minor units), `currency` (ISO 4217), `refunded_minor`, `status`, provider refs, `checkout_url`, `expires_at`, `paid_at`, agent, conversation, contact, creating tool call, unique `(org_id, idempotency_key)`. |
| `payment_events` | Every provider notification, unique per `(provider, provider_event_id)`, with its request, type, redacted payload and `processed_at`. |

Built in #426 (migration 0051, columns in [06 §2.10](06-domain-model.md)). The limits live on
the connection, as the ADR says, rather than in a `payment_limits` table: one connection has one
currency, so its daily total is the per-currency total. A null limit is no cap; the day is the
org's calendar day; expired and cancelled requests stop counting. `createPaymentsService`
(`packages/domain/src/payments/service.ts`) reserves the request under the connection's lock,
calls the provider after the commit and answers `limit_exceeded`, `provider_unavailable`
(`country_without_provider | not_connected`) or `invalid_amount` (the provider would round it).
Tests use `FakePaymentProvider` (`@charla/domain/testing/payments`). Platform credentials:
`PAYMENTS_*` in `packages/config/src/env/payments.ts`.

States: `pending | paid | expired | cancelled | refunded | partially_refunded`. Transitions only
move forward (`pending` → `paid | expired | cancelled`; `paid` → `partially_refunded |
refunded`; `partially_refunded` → `refunded`). A payment confirmed after `expired` or `cancelled`
is still recorded as `paid` and flagged to the owner.

### 5.3 Webhook flow

1. `POST /webhooks/payments/mercadopago` or `/webhooks/payments/stripe` (one per provider, at
   platform level) verifies the signature (Stripe over the raw body; Mercado Pago its
   `x-signature` manifest). Bad signature → `401`, nothing stored.
2. The provider account in the notification routes it to the org's region (registry, ADR-0010);
   an unknown account → `200` and a log line.
3. One transaction: the `payment_events` row (a duplicate stops here with `200`); the row with
   `processed_at` null is its own outbox. After commit the `payments-webhook` job is enqueued
   with the org's and the event's ids (`payment-event-<id>`); `200`. The `maintenance` task
   `payment-dispatch` (every minute) queues again the events older than 2 minutes and younger
   than a day that no job finished.
4. The `payments-webhook` worker (`apps/runtime/src/payments/worker.ts`) fetches the payment from
   the provider (the API is the truth, the notification only a hint) and, holding the request's
   row, applies the transition (`nextPaymentState`, only forward) with its audit entry,
   `payment.*` outbound event and `payment_events.applied_status` in one transaction. On a
   change it wakes the agent with a platform note keyed `payment:<id>:<status>` (the notice
   service's idempotency), so it confirms the payment in the conversation, and only then marks
   the event processed: a retry after a crash only re-sends the note, which the key dedupes.
5. Reconciliation (#432, `apps/runtime/src/payments/reconcile.ts`) repairs missed notifications
   through the same transition. The `maintenance` task `payment-reconcile` (daily, 05:10 UTC)
   checks the `pending` requests created, and the `paid` or `partially_refunded` ones paid,
   within the last 30 days (`PAYMENT_RECONCILE_WINDOW_MS`); `payment-expiry-sweep` (hourly at
   :50) checks the `pending` ones past `expires_at`, which become `expired` when the provider
   says so (a payment that did arrive is applied as `paid`). Both take the requests of `active`
   connections in batches by org (`listReconcileDue`, `SKIP LOCKED` under `withSystem`
   `payment-reconcile:due`) and share the Redis lock `payment-reconcile`: a run that finds it
   taken skips. Per request, `PaymentsService.reconcileRequest` fetches the status and applies
   it with `nextPaymentState`; a change also writes, in that transaction, an unprocessed
   `payment_events` row of type `reconcile` (`provider_event_id`
   `reconcile:<id>:<status>:<refunded>`, unique, so two runs record it once) with its
   `applied_status`, and the run queues it as a `payments-webhook` job (`payment-event-<id>`).
   The worker then only sends the note (`payment:<id>:<status>`) and processes the event; a lost
   enqueue is picked up by `payment-dispatch`. Every correction is logged as a warning with
   both states; a provider failure changes nothing and is logged, and the next run asks again.
   Metric: `charla_payment_reconcile_total{outcome="unchanged|corrected|failed"}`.

### 5.4 Agent tools

Builtins with a policy declared in code and enforced by the dispatcher hooks (docs/09 §3; needs
#425):

| Tool | Behaviour | Policy |
|---|---|---|
| `payments_request` | Creates a link in the connection's currency (Mercado Pago preference with `expiration_date_to`, Stripe Checkout Session; default expiry 24 h, Stripe's maximum); returns `checkout_url`; on WhatsApp a `cta_url` button. Brazil's native `order_details` with Pix waits for F2. | `allow` inside the limits; over them `limit_exceeded`; idempotency key = tool call id; per-conversation hourly rate limit. No provider for the country → `provider_unavailable` (`country_without_provider` or `not_connected`). |
| `payments_request_status` | State of a request of this conversation, from `payment_requests`. | `allow`, read-only. |
| `payments_cancel_request` | Cancels a `pending` request of this conversation (expires the preference or Checkout Session). | `allow`; a paid request answers its state. |
| `payments_request_refund` | Total or partial refund, up to the unrefunded amount. | `approval: ask`, `approvalProof: verified` (dashboard or WhatsApp Flow, never chat buttons), `approvalFallback: refuse`; approver is an owner or admin; idempotency key = action id. |

Rules: integer minor units with one exponent table per provider; provider tokens never reach the
model, logs, traces, jobs or tool results; jobs carry ids only; KYC, disputes and payouts are
the provider's.

Built in #430 (`apps/runtime/src/mastra/tools/payments.ts`; names and policies in
`packages/domain/src/payments/tools.ts`, part of `BUILTIN_TOOL_POLICIES`):

- Offered when the agent version has `features.payments.enabled` (the agent editor's behaviour tab); the
  version's `provider` picks the connection.
- `payments_request` takes `amount` as a decimal string in major units (`"250.50"`, parsed with
  `parseMajor`: never rounded), an optional `currency` that must be the connection's, a
  `description` and `expires_in_hours`. The idempotency key is
  `payments_request:<turn id>:<tool call id>`, so a replayed step returns the same link. Errors
  are `{ status, error, message, … }` with `provider_unavailable` (`reason`), `limit_exceeded`
  (`limit`, `limit_amount`, `remaining_amount`), `unsupported_currency`, `invalid_amount`,
  `rate_limited` (5 links per conversation and hour, the policy's `rateLimit`) and
  `provider_error`; none of them calls the provider. On WhatsApp with the window open the result
  carries a `card` (the stored amount, description and URL, labels from `agent-strings.ts`) that
  the Mastra adapter turns into a `card` event: a `cta_url` button. Elsewhere it returns
  `share_text` with the link for the model to send.
- `payments_request_status` reads the stored request (the latest of the conversation without
  `request_id`) and asks the provider first only for a `pending` one not updated for a minute.
  The unsupported-claim guard (`claimFamiliesOf`) backs «pagado» only with a result in `paid`,
  `partially_refunded` or `refunded`; a created link backs no claim. The webhook's platform note
  tells the agent to read the state before confirming.
- `payments_request_refund` never runs from the model's call. A `beforeToolCall` hook refuses
  what could not be approved (another conversation's request, not paid, more than is left); the
  approval card is built from the stored request (`ActionGatewayDeps.builtinCard`: paid, already
  refunded, to refund); after an owner or admin approves on the dashboard,
  `runApprovedRefund` (`ActionDecisionsDeps.runBuiltin`) re-checks and calls
  `PaymentsService.refund` with the key `refund:<action id>`. Declined or expired, nothing runs.
- Results carry ids, amounts, states and the checkout URL only; never provider references,
  tokens or payer data. Evals hold the four tools (`HELD_BUILTINS`): stubs answer them.

## 6. Metering pipeline

Turn settles → `usage_events` rows (from trace spans) → `credit_ledger` usage entry →
`organizations.credit_balance` cache → Stripe/MP usage record for overage (hourly batch).
Reconciliation job compares provider invoices with our ledger monthly.

Implemented (T-100): one `usage_events` `model` row per model step when the turn closes (none
for held-back turns, except the gallery's test chat with a template, T-152: its rows carry no
`turn_id` and are charged under `credit_ref_type = 'template_try'` by
`CreditLedgerRepo.chargeUsage`, `docs/12` §2.2.5; and an agent's playground, T-173: no
`turn_id` nor `agent_id`, `source_key = agent-try:<agentId>:<id>:model:<step>`, charged under
`'agent_try'`, `docs/12` §2.2.7, so the usage view never counts tests as the agent's
production), priced from the dated table `packages/domain/src/billing/prices.ts` (a
new list gets a new `validFrom`; unknown prices stay `null`, never guessed; reviewed monthly).
The table in force from 2026-11-01 prices Claude Sonnet, Opus and Haiku 5.5 (`auto` resolves to
`DEFAULT_MODEL`, Sonnet 5.5 by default) from Anthropic's public list,
<https://platform.claude.com/docs/en/about-claude/pricing>, read 2026-11-17; Haiku 5.5 has a
second tier for prompts over 100,000 tokens (`longPrompt`). STT prices are still `null` (#197).
The media worker writes `stt` seconds, `vision` images and `extract` documents. The
`usage-reconcile` maintenance task runs daily at 05:00 UTC: for each billable turn that ended on
the previous UTC day it compares the model tokens of its `usage_events` with the
`model_generation` spans of its trace (`mastra.mastra_ai_spans`) and logs every drift as an
error with both totals; it corrects nothing.

Implemented (T-101): `credit_ledger` (append-only, `balance_after` on every entry) with
`organizations.credit_balance` as its cache, both written under a `FOR UPDATE` lock on the org
row (`CreditLedgerRepo`). The turn close charges the turn in its own transaction: each priced
`usage_events` row costs `quantity × unit_cost_usd × (1 + margin)` (margin per feature,
30 % by default; BYOK: model rows 0 plus a flat per-turn fee, **[DECISION NEEDED]** on the figure)
and the turn gets one negative `usage` entry for the exact sum of its rows rounded once to the
ledger's 4 decimals (`usageChargeUnits`): rounding each row would drop every step worth under
0.00005 credits, such as a short Claude Haiku step. Each row's `credits` stores its share of that
total (largest remainder), so the rows still add up to the entry; `unit_cost_usd` keeps 12
decimals (numeric(18,12)) so the blended price per 1k tokens loses nothing; unpriced rows (`TODO price`) are never charged:
the price is looked up when the row is written and the charge runs once, so filling in a price
later does not bill the rows already recorded. The `steer` worker refuses a batch that would start a turn when the balance is ≤ 0 and
one joining a running turn below −0.5 credits (the grace reserve), answers the contact with an
apology and publishes `billing.balance_exhausted`; a charge that crosses 20 % of the last grant
or purchase, or zero, publishes `billing.balance_low` / `billing.balance_exhausted`. Owner
notices and auto top-up are T-104 (below); Stripe is T-102. The usage view per agent and day (org
timezone) is `CreditLedgerRepo.usageByAgentDay`; each row carries its `source` (`production`,
`template_try` for `source_key` `try:…`, `agent_try` for `agent-try:<agentId>:…`, with that agent
as `agentId`), and Settings → Billing shows the tests apart as «Pruebas: plantillas» and
«Pruebas: playground de <agente>» (T-178, without touching `modelUsageDetailSchema`: old rows are
recognised by the same prefixes). Media usage (`stt`, `vision`, `extract`) has no
turn and is not charged yet.

Welcome credits (#471): a new org gets one `grant` of `BILLING_WELCOME_CREDITS` (default 5, the
Free plan's figure in §2; `0` turns it off; **[DECISION NEEDED]** on the final amount) so it can
try its agent before paying. The dashboard's org mirror grants it in the transaction that
creates `public.organizations` (`CreditLedgerRepo.grantWelcome`, ref `welcome:<orgId>`): a
retried creation grants once (the org lock, then the billing-ref unique index), and an org that
existed before (a new member's mirror) gets none. It is not part of an invoice's monthly grant,
so a paid plan's renewal does not expire it. Settings → Billing and the wizard's test step show
it; the playground's out-of-credits error links to Billing.

Implemented (T-104): after the turn close commits, `createBalanceAlerts().afterCharge`
(`apps/runtime/src/billing/balance-alerts.ts`) gets the charge. A charge that crossed 20 % or zero
(the same once-per-crossing rule as the events, so never one notice per turn while the balance
stays low) emails the owner (`settings.notifications.ownerEmail`; Resend, Mailpit locally;
idempotency key = event id) and, when the turn's agent has a team WhatsApp number among its
escalation routes (T-071), texts it while its 24 h window is open; there is no approved billing
template yet, so with the window closed only the email goes out. With
`settings.billing.autoTopup { enabled, packId, maxPerMonth = 3 }`, the charge that crosses 10 %
buys the pack: `BillingProvider.chargeTopUp` creates a one-off Stripe invoice (tax and tax ids as
on Checkout, metadata `charla_topup`), finalises it and pays it off-session with the customer's
default payment method (idempotency key per turn). Paid at once: the runtime adds the `purchase`
(ref = the invoice); still processing (SEPA…): the `invoice.paid` webhook adds it; declined: the
invoice is voided and nothing is added. At most `maxPerMonth` paid or pending top-ups per calendar
month (UTC); each attempt and each notice is a row in `audit_log` (`billing.auto_topup`,
`billing.balance_alert`). The runtime needs `STRIPE_SECRET_KEY` (same account as the web) to
buy; without it the org is only notified. The Stripe provider lives in `@charla/domain` so both
apps share it, imported from the `@charla/domain/billing/stripe` subpath.
