docs/architecture/ARCHITECTURE.md
๐ Languages: ๐บ๐ธ English | ๐ง๐ท Portuguรชs (Brasil) | ๐ช๐ธ Espaรฑol | ๐ซ๐ท Franรงais | ๐ฎ๐น Italiano | ๐ท๐บ ะ ัััะบะธะน | ๐จ๐ณ ไธญๆ (็ฎไฝ) | ๐ฉ๐ช Deutsch | ๐ฎ๐ณ เคนเคฟเคจเฅเคฆเฅ | ๐น๐ญ เนเธเธข | ๐บ๐ฆ ะฃะบัะฐัะฝััะบะฐ | ๐ธ๐ฆ ุงูุนุฑุจูุฉ | ๐ฏ๐ต ๆฅๆฌ่ช | ๐ป๐ณ Tiแบฟng Viแปt | ๐ง๐ฌ ะัะปะณะฐััะบะธ | ๐ฉ๐ฐ Dansk | ๐ซ๐ฎ Suomi | ๐ฎ๐ฑ ืขืืจืืช | ๐ญ๐บ Magyar | ๐ฎ๐ฉ Bahasa Indonesia | ๐ฐ๐ท ํ๊ตญ์ด | ๐ฒ๐พ Bahasa Melayu | ๐ณ๐ฑ Nederlands | ๐ณ๐ด Norsk | ๐ต๐น Portuguรชs (Portugal) | ๐ท๐ด Romรขnฤ | ๐ต๐ฑ Polski | ๐ธ๐ฐ Slovenฤina | ๐ธ๐ช Svenska | ๐ต๐ญ Filipino | ๐จ๐ฟ ฤeลกtina
Last updated: 2026-06-28
OmniRoute is a local AI routing gateway and dashboard built on Next.js.
It provides a single OpenAI-compatible endpoint (/v1/*) and routes traffic across multiple upstream providers with translation, fallback, token refresh, and usage tracking.
Core capabilities:
provider + model + connection) with runtime ordering by compositeTiers/v1/embeddings (6 providers, 9 models)/v1/images/generations (10+ providers, 20+ models)/v1/audio/transcriptions (7 providers)/v1/audio/speech (10 providers)/v1/videos/generations (ComfyUI + SD WebUI)/v1/music/generations (ComfyUI)/v1/search (5 providers)/v1/moderations/v1/rerank<think>...</think>) for reasoning modelscombo_execution_key / combo_step_idsrc/lib/oauth/providers/)/v1/ws)glmt) first-class provider preset/messages/count_tokens with estimation fallback)requestRetry and maxRetryIntervalSecPrimary runtime model:
src/app/api/* implement both dashboard APIs and compatibility APIssrc/sse/* + open-sse/* handles provider execution, translation, streaming, fallback, and usageCanonical, version-controlled Mermaid sources for the v3.8.0 platform live in
docs/diagrams/. Two are reproduced below for orientation;
the rest are linked from their domain-specific guides.
Source: diagrams/request-pipeline.mmd
Source: diagrams/resilience-3layers.mmd โ also linked from RESILIENCE_GUIDE.md and the
CLAUDE.mdresilience reference.
NEXT_PUBLIC_CLOUD_URLMain pages under src/app/(dashboard)/dashboard/:
/dashboard โ quick start + provider overview/dashboard/endpoint โ endpoint proxy + MCP + A2A + API endpoint tabs/dashboard/providers โ provider connections and credentials/dashboard/combos โ combo strategies, templates, step-based builder, model routing rules, manual persisted ordering/dashboard/auto-combo โ Auto Combo Engine: scoring weights, mode packs, virtual factory presets, telemetry/dashboard/costs โ cost aggregation and pricing visibility/dashboard/analytics โ usage analytics, evaluations, combo target health/dashboard/limits โ quota/rate controls/dashboard/cli-tools โ CLI onboarding, runtime detection, config generation/dashboard/agents โ detected ACP agents + custom agent registration/dashboard/cloud-agents โ cloud-hosted agent tasks (Codex Cloud, Devin, Jules) and task lifecycle/dashboard/skills โ A2A skill registry, sandbox execution, built-in skill catalog/dashboard/memory โ persistent conversational memory inspection and retrieval/dashboard/webhooks โ outbound webhook subscriptions, secret rotation, retry stats/dashboard/batch โ batch job submission and progress/dashboard/cache โ read-through and reasoning cache statistics, eviction controls/dashboard/playground โ interactive chat playground against any configured combo/model/dashboard/changelog โ in-app changelog viewer (renders CHANGELOG.md)/dashboard/system โ runtime diagnostics, version info, environment validation surface/dashboard/onboarding โ first-run setup wizard for new installations/dashboard/media โ image/video/music playground/dashboard/search-tools โ search provider testing and history/dashboard/health โ uptime, circuit breakers, rate limits, quota-monitored sessions/dashboard/logs โ request/proxy/audit/console logs/dashboard/settings โ system settings tabs (general, routing, combo defaults, etc.)/dashboard/context/caveman โ Caveman compression rules, language packs, preview, and output mode/dashboard/context/rtk โ RTK command-output filters, preview, and runtime safety settings/dashboard/context/combos โ named compression pipelines assigned to routing combos/dashboard/translator โ translator inspection and request format conversion preview/dashboard/audit โ compliance audit log browser with pagination and structured metadata/dashboard/usage โ per-request usage browser tied to usage_history/dashboard/compression โ compression analytics, statistics, and pipeline assignment/dashboard/api-manager โ API key lifecycle and model permissionsflowchart LR
subgraph Clients[Developer Clients]
C1[Claude Code]
C2[Codex CLI]
C3[OpenClaw / Droid / Cline / Continue / Roo]
C4[Custom OpenAI-compatible clients]
BROWSER[Browser Dashboard]
end
subgraph Router[OmniRoute Local Process]
API[V1 Compatibility API\n/v1/*]
DASH[Dashboard + Management API\n/api/*]
CORE[SSE + Translation Core\nopen-sse + src/sse]
DB[(storage.sqlite)]
UDB[(usage tables + log artifacts)]
end
subgraph Upstreams[Upstream Providers]
P1[OAuth Providers\nClaude/Codex/Gemini/Qoder/GitHub/Kiro/Cursor/Antigravity]
P2[API Key Providers\nOpenAI/Anthropic/OpenRouter/GLM/Kimi/MiniMax\nDeepSeek/Groq/xAI/Mistral/Perplexity\nTogether/Fireworks/Cerebras/Cohere/NVIDIA]
P3[Compatible Nodes\nOpenAI-compatible / Anthropic-compatible]
end
subgraph Cloud[Optional Cloud Sync]
CLOUD[Cloud Sync Endpoint\nNEXT_PUBLIC_CLOUD_URL]
end
C1 --> API
C2 --> API
C3 --> API
C4 --> API
BROWSER --> DASH
API --> CORE
DASH --> DB
CORE --> DB
CORE --> UDB
CORE --> P1
CORE --> P2
CORE --> P3
DASH --> CLOUD
Main directories:
src/app/api/v1/* and src/app/api/v1beta/* for compatibility APIssrc/app/api/* for management/configuration APIsnext.config.mjs map /v1/* to /api/v1/*Important compatibility routes:
src/app/api/v1/chat/completions/route.tssrc/app/api/v1/messages/route.tssrc/app/api/v1/responses/route.tssrc/app/api/v1/models/route.ts โ includes custom models with custom: truesrc/app/api/v1/embeddings/route.ts โ embedding generation (6 providers)src/app/api/v1/images/generations/route.ts โ image generation (4+ providers incl. Antigravity/Nebius)src/app/api/v1/messages/count_tokens/route.tssrc/app/api/v1/providers/[provider]/chat/completions/route.ts โ dedicated per-provider chatsrc/app/api/v1/providers/[provider]/embeddings/route.ts โ dedicated per-provider embeddingssrc/app/api/v1/providers/[provider]/images/generations/route.ts โ dedicated per-provider imagessrc/app/api/v1beta/models/route.tssrc/app/api/v1beta/models/[...path]/route.tsManagement domains:
src/app/api/auth/*, src/app/api/settings/*src/app/api/providers*src/app/api/provider-nodes*src/app/api/provider-models (GET/POST/DELETE)src/app/api/models/route.ts (GET)src/app/api/settings/proxy (GET/PUT/DELETE) + src/app/api/settings/proxy/test (POST)src/app/api/oauth/*src/app/api/keys*, src/app/api/models/alias, src/app/api/combos*, src/app/api/pricingsrc/app/api/usage/*src/app/api/sync/*, src/app/api/cloud/*src/app/api/cli-tools/*src/app/api/settings/ip-filter (GET/PUT)src/app/api/settings/thinking-budget (GET/PUT)src/app/api/settings/system-prompt (GET/PUT)src/app/api/settings/compression, src/app/api/compression/*, and
src/app/api/context/*src/app/api/sessions (GET)src/app/api/rate-limits (GET)src/app/api/resilience (GET/PATCH) โ request queue, connection cooldown, provider breaker, wait-for-cooldown configsrc/app/api/resilience/reset (POST) โ reset provider breakerssrc/app/api/cache/stats (GET/DELETE)src/app/api/telemetry/summary (GET)src/app/api/usage/budget (GET/POST)src/app/api/fallback/chains (GET/POST/DELETE)src/app/api/compliance/audit-log (GET, with pagination + structured metadata)src/app/api/evals (GET/POST), src/app/api/evals/[suiteId] (GET)src/app/api/policies (GET/POST)src/app/api/sync/tokens (GET/POST), src/app/api/sync/tokens/[id] (GET/DELETE)src/app/api/sync/bundle (GET, ETag-versioned snapshot of settings/providers/combos/keys)src/app/api/v1/ws/route.ts โ Upgrade handler for OpenAI-compatible WS clientsMain flow modules:
src/sse/handlers/chat.tsopen-sse/handlers/chatCore.tsopen-sse/executors/*open-sse/services/provider.tssrc/sse/services/model.ts, open-sse/services/model.tsopen-sse/services/accountFallback.tsopen-sse/translator/index.tsopen-sse/utils/stream.ts, open-sse/utils/streamHandler.tsopen-sse/utils/usageTracking.tsopen-sse/utils/thinkTagParser.tsopen-sse/handlers/embeddings.tsopen-sse/config/embeddingRegistry.tsopen-sse/handlers/imageGeneration.tsopen-sse/config/imageRegistry.tsopen-sse/handlers/responseSanitizer.tsopen-sse/services/roleNormalizer.tsServices (business logic):
open-sse/services/accountSelector.tsopen-sse/services/contextManager.tsopen-sse/services/ipFilter.tsopen-sse/services/sessionManager.tsopen-sse/services/signatureCache.tsopen-sse/services/systemPrompt.tsopen-sse/services/thinkingBudget.tsopen-sse/services/wildcardRouter.tsopen-sse/services/rateLimitManager.tssrc/shared/utils/circuitBreaker.tsopen-sse/services/contextHandoff.ts โ handoff summary generation and injection for context-relay strategyopen-sse/services/compression/* โ proactive compression before provider translation;
includes Caveman rules, RTK filters, stacked pipelines, compression combos, stats, and validationopen-sse/services/codexQuotaFetcher.ts โ fetches Codex quota for context-relay handoff decisionssrc/sse/services/cooldownAwareRetry.ts โ per-model cooldown retries with configurable requestRetry / maxRetryIntervalSecsrc/shared/network/safeOutboundFetch.ts โ guarded provider/model fetch with SSRF guard, private-URL blocking, retry, and timeoutsrc/shared/network/outboundUrlGuard.ts โ validates provider URLs against private/localhost CIDR rangesopen-sse/services/providerRequestDefaults.ts โ provider-level maxTokens, temperature, thinkingBudgetTokens defaultsopen-sse/config/glmProvider.ts โ shared GLM models, quota URLs, GLMT timeout/defaultsopen-sse/config/antigravityUpstream.ts โ base URL and discovery path constantsopen-sse/config/codexClient.ts โ versioned user-agent and client-version valuessrc/lib/modelAliasSeed.ts โ seeds 30+ cross-proxy dialect aliases at startupDomain layer modules:
src/domain/costRules.tssrc/domain/fallbackPolicy.tssrc/domain/comboResolver.tssrc/domain/lockoutPolicy.tssrc/domain/policyEngine.ts โ centralized lockout โ budget โ fallback evaluationsrc/shared/constants/errorCodes.tssrc/shared/utils/requestId.tssrc/shared/utils/fetchTimeout.tssrc/shared/utils/requestTelemetry.tssrc/lib/compliance/index.tssrc/lib/evals/evalRunner.tssrc/lib/db/domainState.ts โ SQLite CRUD for fallback chains, budgets, cost history, lockout state, circuit breakersOAuth provider modules (22 individual files under src/lib/oauth/providers/):
src/lib/oauth/providers/index.tsagy.ts, antigravity.ts, claude.ts, cline.ts, codebuddy-cn.ts, codex.ts, cursor.ts, devin-desktop.ts, ghe-copilot.ts, github.ts, gitlab-duo.ts, grok-cli-oauth.ts, grok-cli.ts, kilocode.ts, kimi-coding.ts, kiro.ts, qoder.ts, raycast.ts, trae.ts, xai-oauth.ts, zed-hosted.ts, zed.tssrc/lib/oauth/providers.ts โ re-exports from individual modulesOmniRoute can install, supervise, and route to locally-running AI tool processes called embedded services. Two are shipped in v3.8.4: 9Router and CLIProxyAPI.
Architecture layers:
/dashboard/providers/services) โ two-tab page with lifecycle controls,
live log streaming, API key management, and (for 9Router) embedded native UI via
an internal reverse proxy./api/services/{name}/*) โ 8 endpoints for 9Router, 7 for CLIProxyAPI,
all classified LOCAL_ONLY (hard rule #17). A shared GET /api/services/[name]/logs
SSE endpoint serves both services.src/lib/services/) โ generic ServiceSupervisor class wraps
child_process.spawn, holds a 5 MB ring buffer for SSE log streaming, a health
probe loop, an atomic operation lock, and a SIGTERMโSIGKILL graceful shutdown.
bootstrap.ts wires all configured services at process start.open-sse/executors/ninerouter.ts) โ 9Router is exposed as
a real provider. Models are prefixed 9router/{sub}/{model} and synced every 5 min
from 9Router's /v1/models endpoint.Deep-dive: docs/frameworks/EMBEDDED-SERVICES.md
Auto Combo dynamically scores and picks routing targets at request time, rather than
relying on a static combo definition. It powers the auto/* model prefix family.
open-sse/services/autoCombo/ (autoComboEngine.ts,
scoringEngine.ts, virtualFactory.ts, modePacks.ts)src/domain/comboResolver.ts (auto-detection of auto/ prefix)/dashboard/auto-comboauto_combo_decisions SQLite tableKey capabilities:
fusion (panel fan-out + judge synthesis,
open-sse/services/fusion.ts) is new in v3.8.36.auto/coding, auto/cheap, auto/fast, auto/offline,
auto/smart, auto/lkgp โ each backed by a tuned weight profile.For full algorithmic detail (factor formulas, weight tuning), see
docs/routing/AUTO-COMBO.md.
Cloud Agents wraps third-party hosted code-agent platforms (Codex Cloud, Devin, Jules) behind a uniform DB-backed task lifecycle. All task creation/inspection endpoints require management authentication.
src/lib/cloudAgent/ (baseAgent.ts, registry.ts, api.ts,
types.ts, db.ts, plus per-agent subdirectories under agents/)agents/codex/, agents/devin/, agents/jules//api/v1/agents/tasks/* (list/create/get/cancel)/api/cloud/* (provisioning, status, batch)/dashboard/cloud-agentscloud_agent_tasks tableFor per-agent provisioning and OAuth specifics, see
docs/frameworks/CLOUD_AGENT.md.
The guardrails module is a hot-reloadable middleware layer that inspects requests and responses for PII, prompt injection, and unsafe vision content. Violations short-circuit the request with HTTP 503 plus a structured error code, allowing downstream callers to retry or branch.
src/lib/guardrails/ (base.ts, registry.ts, piiMasker.ts,
promptInjection.ts, visionBridge.ts, visionBridgeHelpers.ts)503 with error.code = "GUARDRAIL_VIOLATION"For ruleset authoring and threshold tuning, see
docs/security/GUARDRAILS.md.
The src/domain/ namespace centralizes policy decisions so route handlers do not
have to assemble lockout/budget/fallback logic themselves.
src/domain/policyEngine.ts โ single entry point for
pre-execution evaluation (lockout โ budget โ fallback ordering)src/domain/costRules.tssrc/domain/fallbackPolicy.tssrc/domain/lockoutPolicy.tssrc/domain/tagRouter.tssrc/domain/comboResolver.ts โ resolves combo names, auto/*
prefixes, and wildcard model targets to concrete execution planssrc/domain/connectionModelRules.tssrc/domain/modelAvailability.tssrc/domain/providerExpiration.tssrc/domain/quotaCache.tssrc/domain/degradation.tssrc/domain/configAudit.tssrc/domain/omnirouteResponseMeta.tssrc/domain/assessment/ โ periodic evaluation jobsThe authorization pipeline classifies every incoming request and applies the appropriate policy chain before dispatch.
src/server/authz/pipeline.tssrc/server/authz/classify.ts โ distinguishes public
compatibility routes from management routessrc/shared/constants/publicApiRoutes.tssrc/server/authz/policies/ โ composable predicates
(requireApiKey, requireManagement, requireFreshAuth, etc.)src/server/authz/headers.tssrc/server/authz/assertAuth.tssrc/server/authz/context.tsPublic vs management routes are a hard boundary: agent/cooldown APIs and provider mutations require management auth (HTTP 401 if missing).
For the full route classification rules, see
docs/architecture/AUTHZ_GUIDE.md.
A finite-state-machine driven router layered above combo selection to direct traffic based on the detected workflow stage (planning, execution, review) and background-task affinity.
open-sse/services/workflowFSM.tsopen-sse/services/taskAwareRouter.tsopen-sse/services/backgroundTaskDetector.tsopen-sse/services/intentClassifier.tsThe FSM transitions feed into Auto Combo's scoring, biasing toward cheaper models for background/automation tasks and toward stronger models for interactive planning/review turns.
Several providers ship dedicated resilience and stealth modules that piggy-back on the global circuit breaker / connection cooldown / model lockout layers:
open-sse/services/antigravity429Engine.ts (rotates
identity, scrubs response headers, drives credits/version tracking via
antigravityCredits.ts, antigravityHeaderScrub.ts, antigravityHeaders.ts,
antigravityIdentity.ts, antigravityVersion.ts)open-sse/services/modelscopePolicy.tsopen-sse/services/claudeCodeCCH.ts,
plus claudeCodeCompatible.ts, claudeCodeConstraints.ts, claudeCodeExtraRemap.ts,
claudeCodeToolRemapper.tsopen-sse/services/claudeCodeFingerprint.tsopen-sse/services/claudeCodeObfuscation.tsopen-sse/services/chatgptTlsClient.ts (curl-impersonate
style for ChatGPT-Web sessions)open-sse/services/chatgptImageCache.tsFor the full stealth playbook and operational guidance, see
docs/security/STEALTH_GUIDE.md.
src/lib/webhookDispatcher.tswebhooks SQLite table (via src/lib/db/webhooks.ts)/dashboard/webhooks (subscriptions, secrets, retry history)docs/frameworks/WEBHOOKS.md.src/lib/db/reasoningCache.tsopen-sse/services/reasoningCache.tsdocs/routing/REASONING_REPLAY.md.src/lib/db/readCache.tsGET /api/cache/stats, dashboard at /dashboard/cachePrimary state DB (SQLite):
src/lib/db/core.ts (better-sqlite3, migrations, WAL)src/lib/localDb.ts (thin compatibility layer for callers)${DATA_DIR}/storage.sqlite (or $XDG_CONFIG_HOME/omniroute/storage.sqlite when set, else ~/.omniroute/storage.sqlite)Usage persistence:
src/lib/usageDb.ts (decomposed modules in src/lib/usage/*)storage.sqlite: usage_history, call_logs, proxy_logs${DATA_DIR}/log.txt, ${DATA_DIR}/call_logs/, <repo>/logs/...)Domain State DB (SQLite):
src/lib/db/domainState.ts โ CRUD operations for domain statesrc/lib/db/core.ts): domain_fallback_chains, domain_budgets, domain_cost_history, domain_lockout_state, domain_circuit_breakerssrc/proxy.ts, src/app/api/auth/login/route.tssrc/shared/utils/apiKey.tsproviderConnections entriesopen-sse/utils/proxyFetch.ts (env vars) and open-sse/utils/networkProxy.ts (configurable per-provider or global)src/shared/network/outboundUrlGuard.ts โ blocks private/loopback/link-local ranges for all provider callssrc/lib/env/runtimeEnv.ts โ Zod schema for all environment variables, surfaced as startup errors/warningssrc/lib/db/syncTokens.ts โ scoped tokens for config bundle download endpoints; backed by sync_tokens SQLite table (migration 024_create_sync_tokens.sql)src/lib/ws/handshake.ts โ validates WS upgrade requests via API key or session cookiesrc/lib/initCloudSync.ts, src/shared/services/initializeCloudSync.ts, src/shared/services/modelSyncScheduler.tssrc/shared/services/cloudSyncScheduler.tssrc/shared/services/modelSyncScheduler.tssrc/app/api/sync/cloud/route.ts/v1/chat/completions)sequenceDiagram
autonumber
participant Client as CLI/SDK Client
participant Route as /api/v1/chat/completions
participant Chat as src/sse/handlers/chat
participant Core as open-sse/handlers/chatCore
participant Model as Model Resolver
participant Auth as Credential Selector
participant Exec as Provider Executor
participant Prov as Upstream Provider
participant Stream as Stream Translator
participant Usage as usageDb
Client->>Route: POST /v1/chat/completions
Route->>Chat: handleChat(request)
Chat->>Model: parse/resolve model or combo
alt Combo model
Chat->>Chat: iterate combo models (handleComboChat)
end
Chat->>Auth: getProviderCredentials(provider)
Auth-->>Chat: active account + tokens/api key
Chat->>Core: handleChatCore(body, modelInfo, credentials)
Core->>Core: detect source format
Core->>Core: translate request to target format
Core->>Exec: execute(provider, transformedBody)
Exec->>Prov: upstream API call
Prov-->>Exec: SSE/JSON response
Exec-->>Core: response + metadata
alt 401/403
Core->>Exec: refreshCredentials()
Exec-->>Core: updated tokens
Core->>Exec: retry request
end
Core->>Stream: translate/normalize stream to client format
Stream-->>Client: SSE chunks / JSON response
Stream->>Usage: extract usage + persist history/log
flowchart TD
A[Incoming model string] --> B{Is combo name?}
B -- Yes --> C[Load combo models sequence]
B -- No --> D[Single model path]
C --> E[Try model N]
E --> F[Resolve provider/model]
D --> F
F --> G[Select account credentials]
G --> H{Credentials available?}
H -- No --> I[Return provider unavailable]
H -- Yes --> J[Execute request]
J --> K{Success?}
K -- Yes --> L[Return response]
K -- No --> M{Fallback-eligible error?}
M -- No --> N[Return error]
M -- Yes --> O[Mark account unavailable cooldown]
O --> P{Another account for provider?}
P -- Yes --> G
P -- No --> Q{In combo with next model?}
Q -- Yes --> E
Q -- No --> R[Return all unavailable]
Fallback decisions are driven by open-sse/services/accountFallback.ts using status codes and error-message heuristics. Combo routing adds one extra guard: provider-scoped 400s such as upstream content-block and role-validation failures are treated as model-local failures so later combo targets can still run.
sequenceDiagram
autonumber
participant UI as Dashboard UI
participant OAuth as /api/oauth/[provider]/[action]
participant ProvAuth as Provider Auth Server
participant DB as localDb
participant Test as /api/providers/[id]/test
participant Exec as Provider Executor
UI->>OAuth: GET authorize or device-code
OAuth->>ProvAuth: create auth/device flow
ProvAuth-->>OAuth: auth URL or device code payload
OAuth-->>UI: flow data
UI->>OAuth: POST exchange or poll
OAuth->>ProvAuth: token exchange/poll
ProvAuth-->>OAuth: access/refresh tokens
OAuth->>DB: createProviderConnection(oauth data)
OAuth-->>UI: success + connection id
UI->>Test: POST /api/providers/[id]/test
Test->>Exec: validate credentials / optional refresh
Exec-->>Test: valid or refreshed token info
Test->>DB: update status/tokens/errors
Test-->>UI: validation result
Refresh during live traffic is executed inside open-sse/handlers/chatCore.ts via executor refreshCredentials().
sequenceDiagram
autonumber
participant UI as Endpoint Page UI
participant Sync as /api/sync/cloud
participant DB as localDb
participant Cloud as External Cloud Sync
participant Claude as ~/.claude/settings.json
UI->>Sync: POST action=enable
Sync->>DB: set cloudEnabled=true
Sync->>DB: ensure API key exists
Sync->>Cloud: POST /sync/{machineId} (providers/aliases/combos/keys)
Cloud-->>Sync: sync result
Sync->>Cloud: GET /{machineId}/v1/verify
Sync-->>UI: enabled + verification status
UI->>Sync: POST action=sync
Sync->>Cloud: POST /sync/{machineId}
Cloud-->>Sync: remote data
Sync->>DB: update newer local tokens/status
Sync-->>UI: synced
UI->>Sync: POST action=disable
Sync->>DB: set cloudEnabled=false
Sync->>Cloud: DELETE /sync/{machineId}
Sync->>Claude: switch ANTHROPIC_BASE_URL back to local (if needed)
Sync-->>UI: disabled
Periodic sync is triggered by CloudSyncScheduler when cloud is enabled.
erDiagram
SETTINGS ||--o{ PROVIDER_CONNECTION : controls
PROVIDER_NODE ||--o{ PROVIDER_CONNECTION : backs_compatible_provider
PROVIDER_CONNECTION ||--o{ USAGE_ENTRY : emits_usage
SETTINGS {
boolean cloudEnabled
number stickyRoundRobinLimit
boolean requireLogin
string password_hash
string fallbackStrategy
json rateLimitDefaults
json providerProfiles
}
PROVIDER_CONNECTION {
string id
string provider
string authType
string name
number priority
boolean isActive
string apiKey
string accessToken
string refreshToken
string expiresAt
string testStatus
string lastError
string rateLimitedUntil
json providerSpecificData
}
PROVIDER_NODE {
string id
string type
string name
string prefix
string apiType
string baseUrl
}
MODEL_ALIAS {
string alias
string targetModel
}
COMBO {
string id
string name
string[] models
}
API_KEY {
string id
string name
string key
string machineId
}
USAGE_ENTRY {
string provider
string model
number prompt_tokens
number completion_tokens
string connectionId
string timestamp
}
CUSTOM_MODEL {
string id
string name
string providerId
}
PROXY_CONFIG {
string global
json providers
}
IP_FILTER {
string mode
string[] allowlist
string[] blocklist
}
THINKING_BUDGET {
string mode
number customBudget
string effortLevel
}
SYSTEM_PROMPT {
boolean enabled
string prompt
string position
}
Physical storage files:
${DATA_DIR}/storage.sqlite${DATA_DIR}/log.txt (compat/debug artifact)${DATA_DIR}/call_logs/<repo>/logs/...flowchart LR
subgraph LocalHost[Developer Host]
CLI[CLI Tools]
Browser[Dashboard Browser]
end
subgraph ContainerOrProcess[OmniRoute Runtime]
Next[Next.js Server\nPORT=20128]
Core[SSE Core + Executors]
MainDB[(storage.sqlite)]
UsageDB[(usage tables + log artifacts)]
end
subgraph External[External Services]
Providers[AI Providers]
SyncCloud[Cloud Sync Service]
end
CLI --> Next
Browser --> Next
Next --> Core
Next --> MainDB
Core --> MainDB
Core --> UsageDB
Core --> Providers
Next --> SyncCloud
src/app/api/v1/*, src/app/api/v1beta/*: compatibility APIssrc/app/api/v1/providers/[provider]/*: dedicated per-provider routes (chat, embeddings, images)src/app/api/providers*: provider CRUD, validation, testingsrc/app/api/provider-nodes*: custom compatible node managementsrc/app/api/provider-models: custom model management (CRUD)src/app/api/models/route.ts: model catalog API (aliases + custom models)src/app/api/oauth/*: OAuth/device-code flowssrc/app/api/keys*: local API key lifecyclesrc/app/api/models/alias: alias managementsrc/app/api/combos*: fallback combo managementsrc/app/api/pricing: pricing overrides for cost calculationsrc/app/api/settings/proxy: proxy configuration (GET/PUT/DELETE)src/app/api/settings/proxy/test: outbound proxy connectivity test (POST)src/app/api/usage/*: usage and logs APIssrc/app/api/sync/* + src/app/api/cloud/*: cloud sync and cloud-facing helperssrc/app/api/cli-tools/*: local CLI config writers/checkerssrc/app/api/settings/ip-filter: IP allowlist/blocklist (GET/PUT)src/app/api/settings/thinking-budget: thinking token budget config (GET/PUT)src/app/api/settings/system-prompt: global system prompt (GET/PUT)src/app/api/settings/compression: global compression settings (GET/PUT)src/app/api/compression/*: compression preview, rule metadata, and language packssrc/app/api/context/caveman/config: Caveman settings alias (GET/PUT)src/app/api/context/rtk/*: RTK config, filter catalog, test endpoint, and raw-output recoverysrc/app/api/context/combos*: compression combo CRUD and routing-combo assignmentssrc/app/api/context/analytics: compression analytics aliassrc/app/api/sessions: active session listing (GET)src/app/api/rate-limits: per-account rate limit status (GET)src/app/api/sync/tokens: sync token CRUD (GET/POST)src/app/api/sync/tokens/[id]: sync token get/delete (GET/DELETE)src/app/api/sync/bundle: config bundle download (GET, ETag versioning)src/app/api/v1/ws: WebSocket upgrade handler for OpenAI-compatible WS clientssrc/sse/handlers/chat.ts: request parse, combo handling, account selection loopopen-sse/handlers/chatCore.ts: translation, executor dispatch, retry/refresh handling, stream setupopen-sse/executors/*: provider-specific network and format behavioropen-sse/translator/index.ts: translator registry and orchestrationopen-sse/translator/request/* (9 modules โ antigravity-to-openai, claude-to-gemini, claude-to-openai, gemini-to-openai, openai-responses, openai-to-claude, openai-to-cursor, openai-to-gemini, openai-to-kiro)open-sse/translator/response/* (8 modules โ claude-to-openai, cursor-to-openai, gemini-to-claude, gemini-to-openai, kiro-to-openai, openai-responses, openai-to-antigravity, openai-to-claude)open-sse/translator/helpers/* (8 modules โ claudeHelper, geminiHelper, geminiToolsSanitizer, maxTokensHelper, openaiHelper, responsesApiHelper, schemaCoercion, toolCallHelper)open-sse/translator/formats.tsopen-sse/translator/bootstrap.ts, open-sse/translator/registry.tsopen-sse/translator/image/src/lib/db/*: persistent config/state and domain persistence on SQLitesrc/lib/localDb.ts: compatibility re-export for DB modulessrc/lib/usageDb.ts: usage history/call logs facade on top of SQLite tablesEach provider has a specialized executor extending BaseExecutor (in open-sse/executors/base.ts), which provides URL building, header construction, retry with exponential backoff, credential refresh hooks, and the execute() orchestration method.
| Executor | Provider(s) | Special Handling |
|---|---|---|
DefaultExecutor | OpenAI, Claude, Gemini, Qwen, OpenRouter, GLM, Kimi, MiniMax, DeepSeek, Groq, xAI, Mistral, Perplexity, Together, Fireworks, Cerebras, Cohere, NVIDIA, etc. | Dynamic URL/header config per provider |
AntigravityExecutor | Google Antigravity | Custom project/session IDs, Retry-After parsing, 429 obfuscation |
AzureOpenAIExecutor | Azure OpenAI | Deployment-based routing, api-version query enforcement |
BlackboxWebExecutor | Blackbox AI (web-mode) | Web-session reverse with TLS fingerprint emulation |
ChatGPTWebExecutor | ChatGPT web | TLS client + session cookie management (chatgptTlsClient.ts) |
ClaudeIdentityExecutor | Claude.ai (CCH path) | Constraint + tool-remap pipelines, fingerprint shaping |
CliProxyApiExecutor | CLIProxyAPI-compatible providers | Custom auth and protocol handling |
CloudflareAiExecutor | Cloudflare Workers AI | Account ID injection, Neurons-based usage tracking |
CodexExecutor | OpenAI Codex | Injects system instructions, forces reasoning effort |
CommandCodeExecutor | Command Code | OAuth + per-session header rotation |
CursorExecutor | Cursor IDE | ConnectRPC protocol, Protobuf encoding, request signing via checksum |
DevinCliExecutor | Devin CLI | Devin task lifecycle bridging via cloud agent module |
GithubExecutor | GitHub Copilot | Copilot token refresh, VSCode-mimicking headers |
GitlabExecutor | GitLab Duo | GitLab OAuth + project-scoped routing |
GlmExecutor | Z.AI GLM (incl. glmt preset) | Thinking-budget aware, GLMT preset constants |
GrokWebExecutor | xAI Grok web | Web-session reverse, mode selection (think/standard) |
KieExecutor | KIE | Custom token issuance with rotating session anchors |
KiroExecutor | AWS CodeWhisperer/Kiro | AWS EventStream binary format โ SSE conversion |
MuseSparkWebExecutor | Muse Spark (web) | Web-session reverse with image-message bridging |
NlpCloudExecutor | NLP Cloud | Provider-specific request body shape |
OpenCodeExecutor | OpenCode | AI SDK compatible provider setup |
PerplexityWebExecutor | Perplexity web | Web-session reverse for chat continuation |
PetalsExecutor | Petals distributed inference | Decentralized swarm routing |
PollinationsExecutor | Pollinations AI | No API key required, rate-limited requests |
QoderExecutor | Qoder AI | PAT and OAuth support, multi-model free tier |
VertexExecutor | Google Vertex AI | Service account auth, region-based endpoints |
DevinDesktopExecutor | Devin Desktop | Imported API key + Connect-protobuf chat streaming |
All other providers (including custom compatible nodes) use the DefaultExecutor.
Note: The matrix below is a representative sample of the 237 registered providers in OmniRoute v3.8.0. For the canonical and continuously-updated list, refer to
docs/reference/PROVIDER_REFERENCE.md(auto-generated) or the source of truth atsrc/shared/constants/providers.ts(Zod-validated at load).
| Provider | Format | Auth | Stream | Non-Stream | Token Refresh | Usage API |
|---|---|---|---|---|---|---|
| Claude | claude | API Key / OAuth | โ | โ | โ | โ ๏ธ Admin only |
| Gemini | gemini | API Key / OAuth | โ | โ | โ | โ ๏ธ Cloud Console |
| Antigravity | antigravity | OAuth | โ | โ | โ | โ Full quota API |
| OpenAI | openai | API Key | โ | โ | โ | โ |
| Codex | openai-responses | OAuth | โ forced | โ | โ | โ Rate limits |
| GitHub Copilot | openai | OAuth + Copilot Token | โ | โ | โ | โ Quota snapshots |
| Cursor | cursor | Custom checksum | โ | โ | โ | โ |
| Kiro | kiro | AWS SSO OIDC | โ (EventStream) | โ | โ | โ Usage limits |
| Qoder | openai | OAuth / PAT | โ | โ | โ | โ ๏ธ Per request |
| Kilo Code | openai | OAuth | โ | โ | โ | โ |
| Cline | openai | OAuth | โ | โ | โ | โ |
| Kimi Coding | openai | OAuth | โ | โ | โ | โ |
| OpenRouter | openai | API Key | โ | โ | โ | โ |
| GLM/Kimi/MiniMax | claude | API Key | โ | โ | โ | โ |
| DeepSeek | openai | API Key | โ | โ | โ | โ |
| Groq | openai | API Key | โ | โ | โ | โ |
| xAI (Grok) | openai | API Key | โ | โ | โ | โ |
| Mistral | openai | API Key | โ | โ | โ | โ |
| Perplexity | openai | API Key | โ | โ | โ | โ |
| Together AI | openai | API Key | โ | โ | โ | โ |
| Fireworks AI | openai | API Key | โ | โ | โ | โ |
| Cerebras | openai | API Key | โ | โ | โ | โ |
| Cohere | openai | API Key | โ | โ | โ | โ |
| NVIDIA NIM | openai | API Key | โ | โ | โ | โ |
| Cloudflare AI | openai | API Token + Acct ID | โ | โ | โ | โ |
| Pollinations | openai | None (no key) | โ | โ | โ | โ |
| Scaleway AI | openai | API Key | โ | โ | โ | โ |
| LongCat | openai | API Key | โ | โ | โ | โ |
| Ollama Cloud | openai | API Key (optional) | โ | โ | โ | โ |
| HuggingFace | openai | API Key | โ | โ | โ | โ |
| Nebius | openai | API Key | โ | โ | โ | โ |
| SiliconFlow | openai | API Key | โ | โ | โ | โ |
| Hyperbolic | openai | API Key | โ | โ | โ | โ |
| Vertex AI | gemini | Service Account | โ | โ | โ | โ ๏ธ Cloud Console |
| Command Code | openai | OAuth | โ | โ | โ | โ ๏ธ Per request |
| Z.AI / GLM | openai | API Key / OAuth | โ | โ | โ | โ |
| GLMT (preset) | claude | API Key | โ | โ | โ | โ ๏ธ Per request |
| Kimi Coding | openai | OAuth / API Key | โ | โ | โ | โ |
| KIE | openai | API Key | โ | โ | โ | โ |
| Devin Desktop | openai | Imported API key | โ (ConnectโSSE) | โ | โ | โ ๏ธ Per request |
| GitLab Duo | openai | OAuth (GitLab) | โ | โ | โ | โ |
| Devin CLI | openai | Local CLI login | โ | โ | โ | โ Task API |
| Codex Cloud | openai-responses | OAuth | โ | โ | โ | โ Rate limits |
| Jules | openai | OAuth | โ | โ | โ | โ Task API |
| AgentRouter | openai | API Key | โ | โ | โ | โ |
| ChatGPT-Web | openai | Session cookie + TLS | โ | โ | โ | โ |
| Grok-Web | openai | Session cookie | โ | โ | โ | โ |
| Perplexity-Web | openai | Session cookie | โ | โ | โ | โ |
| BlackBox-Web | openai | Session cookie + TLS | โ | โ | โ | โ |
| Muse-Spark-Web | openai | Session cookie | โ | โ | โ | โ |
| ModelScope | openai | API Key | โ | โ | โ | โ ๏ธ Quota policy |
| BazaarLink | openai | API Key | โ | โ | โ | โ |
| Petals | openai | None | โ | โ | โ | โ |
| Qoder | openai | OAuth / PAT | โ | โ | โ | โ ๏ธ Per request |
| OpenCode (Go/Zen) | openai | OAuth | โ | โ | โ | โ |
| CLIProxyAPI | openai | Custom | โ | โ | โ | โ |
Detected source formats include:
openaiopenai-responsesclaudegeminiTarget formats include:
Translations use OpenAI as the hub format โ all conversions go through OpenAI as intermediate:
Source Format โ OpenAI (hub) โ Target Format
Translations are selected dynamically based on source payload shape and provider target format.
Additional processing layers in the translation pipeline:
developer โ system for non-OpenAI targets; merges system โ user for models that reject the system role (GLM, ERNIE)<think>...</think> blocks from content into reasoning_content fieldresponse_format.json_schema to Gemini's responseMimeType + responseSchema| Endpoint | Format | Handler |
|---|---|---|
POST /v1/chat/completions | OpenAI Chat | src/sse/handlers/chat.ts |
POST /v1/messages | Claude Messages | Same handler (auto-detected) |
POST /v1/responses | OpenAI Responses | open-sse/handlers/responsesHandler.ts |
POST /v1/embeddings | OpenAI Embeddings | open-sse/handlers/embeddings.ts |
GET /v1/embeddings | Model listing | API route |
POST /v1/images/generations | OpenAI Images | open-sse/handlers/imageGeneration.ts |
GET /v1/images/generations | Model listing | API route |
POST /v1/providers/{provider}/chat/completions | OpenAI Chat | Dedicated per-provider with model validation |
POST /v1/providers/{provider}/embeddings | OpenAI Embeddings | Dedicated per-provider with model validation |
POST /v1/providers/{provider}/images/generations | OpenAI Images | Dedicated per-provider with model validation |
POST /v1/messages/count_tokens | Claude Token Count | API route |
GET /v1/models | OpenAI Models list | API route (chat + embedding + image + custom models) |
GET /api/models/catalog | Catalog | All models grouped by provider + type |
POST /v1beta/models/*:streamGenerateContent | Gemini native | API route |
GET/PUT/DELETE /api/settings/proxy | Proxy Config | Network proxy configuration |
POST /api/settings/proxy/test | Proxy Connectivity | Proxy health/connectivity test endpoint |
GET/POST/DELETE /api/provider-models | Provider Models | Provider model metadata backing custom and managed available models |
The bypass handler (open-sse/utils/bypassHandler.ts) intercepts known "throwaway" requests from Claude CLI โ warmup pings, title extractions, and token counts โ and returns a fake response without consuming upstream provider tokens. This is triggered only when User-Agent contains claude-cli.
The older file-based request logger (open-sse/utils/requestLogger.ts) is retained only for
legacy compatibility. The current runtime contract uses:
APP_LOG_TO_FILE=true for application and audit logs written under <repo>/logs/call_logs${DATA_DIR}/call_logs/YYYY-MM-DD/... artifacts when the call log pipeline is enabled[DONE] handlingsrc/shared/network/outboundUrlGuard.ts blocks all private/loopback/link-local target URLs before they reach provider executorssrc/shared/network/safeOutboundFetch.ts which applies the guard before every outbound requestURL_GUARD_BLOCKED with HTTP 422 and are logged to the compliance audit trail via providerAudit.tsRuntime visibility sources:
src/sse/utils/logger.tsusage_history, call_logs, proxy_logs)request_detail_logs) when settings.detailed_logs_enabled=truelog.txt (optional/compat)logs/ when APP_LOG_TO_FILE=true${DATA_DIR}/call_logs/ when the call log pipeline is enabled/api/usage/*) for UI consumptionDetailed request payload capture stores up to four JSON payload stages per routed call:
JWT_SECRET) secures dashboard session cookie verification/signingINITIAL_PASSWORD) should be explicitly configured for first-run provisioningAPI_KEY_SECRET) secures generated local API key formatEnvironment variables actively used by code:
JWT_SECRET, INITIAL_PASSWORDDATA_DIRALLOW_MULTI_CONNECTIONS_PER_COMPAT_NODEDATA_DIR unset): XDG_CONFIG_HOMEAPI_KEY_SECRET, MACHINE_ID_SALTAPP_LOG_TO_FILE, APP_LOG_RETENTION_DAYS, CALL_LOG_RETENTION_DAYSNEXT_PUBLIC_BASE_URL, NEXT_PUBLIC_CLOUD_URLHTTP_PROXY, HTTPS_PROXY, ALL_PROXY, NO_PROXY and lowercase variantsENABLE_SOCKS5_PROXY, NEXT_PUBLIC_ENABLE_SOCKS5_PROXYAPPDATA, NODE_ENV, PORT, HOSTNAMEusageDb and localDb share the same base directory policy (DATA_DIR -> XDG_CONFIG_HOME/omniroute -> ~/.omniroute) with legacy file migration./api/v1/route.ts delegates to the same unified catalog builder used by /api/v1/models (src/app/api/v1/models/catalog.ts) to avoid semantic drift.NEXT_PUBLIC_BASE_URL and cloud endpoint reachability.open-sse/ directory is published as the @omniroute/open-sse npm workspace package. Source code imports it via @omniroute/open-sse/... (resolved by Next.js transpilePackages). File paths in this document still use the directory name open-sse/ for consistency.tests/e2e/), run via npm run test:e2e. Unit tests use Node.js test runner (tests/unit/), run via npm run test:unit. Source code under src/ is TypeScript (.ts/.tsx); the open-sse/ workspace remains JavaScript (.js).context-relay) is split across two layers: combo.ts decides if a handoff should be generated, chat.ts injects the handoff after account resolution. Handoff data lives in context_handoffs SQLite table. This split is intentional because only chat.ts knows whether the actual account changed.tokenHealthCheck.ts resolves proxy per connection, /api/providers/validate uses runWithProxyContext, and proxyFetch.ts uses undici.fetch() to maintain dispatcher compatibility on Node 22./api/settings/require-login returns nodeVersion and nodeCompatible fields. The login page renders a warning banner when the runtime falls outside the supported secure Node.js lines.npm run builddocker build -t omniroute .GET /api/settingsGET /api/v1/modelshttp://<host>:20128/v1 when PORT=20128