{
  "openapi": "3.1.0",
  "info": {
    "title": "0x Cloud API",
    "version": "1.0.0",
    "summary": "REST API облачного хостинга 0x Cloud: серверы, баланс, ключи, поддержка, вебхуки и MCP.",
    "description": "Базовый адрес – https://0x.cloud/v1. Формат – JSON, время – UTC (ISO 8601), деньги – доллары США.\n\nАвторизация: заголовок `Authorization: Bearer 0x_live_...` (ключ создаётся в кабинете) либо сессия кабинета. У ключа есть права (scopes): `servers.read`, `servers.*`, `*` и так далее. Нужное право указано у каждого метода в поле `x-required-scope`.\n\nИдентификаторы – строки вида `srv_8f3k2m9x4qpz7w1c`: три буквы называют вид (srv – сервер, snp – снапшот, ssh – ключ SSH, key – API-ключ, tkt – обращение, apr – запрос разрешения, evt – событие и так далее), остальное случайно. Числа вместо них не принимаются: поле с неизвестным идентификатором – 422 `unknown_identifier`, адрес с неизвестным идентификатором – 404. Номера образов систем (`os_template_id`) остаются числами из каталога.\n\nОшибки: `{\"error\": {\"code\": \"...\", \"message\": \"...\"}}`. Ошибки проверки полей приходят с кодом 422 в виде `{\"message\": \"...\", \"errors\": {\"поле\": [\"...\"]}}`.\n\nБезопасный повтор: к любому POST, PATCH и DELETE можно добавить заголовок `Idempotency-Key` (8–128 символов: латиница, цифры, `.`, `_`, `:`, `-`). Повтор с тем же ключом и тем же телом в течение 24 часов вернёт сохранённый ответ с заголовком `Idempotent-Replay: true`. Тот же ключ с другим телом – 409 `idempotency_key_reused`. Повтор, пока первый запрос ещё выполняется, – 409 `request_in_progress`.\n\nЧто важно знать заранее:\n- Публичных IPv4-адресов пока нет. Сервер доступен через веб-консоль в кабинете (https://0x.cloud/cabinet). Поля `ip`, `ipv4`, `ipv6` у сервера пустые, `has_public_ip` – false.\n- Онлайн-оплата пока не подключена: POST /topups отвечает 503 `payments_disabled`. Баланс пополняет администратор по обращению в поддержку.\n- Файрвол, бэкапы, снимки, смена тарифа, дополнительные IP, привязка Telegram, вывод средств и оплата картой пока не запущены – методы отвечают `not_available` (409 или 501), а не изображают успех.\n- Административные методы `/admin/*` не входят в публичный контракт и здесь не описаны."
  },
  "servers": [
    { "url": "https://0x.cloud/v1" }
  ],
  "security": [
    { "bearerAuth": [] },
    { "sessionCookie": [] }
  ],
  "tags": [
    { "name": "Public", "description": "Методы без авторизации." },
    { "name": "Auth", "description": "Вход в кабинет по почте и паролю (сессия в cookie)." },
    { "name": "Account", "description": "Аккаунт, профиль, ключи API, SSH-ключи, реферальная программа." },
    { "name": "Billing", "description": "Баланс, операции, пополнения." },
    { "name": "Catalog", "description": "Тарифы, образы, локации." },
    { "name": "Servers", "description": "Серверы и действия с ними." },
    { "name": "Support", "description": "Обращения в поддержку." },
    { "name": "Webhooks", "description": "Уведомления о событиях на ваш адрес." },
    { "name": "MCP", "description": "Удалённый MCP-сервер для ИИ-агентов." },
    { "name": "Not available", "description": "Заявлено, но ещё не запущено. Ответ – 501 not_available." }
  ],
  "paths": {
    "/auth/login": {
      "post": {
        "tags": ["Auth"], "operationId": "authLogin", "summary": "Вход по почте и паролю", "security": [],
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["email", "password"],
          "properties": { "email": { "type": "string", "format": "email" }, "password": { "type": "string" }, "remember": { "type": "boolean", "default": true } }
        } } } },
        "responses": {
          "200": { "description": "Сессия создана.", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "ok": { "type": "boolean" }, "redirect": { "type": "string" }, "user": { "$ref": "#/components/schemas/SessionUser" } }
          } } } },
          "422": { "description": "Неверная почта или пароль: `{\"ok\": false, \"error\": \"...\"}`, либо ошибка проверки полей.", "content": { "application/json": { "schema": { "type": "object" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/auth/register": {
      "post": {
        "tags": ["Auth"], "operationId": "authRegister", "summary": "Регистрация по почте и паролю", "security": [],
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["email", "password"],
          "properties": {
            "email": { "type": "string", "format": "email" },
            "password": { "type": "string", "minLength": 10 },
            "name": { "type": "string", "maxLength": 100 },
            "referral_code": { "type": "string" }
          }
        } } } },
        "responses": {
          "201": { "description": "Аккаунт создан, сессия открыта.", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "ok": { "type": "boolean" }, "redirect": { "type": "string" }, "message": { "type": "string" }, "user": { "$ref": "#/components/schemas/SessionUser" } }
          } } } },
          "422": { "$ref": "#/components/responses/Validation" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/auth/status": {
      "get": {
        "tags": ["Auth"], "operationId": "authStatus", "summary": "Открыта ли сессия", "security": [],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "authenticated": { "type": "boolean" }, "user": { "$ref": "#/components/schemas/SessionUser" } }
        } } } } }
      }
    },
    "/auth/logout": {
      "post": {
        "tags": ["Auth"], "operationId": "authLogout", "summary": "Выход", "security": [],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object", "properties": { "ok": { "type": "boolean" }, "redirect": { "type": "string" } }
        } } } } }
      }
    },
    "/public/pricing": {
      "get": {
        "tags": ["Public"], "operationId": "publicPricing", "summary": "Тарифы и цены без авторизации", "description": "То же самое отдаёт GET /pricing.", "security": [],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": {
            "plans": { "type": "array", "items": {
              "type": "object",
              "properties": {
                "code": { "type": "string" }, "slug": { "type": "string" }, "name": { "type": "string" },
                "vcpu": { "type": "integer" }, "ram_gb": { "type": "integer" }, "disk_gb": { "type": "integer" },
                "monthly_usd": { "type": "string" }, "hourly_usd": { "type": "string" },
                "available": { "type": "integer" }, "has_capacity": { "type": "boolean" },
                "periods": { "description": "Цены по периодам оплаты со скидками." }
              }
            } },
            "currency": { "type": "string", "const": "USD" },
            "discounts": { "type": "object", "description": "Скидки за срок, в процентах." }
          }
        } } } } }
      }
    },
    "/pricing": {
      "get": {
        "tags": ["Public"], "operationId": "pricing", "summary": "Тарифы и цены (то же, что /public/pricing)", "security": [],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object" } } } } }
      }
    },
    "/public/status": {
      "get": {
        "tags": ["Public"], "operationId": "publicStatus", "summary": "Состояние сервиса", "security": [],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "data": {
            "type": "object",
            "properties": {
              "status": { "type": "string", "enum": ["operational", "degraded"] },
              "generated_at": { "type": "string", "format": "date-time" },
              "services": { "type": "object", "additionalProperties": { "type": "string", "enum": ["up", "down", "unknown"] } },
              "sales": { "type": "object", "properties": { "enabled": { "type": "boolean" } } },
              "incidents": { "type": "array", "items": { "type": "object" } }
            }
          } }
        } } } } }
      }
    },
    "/public/capacity": {
      "get": {
        "tags": ["Public"], "operationId": "publicCapacity", "summary": "Наличие мест по тарифам", "security": [],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object", "properties": { "data": { "type": "object", "description": "Ключ – код тарифа." } }
        } } } } }
      }
    },
    "/public/price-log": {
      "get": {
        "tags": ["Public"], "operationId": "publicPriceLog", "summary": "История изменения цен", "security": [],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "data": { "type": "array", "items": { "type": "object", "properties": { "date": { "type": "string" }, "note": { "type": "string" } } } } }
        } } } } }
      }
    },
    "/public/csrf": {
      "get": {
        "tags": ["Public"], "operationId": "publicCsrf", "summary": "CSRF-токен для страниц сайта", "description": "Для методов /v1 токен не нужен.", "security": [],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "token": { "type": "string" } } } } } } }
      }
    },
    "/public/votes": {
      "get": {
        "tags": ["Public"], "operationId": "votesShow", "summary": "Голосование за страну следующей локации", "description": "Доступно без авторизации. Поле my_vote заполнено, если запрос пришёл с сессией или ключом.", "security": [],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/VoteSummary" } } } } }
      },
      "post": {
        "tags": ["Public"], "operationId": "votesStore", "summary": "Проголосовать или изменить голос", "description": "Нужна авторизация (сессия или любой действующий ключ). Один голос на аккаунт; повторный запрос меняет выбор.",
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["country"],
          "properties": { "country": { "type": "string", "enum": ["NL", "FI", "US", "GB", "PL", "SG", "TR", "KZ", "AE"] } }
        } } } },
        "responses": {
          "200": { "description": "Голос учтён.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/VoteSummary" } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "422": { "description": "unknown_country или ошибка проверки полей.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/openapi.json": {
      "get": {
        "tags": ["Public"], "operationId": "openapi", "summary": "Этот документ", "security": [],
        "responses": { "200": { "description": "OpenAPI 3.1", "content": { "application/json": { "schema": { "type": "object" } } } } }
      }
    },
    "/account": {
      "get": {
        "tags": ["Account"], "operationId": "accountShow", "summary": "Аккаунт", "x-required-scope": "account.read",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "data": {
              "type": "object",
              "properties": {
                "id": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" },
                "role": { "type": "string", "enum": ["customer", "admin"] },
                "trust_level": { "type": "integer" },
                "balance": { "type": "string", "example": "12.50" },
                "referral_balance": { "type": "string" },
                "streamer_mode": { "type": "boolean" },
                "theme": { "type": "string" },
                "created_at": { "type": ["string", "null"], "format": "date-time" }
              }
            } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" }
        }
      }
    },
    "/account/limits": {
      "get": {
        "tags": ["Account"], "operationId": "accountLimits", "summary": "Лимиты аккаунта", "x-required-scope": "account.read",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "data": {
              "type": "object",
              "properties": {
                "max_active_servers": { "type": "integer" },
                "current_active_servers": { "type": "integer" },
                "max_monthly_spend_usd": { "type": "string" },
                "trust_level": { "type": "integer" }
              }
            } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" }
        }
      }
    },
    "/account/sessions": {
      "get": {
        "tags": ["Account"], "operationId": "accountSessions", "summary": "Текущая сессия", "description": "Возвращает только сессию, из которой сделан запрос.", "x-required-scope": "account.read",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "data": { "type": "array", "items": {
              "type": "object",
              "properties": { "id": { "type": "string" }, "ip_address": { "type": "string" }, "user_agent": { "type": ["string", "null"] }, "last_active": { "type": "string", "format": "date-time" }, "is_current": { "type": "boolean" } }
            } } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" }
        }
      }
    },
    "/account/audit": {
      "get": {
        "tags": ["Account"], "operationId": "accountAudit", "summary": "Журнал действий (последние 50)", "x-required-scope": "account.read",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "data": { "type": "array", "items": {
              "type": "object",
              "properties": { "id": { "type": "string" }, "action": { "type": "string" }, "details": { "type": ["object", "null"] }, "ip": { "type": ["string", "null"] }, "created_at": { "type": ["string", "null"], "format": "date-time" } }
            } } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" }
        }
      }
    },
    "/account/profile": {
      "get": {
        "tags": ["Account"], "operationId": "profileShow", "summary": "Профиль", "description": "То же самое отдаёт GET /profile.", "x-required-scope": "account.read",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "data": {
              "type": "object",
              "properties": {
                "id": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" }, "role": { "type": "string" },
                "trust_level": { "type": "integer" }, "streamer_mode": { "type": "boolean" }, "theme": { "type": "string" },
                "telegram_id": { "type": ["integer", "null"] }, "telegram_username": { "type": ["string", "null"] }
              }
            } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" }
        }
      },
      "patch": {
        "tags": ["Account"], "operationId": "profileUpdate", "summary": "Изменить профиль или пароль", "description": "То же самое делает PATCH /profile.", "x-required-scope": "account.update",
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object",
          "properties": {
            "name": { "type": "string", "maxLength": 100 },
            "streamer_mode": { "type": "boolean" },
            "theme": { "type": "string", "enum": ["cobalt", "slate", "emerald", "amber"] },
            "current_password": { "type": "string", "description": "Обязателен вместе с new_password." },
            "new_password": { "type": "string", "minLength": 8 }
          }
        } } } },
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "ok": { "type": "boolean" }, "data": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" } } } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "422": { "description": "invalid_current_password или ошибка проверки полей.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/profile": {
      "get": {
        "tags": ["Account"], "operationId": "profileShowAlias", "summary": "Профиль (то же, что GET /account/profile)", "x-required-scope": "account.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object" } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      },
      "patch": {
        "tags": ["Account"], "operationId": "profileUpdateAlias", "summary": "Изменить профиль (то же, что PATCH /account/profile)", "x-required-scope": "account.update",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object" } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/account/delete": {
      "post": {
        "tags": ["Account"], "operationId": "accountDelete", "summary": "Удалить аккаунт", "description": "Возможно, когда на балансе меньше $1.00 и нет серверов (кроме окончательно удалённых).", "x-required-scope": "account.delete",
        "responses": {
          "200": { "$ref": "#/components/responses/Ok" },
          "400": { "description": "balance_not_empty или cannot_delete_with_active_servers.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" }
        }
      }
    },
    "/account/key": {
      "get": {
        "tags": ["Account"], "operationId": "currentKey", "summary": "Ключ, которым сделан запрос", "description": "Права, лимит трат, потрачено и осталось. Доступно любому ключу. Для сессии кабинета – {\"auth\": \"session\"}.",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "allOf": [{ "$ref": "#/components/schemas/ApiKey" }, { "type": "object", "properties": { "auth": { "type": "string", "enum": ["api_key", "session"] } } }] } } } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" }
        }
      }
    },
    "/account/tokens": {
      "get": {
        "tags": ["Account"], "operationId": "tokensList", "summary": "Ключи API", "description": "То же самое отдаёт GET /api-keys.", "x-required-scope": "tokens.read",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": {
            "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/ApiKey" } } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" }
        }
      },
      "post": {
        "tags": ["Account"], "operationId": "tokensCreate", "summary": "Создать ключ API", "description": "То же самое делает POST /api-keys. Ключ показывается один раз.", "x-required-scope": "tokens.write",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["name"],
          "properties": {
            "name": { "type": "string", "maxLength": 100 },
            "scopes": { "type": "array", "maxItems": 20, "items": { "type": "string", "pattern": "^[a-z*]+(\\.[a-z*]+)?$" }, "description": "По умолчанию: servers.*, billing.read, account.read." },
            "rate_limit": { "type": "integer", "minimum": 10, "maximum": 1000, "description": "Запросов в минуту, по умолчанию 120." },
            "spend_mode": { "type": "string", "enum": ["unlimited", "limited", "none"], "description": "Сколько ключ может тратить с баланса: unlimited – без лимита, limited – не больше spend_limit_usd за spend_period, none – тратить нельзя. Без этого поля: положительный spend_limit_usd означает limited, иначе unlimited." },
            "spend_limit_usd": { "type": "number", "minimum": 0, "maximum": 100000, "description": "Лимит для режима limited, не меньше 0.01." },
            "spend_period": { "type": "string", "enum": ["day", "month", "total"], "description": "Период лимита: сутки, календарный месяц (по умолчанию) или всё время действия ключа." },
            "allowed_ips": { "type": "array", "maxItems": 20, "items": { "type": "string" }, "description": "Адреса и сети IPv4, с которых ключ работает. Пусто – с любых." },
            "expires_days": { "type": "integer", "minimum": 0, "maximum": 3650, "description": "0 или отсутствует – без срока." }
          }
        } } } },
        "responses": {
          "201": { "description": "Ключ создан.", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "data": {
              "type": "object",
              "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "key": { "type": "string", "description": "0x_live_... Показывается один раз." }, "key_prefix": { "type": "string" }, "scopes": { "type": "array", "items": { "type": "string" } } }
            } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "422": { "$ref": "#/components/responses/Validation" }
        }
      }
    },
    "/account/tokens/{id}": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "patch": {
        "tags": ["Account"], "operationId": "tokensUpdate", "summary": "Изменить ключ: название, права, лимит трат", "description": "Права, лимиты и срок меняются только из кабинета (сессия). Запрос, подписанный API-ключом, может изменить лишь название – иначе 403 cabinet_only.", "x-required-scope": "tokens.write",
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "properties": { "name": { "type": "string", "maxLength": 100 }, "scopes": { "type": "array", "items": { "type": "string" } }, "rate_limit": { "type": "integer", "minimum": 10, "maximum": 1000 }, "spend_mode": { "type": "string", "enum": ["unlimited", "limited", "none"] }, "spend_limit_usd": { "type": "number", "minimum": 0, "maximum": 100000 }, "spend_period": { "type": "string", "enum": ["day", "month", "total"] }, "allowed_ips": { "type": "array", "items": { "type": "string" } }, "expires_days": { "type": "integer", "minimum": 0, "maximum": 3650 } }
        } } } },
        "responses": { "200": { "$ref": "#/components/responses/Ok" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      },
      "delete": {
        "tags": ["Account"], "operationId": "tokensRevoke", "summary": "Отозвать ключ", "description": "То же самое делает DELETE /api-keys/{id}.", "x-required-scope": "tokens.revoke",
        "responses": { "200": { "$ref": "#/components/responses/Ok" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/api-keys": {
      "get": {
        "tags": ["Account"], "operationId": "apiKeysList", "summary": "Ключи API (то же, что GET /account/tokens)", "x-required-scope": "tokens.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/ApiKey" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      },
      "post": {
        "tags": ["Account"], "operationId": "apiKeysCreate", "summary": "Создать ключ API (то же, что POST /account/tokens)", "x-required-scope": "tokens.write",
        "responses": { "201": { "description": "Ключ создан.", "content": { "application/json": { "schema": { "type": "object" } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "422": { "$ref": "#/components/responses/Validation" } }
      }
    },
    "/api-keys/{id}": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "delete": {
        "tags": ["Account"], "operationId": "apiKeysRevoke", "summary": "Отозвать ключ (то же, что DELETE /account/tokens/{id})", "x-required-scope": "tokens.revoke",
        "responses": { "200": { "$ref": "#/components/responses/Ok" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/account/notifications": {
      "get": {
        "tags": ["Account"], "operationId": "accountNotifications", "summary": "Уведомления", "description": "То же, что GET /notifications: список уведомлений аккаунта.", "x-required-scope": "notifications.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "object" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/account/notifications/{id}/read": {
      "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
      "post": {
        "tags": ["Account"], "operationId": "accountNotificationRead", "summary": "Отметить уведомление прочитанным", "x-required-scope": "notifications.write",
        "responses": { "200": { "$ref": "#/components/responses/Ok" }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/account/telegram/link": {
      "post": {
        "tags": ["Not available"], "operationId": "telegramLink", "summary": "Привязать Telegram – пока не запущено", "x-required-scope": "account.update",
        "responses": { "501": { "$ref": "#/components/responses/NotAvailable" }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/account/telegram": {
      "delete": {
        "tags": ["Not available"], "operationId": "telegramUnlink", "summary": "Отвязать Telegram – пока не запущено", "x-required-scope": "account.update",
        "responses": { "501": { "$ref": "#/components/responses/NotAvailable" }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/ssh-keys": {
      "get": {
        "tags": ["Account"], "operationId": "sshKeysList", "summary": "SSH-ключи", "x-required-scope": "account.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/SshKey" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      },
      "post": {
        "tags": ["Account"], "operationId": "sshKeysCreate", "summary": "Добавить SSH-ключ", "x-required-scope": "account.update",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["name", "public_key"],
          "properties": { "name": { "type": "string", "maxLength": 80 }, "public_key": { "type": "string", "maxLength": 8192, "description": "ssh-ed25519, ssh-rsa или ssh-ecdsa-sha2-nistp256." } }
        } } } },
        "responses": { "201": { "description": "Ключ добавлен.", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/SshKey" } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "422": { "$ref": "#/components/responses/Validation" } }
      }
    },
    "/ssh-keys/{id}": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "delete": {
        "tags": ["Account"], "operationId": "sshKeysDelete", "summary": "Удалить SSH-ключ", "x-required-scope": "account.update",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "object", "properties": { "deleted": { "type": "boolean" } } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/referrals": {
      "get": {
        "tags": ["Account"], "operationId": "referralsShow", "summary": "Реферальная программа", "x-required-scope": "account.read",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "data": {
              "type": "object",
              "properties": {
                "code": { "type": "string" }, "link": { "type": "string" }, "balance": { "type": "string" }, "currency": { "type": "string" },
                "rate_percent": { "type": "integer" }, "referrals_count": { "type": "integer" },
                "earnings": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "amount": { "type": "string" }, "description": { "type": ["string", "null"] }, "created_at": { "type": ["string", "null"], "format": "date-time" } } } }
              }
            } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" }
        }
      }
    },
    "/referrals/transfer": {
      "post": {
        "tags": ["Account"], "operationId": "referralsTransfer", "summary": "Перевести весь реферальный баланс на основной", "x-required-scope": "account.update",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "object", "properties": { "transferred": { "type": "string" }, "currency": { "type": "string" } } } } } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "422": { "description": "referral_balance_empty", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/balance": {
      "get": {
        "tags": ["Billing"], "operationId": "balanceShow", "summary": "Баланс", "x-required-scope": "billing.read",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "data": {
              "type": "object",
              "properties": {
                "balance_usd": { "type": "string", "example": "12.50" },
                "balance_micro": { "type": "integer", "description": "Миллионные доли доллара." },
                "referral_balance_usd": { "type": "string" },
                "currency": { "type": "string", "const": "USD" }
              }
            } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" }
        }
      }
    },
    "/balance/entries": {
      "get": {
        "tags": ["Billing"], "operationId": "balanceEntries", "summary": "Операции по балансу", "description": "По 30 на страницу. То же самое отдаёт GET /transactions. `?format=csv` или GET /balance/entries.csv – выгрузка CSV (до 5000 строк).", "x-required-scope": "billing.read",
        "parameters": [
          { "name": "page", "in": "query", "schema": { "type": "integer", "minimum": 1 } },
          { "name": "format", "in": "query", "schema": { "type": "string", "enum": ["csv"] } }
        ],
        "responses": {
          "200": { "description": "OK", "content": {
            "application/json": { "schema": {
              "type": "object",
              "properties": {
                "data": { "type": "array", "items": { "$ref": "#/components/schemas/Transaction" } },
                "current_page": { "type": "integer" }, "last_page": { "type": "integer" }, "total": { "type": "integer" }
              }
            } },
            "text/csv": { "schema": { "type": "string" } }
          } },
          "401": { "$ref": "#/components/responses/Unauthenticated" }
        }
      }
    },
    "/balance/entries.csv": {
      "get": {
        "tags": ["Billing"], "operationId": "balanceEntriesCsv", "summary": "Операции по балансу в CSV", "x-required-scope": "billing.read",
        "responses": { "200": { "description": "CSV: id, type, amount_usd, balance_after_usd, description, created_at.", "content": { "text/csv": { "schema": { "type": "string" } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/transactions": {
      "get": {
        "tags": ["Billing"], "operationId": "transactions", "summary": "Операции по балансу (то же, что GET /balance/entries)", "x-required-scope": "billing.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object" } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/topups": {
      "get": {
        "tags": ["Billing"], "operationId": "topupsList", "summary": "Пополнения (последние 30)", "x-required-scope": "billing.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Topup" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      },
      "post": {
        "tags": ["Billing"], "operationId": "topupsCreate", "summary": "Создать пополнение", "description": "Онлайн-оплата пока не подключена: метод отвечает 503 payments_disabled. Баланс пополняет администратор по обращению в поддержку.", "x-required-scope": "billing.topup",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["amount_usd"],
          "properties": { "amount_usd": { "type": "number", "minimum": 5, "maximum": 5000 }, "gateway": { "type": "string", "maxLength": 32 }, "currency": { "type": "string", "maxLength": 8 } }
        } } } },
        "responses": {
          "201": { "description": "Пополнение создано (только когда оплата подключена).", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/Topup" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "422": { "$ref": "#/components/responses/Validation" },
          "503": { "description": "payments_disabled – онлайн-оплата не подключена.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/topups/{id}": {
      "parameters": [{ "$ref": "#/components/parameters/TopupId" }],
      "get": {
        "tags": ["Billing"], "operationId": "topupsShow", "summary": "Одно пополнение", "x-required-scope": "billing.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/Topup" } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/topups/{id}/checkout": {
      "parameters": [{ "$ref": "#/components/parameters/TopupId" }],
      "post": {
        "tags": ["Billing"], "operationId": "topupsCheckout", "summary": "Ссылка на оплату пополнения", "x-required-scope": "billing.topup",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "checkout_url": { "type": "string" }, "topup": { "$ref": "#/components/schemas/Topup" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "503": { "description": "payments_disabled", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/topups/{id}/refresh": {
      "parameters": [{ "$ref": "#/components/parameters/TopupId" }],
      "post": {
        "tags": ["Billing"], "operationId": "topupsRefresh", "summary": "Проверить статус пополнения", "x-required-scope": "billing.topup",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/Topup" }, "is_paid": { "type": "boolean" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/invoices/{id}": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Billing"], "operationId": "invoiceShow", "summary": "Счёт", "description": "Счета пока не выставляются: метод всегда отвечает 404 not_found. То же самое – GET /invoices/{id}.pdf.", "x-required-scope": "billing.read",
        "responses": { "404": { "$ref": "#/components/responses/NotFound" }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/invoices/{id}/card-checkout": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Not available"], "operationId": "cardCheckout", "summary": "Оплата картой – пока не запущено", "x-required-scope": "billing.pay",
        "responses": { "501": { "$ref": "#/components/responses/NotAvailable" }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/withdrawals": {
      "post": {
        "tags": ["Not available"], "operationId": "withdrawalsCreate", "summary": "Вывод средств – пока не запущено", "x-required-scope": "billing.withdraw",
        "responses": { "501": { "$ref": "#/components/responses/NotAvailable" }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/plans": {
      "get": {
        "tags": ["Catalog"], "operationId": "plansList", "summary": "Тарифы", "description": "То же самое отдаёт GET /catalog.", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Plan" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/catalog": {
      "get": {
        "tags": ["Catalog"], "operationId": "catalog", "summary": "Тарифы (то же, что GET /plans)", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Plan" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/images": {
      "get": {
        "tags": ["Catalog"], "operationId": "imagesList", "summary": "Операционные системы для тарифа", "description": "Если гипервизор временно недоступен, список пустой.", "x-required-scope": "servers.read",
        "parameters": [{ "name": "plan", "in": "query", "schema": { "type": "string" }, "description": "Код тарифа. Без него – младший тариф." }],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Image" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/apps": {
      "get": {
        "tags": ["Catalog"], "operationId": "appsList", "summary": "Готовые серверы", "description": "Серверы на Ubuntu 24.04 с уже установленными программами: agents – Claude Code, Codex, Node.js, Python, Git, tmux, Docker; bots – Python с библиотеками для Telegram и Discord, Node.js с pm2. Чтобы создать такой сервер, передайте в POST /servers поле app с кодом. available: false – образ ещё не опубликован, такой сервер пока не создаётся.", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "object", "properties": { "code": { "type": "string" }, "name": { "type": "string" }, "summary": { "type": "string" }, "description": { "type": "string" }, "includes": { "type": "array", "items": { "type": "string" } }, "os": { "type": "string" }, "available": { "type": "boolean" }, "min_disk_gb": { "type": ["integer", "null"] }, "updated_at": { "type": ["string", "null"] } } } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/locations": {
      "get": {
        "tags": ["Catalog"], "operationId": "locationsList", "summary": "Локации", "description": "Сейчас одна локация – Франкфурт.", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "data": { "type": "array", "items": {
            "type": "object",
            "properties": { "code": { "type": "string" }, "name": { "type": "string" }, "country": { "type": "string" }, "flag": { "type": "string" }, "available": { "type": "boolean" }, "is_default": { "type": "boolean" } }
          } } }
        } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/servers": {
      "get": {
        "tags": ["Servers"], "operationId": "serversList", "summary": "Серверы", "x-required-scope": "servers.read",
        "parameters": [{ "name": "status", "in": "query", "schema": { "type": "string", "enum": ["deleted"] }, "description": "deleted – показать удалённые серверы вместо действующих." }],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Server" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "403": { "$ref": "#/components/responses/Forbidden" } }
      },
      "post": {
        "tags": ["Servers"], "operationId": "serversCreate", "summary": "Создать сервер", "description": "Сначала отправьте dry_run: true, покажите клиенту точную USD-цену и получите согласие. Реальное создание требует неизменённый pricing_fingerprint из этой котировки (срок 10 минут). Цена и ресурсы сверяются до списания: при изменении условий ответ 409 price_changed содержит error.quote; автоматический повтор по новой цене запрещён. После неизвестного сетевого результата повторяйте точное прежнее тело и Idempotency-Key. Стоимость периода списывается сразу; для почасовой оплаты нужен баланс не меньше $5.00. Почасовая цена содержит шесть дробных знаков и точно соответствует hourly_micro. При dry_run сервер не создаётся и деньги не списываются. Тарифы под заказ после этой же котировки оформляются через POST /server-requests. Лимит – 10 действующих серверов.", "x-required-scope": "servers.create",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["plan"],
          "properties": {
            "plan": { "type": "string", "description": "Код тарифа, например s1-2." },
            "hostname": { "type": "string", "minLength": 2, "maxLength": 63, "pattern": "^[A-Za-z0-9][A-Za-z0-9.-]*$" },
            "os_template_id": { "type": "integer", "minimum": 1, "description": "ID из GET /images." },
            "os_template": { "type": "string", "maxLength": 120, "description": "Название, если ID неизвестен. По умолчанию Ubuntu 24.04." },
            "billing_cycle": { "type": "string", "enum": ["hourly", "monthly", "quarterly", "semiannual", "annual"], "default": "monthly" },
            "ssh_key_id": { "type": "string" },
            "extra_disk_gb": { "type": "integer", "minimum": 0, "maximum": 500 },
            "extra_ips_count": { "type": "integer", "minimum": 0, "maximum": 5, "description": "Дополнительные IPv4 пока недоступны: значение больше 0 – 409 ipv4_unavailable." },
            "ttl_hours": { "type": "integer", "minimum": 1, "maximum": 720, "description": "Таймер: через столько часов сервер удалится сам, неиспользованный остаток вернётся на баланс." },
            "ttl_minutes": { "type": "integer", "minimum": 10, "maximum": 43200, "description": "То же в минутах. Таймер проверяется раз в 5 минут." },
            "startup_script": { "type": "string", "maxLength": 65536, "description": "Скрипт sh: выполнится от root один раз, когда сервер будет готов, как фоновая задача. Состояние – поле startup сервера." },
            "app": { "type": "string", "enum": ["agents", "bots"], "description": "Готовый сервер из GET /apps: система Ubuntu 24.04 с уже установленными программами. Вместо os_template, os_template_id и from_snapshot. 409 app_unavailable – образ ещё не опубликован." },
            "from_snapshot": { "type": "string", "description": "id готового снапшота: сервер поднимется с его диском. Диск тарифа вместе с extra_disk_gb должен быть не меньше disk_gb снапшота. Сервер получает новый пароль root (в ответе) и новое имя; операционная система берётся из снапшота." },
            "dry_run": { "type": "boolean" },
            "pricing_fingerprint": { "type": "string", "minLength": 32, "maxLength": 2048, "description": "Непрозрачная подтверждённая котировка. Обязательна для реального заказа, не нужна при dry_run." }
          }
        }, "example": { "plan": "s1-2", "os_template": "Ubuntu 24.04", "billing_cycle": "hourly", "ttl_hours": 6, "dry_run": true } } } },
        "responses": {
          "200": { "description": "Только при dry_run: расчёт цены.", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": {
              "dry_run": { "type": "boolean", "const": true }, "plan": { "type": "string" }, "billing_cycle": { "type": "string" },
              "monthly_usd": { "type": "string" }, "hourly_usd": { "type": "string", "example": "0.006150", "description": "Точная ставка с шестью дробными знаками." }, "total_usd": { "type": "string" }, "total_micro": { "type": "integer" },
              "monthly_micro": { "type": "integer" }, "hourly_micro": { "type": "integer" }, "pricing_fingerprint": { "type": "string", "minLength": 32, "maxLength": 2048 }, "pricing_expires_at": { "type": "string", "format": "date-time" },
              "resources": { "type": "object", "required": ["vcpu", "ram_mb", "disk_gb"], "properties": { "vcpu": { "type": "integer" }, "ram_mb": { "type": "integer" }, "disk_gb": { "type": "integer", "description": "Полный диск, включая extra_disk_gb." } }, "description": "Покажите ресурсы вместе с ценой перед согласием: смена характеристик при прежней цене тоже требует подтверждения." }
            }
          } } } },
          "201": { "description": "Сервер создаётся. Пароль root показывается один раз.", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "data": { "$ref": "#/components/schemas/Server" }, "username": { "type": "string", "const": "root" }, "password": { "type": ["string", "null"] } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "402": { "description": "insufficient_balance – в ответе поле required_usd.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "description": "plan_not_found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "409": { "description": "price_changed (error.quote содержит новые условия; нужно новое согласие), plan_by_request, server_limit_reached, ipv4_unavailable, idempotency_key_reused, idempotency_authorization_changed или request_in_progress.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "422": { "description": "template_unavailable или ошибка проверки полей.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "502": { "description": "provider_error или provisioning_failed – деньги не списаны.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/servers/{id}": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "serversShow", "summary": "Один сервер", "description": "Статус из базы. Актуальный статус от гипервизора – GET /servers/{id}/state.", "x-required-scope": "servers.read",
        "responses": { "200": { "$ref": "#/components/responses/Server" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      },
      "patch": {
        "tags": ["Servers"], "operationId": "serversUpdate", "summary": "Переименовать сервер", "description": "Сейчас меняется только hostname. Смена тарифа, бэкапы и дополнительные IP отвечают 409 not_available / ipv4_unavailable; PTR – только после появления публичного IP.", "x-required-scope": "servers.update",
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "hostname": { "type": "string", "minLength": 2, "maxLength": 63, "pattern": "^[A-Za-z0-9][A-Za-z0-9.-]*$" }, "ptr": { "type": "string", "maxLength": 255 } }
        } } } },
        "responses": { "200": { "$ref": "#/components/responses/Server" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" }, "409": { "$ref": "#/components/responses/Conflict" }, "422": { "$ref": "#/components/responses/Validation" } }
      },
      "delete": {
        "tags": ["Servers"], "operationId": "serversDelete", "summary": "Удалить сервер", "description": "Неиспользованный оплаченный остаток возвращается на баланс с точностью до цента. Сервер выключается и 24 часа может быть восстановлен через POST /servers/{id}/restore.", "x-required-scope": "servers.delete",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "responses": {
          "200": { "description": "Удалён.", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": { "ok": { "type": "boolean" }, "refund_usd": { "type": "string" }, "restorable_until": { "type": "string", "format": "date-time" } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "server_already_deleted", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/servers/{id}/restore": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Servers"], "operationId": "serversRestore", "summary": "Восстановить удалённый сервер", "description": "В течение 24 часов после удаления. С баланса списывается сумма, возвращённая при удалении.", "x-required-scope": "servers.update",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "responses": {
          "200": { "$ref": "#/components/responses/Server" },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "402": { "description": "insufficient_balance", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "server_not_restorable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/servers/{id}/freeze": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Servers"], "operationId": "serversFreeze", "summary": "Заморозить сервер", "description": "Сервер выключается, его диск переносится в хранилище, машина освобождается. Статус `frozen`; пока идёт перенос (1–3 минуты) – `operation: freezing`. Неиспользованный остаток оплаченного периода возвращается на баланс (`refund_usd`). Хранение стоит `freeze_price_monthly` и списывается по часам.", "x-required-scope": "servers.update",
        "responses": {
          "200": { "$ref": "#/components/responses/Server" },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "server_frozen, server_not_ready, snapshot_in_progress", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "503": { "description": "freeze_unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/servers/{id}/unfreeze": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Servers"], "operationId": "serversUnfreeze", "summary": "Разморозить сервер", "description": "Сервер собирается заново из сохранённой копии (2–5 минут, статус `provisioning`, затем `running`). Данные, пароль root и SSH-ключи остаются прежними. Для сервера с оплатой за период списывается новый период – сумма в `freeze.unfreeze_charge`.", "x-required-scope": "servers.update",
        "responses": {
          "200": { "$ref": "#/components/responses/Server" },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "402": { "description": "insufficient_balance", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "server_not_frozen, server_busy, no_capacity", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "503": { "description": "unfreeze_unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/servers/{id}/power": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Servers"], "operationId": "serversPower", "summary": "Питание", "description": "boot (start) – включить; shutdown (stop) – выключить корректно; reboot (restart) – перезагрузить; poweroff (powerOff, reset) – принудительно.", "x-required-scope": "servers.power",
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["action"],
          "properties": { "action": { "type": "string", "enum": ["boot", "start", "shutdown", "stop", "reboot", "restart", "poweroff", "powerOff", "reset"] } }
        } } } },
        "responses": {
          "200": { "description": "Команда принята гипервизором.", "content": { "application/json": { "schema": {
            "type": "object", "properties": { "ok": { "type": "boolean" }, "status": { "type": "string" }, "server": { "$ref": "#/components/schemas/Server" } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "server_busy, server_suspended, server_deleted или server_not_provisioned.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "422": { "$ref": "#/components/responses/Validation" },
          "502": { "$ref": "#/components/responses/ProviderError" }
        }
      }
    },
    "/servers/{id}/state": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "serversState", "summary": "Сервер с актуальным статусом от гипервизора", "x-required-scope": "servers.read",
        "responses": { "200": { "$ref": "#/components/responses/Server" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/servers/{id}/wait": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "serversWait", "summary": "Дождаться конца установки", "description": "Держит соединение, пока сервер в статусе provisioning, но не дольше timeout секунд. ready = false – повторите запрос.", "x-required-scope": "servers.read",
        "parameters": [{ "name": "timeout", "in": "query", "schema": { "type": "integer", "minimum": 1, "maximum": 25, "default": 20 } }],
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/Server" }, "ready": { "type": "boolean" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/servers/{id}/capabilities": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "serversCapabilities", "summary": "Что сейчас можно делать с сервером", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "data": {
            "type": "object",
            "properties": {
              "power": { "type": "boolean" }, "console": { "type": "boolean" }, "reinstall": { "type": "boolean" }, "password_reset": { "type": "boolean" },
              "public_ipv4": { "type": "boolean", "const": false }, "ptr": { "type": "boolean", "const": false }, "firewall": { "type": "boolean", "const": false },
              "backups": { "type": "boolean", "const": false }, "snapshots": { "type": "boolean" }, "rescue": { "type": "boolean", "const": false }
            }
          } }
        } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/servers/{id}/ips": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "serversIps", "summary": "Сеть сервера", "description": "Публичные адреса пока не подключены: ipv4 и ipv6 – null, в поле note – пояснение.", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "data": {
            "type": "object",
            "properties": {
              "ipv4": { "type": ["string", "null"] }, "ipv6": { "type": ["string", "null"] }, "gateway": { "type": "null" }, "netmask": { "type": "null" }, "rdns_ptr": { "type": "null" },
              "extra_ips": { "type": "array", "items": { "type": "string" } }, "public_network": { "type": "boolean" }, "note": { "type": ["string", "null"] }
            }
          } }
        } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/servers/{id}/metrics": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "serversMetrics", "summary": "Текущая нагрузка", "description": "Данные гипервизора и гостевого агента, кэш 10 секунд. available = false – данных сейчас нет.", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "data": {
            "type": "object",
            "properties": {
              "available": { "type": "boolean" },
              "cpu_usage_percent": { "type": ["number", "null"] },
              "ram_usage_mb": { "type": ["integer", "null"] }, "ram_total_mb": { "type": ["integer", "null"] },
              "disk_usage_gb": { "type": ["number", "null"] }, "disk_total_gb": { "type": "integer" },
              "traffic_rx_gb": { "type": ["number", "null"] }, "traffic_tx_gb": { "type": ["number", "null"] },
              "sampled_at": { "type": "string", "format": "date-time" }
            }
          } }
        } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/servers/{id}/backups": {
      "parameters": [{"$ref": "#/components/parameters/Id"}],
      "get": {"tags": ["Servers"], "operationId": "serversBackups", "summary": "Бэкапы: состояние, цена и список копий", "description": "Платная услуга: 20% от цены тарифа в месяц. Если хранилище копий недоступно, включение отвечает 503 backups_unavailable и ничего не списывает.", "x-required-scope": "servers.read", "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"available": {"type": "boolean"}, "is_backup_enabled": {"type": "boolean"}, "price_monthly_usd": {"type": "string"}, "price_hourly_usd": {"type": "string"}, "charge_now_usd": {"type": "string", "description": "Сколько спишется при включении за остаток оплаченного периода (0.00 для почасовых)."}, "percent": {"type": "integer"}, "running": {"type": "boolean", "description": "Копия создаётся прямо сейчас."}, "backups": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "created_at": {"type": ["string", "null"], "format": "date-time"}, "type": {"type": ["string", "null"]}, "size_bytes": {"type": ["integer", "null"]}}}}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}},
      "post": {"tags": ["Servers"], "operationId": "serversBackupCreate", "summary": "Бэкапы: создать копию сейчас", "description": "Бэкапы должны быть включены. Между ручными копиями должно пройти не меньше часа; иначе 409 backup_not_started.", "x-required-scope": "servers.update", "responses": {"202": {"description": "Копия создаётся"}, "409": {"description": "backups_not_enabled или backup_not_started"}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}
    },
    "/servers/{id}/backups/enable": {
      "parameters": [{"$ref": "#/components/parameters/Id"}],
      "post": {"tags": ["Servers"], "operationId": "serversBackupsEnable", "summary": "Бэкапы: включить", "description": "Цена сервера растёт на 20% от цены тарифа. Для оплаченного периода сразу списывается доля за его остаток; для почасовых растёт почасовая цена. Первая копия запускается сразу. Если хранилище копий недоступно, включение отвечает 503 backups_unavailable и ничего не списывает.", "x-required-scope": "servers.update", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "properties": {"dry_run": {"type": "boolean", "description": "Только показать цену, ничего не менять."}}}}}}, "responses": {"200": {"description": "Включено; в ответе charged_usd, price_monthly_usd и server"}, "402": {"description": "insufficient_balance"}, "409": {"description": "backups_already_enabled или server_busy"}, "503": {"description": "backups_unavailable – ничего не списано"}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}
    },
    "/servers/{id}/backups/disable": {
      "parameters": [{"$ref": "#/components/parameters/Id"}],
      "post": {"tags": ["Servers"], "operationId": "serversBackupsDisable", "summary": "Бэкапы: отключить", "description": "Новые копии не создаются, цена сервера уменьшается. Уже оплаченное время за бэкапы не возвращается.", "x-required-scope": "servers.update", "responses": {"200": {"$ref": "#/components/responses/Ok"}, "409": {"description": "backups_not_enabled"}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}
    },
    "/servers/{id}/backups/schedule": {
      "parameters": [{"$ref": "#/components/parameters/Id"}],
      "put": {"tags": ["Servers"], "operationId": "serversBackupsSchedule", "summary": "Бэкапы: своё расписание копий", "description": "Расписание задаётся отдельно для каждого сервера: частота, час (UTC) и день недели для еженедельных копий. manual – автоматических копий нет. В ответе next_run_at.", "x-required-scope": "servers.update", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "properties": {"frequency": {"type": "string", "enum": ["manual", "6h", "12h", "daily", "2d", "weekly"]}, "hour_utc": {"type": "integer", "minimum": 0, "maximum": 23}, "weekday": {"type": ["integer", "null"], "minimum": 1, "maximum": 7, "description": "День недели ISO (1 – понедельник) для weekly."}}}}}}, "responses": {"200": {"description": "Сохранено; в ответе schedule"}, "409": {"description": "backups_not_enabled"}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}
    },
    "/servers/{id}/backups/restore": {
      "parameters": [{"$ref": "#/components/parameters/Id"}],
      "post": {"tags": ["Servers"], "operationId": "serversBackupRestore", "summary": "Бэкапы: восстановить сервер из копии", "description": "Сервер останавливается, его диск заменяется копией. Всё, что изменилось после копии, теряется.", "x-required-scope": "servers.install", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["backup_id", "confirm"], "properties": {"backup_id": {"type": "string"}, "confirm": {"type": "boolean", "const": true}}}}}}, "responses": {"202": {"description": "Восстановление запущено"}, "404": {"description": "backup_not_found"}, "409": {"description": "backups_not_enabled"}, "401": {"$ref": "#/components/responses/Unauthenticated"}}}
    },
    "/servers/{id}/metrics/history": {
      "parameters": [{"$ref": "#/components/parameters/Id"}],
      "get": {"tags": ["Servers"], "operationId": "serversMetricsHistory", "summary": "История нагрузки сервера", "description": "Процессор, память, диск (в процентах от тарифа и в абсолютных значениях) и скорость сети в Мбит/с. hour и day – точка раз в 5 минут (хранятся 48 часов), week и month – средние за час (хранятся 35 дней). Точки появляются, пока сервер работает.", "x-required-scope": "servers.read", "parameters": [{"name": "range", "in": "query", "schema": {"type": "string", "enum": ["hour", "day", "week", "month"], "default": "day"}}], "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"range": {"type": "string"}, "step_seconds": {"type": "integer"}, "points": {"type": "array", "items": {"type": "object", "properties": {"t": {"type": "string", "format": "date-time"}, "cpu": {"type": ["number", "null"]}, "ram": {"type": ["number", "null"], "description": "% от памяти тарифа"}, "ram_mb": {"type": ["integer", "null"]}, "disk": {"type": ["number", "null"], "description": "% от диска"}, "disk_gb": {"type": ["number", "null"]}, "rx": {"type": ["number", "null"], "description": "Мбит/с, входящий"}, "tx": {"type": ["number", "null"], "description": "Мбит/с, исходящий"}}}}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}, "422": {"description": "bad_range"}}}
    },
    "/servers/{id}/password": {
      "parameters": [{"$ref": "#/components/parameters/Id"}],
      "post": {"tags": ["Servers"], "operationId": "serversPassword", "summary": "Пароль root, известный консоли", "description": "Пароль, который консоль задала при установке системы или последнем сбросе. Если пароль меняли внутри системы, он уже другой. Сброс: POST /servers/{id}/password-reset – сервер не перезагружается; пока система загружается (до трёх минут после включения), сброс отвечает 409 password_reset_unavailable с retry_after.", "x-required-scope": "servers.credentials", "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"username": {"type": "string"}, "password": {"type": ["string", "null"]}, "known": {"type": "boolean"}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}
    },
    "/servers/{id}/snapshots": {
      "parameters": [{"$ref": "#/components/parameters/Id"}],
      "get": {"tags": ["Servers"], "operationId": "serversSnapshots", "summary": "Снапшоты: список снапшотов сервера", "description": "Снапшот – копия диска сервера на момент снятия. Принадлежит аккаунту, а не серверу: при удалении сервера остаётся. Платно: фиксированная цена в месяц за каждый (meta.price_monthly_usd), первый месяц списывается при создании и возвращается, если копия не удалась.", "x-required-scope": "servers.read", "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "name": {"type": "string"}, "status": {"type": "string", "enum": ["creating", "ready", "error"]}, "server_id": {"type": ["string", "null"], "description": "Сервер, с которого снят снапшот."}, "server_hostname": {"type": ["string", "null"]}, "server_exists": {"type": "boolean", "description": "false – исходный сервер удалён, снапшот при этом остаётся."}, "disk_gb": {"type": "integer", "description": "Размер диска в снапшоте. Сервер из снапшота должен иметь диск не меньше."}, "consistent": {"type": ["boolean", "null"], "description": "false – снапшот снят с работающего сервера без гостевого агента: запись на диск не приостанавливалась, состояние как после внезапного отключения питания. true – сервер был выключен или агент приостановил запись. null – неизвестно (старые снапшоты)."}, "size_bytes": {"type": ["integer", "null"]}, "os": {"type": ["string", "null"]}, "price_monthly_usd": {"type": "string"}, "paid_until": {"type": ["string", "null"], "format": "date-time"}, "unpaid_until": {"type": ["string", "null"], "format": "date-time", "description": "Задан, когда на продление не хватило денег: до этой даты снапшот хранится, потом удаляется."}, "error": {"type": ["string", "null"]}, "created_at": {"type": ["string", "null"], "format": "date-time"}, "ready_at": {"type": ["string", "null"], "format": "date-time"}}}}, "meta": {"type": "object", "properties": {"available": {"type": "boolean", "description": "false – хранилище снапшотов на площадке не подключено, создание отвечает 503."}, "price_monthly_usd": {"type": "string"}, "limit": {"type": "integer"}, "used": {"type": "integer"}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}},
      "post": {"tags": ["Servers"], "operationId": "serversSnapshotCreate", "summary": "Снапшоты: снять снапшот", "description": "Сервер должен работать или быть выключен; он не останавливается. Копирование идёт в фоне: статус creating, затем ready (событие вебхука snapshot.ready) или error с возвратом денег. Пока копия создаётся, питание, переустановка и смена тарифа сервера отвечают 409 snapshot_in_progress.", "x-required-scope": "servers.update", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "properties": {"name": {"type": "string", "maxLength": 80}}}}}}, "responses": {"202": {"description": "Копирование началось; в data – снапшот со статусом creating"}, "402": {"description": "insufficient_balance"}, "409": {"description": "server_not_ready, snapshot_in_progress или snapshot_limit_reached"}, "503": {"description": "snapshots_unavailable – ничего не списано"}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}
    },
    "/servers/{id}/snapshots/{snapshot}/restore": {
      "parameters": [{"$ref": "#/components/parameters/Id"}, {"name": "snapshot", "in": "path", "required": true, "schema": {"type": "string"}}],
      "post": {"tags": ["Servers"], "operationId": "serversSnapshotRestore", "summary": "Снапшоты: записать снапшот на диск сервера", "description": "Подходит любой свой сервер с диском не меньше снапшота. Сервер выключается, его диск заменяется содержимым снапшота, затем сервер включается (если работал). Всё, что было на диске, теряется. Пока идёт запись, статус сервера provisioning, поле operation = snapshot_restore.", "x-required-scope": "servers.install", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["confirm"], "properties": {"confirm": {"type": "boolean", "const": true}}}}}}, "responses": {"202": {"description": "Восстановление запущено"}, "402": {"description": "snapshot_unpaid"}, "409": {"description": "server_not_ready, snapshot_not_ready или snapshot_in_progress"}, "422": {"description": "disk_too_small"}, "503": {"description": "snapshots_unavailable"}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}
    },
    "/snapshots": {
      "get": {"tags": ["Servers"], "operationId": "snapshotsList", "summary": "Снапшоты: все снапшоты аккаунта", "description": "Снапшот – копия диска сервера на момент снятия. Принадлежит аккаунту, а не серверу: при удалении сервера остаётся. Платно: фиксированная цена в месяц за каждый (meta.price_monthly_usd), первый месяц списывается при создании и возвращается, если копия не удалась. Новый сервер из снапшота: POST /servers с полем from_snapshot.", "x-required-scope": "servers.read", "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "name": {"type": "string"}, "status": {"type": "string", "enum": ["creating", "ready", "error"]}, "server_id": {"type": ["string", "null"], "description": "Сервер, с которого снят снапшот."}, "server_hostname": {"type": ["string", "null"]}, "server_exists": {"type": "boolean", "description": "false – исходный сервер удалён, снапшот при этом остаётся."}, "disk_gb": {"type": "integer", "description": "Размер диска в снапшоте. Сервер из снапшота должен иметь диск не меньше."}, "consistent": {"type": ["boolean", "null"], "description": "false – снапшот снят с работающего сервера без гостевого агента: запись на диск не приостанавливалась, состояние как после внезапного отключения питания. true – сервер был выключен или агент приостановил запись. null – неизвестно (старые снапшоты)."}, "size_bytes": {"type": ["integer", "null"]}, "os": {"type": ["string", "null"]}, "price_monthly_usd": {"type": "string"}, "paid_until": {"type": ["string", "null"], "format": "date-time"}, "unpaid_until": {"type": ["string", "null"], "format": "date-time", "description": "Задан, когда на продление не хватило денег: до этой даты снапшот хранится, потом удаляется."}, "error": {"type": ["string", "null"]}, "created_at": {"type": ["string", "null"], "format": "date-time"}, "ready_at": {"type": ["string", "null"], "format": "date-time"}}}}, "meta": {"type": "object", "properties": {"available": {"type": "boolean", "description": "false – хранилище снапшотов на площадке не подключено, создание отвечает 503."}, "price_monthly_usd": {"type": "string"}, "limit": {"type": "integer"}, "used": {"type": "integer"}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}}}
    },
    "/snapshots/{id}": {
      "parameters": [{"$ref": "#/components/parameters/Id"}],
      "patch": {"tags": ["Servers"], "operationId": "snapshotsRename", "summary": "Снапшоты: переименовать", "x-required-scope": "servers.update", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["name"], "properties": {"name": {"type": "string", "maxLength": 80}}}}}}, "responses": {"200": {"description": "OK"}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}},
      "delete": {"tags": ["Servers"], "operationId": "snapshotsDelete", "summary": "Снапшоты: удалить", "description": "Удаляется без возможности восстановления. Серверы, созданные из снапшота, не затрагиваются. Оплата за текущий месяц не возвращается.", "x-required-scope": "servers.delete", "responses": {"200": {"$ref": "#/components/responses/Ok"}, "409": {"description": "snapshot_in_progress или snapshot_in_use"}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}
    },
    "/servers/{id}/templates": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "serversTemplates", "summary": "Системы, которые можно установить на этот сервер", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Image" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" }, "409": { "$ref": "#/components/responses/Conflict" }, "502": { "$ref": "#/components/responses/ProviderError" } }
      }
    },
    "/servers/{id}/install": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Servers"], "operationId": "serversInstall", "summary": "Переустановить систему", "description": "Все данные на диске стираются. Бесплатно. Новый пароль root показывается один раз.", "x-required-scope": "servers.install",
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "template_id": { "type": "integer", "minimum": 1 }, "os_template": { "type": "string", "maxLength": 120 }, "ssh_key_id": { "type": "string" } }
        } } } },
        "responses": {
          "200": { "description": "Установка началась.", "content": { "application/json": { "schema": {
            "type": "object", "properties": { "ok": { "type": "boolean" }, "password": { "type": ["string", "null"] }, "username": { "type": "string" }, "server": { "$ref": "#/components/schemas/Server" } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "$ref": "#/components/responses/Conflict" },
          "422": { "description": "template_unavailable или ошибка проверки полей.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "502": { "$ref": "#/components/responses/ProviderError" }
        }
      }
    },
    "/servers/{id}/iso": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "serversIsoState", "summary": "Свой ISO: состояние", "description": "Подключён ли к серверу свой ISO-образ и какой порядок загрузки.", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "object", "properties": { "mounted": { "type": "boolean" }, "url": { "type": ["string", "null"] }, "name": { "type": ["string", "null"] }, "boot_order": { "type": ["array", "null"], "items": { "type": "string" } } } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      },
      "post": {
        "tags": ["Servers"], "operationId": "serversIsoMount", "summary": "Свой ISO: безопасная подготовка", "description": "Консоль скачивает ISO сама с закреплённым публичным DNS-адресом и лимитом потока, затем передаёт VirtFusion только временный URL неизменяемого локального артефакта. Ответ 202 означает, что подготовка поставлена в очередь; состояние доступно через GET этого же ресурса. Исходный URL не возвращается.", "x-required-scope": "servers.install",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "required": ["url"], "properties": { "url": { "type": "string", "example": "https://example.com/images/install.iso" }, "restart": { "type": "boolean", "default": true } } } } } },
        "responses": { "202": { "description": "ISO поставлена в очередь на безопасную подготовку" }, "422": { "description": "invalid_iso_url" }, "429": { "description": "rate_limited" }, "501": { "description": "custom_iso_unavailable (функция отключена конфигурацией)" }, "503": { "description": "iso_storage_full" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" }, "409": { "description": "iso_in_progress или сервер занят" } }
      },
      "delete": {
        "tags": ["Servers"], "operationId": "serversIsoEject", "summary": "Свой ISO: извлечь", "description": "Отключает образ; сервер снова загружается со своего диска.", "x-required-scope": "servers.install",
        "responses": { "200": { "$ref": "#/components/responses/Ok" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/servers/{id}/resize": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Servers"], "operationId": "serversResize", "summary": "Перейти на тариф больше", "description": "Только на тариф с большими ресурсами: данные сохраняются, диск увеличивается, сервер перезапускается. С баланса списывается разница за остаток оплаченного периода. С dry_run = true ничего не меняется – в ответе только сумма доплаты.", "x-required-scope": "servers.update",
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["plan"], "properties": { "plan": { "type": "string", "example": "s2-4" }, "dry_run": { "type": "boolean" } }
        } } } },
        "responses": {
          "200": { "description": "OK" },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "Тариф не больше текущего или сервер занят" }
        }
      }
    },
    "/servers/{id}/password-reset": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Servers"], "operationId": "serversPasswordReset", "summary": "Сбросить пароль root", "description": "Только на запущенном сервере. Пароль показывается один раз и применяется в течение минуты.", "x-required-scope": "servers.credentials",
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": {
            "type": "object", "properties": { "ok": { "type": "boolean" }, "username": { "type": "string" }, "password": { "type": "string" }, "note": { "type": "string" } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "server_not_running, password_reset_unavailable, server_deleted или server_not_provisioned.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/servers/{id}/console": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Servers"], "operationId": "serversConsole", "summary": "Одноразовый доступ к веб-консоли", "description": "Используется кабинетом: билет действует недолго и подходит только для веб-консоли на https://0x.cloud. Поля продублированы в data.", "x-required-scope": "servers.console",
        "responses": {
          "201": { "description": "Билет выдан.", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": {
              "ticket": { "type": "string" }, "password": { "type": ["string", "null"] }, "websocket_path": { "type": "string" },
              "expires_in": { "type": "integer" }, "expires_at": { "type": "string", "format": "date-time" },
              "server_id": { "type": "string" }, "hostname": { "type": "string" }, "data": { "type": "object" }
            }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "$ref": "#/components/responses/Conflict" },
          "503": { "description": "console_unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/servers/{id}/history": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "serversHistory", "summary": "История действий с сервером (последние 50)", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/ServerOperation" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/servers/{id}/operations/{operation}": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }, { "name": "operation", "in": "path", "required": true, "schema": { "type": "string" } }],
      "get": {
        "tags": ["Servers"], "operationId": "serversOperation", "summary": "Одно действие из истории", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/ServerOperation" } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/servers/{id}/cancellation": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "cancellationShow", "summary": "Отключено ли продление", "x-required-scope": "servers.read",
        "responses": { "200": { "$ref": "#/components/responses/Cancellation" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      },
      "post": {
        "tags": ["Servers"], "operationId": "cancellationSet", "summary": "Не продлевать после оплаченного срока", "description": "В конце оплаченного периода сервер будет выключен и удалён с окном восстановления 24 часа.", "x-required-scope": "servers.delete",
        "responses": { "200": { "$ref": "#/components/responses/Cancellation" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      },
      "delete": {
        "tags": ["Servers"], "operationId": "cancellationUndo", "summary": "Вернуть продление", "x-required-scope": "servers.update",
        "responses": { "200": { "$ref": "#/components/responses/Cancellation" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/confirmations/{id}": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Servers"], "operationId": "confirmationShow", "summary": "Данные для окна подтверждения в кабинете", "description": "id – ID сервера.", "x-required-scope": "account.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object", "properties": { "data": { "type": "object", "properties": { "server": { "$ref": "#/components/schemas/Server" }, "can_delete": { "type": "boolean" }, "can_rebuild": { "type": "boolean" } } } }
        } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/large-plan-requests": {
      "get": {
        "tags": ["Servers"], "operationId": "largePlanRequestsList", "summary": "Заявки на тарифы под заказ", "x-required-scope": "servers.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "data": { "type": "array", "items": {
            "type": "object", "properties": { "id": { "type": "string" }, "plan": { "type": "string" }, "hostname": { "type": ["string", "null"] }, "price_monthly_usd": { "type": "string" }, "charge_usd": { "type": "string" }, "status": { "type": "string", "enum": ["pending", "approved", "denied", "cancelled"] }, "created_at": { "type": ["string", "null"], "format": "date-time" } }
          } } }
        } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      },
      "post": {
        "tags": ["Servers"], "operationId": "largePlanRequestsCreate", "summary": "Заявка на тариф под заказ", "description": "Совместимый адрес POST /server-requests. Это отдельная заявка на ручную выдачу до 48 часов, не обращение в поддержку. Сначала получите котировку через POST /servers с dry_run: true для тарифа is_auto_provision=false и подтвердите цену и ручную выдачу. Передайте pricing_fingerprint и accept_manual_issue:true. Согласованные цена и ресурсы сохраняются; изменение условий до одобрения не вызывает автоматического списания по новой цене. Деньги списываются при фактической выдаче. При price_changed нужно новое согласие, при обрыве связи — точный повтор прежнего тела с тем же Idempotency-Key.", "x-required-scope": "servers.create",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["accept_manual_issue", "pricing_fingerprint"], "anyOf": [{"required":["plan"]},{"required":["plan_code"]}],
          "properties": { "plan": { "type": "string", "maxLength": 32 }, "plan_code": { "type": "string", "maxLength": 32 }, "accept_manual_issue": { "type": "boolean", "const": true }, "pricing_fingerprint": { "type": "string", "minLength": 32, "maxLength": 2048 }, "hostname": { "type": "string", "maxLength": 63 }, "note": { "type": "string", "maxLength": 2000 }, "os_template": { "type": "string", "maxLength": 120 }, "os_template_id": { "type": "integer", "minimum": 1 }, "ssh_key_id": { "type": "string" }, "app": { "type": "string" }, "billing_cycle": { "type": "string", "enum": ["hourly","monthly","quarterly","semiannual","annual"] } }
        } } } },
        "responses": {
          "202": { "description": "Заявка принята, деньги ещё не списаны.", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "object", "properties": { "id": { "type": "string" }, "plan": { "type": "string" }, "price_monthly_usd": { "type": "string" }, "charge_usd": { "type": "string" }, "status": { "type": "string", "const": "pending" } } } } } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "404": { "description": "plan_not_found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "409": { "description": "price_changed с error.quote, plan_not_by_request или too_many_requests_pending.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "422": { "$ref": "#/components/responses/Validation" }
        }
      }
    },
    "/server-requests": {
      "get": { "tags": ["Servers"], "operationId": "serverRequestsList", "summary": "Заявки на ручную выдачу", "x-required-scope": "servers.read", "responses": { "200": { "$ref": "#/paths/~1large-plan-requests/get/responses/200" }, "401": { "$ref": "#/components/responses/Unauthenticated" } } },
      "post": { "tags": ["Servers"], "operationId": "serverRequestsCreate", "summary": "Заказать ручную выдачу по подтверждённой котировке", "description": "Канонический адрес ручной заявки. Контракт и условия согласия совпадают с POST /large-plan-requests.", "x-required-scope": "servers.create", "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }], "requestBody": { "$ref": "#/paths/~1large-plan-requests/post/requestBody" }, "responses": { "202": { "$ref": "#/paths/~1large-plan-requests/post/responses/202" }, "403": { "$ref": "#/components/responses/Forbidden" }, "409": { "$ref": "#/paths/~1large-plan-requests/post/responses/409" }, "422": { "$ref": "#/components/responses/Validation" } } }
    },
    "/support/departments": {
      "get": {
        "tags": ["Support"], "operationId": "supportDepartments", "summary": "Отделы поддержки", "x-required-scope": "support.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object", "properties": { "data": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string", "enum": ["tech", "billing", "general"] }, "name": { "type": "string" }, "description": { "type": "string" } } } } }
        } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/tickets": {
      "get": {
        "tags": ["Support"], "operationId": "ticketsList", "summary": "Обращения", "description": "По 20 на страницу.", "x-required-scope": "support.read",
        "parameters": [{ "name": "page", "in": "query", "schema": { "type": "integer", "minimum": 1 } }],
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/Ticket" } }, "current_page": { "type": "integer" }, "last_page": { "type": "integer" } }
        } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "403": { "$ref": "#/components/responses/Forbidden" } }
      },
      "post": {
        "tags": ["Support"], "operationId": "ticketsCreate", "summary": "Создать обращение", "x-required-scope": "support.write",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["subject", "department", "message"],
          "properties": {
            "subject": { "type": "string", "minLength": 3, "maxLength": 200 },
            "department": { "type": "string", "enum": ["tech", "billing", "general"] },
            "message": { "type": "string", "minLength": 5, "maxLength": 10000 },
            "server_id": { "type": "string" }
          }
        } } } },
        "responses": { "201": { "description": "Создано.", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/Ticket" } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "422": { "$ref": "#/components/responses/Validation" } }
      }
    },
    "/tickets/{id}": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Support"], "operationId": "ticketsShow", "summary": "Обращение с перепиской", "x-required-scope": "support.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": { "data": {
            "type": "object",
            "properties": {
              "id": { "type": "string" }, "subject": { "type": "string" }, "department": { "type": "string" }, "status": { "type": "string", "enum": ["open", "answered", "customer_reply", "closed"] },
              "priority": { "type": "string" }, "server_id": { "type": ["string", "null"] }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" },
              "messages": { "type": "array", "items": { "$ref": "#/components/schemas/TicketMessage" } }
            }
          } }
        } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/tickets/{id}/messages": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Support"], "operationId": "ticketMessagesList", "summary": "Сообщения обращения", "x-required-scope": "support.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/TicketMessage" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      },
      "post": {
        "tags": ["Support"], "operationId": "ticketMessagesCreate", "summary": "Ответить в обращении", "x-required-scope": "support.write",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "required": ["message"], "properties": { "message": { "type": "string", "minLength": 1, "maxLength": 10000 } } } } } },
        "responses": {
          "201": { "description": "Отправлено.", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/TicketMessage" } } } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "ticket_closed", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "422": { "$ref": "#/components/responses/Validation" }
        }
      }
    },
    "/tickets/{id}/close": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Support"], "operationId": "ticketsClose", "summary": "Закрыть обращение", "x-required-scope": "support.write",
        "responses": { "200": { "$ref": "#/components/responses/Ok" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/tickets/{id}/attachments/{attachment}": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }, { "name": "attachment", "in": "path", "required": true, "schema": { "type": "integer" } }],
      "get": {
        "tags": ["Support"], "operationId": "ticketAttachment", "summary": "Вложение", "description": "Вложения пока не поддерживаются: метод всегда отвечает 404.", "x-required-scope": "support.read",
        "responses": { "404": { "$ref": "#/components/responses/NotFound" }, "401": { "$ref": "#/components/responses/Unauthenticated" } }
      }
    },
    "/webhooks": {
      "get": {
        "tags": ["Webhooks"], "operationId": "webhooksList", "summary": "Вебхуки", "x-required-scope": "webhooks.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": {
          "type": "object",
          "properties": {
            "data": { "type": "array", "items": { "$ref": "#/components/schemas/Webhook" } },
            "available_events": { "type": "array", "items": { "type": "string" } },
            "limit": { "type": "integer", "const": 10 }
          }
        } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "403": { "$ref": "#/components/responses/Forbidden" } }
      },
      "post": {
        "tags": ["Webhooks"], "operationId": "webhooksCreate", "summary": "Добавить вебхук", "description": "Только https и только публичные адреса. Не больше 10 вебхуков на аккаунт. Секрет для проверки подписи показывается один раз.\n\nКаждое событие – POST с телом `{\"id\": \"evt_...\", \"event\": \"server.created\", \"created_at\": \"...\", \"data\": {...}}` и заголовками `X-0x-Event`, `X-0x-Delivery`, `X-0x-Signature: t=<unix>,v1=<hex>`. Подпись: HMAC-SHA256 от строки `<t>.<тело запроса>` с секретом вебхука. Успех – любой ответ 2xx за 8 секунд; перенаправления не выполняются. Повторы при неудаче: через 1 минуту, 5 минут, 30 минут, 2 часа и 12 часов (всего 6 попыток).", "x-required-scope": "webhooks.write",
        "parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": {
          "type": "object", "required": ["url", "events"],
          "properties": {
            "url": { "type": "string", "format": "uri", "maxLength": 255, "pattern": "^https://" },
            "events": { "type": "array", "minItems": 1, "items": { "$ref": "#/components/schemas/WebhookEvent" } }
          }
        }, "example": { "url": "https://example.com/hooks/0x", "events": ["server.created", "server.deleted"] } } } },
        "responses": {
          "201": { "description": "Вебхук добавлен.", "content": { "application/json": { "schema": {
            "type": "object",
            "properties": {
              "data": { "allOf": [{ "$ref": "#/components/schemas/Webhook" }, { "type": "object", "properties": { "secret": { "type": "string", "description": "whsec_... Показывается один раз." } } }] },
              "note": { "type": "string" }
            }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "409": { "description": "webhook_limit_reached", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "422": { "description": "webhook_url_invalid (поле reason: https_required, credentials_in_url, host_not_resolved, host_not_public) или ошибка проверки полей.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/webhooks/{id}": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "delete": {
        "tags": ["Webhooks"], "operationId": "webhooksDelete", "summary": "Удалить вебхук", "x-required-scope": "webhooks.write",
        "responses": { "200": { "$ref": "#/components/responses/Ok" }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/webhooks/{id}/test": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "post": {
        "tags": ["Webhooks"], "operationId": "webhooksTest", "summary": "Отправить проверочное событие ping", "description": "Не чаще 10 раз в минуту.", "x-required-scope": "webhooks.write",
        "responses": {
          "202": { "description": "Событие поставлено в очередь.", "content": { "application/json": { "schema": {
            "type": "object", "properties": { "ok": { "type": "boolean" }, "data": { "$ref": "#/components/schemas/WebhookDelivery" }, "note": { "type": "string" } }
          } } } },
          "401": { "$ref": "#/components/responses/Unauthenticated" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    },
    "/webhooks/{id}/deliveries": {
      "parameters": [{ "$ref": "#/components/parameters/Id" }],
      "get": {
        "tags": ["Webhooks"], "operationId": "webhooksDeliveries", "summary": "Последние 50 доставок", "x-required-scope": "webhooks.read",
        "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "array", "items": { "$ref": "#/components/schemas/WebhookDelivery" } } } } } } }, "401": { "$ref": "#/components/responses/Unauthenticated" }, "404": { "$ref": "#/components/responses/NotFound" } }
      }
    },
    "/servers/{id}/exec": {"parameters": [{"$ref": "#/components/parameters/Id"}], "post": {"tags": ["Servers"], "operationId": "serverExec", "summary": "Выполнить команду на сервере от root", "x-required-scope": "servers.exec", "description": "Команда идёт через гостевой агент сервера: SSH, пароль и сетевой адрес не нужны. Каждый вызов – новая оболочка sh, без интерактивного ввода. Если команда не закончилась за wait секунд, ответ – status=running и command_id.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["command"], "properties": {"command": {"type": "string", "maxLength": 60000, "description": "Скрипт для sh."}, "stdin": {"type": "string", "maxLength": 500000}, "timeout": {"type": "integer", "minimum": 1, "maximum": 3600, "default": 30, "description": "Через сколько секунд команда останавливается."}, "wait": {"type": "integer", "minimum": 0, "maximum": 45, "description": "Сколько секунд ждать ответа в этом запросе."}}}}}}, "responses": {"200": {"description": "Результат или status=running.", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CommandResult"}}}}}}, "422": {"$ref": "#/components/responses/Validation"}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "503": {"description": "exec_unavailable.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/servers/{id}/exec/{command_id}": {"parameters": [{"$ref": "#/components/parameters/Id"}, {"name": "command_id", "in": "path", "required": true, "schema": {"type": "string", "pattern": "^[0-9a-f]{24}$"}}, {"name": "wait", "in": "query", "schema": {"type": "integer", "minimum": 0, "maximum": 45}}], "get": {"tags": ["Servers"], "operationId": "serverExecResult", "summary": "Результат команды, которая ещё выполнялась", "x-required-scope": "servers.exec", "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CommandResult"}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "503": {"description": "exec_unavailable.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/servers/{id}/files": {"parameters": [{"$ref": "#/components/parameters/Id"}], "get": {"tags": ["Servers"], "operationId": "serverFileRead", "summary": "Прочитать файл на сервере", "x-required-scope": "servers.exec", "parameters": [{"name": "path", "in": "query", "required": true, "schema": {"type": "string"}}, {"name": "offset", "in": "query", "schema": {"type": "integer", "minimum": 0}}, {"name": "max_bytes", "in": "query", "schema": {"type": "integer", "minimum": 1, "maximum": 200000}}], "responses": {"200": {"description": "content – текст или base64 (encoding); next_offset – откуда читать дальше.", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"path": {"type": "string"}, "size": {"type": "integer"}, "offset": {"type": "integer"}, "bytes": {"type": "integer"}, "encoding": {"type": "string", "enum": ["text", "base64"]}, "content": {"type": "string"}, "truncated": {"type": "boolean"}, "next_offset": {"type": ["integer", "null"]}}}}}}}}, "422": {"description": "bad_path, is_directory, file_error.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "503": {"description": "exec_unavailable.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}, "put": {"tags": ["Servers"], "operationId": "serverFileWrite", "summary": "Записать файл на сервере", "x-required-scope": "servers.exec", "description": "Заменяет файл одним шагом или дописывает в конец. До 500 КБ за запрос.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["path", "content"], "properties": {"path": {"type": "string"}, "content": {"type": "string"}, "encoding": {"type": "string", "enum": ["text", "base64"], "default": "text"}, "mode": {"type": "string", "pattern": "^[0-7]{3,4}$"}, "append": {"type": "boolean"}}}}}}, "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object"}}}}}}, "422": {"description": "bad_path, bad_content, content_too_large, is_directory, file_error.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "503": {"description": "exec_unavailable.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/servers/{id}/firewall": {"parameters": [{"$ref": "#/components/parameters/Id"}], "get": {"tags": ["Servers"], "operationId": "serverFirewall", "summary": "Файрвол сервера", "x-required-scope": "servers.read", "description": "Файрвол работает на гипервизоре, на сетевом интерфейсе сервера, а не внутри системы.", "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"enabled": {"type": "boolean"}, "rules": {"type": "array", "items": {"type": "object", "properties": {"direction": {"type": "string", "enum": ["in", "out"], "default": "in"}, "protocol": {"type": "string", "enum": ["tcp", "udp", "icmp", "any"], "default": "tcp"}, "ports": {"type": ["string", "null"], "description": "22 | 80,443 | 8000-8100; только для tcp и udp"}, "cidrs": {"type": "array", "items": {"type": "string"}, "description": "Откуда (in) или куда (out); пусто – любой адрес"}, "description": {"type": ["string", "null"], "maxLength": 100}}}}, "status": {"type": "string", "enum": ["applied", "pending", "error"]}, "applied_at": {"type": ["string", "null"], "format": "date-time"}, "error": {"type": ["string", "null"]}, "outgoing_mail": {"type": "object", "properties": {"allowed": {"type": "boolean"}, "requested_at": {"type": ["string", "null"], "format": "date-time"}}}, "note": {"type": "string"}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}, "put": {"tags": ["Servers"], "operationId": "serverFirewallSet", "summary": "Настроить файрвол", "x-required-scope": "servers.update", "description": "Список правил заменяется целиком. Включён – входящие закрыты, кроме разрешённых; исходящие открыты, пока нет правил out.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["enabled"], "properties": {"enabled": {"type": "boolean"}, "rules": {"type": "array", "maxItems": 50, "items": {"type": "object", "properties": {"direction": {"type": "string", "enum": ["in", "out"], "default": "in"}, "protocol": {"type": "string", "enum": ["tcp", "udp", "icmp", "any"], "default": "tcp"}, "ports": {"type": ["string", "null"], "description": "22 | 80,443 | 8000-8100; только для tcp и udp"}, "cidrs": {"type": "array", "items": {"type": "string"}, "description": "Откуда (in) или куда (out); пусто – любой адрес"}, "description": {"type": ["string", "null"], "maxLength": 100}}}}}}}}}, "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"enabled": {"type": "boolean"}, "rules": {"type": "array", "items": {"type": "object", "properties": {"direction": {"type": "string", "enum": ["in", "out"], "default": "in"}, "protocol": {"type": "string", "enum": ["tcp", "udp", "icmp", "any"], "default": "tcp"}, "ports": {"type": ["string", "null"], "description": "22 | 80,443 | 8000-8100; только для tcp и udp"}, "cidrs": {"type": "array", "items": {"type": "string"}, "description": "Откуда (in) или куда (out); пусто – любой адрес"}, "description": {"type": ["string", "null"], "maxLength": 100}}}}, "status": {"type": "string", "enum": ["applied", "pending", "error"]}, "applied_at": {"type": ["string", "null"], "format": "date-time"}, "error": {"type": ["string", "null"]}, "outgoing_mail": {"type": "object", "properties": {"allowed": {"type": "boolean"}, "requested_at": {"type": ["string", "null"], "format": "date-time"}}}, "note": {"type": "string"}}}}}}}}, "422": {"description": "bad_rule.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "502": {"description": "firewall_not_applied: действуют прежние правила.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "503": {"description": "firewall_unavailable.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "server_deleted.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/servers/{id}/monitoring": {"parameters": [{"$ref": "#/components/parameters/Id"}], "get": {"tags": ["Servers"], "operationId": "serverMonitoring", "summary": "Мониторинг сервера", "x-required-scope": "servers.read", "responses": {"200": {"description": "Настройки, текущие значения (current), идущие оповещения (firing) и последние 20 (alerts).", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"enabled": {"type": "boolean"}, "cpu_percent": {"type": ["integer", "null"], "minimum": 50, "maximum": 99}, "memory_percent": {"type": ["integer", "null"], "minimum": 50, "maximum": 99}, "disk_percent": {"type": ["integer", "null"], "minimum": 50, "maximum": 99}, "offline": {"type": "boolean"}, "for_minutes": {"type": "integer", "minimum": 5, "maximum": 60}, "notify_email": {"type": "boolean"}, "firing": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "server_id": {"type": "string"}, "hostname": {"type": "string"}, "kind": {"type": "string", "enum": ["cpu", "memory", "disk", "offline"]}, "status": {"type": "string", "enum": ["firing", "resolved"]}, "value": {"type": ["number", "null"]}, "threshold": {"type": ["integer", "null"]}, "started_at": {"type": "string", "format": "date-time"}, "resolved_at": {"type": ["string", "null"], "format": "date-time"}}}}, "alerts": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "server_id": {"type": "string"}, "hostname": {"type": "string"}, "kind": {"type": "string", "enum": ["cpu", "memory", "disk", "offline"]}, "status": {"type": "string", "enum": ["firing", "resolved"]}, "value": {"type": ["number", "null"]}, "threshold": {"type": ["integer", "null"]}, "started_at": {"type": "string", "format": "date-time"}, "resolved_at": {"type": ["string", "null"], "format": "date-time"}}}}, "current": {"type": "object"}, "supported": {"type": "object"}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}, "put": {"tags": ["Servers"], "operationId": "serverMonitoringSet", "summary": "Настроить мониторинг", "x-required-scope": "servers.update", "description": "Меняются только переданные поля; порог null выключает проверку.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "properties": {"enabled": {"type": "boolean"}, "cpu_percent": {"type": ["integer", "null"], "minimum": 50, "maximum": 99}, "memory_percent": {"type": ["integer", "null"], "minimum": 50, "maximum": 99}, "disk_percent": {"type": ["integer", "null"], "minimum": 50, "maximum": 99}, "offline": {"type": "boolean"}, "for_minutes": {"type": "integer", "minimum": 5, "maximum": 60}, "notify_email": {"type": "boolean"}}}}}}, "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"enabled": {"type": "boolean"}, "cpu_percent": {"type": ["integer", "null"], "minimum": 50, "maximum": 99}, "memory_percent": {"type": ["integer", "null"], "minimum": 50, "maximum": 99}, "disk_percent": {"type": ["integer", "null"], "minimum": 50, "maximum": 99}, "offline": {"type": "boolean"}, "for_minutes": {"type": "integer", "minimum": 5, "maximum": 60}, "notify_email": {"type": "boolean"}}}}}}}}, "422": {"description": "monitoring_nothing_to_watch или ошибка в полях.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "server_deleted.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/alerts": {"get": {"tags": ["Servers"], "operationId": "alerts", "summary": "Оповещения мониторинга", "x-required-scope": "servers.read", "parameters": [{"name": "status", "in": "query", "schema": {"type": "string", "enum": ["firing", "resolved"]}}, {"name": "server_id", "in": "query", "schema": {"type": "string"}}, {"name": "limit", "in": "query", "schema": {"type": "integer", "minimum": 1, "maximum": 200}}, {"name": "before", "in": "query", "schema": {"type": "integer"}}], "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "server_id": {"type": "string"}, "hostname": {"type": "string"}, "kind": {"type": "string", "enum": ["cpu", "memory", "disk", "offline"]}, "status": {"type": "string", "enum": ["firing", "resolved"]}, "value": {"type": ["number", "null"]}, "threshold": {"type": ["integer", "null"]}, "started_at": {"type": "string", "format": "date-time"}, "resolved_at": {"type": ["string", "null"], "format": "date-time"}}}}, "meta": {"type": "object"}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}}}},
    "/servers/{id}/port25-request": {"parameters": [{"$ref": "#/components/parameters/Id"}], "post": {"tags": ["Servers"], "operationId": "serverPort25Request", "summary": "Попросить открыть исходящий порт 25", "x-required-scope": "servers.update", "description": "Порт 25 закрыт у всех серверов. Запрос уходит в поддержку, решает человек.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["reason"], "properties": {"reason": {"type": "string", "minLength": 10, "maxLength": 2000}}}}}}, "responses": {"201": {"description": "Запрос отправлен.", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"requested": {"type": "boolean"}, "ticket_id": {"type": "string"}, "note": {"type": "string"}}}}}}}}, "409": {"description": "port25_already_open, port25_already_requested.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}}}},
    "/servers/{id}/files/edit": {"parameters": [{"$ref": "#/components/parameters/Id"}], "post": {"tags": ["Servers"], "operationId": "serverFileEdit", "summary": "Заменить кусок текста в файле", "x-required-scope": "servers.exec", "description": "old_string должен совпадать с содержимым точно и встречаться один раз, если не задан replace_all. Файлы до 250 КБ.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["path", "old_string", "new_string"], "properties": {"path": {"type": "string"}, "old_string": {"type": "string"}, "new_string": {"type": "string"}, "replace_all": {"type": "boolean"}}}}}}, "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"path": {"type": "string"}, "replacements": {"type": "integer"}, "size": {"type": "integer"}, "mode": {"type": "string"}, "owner": {"type": "string"}}}}}}}}, "422": {"description": "string_not_found, string_not_unique (occurrences), file_too_large, is_directory, no_change, bad_edit.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"description": "file_not_found.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/servers/{id}/dir": {"parameters": [{"$ref": "#/components/parameters/Id"}], "get": {"tags": ["Servers"], "operationId": "serverDir", "summary": "Содержимое каталога на сервере", "x-required-scope": "servers.exec", "parameters": [{"name": "path", "in": "query", "required": true, "schema": {"type": "string"}}], "responses": {"200": {"description": "До 1000 записей, каталоги первыми.", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"path": {"type": "string"}, "entries": {"type": "array", "items": {"type": "object", "properties": {"name": {"type": "string"}, "type": {"type": "string", "enum": ["file", "dir", "link", "other"]}, "size": {"type": "integer"}, "mode": {"type": "string"}, "owner": {"type": "string"}, "modified_at": {"type": "string", "format": "date-time"}}}}, "truncated": {"type": "boolean"}}}}}}}}, "422": {"description": "not_a_directory, bad_path.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"description": "file_not_found.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/servers/{id}/search": {"parameters": [{"$ref": "#/components/parameters/Id"}], "get": {"tags": ["Servers"], "operationId": "serverSearch", "summary": "Найти текст в файлах на сервере", "x-required-scope": "servers.exec", "parameters": [{"name": "path", "in": "query", "required": true, "schema": {"type": "string"}}, {"name": "pattern", "in": "query", "required": true, "schema": {"type": "string", "maxLength": 1000}}, {"name": "regex", "in": "query", "schema": {"type": "boolean"}}, {"name": "max", "in": "query", "schema": {"type": "integer", "minimum": 1, "maximum": 200}}], "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"path": {"type": "string"}, "matches": {"type": "array", "items": {"type": "object", "properties": {"file": {"type": "string"}, "line": {"type": "integer"}, "text": {"type": "string"}}}}, "truncated": {"type": "boolean"}}}}}}}}, "422": {"description": "bad_pattern, bad_path, search_too_long.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"description": "file_not_found.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/overview": {"get": {"tags": ["Account"], "operationId": "overview", "summary": "Обзор для агента: ключ, деньги, серверы, ожидающие запросы", "description": "Всё, чтобы начать или продолжить работу, одним ответом. Разделы зависят от прав ключа.", "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"account": {"type": "object"}, "key": {"type": "object"}, "servers": {"type": "array", "items": {"type": "object"}}, "money": {"type": "object"}, "approvals_pending": {"type": "array", "items": {"type": "object"}}, "events_cursor": {"type": "string"}, "good_to_know": {"type": "array", "items": {"type": "string"}}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}}}},
    "/account/key/activity": {"get": {"tags": ["Account"], "operationId": "ownKeyActivity", "summary": "Журнал ключа, которым сделан запрос", "parameters": [{"name": "page", "in": "query", "schema": {"type": "integer", "minimum": 1}}], "responses": {"200": {"description": "Тот же формат, что у /api-keys/{id}/activity.", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "array", "items": {"type": "object"}}, "meta": {"type": "object"}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "422": {"description": "api_key_only.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/servers/{id}/jobs": {"parameters": [{"$ref": "#/components/parameters/Id"}], "get": {"tags": ["Servers"], "operationId": "serverJobs", "summary": "Фоновые задачи сервера", "x-required-scope": "servers.exec", "description": "Задачи, запущенные через POST /servers/{id}/exec с background=true, за последние 7 дней.", "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "array", "items": {"type": "object", "properties": {"job_id": {"type": "string"}, "status": {"type": "string", "enum": ["running", "finished", "stopped", "lost"]}, "exit_code": {"type": ["integer", "null"]}, "started_at": {"type": "string", "format": "date-time"}, "command": {"type": "string"}, "log_bytes": {"type": "integer"}}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/servers/{id}/jobs/{job_id}": {"parameters": [{"$ref": "#/components/parameters/Id"}, {"name": "job_id", "in": "path", "required": true, "schema": {"type": "string", "pattern": "^[0-9a-f]{12}$"}}], "get": {"tags": ["Servers"], "operationId": "serverJob", "summary": "Состояние фоновой задачи и её вывод", "x-required-scope": "servers.exec", "description": "Вывод читается частями: следующий запрос – с offset=next_offset. С wait запрос ждёт нового вывода или окончания задачи.", "parameters": [{"name": "offset", "in": "query", "schema": {"type": "integer", "minimum": 0}}, {"name": "wait", "in": "query", "schema": {"type": "integer", "minimum": 0, "maximum": 30}}, {"name": "max_bytes", "in": "query", "schema": {"type": "integer", "minimum": 1, "maximum": 200000}}], "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"job_id": {"type": "string"}, "status": {"type": "string", "enum": ["running", "finished", "stopped", "lost"]}, "exit_code": {"type": ["integer", "null"]}, "output": {"type": "string"}, "offset": {"type": "integer"}, "next_offset": {"type": "integer"}, "log_bytes": {"type": "integer"}, "more": {"type": "boolean"}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"description": "job_not_found.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}, "delete": {"tags": ["Servers"], "operationId": "serverJobStop", "summary": "Остановить фоновую задачу", "x-required-scope": "servers.exec", "responses": {"200": {"description": "stopped или finished (задача уже закончилась).", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object"}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"description": "job_not_found.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/servers/{id}/health": {"parameters": [{"$ref": "#/components/parameters/Id"}], "get": {"tags": ["Servers"], "operationId": "serverHealth", "summary": "Состояние сервера изнутри", "x-required-scope": "servers.read", "description": "Загрузка, память, диски, самые тяжёлые процессы, незапустившиеся службы и советы (advice). Только для работающего сервера.", "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"os": {"type": "string"}, "cpus": {"type": "integer"}, "load": {"type": "object"}, "memory": {"type": "object"}, "disks": {"type": "array", "items": {"type": "object"}}, "top_processes": {"type": "array", "items": {"type": "object"}}, "failed_services": {"type": "array", "items": {"type": "string"}}, "advice": {"type": "array", "items": {"type": "string"}}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/events": {"get": {"tags": ["Account"], "operationId": "events", "summary": "События аккаунта, с ожиданием", "x-required-scope": "servers.read", "description": "События после after. С wait запрос остаётся открытым, пока не появится подходящее событие. cursor из ответа передаётся как after в следующий запрос.", "parameters": [{"name": "after", "in": "query", "schema": {"type": "string"}}, {"name": "types", "in": "query", "description": "Через запятую: точные имена или группы вида server.*", "schema": {"type": "string"}}, {"name": "server_id", "in": "query", "schema": {"type": "string"}}, {"name": "wait", "in": "query", "schema": {"type": "integer", "minimum": 0, "maximum": 25}}], "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "type": {"type": "string"}, "server_id": {"type": ["string", "null"]}, "data": {"type": "object"}, "created_at": {"type": "string", "format": "date-time"}}}}, "cursor": {"type": "string"}, "timed_out": {"type": "boolean"}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}}}},
    "/approvals": {"get": {"tags": ["Account"], "operationId": "approvals", "summary": "Запросы на разрешение владельца", "description": "Ключ видит свои запросы, сессия кабинета – все.", "parameters": [{"name": "status", "in": "query", "schema": {"type": "string", "enum": ["pending", "approved", "denied", "used", "expired"]}}], "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "approved", "denied", "used", "expired"]}, "kind": {"type": "string", "enum": ["spend", "action"]}, "action": {"type": "string"}, "summary": {"type": "string"}, "amount_usd": {"type": ["string", "null"]}, "server_id": {"type": ["string", "null"]}, "api_key_name": {"type": "string"}, "expires_at": {"type": "string", "format": "date-time"}}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}}}, "post": {"tags": ["Account"], "operationId": "approvalRequest", "summary": "Попросить разовое разрешение на трату", "description": "Только для API-ключа. Одобренное разрешение покрывает одно платное действие до этой суммы в течение 24 часов.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["amount_usd", "reason"], "properties": {"amount_usd": {"type": "string"}, "reason": {"type": "string", "minLength": 5, "maxLength": 400}}}}}}, "responses": {"201": {"description": "Создан", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"id": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "approved", "denied", "used", "expired"]}, "kind": {"type": "string", "enum": ["spend", "action"]}, "action": {"type": "string"}, "summary": {"type": "string"}, "amount_usd": {"type": ["string", "null"]}, "server_id": {"type": ["string", "null"]}, "api_key_name": {"type": "string"}, "expires_at": {"type": "string", "format": "date-time"}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "422": {"description": "api_key_only или ошибка в полях.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/approvals/{approval_id}": {"parameters": [{"name": "approval_id", "in": "path", "required": true, "schema": {"type": "string"}}], "get": {"tags": ["Account"], "operationId": "approval", "summary": "Запрос на разрешение, с ожиданием ответа", "parameters": [{"name": "wait", "in": "query", "schema": {"type": "integer", "minimum": 0, "maximum": 25}}], "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object", "properties": {"id": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "approved", "denied", "used", "expired"]}, "kind": {"type": "string", "enum": ["spend", "action"]}, "action": {"type": "string"}, "summary": {"type": "string"}, "amount_usd": {"type": ["string", "null"]}, "server_id": {"type": ["string", "null"]}, "api_key_name": {"type": "string"}, "expires_at": {"type": "string", "format": "date-time"}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"description": "approval_not_found.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/api-keys/{id}/activity": {"parameters": [{"$ref": "#/components/parameters/Id"}], "get": {"tags": ["Account"], "operationId": "apiKeyActivity", "summary": "Журнал действий ключа", "x-required-scope": "tokens.read", "description": "Запросы ключа, которые что-то меняли, и чтение файлов на серверах. Новые первыми, по 50 на страницу, хранится 90 дней.", "parameters": [{"name": "page", "in": "query", "schema": {"type": "integer", "minimum": 1}}], "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "array", "items": {"type": "object", "properties": {"at": {"type": "string", "format": "date-time"}, "tool": {"type": ["string", "null"]}, "method": {"type": "string"}, "path": {"type": "string"}, "server_id": {"type": ["string", "null"]}, "summary": {"type": ["string", "null"]}, "status": {"type": "integer"}, "ok": {"type": "boolean"}, "error": {"type": ["string", "null"]}, "cost_usd": {"type": ["string", "null"]}}}}, "meta": {"type": "object"}}}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"description": "api_key_not_found.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/servers/{id}/authorized-keys": {"parameters": [{"$ref": "#/components/parameters/Id"}], "post": {"tags": ["Servers"], "operationId": "serverAuthorizeKey", "summary": "Добавить SSH-ключ пользователю работающего сервера", "x-required-scope": "servers.exec", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "properties": {"ssh_key_id": {"type": "string"}, "public_key": {"type": "string"}, "user": {"type": "string", "default": "root"}}}}}}, "responses": {"200": {"description": "OK", "content": {"application/json": {"schema": {"type": "object", "properties": {"data": {"type": "object"}}}}}}, "422": {"description": "bad_public_key.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "401": {"$ref": "#/components/responses/Unauthenticated"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "server_not_running, guest_agent_unavailable (retry_after), guest_exec_disabled, server_busy.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "503": {"description": "exec_unavailable.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}},
    "/mcp": {
      "post": {
        "tags": ["MCP"], "operationId": "mcp", "summary": "Удалённый MCP-сервер (Streamable HTTP, JSON-RPC 2.0)", "description": "Без сессий и без потока событий: на каждый запрос – обычный JSON-ответ. Авторизация – только API-ключ в заголовке Authorization. Методы: initialize, notifications/initialized, ping, tools/list, tools/call. Инструменты: list_plans, list_images, get_balance, list_servers, get_server, create_server, server_power, reset_password, reinstall_server, delete_server, restore_server, wait_server, list_tickets, create_ticket. Каждый инструмент выполняет соответствующий метод этого API с правами и лимитами ключа. delete_server и reinstall_server требуют аргумент confirm = true. Веб-консоль через MCP не выдаётся. GET и DELETE отвечают 405.",
        "security": [{ "bearerAuth": [] }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/JsonRpcRequest" }, "example": { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "list_servers", "arguments": {} } } } } },
        "responses": {
          "200": { "description": "Ответ JSON-RPC. Результат инструмента: `{\"content\": [{\"type\": \"text\", \"text\": \"<JSON>\"}], \"isError\": false}`.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/JsonRpcResponse" } } } },
          "202": { "description": "Уведомление принято, тела нет." },
          "400": { "description": "Тело не является сообщением JSON-RPC.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/JsonRpcResponse" } } } },
          "401": { "description": "Нет ключа или ключ недействителен. Заголовок WWW-Authenticate: Bearer.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
          "429": { "$ref": "#/components/responses/RateLimited" }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": { "type": "http", "scheme": "bearer", "bearerFormat": "0x_live_...", "description": "API-ключ из кабинета (раздел «API и MCP»)" },
      "sessionCookie": { "type": "apiKey", "in": "cookie", "name": "session", "description": "Сессия кабинета после POST /auth/login. Имя cookie задаётся сервером." }
    },
    "parameters": {
      "Id": { "name": "id", "in": "path", "required": true, "schema": { "type": "string" } },
      "TopupId": { "name": "id", "in": "path", "required": true, "schema": { "type": "string", "format": "uuid" } },
      "IdempotencyKey": { "name": "Idempotency-Key", "in": "header", "required": false, "description": "Ключ безопасного повтора. Работает на любом POST, PATCH и DELETE; здесь отмечены методы, где он особенно полезен.", "schema": { "type": "string", "minLength": 8, "maxLength": 128, "pattern": "^[A-Za-z0-9._:-]+$" } }
    },
    "responses": {
      "Ok": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "ok": { "type": "boolean", "const": true } } } } } },
      "Server": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "$ref": "#/components/schemas/Server" } } } } } },
      "Cancellation": { "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "data": { "type": "object", "properties": { "cancel_at_period_end": { "type": "boolean" }, "paid_until": { "type": ["string", "null"], "format": "date-time" } } } } } } } },
      "Unauthenticated": { "description": "unauthenticated – нет ключа или сессии, ключ недействителен или истёк.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "Forbidden": { "description": "insufficient_scope – у ключа нет нужного права; оно названо в поле required.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "NotFound": { "description": "Не найдено или принадлежит другому аккаунту.", "content": { "application/json": { "schema": { "type": "object" } } } },
      "Conflict": { "description": "Действие сейчас невозможно: not_available, server_busy, server_deleted, server_not_provisioned и подобные. Причина – в error.code и error.message.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "Validation": { "description": "Ошибка проверки полей.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ValidationError" } } } },
      "RateLimited": { "description": "rate_limited – слишком много запросов. Заголовок Retry-After.", "content": { "application/json": { "schema": { "type": "object" } } } },
      "NotAvailable": { "description": "not_available – возможность пока не запущена.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "ProviderError": { "description": "provider_error – гипервизор не выполнил действие. Ничего не изменилось, можно повторить.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "required": ["error"],
        "properties": { "error": {
          "type": "object",
          "required": ["code"],
          "properties": { "code": { "type": "string" }, "message": { "type": "string", "description": "Пояснение на русском языке." } },
          "additionalProperties": true
        } }
      },
      "ValidationError": {
        "type": "object",
        "properties": { "message": { "type": "string" }, "errors": { "type": "object", "additionalProperties": { "type": "array", "items": { "type": "string" } } } }
      },
      "SessionUser": {
        "type": "object",
        "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" }, "role": { "type": "string" }, "balance_usd": { "type": "string" } }
      },
      "Server": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "uuid": { "type": "string" },
          "name": { "type": "string" },
          "hostname": { "type": "string" },
          "plan": { "type": "string" },
          "plan_name": { "type": "string" },
          "vcpu": { "type": "integer" },
          "ram_gb": { "type": "integer" },
          "disk_gb": { "type": "integer" },
          "os": { "type": "string" },
          "ip": { "type": "string", "description": "Пустая строка: публичных адресов пока нет." },
          "ipv4": { "type": "string" },
          "ipv6": { "type": "string" },
          "has_public_ip": { "type": "boolean" },
          "ptr": { "type": ["string", "null"] },
          "billing": { "type": "string", "enum": ["h", "m"] },
          "billing_period": { "type": "string", "enum": ["hourly", "monthly", "quarterly", "semiannual", "annual"] },
          "status": { "type": "string", "enum": ["provisioning", "running", "stopped", "paused", "suspended", "frozen", "deleted_pending", "deleted", "error"] },
          "price_monthly": { "type": "string" },
          "price_hourly": { "type": "string" },
          "paid_until": { "type": ["string", "null"], "format": "date-time" },
          "created_at": { "type": ["string", "null"], "format": "date-time" },
          "cancel_at_period_end": { "type": "boolean" },
          "is_backup_enabled": { "type": "boolean" },
          "extra_ips_count": { "type": "integer" },
          "location": { "type": "string" },
          "restorable": { "type": "boolean" },
          "restore_time_left": { "type": ["string", "null"] }
        }
      },
      "ServerOperation": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "action": { "type": "string", "description": "power.boot, os.install, password.reset, console.open и так далее." },
          "status": { "type": "string", "enum": ["succeeded", "failed"] },
          "details": { "type": ["object", "null"] },
          "created_at": { "type": ["string", "null"], "format": "date-time" }
        }
      },
      "Plan": {
        "type": "object",
        "properties": {
          "id": { "type": "string" }, "slug": { "type": "string" }, "name": { "type": "string" },
          "vcpu": { "type": "integer" }, "ram_mb": { "type": "integer" }, "disk_gb": { "type": "integer" },
          "bandwidth_mbps": { "type": "integer" }, "iops": { "type": "integer" },
          "price_monthly_usd": { "type": "string" }, "price_hourly_usd": { "type": "string" }, "price_monthly_micro": { "type": "integer" },
          "is_auto_provision": { "type": "boolean", "description": "false – тариф выдаётся по заявке." }
        }
      },
      "Image": {
        "type": "object",
        "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "group": { "type": "string" }, "version": { "type": "string" }, "eol": { "type": "boolean" }, "default": { "type": "boolean" } }
      },
      "CommandResult": {"type": "object", "properties": {"status": {"type": "string", "enum": ["finished", "running"]}, "command_id": {"type": "string"}, "exit_code": {"type": ["integer", "null"]}, "stdout": {"type": "string"}, "stderr": {"type": "string"}, "duration_ms": {"type": "integer"}, "timed_out": {"type": "boolean"}, "truncated": {"type": "boolean", "description": "Вывод длиннее 256 КБ: показаны начало и конец."}, "binary": {"type": "boolean", "description": "В выводе были байты не в UTF-8, они заменены."}, "note": {"type": "string"}}},
      "KeySpend": {
        "type": "object",
        "description": "Сколько ключ может тратить с баланса. Счётчик – чистый расход: списания по запросам ключа минус возвраты, плюс почасовая оплата и продление серверов, созданных ключом.",
        "properties": {
          "mode": { "type": "string", "enum": ["unlimited", "limited", "none"] },
          "period": { "type": ["string", "null"], "enum": ["day", "month", "total", null] },
          "limit_usd": { "type": ["string", "null"] },
          "spent_usd": { "type": "string", "description": "Потрачено в текущем периоде." },
          "remaining_usd": { "type": ["string", "null"], "description": "Сколько ещё можно потратить; null – без лимита." },
          "resets_at": { "type": ["string", "null"], "format": "date-time", "description": "Когда счётчик начнётся с нуля." },
          "spent_total_usd": { "type": "string", "description": "Потрачено за всё время ключа." }
        }
      },
      "ApiKey": {
        "type": "object",
        "properties": {
          "id": { "type": "string" }, "name": { "type": "string" }, "key_prefix": { "type": "string" },
          "scopes": { "type": "array", "items": { "type": "string" } },
          "rate_limit_per_minute": { "type": "integer" },
          "spend": { "$ref": "#/components/schemas/KeySpend" },
          "spend_limit_usd": { "type": "string", "description": "Лимит одним числом для старых клиентов; \"0.00\", когда лимита нет. Смотрите spend." },
          "allowed_ips": { "type": "array", "items": { "type": "string" } },
          "is_current": { "type": "boolean", "description": "Этим ключом сделан запрос." },
          "expires_at": { "type": ["string", "null"], "format": "date-time" },
          "last_used_at": { "type": ["string", "null"], "format": "date-time" },
          "created_at": { "type": ["string", "null"], "format": "date-time" }
        }
      },
      "SshKey": {
        "type": "object",
        "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "fingerprint": { "type": "string" }, "created_at": { "type": "string", "format": "date-time" } }
      },
      "Transaction": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "server_id": { "type": ["string", "null"] },
          "type": { "type": "string", "enum": ["topup", "hourly_usage", "period_payment", "refund", "withdrawal", "manual_credit", "manual_debit", "referral_earning"] },
          "amount_micro": { "type": "integer", "description": "Миллионные доли доллара." },
          "balance_after_micro": { "type": "integer" },
          "currency": { "type": "string" },
          "description": { "type": ["string", "null"] },
          "created_at": { "type": "string", "format": "date-time" }
        },
        "additionalProperties": true
      },
      "Topup": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "format": "uuid" },
          "amount_micro": { "type": "integer" },
          "currency": { "type": "string" },
          "provider": { "type": "string" },
          "status": { "type": "string", "enum": ["pending", "completed", "expired"] },
          "checkout_url": { "type": ["string", "null"] },
          "credited_at": { "type": ["string", "null"], "format": "date-time" },
          "expires_at": { "type": ["string", "null"], "format": "date-time" },
          "created_at": { "type": "string", "format": "date-time" }
        },
        "additionalProperties": true
      },
      "Ticket": {
        "type": "object",
        "properties": {
          "id": { "type": "string" }, "subject": { "type": "string" }, "department": { "type": "string" },
          "status": { "type": "string", "enum": ["open", "answered", "customer_reply", "closed"] },
          "priority": { "type": "string" }, "server_id": { "type": ["string", "null"] },
          "messages_count": { "type": "integer" },
          "last_reply_at": { "type": ["string", "null"], "format": "date-time" },
          "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" }
        },
        "additionalProperties": true
      },
      "TicketMessage": {
        "type": "object",
        "properties": { "id": { "type": "string" }, "message": { "type": "string" }, "is_admin": { "type": "boolean" }, "author": { "type": "string" }, "created_at": { "type": ["string", "null"], "format": "date-time" } }
      },
      "WebhookEvent": {
        "type": "string",
        "enum": ["*", "server.created", "server.running", "server.stopped", "server.deleted", "server.restored", "server.reinstalled", "server.error", "balance.credited", "balance.low", "ticket.answered", "ping"]
      },
      "Webhook": {
        "type": "object",
        "properties": {
          "id": { "type": "string" }, "url": { "type": "string" },
          "events": { "type": "array", "items": { "$ref": "#/components/schemas/WebhookEvent" } },
          "is_active": { "type": "boolean" },
          "created_at": { "type": ["string", "null"], "format": "date-time" }
        }
      },
      "WebhookDelivery": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "event": { "type": "string" },
          "event_id": { "type": ["string", "null"], "description": "evt_... – то же значение, что поле id в теле события." },
          "status": { "type": "string", "enum": ["pending", "delivered", "failed"] },
          "success": { "type": "boolean" },
          "attempts": { "type": "integer" },
          "response_status": { "type": ["integer", "null"] },
          "response_body": { "type": ["string", "null"], "description": "Первые 2000 символов ответа." },
          "error": { "type": ["string", "null"] },
          "next_attempt_at": { "type": ["string", "null"], "format": "date-time" },
          "created_at": { "type": ["string", "null"], "format": "date-time" }
        }
      },
      "VoteSummary": {
        "type": "object",
        "properties": { "data": {
          "type": "object",
          "properties": {
            "options": { "type": "array", "items": { "type": "object", "properties": { "code": { "type": "string" }, "name": { "type": "string" } } } },
            "totals": { "type": "object", "additionalProperties": { "type": "integer" }, "description": "Ключ – код страны." },
            "my_vote": { "type": ["string", "null"] }
          }
        } }
      },
      "JsonRpcRequest": {
        "type": "object",
        "required": ["jsonrpc", "method"],
        "properties": {
          "jsonrpc": { "type": "string", "const": "2.0" },
          "id": { "type": ["string", "integer"], "description": "Отсутствует у уведомлений." },
          "method": { "type": "string", "enum": ["initialize", "notifications/initialized", "ping", "tools/list", "tools/call"] },
          "params": { "type": "object" }
        }
      },
      "JsonRpcResponse": {
        "type": "object",
        "required": ["jsonrpc"],
        "properties": {
          "jsonrpc": { "type": "string", "const": "2.0" },
          "id": { "type": ["string", "integer", "null"] },
          "result": { "type": "object" },
          "error": { "type": "object", "properties": { "code": { "type": "integer" }, "message": { "type": "string" } } }
        }
      }
    }
  },
  "x-paths-pending-documentation": {
    "description": "Методы, которые добавляются отдельно и появятся в этом документе после сверки с кодом: двухфакторная защита, список сессий, восстановление пароля, подтверждение почты, запрос на удаление аккаунта, уведомления.",
    "paths": ["/account/2fa*", "/account/sessions-list*", "/auth/2fa", "/auth/password/forgot", "/auth/password/reset", "/auth/email/verify", "/auth/email/resend", "/account/delete-request", "/notifications*"]
  }
}
