extreme-router-gateway-engine
Skill44 starsChanged 4 months agoMITView on GitHub
AI Gateway routing, provider management, and core engine expertise for ExtremeRouter. Use when working on request routing, provider fallback, token refresh, format translation, streaming, or when the user asks about "how does routing work", "add a new provider", "fix the fallback logic", "optimize token usage", or mentions providers, models, or API compatibility.
In this repository13 other files it gives its agents.
- AGENTS.mdAGENTS.md
- open-sse/AGENTS.mdAGENTS.md
- extreme-router-code-auditSkill
- extreme-router-refactorSkill
- extreme-router-ui-designSkill
- extremerouter-chatSkill
- extremerouter-embeddingsSkill
- extremerouter-imageSkill
- extremerouterSkill
- extremerouter-sttSkill
- extremerouter-ttsSkill
- extremerouter-web-fetchSkill
- extremerouter-web-searchSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
24 rules. About 0 are common, 20 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈20
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 77
Add provider config (baseUrl, headers, capabilities)
- Very specific: line 87
Create OAuth handler in src/app/api/oauth/[provider]/*
- Distinctive: line 98
When a request fails:
- Distinctive: line 112
Check if provider supports refresh
- Very specific: line 177
Add to REQUEST_TRANSLATORS map
- Very specific: line 181
Create concern in open-sse/translator/concerns/
- Distinctive: line 182
Import and use in translators
- Distinctive: line 217
Update provider quota tracking
- Very specific: line 271
Use Promise.all for independent operations
- Distinctive: line 277
Start streaming immediately (don't buffer)
- Distinctive: line 279
Avoid blocking the event loop
- Distinctive: line 285
Check API key validation (settings.requireApiKey)
- Distinctive: line 286
Check model resolution (is model in combo?)
- Distinctive: line 287
Check account selection (is account active?)
- Distinctive: line 288
Check executor selection (is provider registered?)
- Distinctive: line 292
Check credentials (are tokens valid?)
- Distinctive: line 293
Check request format (is translation correct?)
- Distinctive: line 294
Check provider status (is provider down?)
- Distinctive: line 295
Check rate limits (is account rate-limited?)
- Distinctive: line 299
Check stream controller (is connection alive?)
- Distinctive: line 300
Check response translation (is format correct?)
- Distinctive: line 301
Check error handling (is error being swallowed?)
- Distinctive: line 302
Check client disconnect (did client abort?)
- Distinctive: line 306
When adding a new provider, structure your response as:
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AI Gateway Engine Expertise
You are an expert in AI Gateway architecture, provider routing, and API compatibility.
Core Concepts
Request Flow
Client Request → /v1/* endpoint
→ Route handler (src/app/api/v1/*)
→ Chat handler (src/sse/handlers/chat.js)
→ Core orchestrator (open-sse/handlers/chatCore.js)
→ Provider executor (open-sse/executors/*)
→ Upstream provider API
→ Response translation (open-sse/translator/*)
→ Client response (SSE stream or JSON)Key Components
1. Route Handlers (src/app/api/v1/*)
- Receive client requests
- Validate API keys
- Delegate to chat handler
- Handle errors
2. Chat Handler (src/sse/handlers/chat.js)
- Parse request body
- Resolve model/combo
- Select provider account
- Call core orchestrator
- Handle combo/fusion routing
3. Core Orchestrator (open-sse/handlers/chatCore.js)
- Detect source format (OpenAI/Claude/Gemini/etc)
- Translate request to target format
- Select executor
- Execute request with retry/refresh
- Translate response back to client format
- Stream response to client
- Track usage
4. Provider Executors (open-sse/executors/*)
- Build provider-specific headers
- Construct provider-specific URLs
- Handle provider-specific auth (OAuth, API key, device code)
- Parse provider-specific responses
- Handle provider-specific errors
5. Format Translators (open-sse/translator/*)
- Convert between API formats
- Request translators:
openai-to-*,claude-to-*, etc - Response translators:
*-to-openai, etc - Concerns: shared translation logic (tool calls, usage, reasoning, etc)
Provider Management
Adding a New Provider
- Create executor (
open-sse/executors/[provider].js)- Extend
BaseExecutor - Implement
buildHeaders(credentials, stream) - Implement
buildUrl(model, stream, urlIndex, credentials) - Implement
execute(request, credentials, options) - Handle provider-specific auth refresh
- Extend
- Register provider (
open-sse/config/providers.js)- Add provider config (baseUrl, headers, capabilities)
- Define supported models
- Set auth type (oauth/api_key/device_code)
- Create translators (if needed)
- Request translator:
open-sse/translator/request/openai-to-[provider].js - Response translator:
open-sse/translator/response/[provider]-to-openai.js - Register in
open-sse/translator/index.js
- Request translator:
- Add OAuth flow (if OAuth provider)
- Create OAuth handler in
src/app/api/oauth/[provider]/* - Implement token refresh in
open-sse/services/tokenRefresh/providers.js - Add to
src/lib/oauth/providers.js
- Create OAuth handler in
- Add provider registry (
open-sse/providers/registry/[provider].js)- Define provider metadata
- List supported models
- Set pricing/capabilities
Provider Fallback Logic
When a request fails:
- Check error type (401/403 → auth issue, 429 → rate limit, 5xx → server error)
- Try next account (if multiple accounts for same provider)
- Try next model in combo (if using combo routing)
- Return error (if all fallbacks exhausted)
Key files:
open-sse/services/accountFallback.js— account-level fallbackopen-sse/services/combo.js— combo/fusion routing
Token Refresh Flow
When credentials expire:
- Detect 401/403 response
- Check if provider supports refresh
- Call
refreshCredentials(credentials) - Retry request with new credentials
- Update stored credentials
Key files:
open-sse/services/tokenRefresh.js— refresh orchestrationopen-sse/services/tokenRefresh/providers.js— provider-specific refresh logic
Format Translation
Supported Formats
Source formats (what clients send):
openai— OpenAI Chat Completionsopenai-responses— OpenAI Responses APIclaude— Anthropic Messages APIgemini— Google Gemini APIgemini-cli— Gemini CLI formatantigravity— Antigravity IDE format
Target formats (what providers accept):
- OpenAI Chat
- OpenAI Responses
- Claude Messages
- Gemini
- Gemini CLI
- Kiro (AWS CodeWhisperer)
- Cursor
- Ollama
- CommandCode
Translation Architecture
Request Translation:
Client Format → Detect → Translate → Provider Format
Response Translation:
Provider Format → Translate → Client FormatTranslator Registry (open-sse/translator/index.js):
- Maps (source, target) pairs to translator functions
- Auto-detects source format from request shape
- Selects appropriate translator
Concerns (open-sse/translator/concerns/*):
- Shared translation logic (tool calls, usage, reasoning, thinking, etc)
- Reused across multiple translators
- Keep translators DRY
Adding a New Translator
- Create request translator (
open-sse/translator/request/[source]-to-[target].js)- Export
translate(body, options)function - Convert messages, tools, parameters
- Handle streaming vs non-streaming
- Export
- Create response translator (
open-sse/translator/response/[target]-to-[source].js)- Export
translate(chunk, options)function - Convert SSE chunks or JSON response
- Map finish reasons, usage, tool calls
- Export
- Register translators (
open-sse/translator/index.js)- Add to
REQUEST_TRANSLATORSmap - Add to
RESPONSE_TRANSLATORSmap
- Add to
- Add concerns (if new translation logic needed)
- Create concern in
open-sse/translator/concerns/ - Import and use in translators
- Create concern in
Streaming
SSE Stream Flow
Provider SSE Stream
→ Executor parses chunks
→ Response translator converts format
→ StreamController manages client connection
→ Client receives translated SSE streamKey files:
open-sse/utils/streamHandler.js— StreamControlleropen-sse/utils/stream.js— stream utilitiesopen-sse/handlers/chatCore/streamingHandler.js— streaming orchestration
Stream Safety
- Handle client disconnect (abort controller)
- Flush pending data on stream end
- Send
[DONE]marker for OpenAI format - Translate finish reasons correctly
- Extract usage from final chunk
Token Usage & Cost Tracking
Usage Extraction
After request completes:
- Extract usage from response (prompt_tokens, completion_tokens)
- Calculate cost (using pricing config)
- Save to usage database (
src/lib/db/repos/usageRepo.js) - Update provider quota tracking
Key files:
open-sse/utils/usageTracking.js— usage extractionopen-sse/providers/pricing.js— pricing configsrc/lib/db/repos/usageRepo.js— usage persistence
RTK Token Saver
RTK (Router Token Killer) compresses tool_result content to save tokens:
open-sse/rtk/caveman.js— aggressive compressionopen-sse/rtk/ponytail.js— moderate compressionopen-sse/rtk/headroom.js— external service compression
Enabled per-request via rtkEnabled flag in handleChatCore.
Provider Capabilities
Model Capabilities
Each model has capabilities:
- Context window size
- Max output tokens
- Supported features (tools, vision, streaming, etc)
- Pricing (input/output cost per token)
Defined in:
open-sse/providers/capabilities.js— capability lookupopen-sse/providers/models/— model definitionsopen-sse/providers/pricing.js— pricing config
Provider Health
Track provider health:
- Success rate
- Latency
- Error rates
- Rate limit status
Use for:
- Routing decisions (prefer healthy providers)
- Fallback triggers (switch on high error rate)
- Dashboard display (show provider status)
Performance Optimization
Caching
- Cache provider capabilities (avoid repeated lookups)
- Cache model pricing (avoid repeated DB reads)
- Cache OAuth tokens (avoid repeated refresh)
Parallel Requests
- Use
Promise.allfor independent operations - Prefetch remote images (parallel fetch)
- Parallel account selection (try multiple accounts)
Streaming
- Start streaming immediately (don't buffer)
- Translate chunks incrementally
- Avoid blocking the event loop
Debugging Tips
Request Not Reaching Provider
- Check API key validation (settings.requireApiKey)
- Check model resolution (is model in combo?)
- Check account selection (is account active?)
- Check executor selection (is provider registered?)
Provider Returns Error
- Check credentials (are tokens valid?)
- Check request format (is translation correct?)
- Check provider status (is provider down?)
- Check rate limits (is account rate-limited?)
Response Not Reaching Client
- Check stream controller (is connection alive?)
- Check response translation (is format correct?)
- Check error handling (is error being swallowed?)
- Check client disconnect (did client abort?)
Example: Adding a Provider
When adding a new provider, structure your response as:
## Provider Overview
[name, API type, auth method]
## Implementation Plan
1. Create executor
2. Register provider config
3. Create translators (if needed)
4. Add OAuth flow (if OAuth)
5. Add provider registry entry
6. Test with sample requests
## Executor Code
[open-sse/executors/[provider].js]
## Provider Config
[open-sse/config/providers.js addition]
## Translators (if needed)
[open-sse/translator/request/openai-to-[provider].js]
[open-sse/translator/response/[provider]-to-openai.js]
## OAuth Flow (if OAuth)
[src/app/api/oauth/[provider]/*]
## Testing
[sample requests to verify]Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

