# Billing and limits

Usage metering, тарифные планы и лимиты 1C MCP Gateway.

## Prerequisites

- HTTP gateway (`npm run dev:http`) для billing API.
- Organization в Web Console (default: `default-org`).
- Понимание immutable usage events (TZ §9.1).

## Пошаговая настройка

### 1. Event-based accounting

Источник истины — append-only events:

| Event | Когда |
|-------|-------|
| `ToolCallCreated` | Каждый `tools/call` |
| `ResourceReadCreated` | MCP resource read |
| `ConnectionCreated` | Новый профиль |
| `ActiveProfileSwitched` | Смена базы |
| `IndexJobStarted/Finished` | BSL index rebuild |
| `EndpointRequestAccepted` | HTTP `/mcp` request |
| `BillingPeriodClosed` | Закрытие периода (Team+) |

Хранение: `.data/usage-events.jsonl` (или `ONEC_MCP_DATA_DIR`).

### 2. MVP metrics (аналитика)

Считаются без billing provider:

- tool calls / resource reads
- active projects / infobases
- indexed modules / objects
- index jobs / diagnostics jobs

API: `GET /api/billing?organizationId=default-org`

### 3. Тарифные планы

| Plan ID | Аудитория | Ключевые лимиты |
|---------|-----------|-----------------|
| `free-local` | Solo dev | 1 user, local stdio, index cap |
| `developer` | Dev/test | BSL context, diagnostics, docs |
| `team` | Org | Hosted endpoint, audit, shared index |
| `enterprise` | On-prem | SSO, vault, custom policies, dedicated |

Список планов: `GET /api/billing/plans`

Подписка (beta):

```http
POST /api/billing/subscription
Content-Type: application/json

{
  "organizationId": "default-org",
  "planId": "developer"
}
```

### 4. Pricing primitives (commercial)

Единицы биллинга (не смешивать в одном счёте хаотично):

- seats (users/principals)
- active projects / infobases
- hosted MCP endpoint
- indexed storage tier
- compute jobs (index, diagnostics, EDT validation)
- enterprise dedicated deployment

`risk multiplier` — internal rate-limit factor, не line item для клиента.

### 5. Rate limits на tokens

При выпуске HTTP MCP token:

```json
"rateLimit": { "windowSeconds": 60, "maxRequests": 120 }
```

Превышение → HTTP 429, event `EndpointRequestAccepted` с reject flag.

### 6. Usage alerts (Team Beta+)

Настройте мониторинг порогов:

- tool calls / day > plan limit
- index storage > tier
- diagnostics jobs queue depth

(Webhook billing provider — post-MVP.)

## Copy-ready config

```bash
export ONEC_MCP_DATA_DIR=/var/lib/onec-mcp-gateway
export ONEC_MCP_ACTOR=web-console
npm run dev:http

# Проверка статуса
curl -s "http://localhost:3000/api/billing?organizationId=default-org" | jq .
curl -s http://localhost:3000/api/billing/plans | jq .
```

Free/local — без subscription POST; лимиты enforced soft в metering.

## Проверка tools/list

Billing не добавляет tools. Проверка интеграции:

```
GET /api/billing → usage.toolCalls, usage.resourceReads за 30 дней
```

После серии tool calls счётчик должен расти.

## Первый тестовый prompt

```
Вызови list_profiles и bsl_search «тест» три раза. Затем через Web Console API
или описание usage проверь, что ToolCallCreated events увеличились.
Не выводи содержимое audit с PII.
```

## Типовые ошибки

| Симптом | Решение |
|---------|---------|
| usage = 0 | Wrong `organizationId`, events not flushed |
| 429 на /mcp | Token rateLimit — новый token или wait |
| Plan downgrade blocked | Active profiles > new plan cap — archive |
| Index cap exceeded | Cleanup old index cache, upgrade tier |
| Duplicate billing events | Idempotency on provider webhooks (enterprise) |

## Security warning

- Usage events могут содержать `profileId`, `toolName` — не log arguments with secrets.
- Billing API на `:3000` — protect auth (OIDC) before exposing publicly.
- Do not use usage metrics as security audit — use `.data/audit.jsonl`.
- Enterprise invoices — no PII from 1C OData in usage payloads.

## Related docs

- [SECURITY_MODEL.md](./SECURITY_MODEL.md) — token rate limits
- [DEPLOYMENT.md](./DEPLOYMENT.md) — prod scaling
- [PRODUCTION_STORAGE.md](./PRODUCTION_STORAGE.md) — usage file backup
- [RUNBOOK.md](./RUNBOOK.md) — incident on quota
