{
  "openapi": "3.1.0",
  "info": {
    "title": "RRC Gateway Developer API",
    "version": "1.0.0",
    "description": "RRC Gateway is an intelligent, high-throughput drop-in AI API proxy that reduces OpenAI, Anthropic Claude, and Google Gemini API costs by up to 90% using Semantic Caching, Virtual Memory Context Optimization, and Autonomous Smart Model Routing.\n\n### Verification Status Note\nThis specification documents **verified, implemented functionality** extracted directly from the active RRC Gateway codebase (`gateway.rrcsolutions.me` and local gateway runtime). Features that are experimental or server-specific are explicitly marked.",
    "contact": {
      "name": "RRC Solutions Support",
      "email": "feedback@rrc.dev",
      "url": "https://gateway.rrcsolutions.me"
    }
  },
  "servers": [
    {
      "url": "https://gateway.rrcsolutions.me",
      "description": "Production Edge Gateway (Vercel Global Edge Network)"
    },
    {
      "url": "http://localhost:8000",
      "description": "Local Development Server (FastAPI / Uvicorn)"
    }
  ],
  "tags": [
    {
      "name": "Chat Completions",
      "description": "OpenAI-compatible inference proxy with intelligent 3-pillar cost optimization."
    },
    {
      "name": "Models",
      "description": "Universal model auto-discovery and live tier pricing across multiple providers."
    },
    {
      "name": "Authentication & Config",
      "description": "Client authentication configuration and verification services."
    },
    {
      "name": "Waitlist & Community",
      "description": "Public waitlist registration and community access."
    },
    {
      "name": "Admin",
      "description": "Secured administrative dashboard and subscriber analytics."
    },
    {
      "name": "Benchmark (Engine Specific)",
      "description": "Automated latency, accuracy, and cost-reduction benchmarking endpoints (FastAPI server)."
    }
  ],
  "paths": {
    "/v1/chat/completions": {
      "post": {
        "tags": ["Chat Completions"],
        "summary": "Create chat completion with 3-pillar optimization",
        "description": "Accepts standard OpenAI-formatted chat completion payloads. Applies safe context compression (Pillar 1), autonomous model tier routing (Pillar 2), and exact/semantic caching against the Universal Common DB (Pillar 3). Returns an OpenAI-compatible completion object enriched with `rrc` cost, token, and routing telemetry metadata.",
        "operationId": "createChatCompletion",
        "security": [
          { "BearerAuth": [] },
          { "CommunityDemoAuth": [] }
        ],
        "parameters": [
          {
            "name": "X-RRC-Consent",
            "in": "header",
            "required": false,
            "description": "Opt-in or opt-out of Common DB caching and model training data sharing. Set to `'false'` to enable Zero-Trust Private Mode (disables cache persistence and semantic reuse). Defaults to `'true'`.",
            "schema": {
              "type": "string",
              "enum": ["true", "false"],
              "default": "true"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ChatCompletionRequest"
              },
              "examples": {
                "standard": {
                  "summary": "Standard Chat Request",
                  "value": {
                    "model": "openai/gpt-oss-20b",
                    "messages": [
                      { "role": "system", "content": "You are a helpful coding assistant." },
                      { "role": "user", "content": "Write a Python function to check for prime numbers." }
                    ],
                    "temperature": 0.7,
                    "max_tokens": 512,
                    "stream": false,
                    "consent": true
                  }
                },
                "frontier_routing": {
                  "summary": "Frontier Model with Smart Routing",
                  "value": {
                    "model": "gpt-4o",
                    "messages": [
                      { "role": "user", "content": "What is the capital of France?" }
                    ],
                    "stream": false
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successful completion with RRC optimization telemetry.",
            "headers": {
              "X-RRC-Cache": {
                "description": "Cache hit status: EXACT, SEMANTIC, or MISS.",
                "schema": { "type": "string", "enum": ["EXACT", "SEMANTIC", "MISS"] }
              },
              "X-RRC-Routing": {
                "description": "Routing status: DIRECT (kept requested model) or DOWNSCALED (routed to efficient tier model).",
                "schema": { "type": "string", "enum": ["DIRECT", "DOWNSCALED"] }
              },
              "X-RRC-Tokens-Compressed": {
                "description": "Number of input context tokens eliminated by Virtual Memory compression.",
                "schema": { "type": "string" }
              },
              "X-RRC-Tokens-Saved": {
                "description": "Total tokens saved across caching and compression.",
                "schema": { "type": "string" }
              },
              "X-RRC-Cost-Saved": {
                "description": "Net USD saved on this request compared to standard direct API rates.",
                "schema": { "type": "string" }
              },
              "X-RRC-Latency-Ms": {
                "description": "Server execution and round-trip duration in milliseconds.",
                "schema": { "type": "string" }
              },
              "X-RRC-Common-DB-Hit": {
                "description": "Whether the response was served from the shared Universal Common DB.",
                "schema": { "type": "string", "enum": ["true", "false"] }
              },
              "X-RRC-Common-DB-Saved": {
                "description": "Whether the response was saved to the shared Universal Common DB.",
                "schema": { "type": "string", "enum": ["true", "false"] }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatCompletionResponse"
                }
              }
            }
          },
          "400": {
            "description": "Invalid request (e.g. missing `messages` array, or streaming requested when unsupported).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "401": {
            "description": "Authentication failed or missing Authorization header.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "405": {
            "description": "Method Not Allowed (Only POST is accepted).",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "500": {
            "description": "Internal gateway server error or upstream connection timeout.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "502": {
            "description": "Bad Gateway: Upstream provider returned an unreachable error.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          }
        }
      }
    },
    "/v1/models": {
      "get": {
        "tags": ["Models"],
        "summary": "List available models with pricing & tier metadata",
        "description": "Discovers and lists available models based on the provided API key. Automatically routes to Google Gemini, Groq, OpenAI, or OpenRouter based on key signature. When unauthenticated or using demo keys, returns the Groq and community catalog.",
        "operationId": "listModels",
        "security": [
          { "BearerAuth": [] },
          { "CommunityDemoAuth": [] },
          {}
        ],
        "parameters": [
          {
            "name": "key",
            "in": "query",
            "required": false,
            "description": "Optional API key passed as query parameter for model auto-discovery.",
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": {
            "description": "OpenAI-compatible model list with pricing and efficiency tier metadata.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ModelListResponse"
                }
              }
            }
          }
        }
      }
    },
    "/api/auth/config": {
      "get": {
        "tags": ["Authentication & Config"],
        "summary": "Get client Supabase authentication configuration",
        "description": "Returns client-side Supabase connection URL and public publishable key for client session establishment and analytics logging.",
        "operationId": "getAuthConfig",
        "responses": {
          "200": {
            "description": "Supabase configuration object.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "supabaseUrl": { "type": "string", "example": "https://wqayntphckoyjsviuksv.supabase.co" },
                    "supabaseAnonKey": { "type": "string", "example": "sb_publishable_4UugcdV7UkGRVGmpki_0rA_xwxbir0R" },
                    "hasSupabase": { "type": "boolean", "example": true }
                  },
                  "required": ["supabaseUrl", "supabaseAnonKey", "hasSupabase"]
                }
              }
            }
          }
        }
      }
    },
    "/api/auth/verify": {
      "post": {
        "tags": ["Authentication & Config"],
        "summary": "Verify Cloudflare Turnstile CAPTCHA token",
        "description": "Verifies client-provided Cloudflare Turnstile token for human verification during authentication or waitlist submission.",
        "operationId": "verifyTurnstile",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "token": { "type": "string", "description": "Cloudflare Turnstile token" }
                },
                "required": ["token"]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Verification result.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": { "type": "boolean", "example": true }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/waitlist": {
      "post": {
        "tags": ["Waitlist & Community"],
        "summary": "Register email for gateway access / waitlist",
        "description": "Adds email to the waitlist queue and persists entry in database or Vercel Blob store.",
        "operationId": "submitWaitlist",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "email": { "type": "string", "format": "email", "example": "dev@example.com" }
                },
                "required": ["email"]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Registration status.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": { "type": "string", "example": "success" }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/admin/login": {
      "post": {
        "tags": ["Admin"],
        "summary": "Administrator authentication",
        "description": "Validates administrator credentials and issues an HTTP-only secure cookie and token for the admin dashboard.",
        "operationId": "adminLogin",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "username": { "type": "string", "example": "RRC" },
                  "password": { "type": "string", "format": "password" }
                },
                "required": ["username", "password"]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Authentication successful.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": { "type": "string", "example": "success" },
                    "token": { "type": "string" },
                    "message": { "type": "string", "example": "Authentication successful." }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Invalid username or password."
          }
        }
      }
    },
    "/api/admin/signups": {
      "get": {
        "tags": ["Admin"],
        "summary": "List subscriber and waitlist signups",
        "description": "Retrieves the registered user list from Vercel Blob storage. Requires admin Bearer token or admin session cookie.",
        "operationId": "getAdminSignups",
        "security": [
          { "AdminTokenAuth": [] }
        ],
        "responses": {
          "200": {
            "description": "List of subscribers.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": { "type": "string", "example": "success" },
                    "total": { "type": "integer", "example": 3 },
                    "signups": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": { "type": "integer" },
                          "email": { "type": "string" },
                          "status": { "type": "string" },
                          "timestamp": { "type": "string" }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized access."
          }
        }
      }
    },
    "/health": {
      "get": {
        "tags": ["Authentication & Config"],
        "summary": "Gateway health check",
        "description": "Verifies that the gateway service is online and reports custom backend connectivity status if configured.",
        "operationId": "healthCheck",
        "responses": {
          "200": {
            "description": "Gateway status.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": { "type": "string", "example": "ok" },
                    "custom_backend": {
                      "type": "object",
                      "nullable": true,
                      "properties": {
                        "status": { "type": "string", "example": "ok" },
                        "url": { "type": "string" },
                        "model": { "type": "string" }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/v1/benchmark/run": {
      "post": {
        "tags": ["Benchmark (Engine Specific)"],
        "summary": "Trigger automated benchmark execution",
        "description": "Asynchronously executes an end-to-end benchmark run evaluating latency, compression ratio, cache hit rates, and cost savings across synthetic datasets. (Implemented in local FastAPI backend for Codex benchmark engine testing).",
        "operationId": "triggerBenchmark",
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "profile": { "type": "string", "default": "BALANCED", "enum": ["AGGRESSIVE", "BALANCED", "CONSERVATIVE", "QUALITY_FIRST"] },
                  "dataset_size": { "type": "integer", "default": 25 },
                  "mode": { "type": "string", "default": "RRC_FULL", "enum": ["RRC_FULL", "CACHE_ONLY", "ROUTING_ONLY", "BASELINE_DIRECT"] },
                  "model": { "type": "string", "default": "groq/qwen/qwen3.6-27b" }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Benchmark execution launched successfully.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": { "type": "string", "example": "started" },
                    "benchmark_run_id": { "type": "string", "example": "RRC-BENCH-2026-11-16-492" },
                    "message": { "type": "string", "example": "Real benchmark execution launched successfully." }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/v1/benchmark/status/{run_id}": {
      "get": {
        "tags": ["Benchmark (Engine Specific)"],
        "summary": "Check benchmark execution status",
        "description": "Polls status of a running or completed benchmark run.",
        "operationId": "getBenchmarkStatus",
        "parameters": [
          { "name": "run_id", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "Benchmark execution status record." },
          "404": { "description": "Benchmark run ID not found." }
        }
      }
    },
    "/v1/benchmark/results/{run_id}": {
      "get": {
        "tags": ["Benchmark (Engine Specific)"],
        "summary": "Retrieve complete benchmark metrics & traces",
        "description": "Returns full aggregated metrics, latency percentiles (P50, P90, P99), total tokens saved, and individual request traces for a completed run.",
        "operationId": "getBenchmarkResults",
        "parameters": [
          { "name": "run_id", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "Benchmark full metrics and traces." },
          "404": { "description": "Benchmark run ID not found." }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "BearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "API Key",
        "description": "Upstream provider API key passed in the standard Authorization header. The key prefix automatically routes the query to the corresponding upstream provider:\n- `AQ.*`, `AIzaSy*`, `AIza*`: Google Gemini\n- `gsk_*`: Groq\n- `sk-or-v1-*`: OpenRouter\n- `sk-ant-*`: OpenRouter (Claude 3.5 Sonnet)\n- `sk-proj-*`, `sk-admin-*`, `sk-*`: OpenAI"
      },
      "CommunityDemoAuth": {
        "type": "http",
        "scheme": "bearer",
        "description": "Pass `Bearer demo`, `Bearer community`, or `Bearer public` to access the free community inference tier powered by Groq."
      },
      "AdminTokenAuth": {
        "type": "http",
        "scheme": "bearer",
        "description": "SHA-256 derived administrator session token for management endpoints."
      }
    },
    "schemas": {
      "ChatMessage": {
        "type": "object",
        "properties": {
          "role": {
            "type": "string",
            "enum": ["system", "user", "assistant"],
            "description": "The role of the messages author."
          },
          "content": {
            "oneOf": [
              { "type": "string", "description": "Text content of the message." },
              {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "type": { "type": "string", "enum": ["text", "image_url"] },
                    "text": { "type": "string" }
                  }
                }
              }
            ],
            "description": "The contents of the message."
          },
          "name": { "type": "string", "description": "Optional author name." }
        },
        "required": ["role", "content"]
      },
      "ChatCompletionRequest": {
        "type": "object",
        "properties": {
          "messages": {
            "type": "array",
            "items": { "$ref": "#/components/schemas/ChatMessage" },
            "description": "A list of messages comprising the conversation so far."
          },
          "model": {
            "type": "string",
            "description": "ID of the model to use. Defaults to the provider's default model (e.g. `openai/gpt-oss-20b` for Groq, `gemini-2.5-flash` for Gemini, `gpt-4o-mini` for OpenAI). Frontier models (e.g. `gpt-4o`, `claude-3-5-sonnet`) are automatically evaluated by the Autonomous Complexity Classifier.",
            "example": "openai/gpt-oss-20b"
          },
          "temperature": {
            "type": "number",
            "minimum": 0.0,
            "maximum": 2.0,
            "default": 1.0,
            "description": "Sampling temperature."
          },
          "max_tokens": {
            "type": "integer",
            "nullable": true,
            "description": "The maximum number of tokens to generate in the completion."
          },
          "stream": {
            "type": "boolean",
            "default": false,
            "description": "NOTE: Server-sent event (SSE) streaming is not supported in the current MVP version. Must be set to `false` or omitted."
          },
          "consent": {
            "type": "boolean",
            "default": true,
            "description": "Controls whether this request is eligible to be cached in and read from the shared Universal Common DB. If `false`, Private Zero-Trust Mode is activated."
          }
        },
        "required": ["messages"]
      },
      "ChatChoice": {
        "type": "object",
        "properties": {
          "index": { "type": "integer", "example": 0 },
          "message": { "$ref": "#/components/schemas/ChatMessage" },
          "finish_reason": { "type": "string", "example": "stop" }
        },
        "required": ["index", "message", "finish_reason"]
      },
      "UsageInfo": {
        "type": "object",
        "properties": {
          "prompt_tokens": { "type": "integer", "example": 45 },
          "completion_tokens": { "type": "integer", "example": 120 },
          "total_tokens": { "type": "integer", "example": 165 }
        },
        "required": ["prompt_tokens", "completion_tokens", "total_tokens"]
      },
      "RRCSavingsBreakdown": {
        "type": "object",
        "properties": {
          "cache_saved_usd": { "type": "number", "example": 0.00045, "description": "Dollars saved from cache hits." },
          "routing_saved_usd": { "type": "number", "example": 0.00015, "description": "Dollars saved by autonomous model tier downscaling." },
          "compression_saved_usd": { "type": "number", "example": 0.00003, "description": "Dollars saved by context compression." }
        },
        "required": ["cache_saved_usd", "routing_saved_usd", "compression_saved_usd"]
      },
      "RRCTelemetry": {
        "type": "object",
        "description": "Enriched RRC Gateway optimization, routing, and economic telemetry metadata.",
        "properties": {
          "cache": {
            "type": "string",
            "enum": ["exact", "semantic", "miss"],
            "description": "Cache evaluation outcome: `exact` (identical normalized key match), `semantic` (topical keyword/Jaccard similarity >= 0.65), or `miss`."
          },
          "routed": {
            "type": "boolean",
            "description": "True if the query was autonomously downscaled from a frontier model to an optimized tier model."
          },
          "requested_model": { "type": "string", "example": "gpt-4o" },
          "served_model": { "type": "string", "example": "gpt-4o-mini" },
          "tokens_prompt": { "type": "integer", "example": 42 },
          "tokens_completion": { "type": "integer", "example": 88 },
          "tokens_total": { "type": "integer", "example": 130 },
          "tokens_compressed": { "type": "integer", "example": 18, "description": "Tokens eliminated from the input context by Pillar 1 Virtual Memory compression." },
          "tokens_saved": { "type": "integer", "example": 18, "description": "Net tokens saved on this invocation." },
          "cost_standard_usd": { "type": "number", "example": 0.000985, "description": "What this invocation would have cost at standard upstream provider rates." },
          "cost_gateway_usd": { "type": "number", "example": 0.000059, "description": "Actual cost incurred through RRC Gateway." },
          "cost_saved_usd": { "type": "number", "example": 0.000926, "description": "Net USD saved by RRC Gateway optimizations." },
          "savings_pct": { "type": "integer", "example": 94, "description": "Percentage savings (0% to 100%)." },
          "savings_breakdown": { "$ref": "#/components/schemas/RRCSavingsBreakdown" },
          "latency_ms": { "type": "integer", "example": 124, "description": "Total gateway processing and upstream turnaround in milliseconds." },
          "speed_multiplier": { "type": "string", "example": "50x faster (Exact KV Hit)" },
          "provider": { "type": "string", "enum": ["groq", "gemini", "openai", "openrouter"] },
          "model": { "type": "string", "example": "gpt-4o-mini" },
          "common_db_hit": { "type": "boolean", "description": "True if served from the shared Universal Common DB." },
          "common_db_saved": { "type": "boolean", "description": "True if response was saved to the shared Universal Common DB." },
          "private_mode": { "type": "boolean", "description": "True if Zero-Trust Private Mode was activated via consent header/body." },
          "consent_granted": { "type": "boolean" }
        },
        "required": [
          "cache", "routed", "requested_model", "served_model", "tokens_prompt",
          "tokens_completion", "tokens_total", "tokens_compressed", "tokens_saved",
          "cost_standard_usd", "cost_gateway_usd", "cost_saved_usd", "savings_pct",
          "savings_breakdown", "latency_ms", "provider", "model"
        ]
      },
      "ChatCompletionResponse": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "example": "chatcmpl-9xZ123abc" },
          "object": { "type": "string", "example": "chat.completion" },
          "created": { "type": "integer", "example": 1731776000 },
          "model": { "type": "string", "example": "openai/gpt-oss-20b" },
          "choices": {
            "type": "array",
            "items": { "$ref": "#/components/schemas/ChatChoice" }
          },
          "usage": { "$ref": "#/components/schemas/UsageInfo" },
          "rrc": { "$ref": "#/components/schemas/RRCTelemetry" }
        },
        "required": ["id", "object", "created", "model", "choices", "usage", "rrc"]
      },
      "ModelItem": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "example": "gemini-2.5-flash" },
          "object": { "type": "string", "example": "model" },
          "created": { "type": "integer", "example": 1731776000 },
          "owned_by": { "type": "string", "example": "google" },
          "name": { "type": "string", "example": "Gemini 2.5 Flash" },
          "provider": { "type": "string", "example": "Google Gemini" },
          "tier": { "type": "string", "example": "Fast & Optimized" },
          "savings_potential": { "type": "string", "example": "Up to 96% cheaper ($0.075/1M)" },
          "pricing_prompt_1m": { "type": "number", "example": 0.075 },
          "pricing_completion_1m": { "type": "number", "example": 0.30 }
        },
        "required": ["id", "object", "name", "provider"]
      },
      "ModelListResponse": {
        "type": "object",
        "properties": {
          "object": { "type": "string", "example": "list" },
          "data": {
            "type": "array",
            "items": { "$ref": "#/components/schemas/ModelItem" }
          }
        },
        "required": ["object", "data"]
      },
      "ErrorDetail": {
        "type": "object",
        "properties": {
          "message": { "type": "string", "example": "Missing API key. Please provide your API key in the Authorization header: Bearer <API_KEY>" },
          "type": { "type": "string", "example": "authentication_error" },
          "param": { "type": "string", "nullable": true },
          "code": { "type": "string", "example": "missing_api_key" }
        }
      },
      "ErrorResponse": {
        "type": "object",
        "properties": {
          "error": {
            "oneOf": [
              { "type": "string", "example": "Missing or invalid \"messages\" array." },
              { "$ref": "#/components/schemas/ErrorDetail" }
            ]
          }
        },
        "required": ["error"]
      }
    }
  }
}
