Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat: add TypeScript types and modularize translator registry

diegosouzapw20860877b8d4
diff --git a/open-sse/config/providerModels.ts b/open-sse/config/providerModels.ts
index f43f9672ba..63cd97ad91 100644
--- a/open-sse/config/providerModels.ts
+++ b/open-sse/config/providerModels.ts
@@ -1,4 +1,4 @@
-import { generateModels, generateAliasMap } from "./providerRegistry.ts";
+import { generateModels, generateAliasMap, type RegistryModel } from "./providerRegistry.ts";
// Provider models - Generated from providerRegistry.js (single source of truth)
export const PROVIDER_MODELS = generateModels();
@@ -7,37 +7,41 @@ export const PROVIDER_MODELS = generateModels();
export const PROVIDER_ID_TO_ALIAS = generateAliasMap();
// Helper functions
-export function getProviderModels(aliasOrId) {
+export function getProviderModels(aliasOrId: string): RegistryModel[] {
return PROVIDER_MODELS[aliasOrId] || [];
}
-export function getDefaultModel(aliasOrId) {
+export function getDefaultModel(aliasOrId: string): string | null {
const models = PROVIDER_MODELS[aliasOrId];
return models?.[0]?.id || null;
}
-export function isValidModel(aliasOrId, modelId, passthroughProviders = new Set()) {
+export function isValidModel(
+ aliasOrId: string,
+ modelId: string,
+ passthroughProviders = new Set<string>()
+): boolean {
if (passthroughProviders.has(aliasOrId)) return true;
const models = PROVIDER_MODELS[aliasOrId];
if (!models) return false;
return models.some((m) => m.id === modelId);
}
-export function findModelName(aliasOrId, modelId) {
+export function findModelName(aliasOrId: string, modelId: string): string {
const models = PROVIDER_MODELS[aliasOrId];
if (!models) return modelId;
const found = models.find((m) => m.id === modelId);
return found?.name || modelId;
}
-export function getModelTargetFormat(aliasOrId, modelId) {
+export function getModelTargetFormat(aliasOrId: string, modelId: string): string | null {
const models = PROVIDER_MODELS[aliasOrId];
if (!models) return null;
const found = models.find((m) => m.id === modelId);
return found?.targetFormat || null;
}
-export function getModelsByProviderId(providerId) {
+export function getModelsByProviderId(providerId: string): RegistryModel[] {
const alias = PROVIDER_ID_TO_ALIAS[providerId] || providerId;
return PROVIDER_MODELS[alias] || [];
}
diff --git a/open-sse/config/providerRegistry.ts b/open-sse/config/providerRegistry.ts
index 9ca49f5dd2..16f08bd283 100644
--- a/open-sse/config/providerRegistry.ts
+++ b/open-sse/config/providerRegistry.ts
@@ -49,6 +49,21 @@ export interface RegistryEntry {
passthroughModels?: boolean;
}
+interface LegacyProvider {
+ format: string;
+ baseUrl?: string;
+ baseUrls?: string[];
+ responsesBaseUrl?: string;
+ headers?: Record<string, string>;
+ clientId?: string;
+ clientSecret?: string;
+ tokenUrl?: string;
+ refreshUrl?: string;
+ authUrl?: string;
+ chatPath?: string;
+ clientVersion?: string;
+}
+
// ── Registry ──────────────────────────────────────────────────────────────
export const REGISTRY: Record<string, RegistryEntry> = {
@@ -108,7 +123,7 @@ export const REGISTRY: Record<string, RegistryEntry> = {
clientIdEnv: "GEMINI_OAUTH_CLIENT_ID",
clientIdDefault: "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com",
clientSecretEnv: "GEMINI_OAUTH_CLIENT_SECRET",
- clientSecretDefault: "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",
+ clientSecretDefault: "",
},
models: [
{ id: "gemini-3.1-pro", name: "Gemini 3.1 Pro" },
@@ -137,7 +152,7 @@ export const REGISTRY: Record<string, RegistryEntry> = {
clientIdEnv: "GEMINI_CLI_OAUTH_CLIENT_ID",
clientIdDefault: "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com",
clientSecretEnv: "GEMINI_CLI_OAUTH_CLIENT_SECRET",
- clientSecretDefault: "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",
+ clientSecretDefault: "",
},
models: [
{ id: "gemini-3.1-pro", name: "Gemini 3.1 Pro" },
@@ -228,7 +243,7 @@ export const REGISTRY: Record<string, RegistryEntry> = {
clientIdEnv: "IFLOW_OAUTH_CLIENT_ID",
clientIdDefault: "10009311001",
clientSecretEnv: "IFLOW_OAUTH_CLIENT_SECRET",
- clientSecretDefault: "4Z3YjXycVsQvyGF1etiNlIBB4RsqSDtW",
+ clientSecretDefault: "",
tokenUrl: "https://iflow.cn/oauth/token",
authUrl: "https://iflow.cn/oauth",
},
@@ -266,7 +281,7 @@ export const REGISTRY: Record<string, RegistryEntry> = {
clientIdEnv: "ANTIGRAVITY_OAUTH_CLIENT_ID",
clientIdDefault: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",
clientSecretEnv: "ANTIGRAVITY_OAUTH_CLIENT_SECRET",
- clientSecretDefault: "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",
+ clientSecretDefault: "",
},
models: [
{ id: "claude-opus-4-6-thinking", name: "Claude Opus 4.6 Thinking" },
@@ -844,10 +859,10 @@ export const REGISTRY: Record<string, RegistryEntry> = {
// ── Generator Functions ───────────────────────────────────────────────────
/** Generate legacy PROVIDERS object shape for constants.js backward compatibility */
-export function generateLegacyProviders(): Record<string, any> {
- const providers: Record<string, any> = {};
+export function generateLegacyProviders(): Record<string, LegacyProvider> {
+ const providers: Record<string, LegacyProvider> = {};
for (const [id, entry] of Object.entries(REGISTRY)) {
- const p: Record<string, any> = { format: entry.format };
+ const p: LegacyProvider = { format: entry.format };
// URL(s)
if (entry.baseUrls) {
@@ -917,7 +932,7 @@ export function generateAliasMap(): Record<string, string> {
// ── Registry Lookup Helpers ───────────────────────────────────────────────
-const _byAlias = new Map();
+const _byAlias = new Map<string, RegistryEntry>();
for (const entry of Object.values(REGISTRY)) {
if (entry.alias && entry.alias !== entry.id) {
_byAlias.set(entry.alias, entry);
diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.ts
index 95d404cb34..cbbb5a5199 100644
--- a/open-sse/handlers/chatCore.ts
+++ b/open-sse/handlers/chatCore.ts
@@ -283,6 +283,7 @@ export async function handleChatCore({
comboName,
apiKeyId: apiKeyInfo?.id || null,
apiKeyName: apiKeyInfo?.name || null,
+ noLog: apiKeyInfo?.noLog === true,
}).catch(() => {});
if (error.name === "AbortError") {
streamController.handleError(error);
@@ -298,11 +299,14 @@ export async function handleChatCore({
providerResponse.status === HTTP_STATUS.UNAUTHORIZED ||
providerResponse.status === HTTP_STATUS.FORBIDDEN
) {
- const newCredentials = await refreshWithRetry(
+ const newCredentials = (await refreshWithRetry(
() => executor.refreshCredentials(credentials, log),
3,
log
- );
+ )) as null | {
+ accessToken?: string;
+ copilotToken?: string;
+ };
if (newCredentials?.accessToken || newCredentials?.copilotToken) {
log?.info?.("TOKEN", `${provider.toUpperCase()} | refreshed`);
@@ -363,6 +367,7 @@ export async function handleChatCore({
comboName,
apiKeyId: apiKeyInfo?.id || null,
apiKeyName: apiKeyInfo?.name || null,
+ noLog: apiKeyInfo?.noLog === true,
}).catch(() => {});
const errMsg = formatProviderError(new Error(message), provider, model, statusCode);
console.log(`${COLORS.red}[ERROR] ${errMsg}${COLORS.reset}`);
@@ -454,6 +459,7 @@ export async function handleChatCore({
comboName,
apiKeyId: apiKeyInfo?.id || null,
apiKeyName: apiKeyInfo?.name || null,
+ noLog: apiKeyInfo?.noLog === true,
}).catch(() => {});
if (usage && typeof usage === "object") {
const msg = `[${new Date().toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit" })}] 📊 [USAGE] ${provider.toUpperCase()} | in=${usage?.prompt_tokens || 0} | out=${usage?.completion_tokens || 0}${connectionId ? ` | account=${connectionId.slice(0, 8)}...` : ""}`;
@@ -556,6 +562,7 @@ export async function handleChatCore({
comboName,
apiKeyId: apiKeyInfo?.id || null,
apiKeyName: apiKeyInfo?.name || null,
+ noLog: apiKeyInfo?.noLog === true,
}).catch(() => {});
};
diff --git a/open-sse/mcp-server/scopeEnforcement.ts b/open-sse/mcp-server/scopeEnforcement.ts
new file mode 100644
index 0000000000..4c622d1e2f
--- /dev/null
+++ b/open-sse/mcp-server/scopeEnforcement.ts
@@ -0,0 +1,133 @@
+import { MCP_TOOL_MAP } from "./schemas/tools.ts";
+
+type AuthInfoLike = {
+ clientId?: string;
+ scopes?: string[];
+};
+
+export type McpToolExtraLike = {
+ authInfo?: AuthInfoLike;
+ sessionId?: string;
+ _meta?: unknown;
+};
+
+export type ScopeSource = "authInfo" | "meta" | "env" | "none";
+
+export interface CallerScopeContext {
+ callerId: string;
+ scopes: string[];
+ source: ScopeSource;
+}
+
+export interface ScopeCheckResult {
+ allowed: boolean;
+ required: string[];
+ provided: string[];
+ missing: string[];
+ reason?: string;
+}
+
+function normalizeScopeList(raw: unknown): string[] {
+ if (!Array.isArray(raw)) return [];
+ const normalized = raw
+ .filter((value) => typeof value === "string")
+ .map((value) => value.trim())
+ .filter(Boolean);
+ return Array.from(new Set(normalized));
+}
+
+function extractMetaScopeList(meta: unknown): string[] {
+ if (!meta || typeof meta !== "object") return [];
+ const metaRecord = meta as Record<string, unknown>;
+
+ const direct = normalizeScopeList(metaRecord.scopes);
+ if (direct.length > 0) return direct;
+
+ const auth = metaRecord.auth;
+ if (auth && typeof auth === "object") {
+ const authScopes = normalizeScopeList((auth as Record<string, unknown>).scopes);
+ if (authScopes.length > 0) return authScopes;
+ }
+
+ const omni = metaRecord.omniroute;
+ if (omni && typeof omni === "object") {
+ const omniScopes = normalizeScopeList((omni as Record<string, unknown>).scopes);
+ if (omniScopes.length > 0) return omniScopes;
+ }
+
+ return [];
+}
+
+function scopeMatches(grantedScope: string, requiredScope: string): boolean {
+ if (grantedScope === "*" || grantedScope === requiredScope) {
+ return true;
+ }
+ if (grantedScope.endsWith("*")) {
+ const prefix = grantedScope.slice(0, -1);
+ return requiredScope.startsWith(prefix);
+ }
+ return false;
+}
+
+export function resolveCallerScopeContext(
+ extra: McpToolExtraLike | undefined,
+ fallbackScopes: readonly string[] = []
+): CallerScopeContext {
+ const callerId =
+ (typeof extra?.authInfo?.clientId === "string" && extra.authInfo.clientId.trim()) ||
+ (typeof extra?.sessionId === "string" && extra.sessionId.trim()) ||
+ "anonymous";
+
+ const authScopes = normalizeScopeList(extra?.authInfo?.scopes);
+ if (authScopes.length > 0) {
+ return { callerId, scopes: authScopes, source: "authInfo" };
+ }
+
+ const metaScopes = extractMetaScopeList(extra?._meta);
+ if (metaScopes.length > 0) {
+ return { callerId, scopes: metaScopes, source: "meta" };
+ }
+
+ const fallback = normalizeScopeList(fallbackScopes);
+ if (fallback.length > 0) {
+ return { callerId, scopes: fallback, source: "env" };
+ }
+
+ return { callerId, scopes: [], source: "none" };
+}
+
+export function evaluateToolScopes(
+ toolName: string,
+ callerScopes: readonly string[],
+ enforceScopes: boolean
+): ScopeCheckResult {
+ const toolDef = MCP_TOOL_MAP[toolName];
+ if (!toolDef) {
+ return {
+ allowed: false,
+ required: [],
+ provided: Array.from(callerScopes),
+ missing: [],
+ reason: "tool_definition_missing",
+ };
+ }
+
+ const required = Array.isArray(toolDef.scopes) ? Array.from(toolDef.scopes) : [];
+ const provided = normalizeScopeList(callerScopes);
+
+ if (!enforceScopes || required.length === 0) {
+ return { allowed: true, required, provided, missing: [] };
+ }
+
+ const missing = required.filter(
+ (requiredScope) => !provided.some((grantedScope) => scopeMatches(grantedScope, requiredScope))
+ );
+
+ return {
+ allowed: missing.length === 0,
+ required,
+ provided,
+ missing,
+ reason: missing.length > 0 ? "missing_scopes" : undefined,
+ };
+}
diff --git a/open-sse/mcp-server/server.ts b/open-sse/mcp-server/server.ts
index 97c5a835d7..f6125c9e11 100644
--- a/open-sse/mcp-server/server.ts
+++ b/open-sse/mcp-server/server.ts
@@ -22,10 +22,22 @@ import {
routeRequestInput,
costReportInput,
listModelsCatalogInput,
- MCP_ESSENTIAL_TOOLS,
+ simulateRouteInput,
+ setBudgetGuardInput,
+ setResilienceProfileInput,
+ testComboInput,
+ getProviderMetricsInput,
+ bestComboForTaskInput,
+ explainRouteInput,
+ getSessionSnapshotInput,
} from "./schemas/tools.ts";
import { logToolCall } from "./audit.ts";
+import {
+ evaluateToolScopes,
+ resolveCallerScopeContext,
+ type McpToolExtraLike,
+} from "./scopeEnforcement.ts";
import {
handleSimulateRoute,
@@ -43,6 +55,54 @@ import { normalizeQuotaResponse } from "@/shared/contracts/quota";
const OMNIROUTE_BASE_URL = process.env.OMNIROUTE_BASE_URL || "http://localhost:20128";
const OMNIROUTE_API_KEY = process.env.OMNIROUTE_API_KEY || "";
+const MCP_ENFORCE_SCOPES = process.env.OMNIROUTE_MCP_ENFORCE_SCOPES === "true";
+const MCP_ALLOWED_SCOPES = new Set(
+ (process.env.OMNIROUTE_MCP_SCOPES || "")
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean)
+);
+
+type JsonRecord = Record<string, unknown>;
+
+type TextToolResult = {
+ content: Array<{ type: "text"; text: string }>;
+ isError?: boolean;
+};
+
+function toRecord(value: unknown): JsonRecord {
+ return value && typeof value === "object" ? (value as JsonRecord) : {};
+}
+
+function toArray(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
+
+function toString(value: unknown, fallback = ""): string {
+ return typeof value === "string" ? value : fallback;
+}
+
+function toNumber(value: unknown, fallback = 0): number {
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
+}
+
+function toStringArray(value: unknown, fallback: string[] = []): string[] {
+ const values = toArray(value).filter((entry): entry is string => typeof entry === "string");
+ return values.length > 0 ? values : fallback;
+}
+
+function normalizeComboModels(
+ rawModels: unknown
+): Array<{ provider: string; model: string; priority: number }> {
+ return toArray(rawModels).map((rawModel, index) => {
+ const model = toRecord(rawModel);
+ return {
+ provider: toString(model.provider, "unknown"),
+ model: toString(model.model, "unknown"),
+ priority: toNumber(model.priority, index + 1),
+ };
+ });
+}
/**
* Internal fetch helper that calls OmniRoute API endpoints.
@@ -65,6 +125,49 @@ async function omniRouteFetch(path: string, options: RequestInit = {}): Promise<
return response.json();
}
+function withScopeEnforcement(
+ toolName: string,
+ handler: (args: unknown, extra?: McpToolExtraLike) => Promise<TextToolResult>
+) {
+ return async (args: unknown, extra?: McpToolExtraLike): Promise<TextToolResult> => {
+ const scopeContext = resolveCallerScopeContext(extra, Array.from(MCP_ALLOWED_SCOPES));
+ const scopeCheck = evaluateToolScopes(toolName, scopeContext.scopes, MCP_ENFORCE_SCOPES);
+ if (!scopeCheck.allowed) {
+ const missingScopes =
+ scopeCheck.missing.length > 0 ? scopeCheck.missing.join(", ") : "unavailable";
+ const reason = scopeCheck.reason || "scope_check_failed";
+ const msg =
+ `Insufficient MCP scopes for ${toolName}. ` +
+ `Missing: ${missingScopes}. ` +
+ `Caller=${scopeContext.callerId}, source=${scopeContext.source}.`;
+ const safeArgs = args && typeof args === "object" ? toRecord(args) : { rawArgs: args };
+ await logToolCall(
+ toolName,
+ {
+ ...safeArgs,
+ _scopeCheck: {
+ callerId: scopeContext.callerId,
+ source: scopeContext.source,
+ required: scopeCheck.required,
+ provided: scopeCheck.provided,
+ missing: scopeCheck.missing,
+ },
+ },
+ null,
+ 0,
+ false,
+ `scope_denied:${reason}`
+ );
+ return {
+ content: [{ type: "text" as const, text: `Error: ${msg}` }],
+ isError: true,
+ };
+ }
+
+ return handler(args, extra);
+ };
+}
+
// ============ Tool Handlers ============
async function handleGetHealth() {
@@ -76,22 +179,31 @@ async function handleGetHealth() {
omniRouteFetch("/api/rate-limits"),
]);
- const health =
- healthRaw.status === "fulfilled" ? (healthRaw.value as Record<string, unknown>) : {};
- const resilience =
- resilienceRaw.status === "fulfilled" ? (resilienceRaw.value as Record<string, unknown>) : {};
- const rateLimits =
- rateLimitsRaw.status === "fulfilled" ? (rateLimitsRaw.value as Record<string, unknown>) : {};
+ const health = healthRaw.status === "fulfilled" ? toRecord(healthRaw.value) : {};
+ const resilience = resilienceRaw.status === "fulfilled" ? toRecord(resilienceRaw.value) : {};
+ const rateLimits = rateLimitsRaw.status === "fulfilled" ? toRecord(rateLimitsRaw.value) : {};
+ const memoryUsageRaw = toRecord(health.memoryUsage);
+ const cacheStatsRaw = toRecord(health.cacheStats);
+ const resilienceCircuitBreakers = toArray(resilience.circuitBreakers);
+ const rateLimitEntries = toArray(rateLimits.limits);
const result = {
- uptime: String((health as any)?.uptime || "unknown"),
- version: String((health as any)?.version || "unknown"),
- memoryUsage: (health as any)?.memoryUsage || { heapUsed: 0, heapTotal: 0 },
- circuitBreakers: Array.isArray((resilience as any)?.circuitBreakers)
- ? (resilience as any).circuitBreakers
- : [],
- rateLimits: Array.isArray((rateLimits as any)?.limits) ? (rateLimits as any).limits : [],
- cacheStats: (health as any)?.cacheStats || undefined,
+ uptime: toString(health.uptime, "unknown"),
+ version: toString(health.version, "unknown"),
+ memoryUsage: {
+ heapUsed: toNumber(memoryUsageRaw.heapUsed, 0),
+ heapTotal: toNumber(memoryUsageRaw.heapTotal, 0),
+ },
+ circuitBreakers: resilienceCircuitBreakers,
+ rateLimits: rateLimitEntries,
+ cacheStats:
+ Object.keys(cacheStatsRaw).length > 0
+ ? {
+ hits: toNumber(cacheStatsRaw.hits, 0),
+ misses: toNumber(cacheStatsRaw.misses, 0),
+ hitRate: toNumber(cacheStatsRaw.hitRate, 0),
+ }
+ : undefined,
};
await logToolCall("omniroute_get_health", {}, result, Date.now() - start, true);
@@ -106,31 +218,34 @@ async function handleGetHealth() {
async function handleListCombos(args: { includeMetrics?: boolean }) {
const start = Date.now();
try {
- const combosRaw = (await omniRouteFetch("/api/combos")) as any;
- const combos = Array.isArray(combosRaw?.combos)
- ? combosRaw.combos
+ const combosRaw = await omniRouteFetch("/api/combos");
+ const combosRecord = toRecord(combosRaw);
+ const combos = Array.isArray(combosRecord.combos)
+ ? combosRecord.combos
: Array.isArray(combosRaw)
? combosRaw
: [];
- let metrics: Record<string, unknown> = {};
+ let metrics: JsonRecord = {};
if (args.includeMetrics) {
- metrics = (await omniRouteFetch("/api/combos/metrics").catch(() => ({}))) as Record<
- string,
- unknown
- >;
+ metrics = toRecord(await omniRouteFetch("/api/combos/metrics").catch(() => ({})));
}
const result = {
- combos: Array.isArray(combos)
- ? combos.map((c: any) => ({
- id: c.id,
- name: c.name,
- models: c.models || c.data?.models || [],
- strategy: c.strategy || c.data?.strategy || "priority",
- enabled: c.enabled !== false,
- ...(args.includeMetrics ? { metrics: (metrics as any)?.[c.id] || null } : {}),
- }))
- : [],
+ combos: toArray(combos).map((rawCombo) => {
+ const combo = toRecord(rawCombo);
+ const comboData = toRecord(combo.data);
+ const comboId = toString(combo.id, "");
+ const modelsSource =
+ Array.isArray(combo.models) && combo.models.length > 0 ? combo.models : comboData.models;
+ return {
+ id: comboId,
+ name: toString(combo.name, comboId || "unnamed"),
+ models: normalizeComboModels(modelsSource),
+ strategy: toString(combo.strategy, toString(comboData.strategy, "priority")),
+ enabled: combo.enabled !== false,
+ ...(args.includeMetrics ? { metrics: metrics[comboId] ?? null } : {}),
+ };
+ }),
};
await logToolCall("omniroute_list_combos", args, result, Date.now() - start, true);
@@ -216,24 +331,31 @@ async function handleRouteRequest(args: {
const raw = (await omniRouteFetch("/v1/chat/completions", {
method: "POST",
body: JSON.stringify(body),
- })) as any;
+ })) as JsonRecord;
+ const choices = toArray(raw.choices);
+ const firstChoice = toRecord(choices[0]);
+ const firstMessage = toRecord(firstChoice.message);
+ const usage = toRecord(raw.usage);
const result = {
response: {
- content: raw?.choices?.[0]?.message?.content || "",
- model: raw?.model || args.model,
+ content: toString(firstMessage.content, ""),
+ model: toString(raw.model, args.model),
tokens: {
- prompt: raw?.usage?.prompt_tokens || 0,
- completion: raw?.usage?.completion_tokens || 0,
+ prompt: toNumber(usage.prompt_tokens, 0),
+ completion: toNumber(usage.completion_tokens, 0),
},
},
routing: {
- provider: raw?.provider || "unknown",
- combo: raw?.combo || null,
- fallbacksTriggered: raw?.fallbacksTriggered || 0,
- cost: raw?.cost || 0,
+ provider: toString(raw.provider, "unknown"),
+ combo: raw.combo ?? null,
+ fallbacksTriggered: toNumber(raw.fallbacksTriggered, 0),
+ cost: toNumber(raw.cost, 0),
latencyMs: Date.now() - start,
- routingExplanation: raw?.routingExplanation || "Request routed through primary provider",
+ routingExplanation: toString(
+ raw.routingExplanation,
+ "Request routed through primary provider"
+ ),
},
};
@@ -263,18 +385,26 @@ async function handleCostReport(args: { period?: string }) {
const start = Date.now();
try {
const period = args.period || "session";
- const raw = (await omniRouteFetch(
- `/api/usage/analytics?period=${encodeURIComponent(period)}`
- )) as any;
+ const raw = toRecord(
+ await omniRouteFetch(`/api/usage/analytics?period=${encodeURIComponent(period)}`)
+ );
+ const tokenCount = toRecord(raw.tokenCount);
+ const budget = toRecord(raw.budget);
const result = {
period,
- totalCost: raw?.totalCost || 0,
- requestCount: raw?.requestCount || 0,
- tokenCount: raw?.tokenCount || { prompt: 0, completion: 0 },
- byProvider: raw?.byProvider || [],
- byModel: raw?.byModel || [],
- budget: raw?.budget || { limit: null, remaining: null },
+ totalCost: toNumber(raw.totalCost, 0),
+ requestCount: toNumber(raw.requestCount, 0),
+ tokenCount: {
+ prompt: toNumber(tokenCount.prompt, 0),
+ completion: toNumber(tokenCount.completion, 0),
+ },
+ byProvider: toArray(raw.byProvider),
+ byModel: toArray(raw.byModel),
+ budget: {
+ limit: budget.limit ?? null,
+ remaining: budget.remaining ?? null,
+ },
};
await logToolCall("omniroute_cost_report", args, result, Date.now() - start, true);
@@ -295,17 +425,18 @@ async function handleListModelsCatalog(args: { provider?: string; capability?: s
if (args.capability) params.set("capability", args.capability);
if (params.toString()) path += `?${params.toString()}`;
- const raw = (await omniRouteFetch(path)) as any;
+ const raw = toRecord(await omniRouteFetch(path));
const result = {
- models: Array.isArray(raw?.data)
- ? raw.data.map((m: any) => ({
- id: m.id,
- provider: m.owned_by || m.provider || "unknown",
- capabilities: m.capabilities || ["chat"],
- status: m.status || "available",
- pricing: m.pricing || undefined,
- }))
- : [],
+ models: toArray(raw.data).map((rawModel) => {
+ const model = toRecord(rawModel);
+ return {
+ id: toString(model.id, ""),
+ provider: toString(model.owned_by, toString(model.provider, "unknown")),
+ capabilities: toStringArray(model.capabilities, ["chat"]),
+ status: toString(model.status, "available"),
+ pricing: model.pricing,
+ };
+ }),
};
await logToolCall(
@@ -335,181 +466,193 @@ export function createMcpServer(): McpServer {
});
// Register essential tools
- server.tool(
+ server.registerTool(
"omniroute_get_health",
- "Returns OmniRoute health status including uptime, memory, circuit breakers, rate limits, and cache stats",
- {},
- handleGetHealth
+ {
+ description:
+ "Returns OmniRoute health status including uptime, memory, circuit breakers, rate limits, and cache stats",
+ inputSchema: getHealthInput,
+ },
+ withScopeEnforcement("omniroute_get_health", async (args) => {
+ getHealthInput.parse(args ?? {});
+ return handleGetHealth();
+ })
);
- server.tool(
+ server.registerTool(
"omniroute_list_combos",
- "Lists all configured combos (model chains) with strategies and optional metrics",
- { includeMetrics: { type: "boolean", description: "Include performance metrics per combo" } },
- (args) => handleListCombos(args as any)
+ {
+ description:
+ "Lists all configured combos (model chains) with strategies and optional metrics",
+ inputSchema: listCombosInput,
+ },
+ withScopeEnforcement("omniroute_list_combos", (args) =>
+ handleListCombos(listCombosInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_get_combo_metrics",
- "Returns detailed performance metrics for a specific combo",
- { comboId: { type: "string", description: "ID of the combo to get metrics for" } },
- (args) => handleGetComboMetrics(args as any)
+ {
+ description: "Returns detailed performance metrics for a specific combo",
+ inputSchema: getComboMetricsInput,
+ },
+ withScopeEnforcement("omniroute_get_combo_metrics", (args) =>
+ handleGetComboMetrics(getComboMetricsInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_switch_combo",
- "Activates or deactivates a combo for routing",
{
- comboId: { type: "string", description: "ID of the combo" },
- active: { type: "boolean", description: "Whether to enable or disable" },
+ description: "Activates or deactivates a combo for routing",
+ inputSchema: switchComboInput,
},
- (args) => handleSwitchCombo(args as any)
+ withScopeEnforcement("omniroute_switch_combo", (args) =>
+ handleSwitchCombo(switchComboInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_check_quota",
- "Checks remaining API quota for one or all providers",
{
- provider: { type: "string", description: "Filter by provider name (optional)" },
- connectionId: { type: "string", description: "Filter by connection ID (optional)" },
+ description: "Checks remaining API quota for one or all providers",
+ inputSchema: checkQuotaInput,
},
- (args) => handleCheckQuota(args as any)
+ withScopeEnforcement("omniroute_check_quota", (args) =>
+ handleCheckQuota(checkQuotaInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_route_request",
- "Sends a chat completion request through OmniRoute intelligent routing",
{
- model: { type: "string", description: "Model identifier" },
- messages: {
- type: "array",
- items: {
- type: "object",
- properties: { role: { type: "string" }, content: { type: "string" } },
- },
- description: "Chat messages",
- },
- combo: { type: "string", description: "Specific combo to route through (optional)" },
- budget: { type: "number", description: "Max cost in USD (optional)" },
- role: {
- type: "string",
- description: "Task role hint: coding, review, planning, analysis (optional)",
- },
+ description: "Sends a chat completion request through OmniRoute intelligent routing",
+ inputSchema: routeRequestInput,
},
- (args) => handleRouteRequest(args as any)
+ withScopeEnforcement("omniroute_route_request", (args) =>
+ handleRouteRequest(routeRequestInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_cost_report",
- "Generates a cost report for the specified period",
{
- period: {
- type: "string",
- description: "Time period: session, day, week, month (default: session)",
- },
+ description: "Generates a cost report for the specified period",
+ inputSchema: costReportInput,
},
- (args) => handleCostReport(args as any)
+ withScopeEnforcement("omniroute_cost_report", (args) =>
+ handleCostReport(costReportInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_list_models_catalog",
- "Lists all available AI models across providers with capabilities and pricing",
{
- provider: { type: "string", description: "Filter by provider name (optional)" },
- capability: {
- type: "string",
- description: "Filter by capability: chat, embedding, image (optional)",
- },
+ description: "Lists all available AI models across providers with capabilities and pricing",
+ inputSchema: listModelsCatalogInput,
},
- (args) => handleListModelsCatalog(args as any)
+ withScopeEnforcement("omniroute_list_models_catalog", (args) =>
+ handleListModelsCatalog(listModelsCatalogInput.parse(args))
+ )
);
// ── Advanced Tools (Phase 3) ──────────────────────────────
- server.tool(
+ server.registerTool(
"omniroute_simulate_route",
- "Simulates the routing path a request would take without executing it (dry-run)",
{
- model: { type: "string", description: "Target model identifier" },
- promptTokenEstimate: { type: "number", description: "Estimated prompt token count" },
- combo: {
- type: "string",
- description: "Specific combo to simulate (optional, default: active)",
- },
+ description: "Simulates the routing path a request would take without executing it (dry-run)",
+ inputSchema: simulateRouteInput,
},
- (args) => handleSimulateRoute(args as any)
+ withScopeEnforcement("omniroute_simulate_route", (args) =>
+ handleSimulateRoute(simulateRouteInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_set_budget_guard",
- "Sets a session budget limit with configurable action when exceeded (degrade/block/alert)",
{
- maxCost: { type: "number", description: "Maximum cost in USD for the session" },
- action: { type: "string", description: "Action on exceed: degrade, block, or alert" },
- degradeToTier: {
- type: "string",
- description: "If action=degrade, target tier: cheap or free (optional)",
- },
+ description:
+ "Sets a session budget limit with configurable action when exceeded (degrade/block/alert)",
+ inputSchema: setBudgetGuardInput,
},
- (args) => handleSetBudgetGuard(args as any)
+ withScopeEnforcement("omniroute_set_budget_guard", (args) =>
+ handleSetBudgetGuard(setBudgetGuardInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_set_resilience_profile",
- "Applies a resilience profile controlling circuit breakers, retries, timeouts, and fallback depth",
{
- profile: { type: "string", description: "Profile: aggressive, balanced, or conservative" },
+ description:
+ "Applies a resilience profile controlling circuit breakers, retries, timeouts, and fallback depth",
+ inputSchema: setResilienceProfileInput,
},
- (args) => handleSetResilienceProfile(args as any)
+ withScopeEnforcement("omniroute_set_resilience_profile", (args) =>
+ handleSetResilienceProfile(setResilienceProfileInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_test_combo",
- "Tests each provider in a combo with a real prompt, reporting latency, cost, and success per provider",
{
- comboId: { type: "string", description: "ID or name of the combo to test" },
- testPrompt: { type: "string", description: "Short test prompt (max 200 chars)" },
+ description:
+ "Tests each provider in a combo with a real prompt, reporting latency, cost, and success per provider",
+ inputSchema: testComboInput,
},
- (args) => handleTestCombo(args as any)
+ withScopeEnforcement("omniroute_test_combo", (args) =>
+ handleTestCombo(testComboInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_get_provider_metrics",
- "Returns detailed metrics for a specific provider including latency percentiles and circuit breaker state",
{
- provider: { type: "string", description: "Provider name" },
+ description:
+ "Returns detailed metrics for a specific provider including latency percentiles and circuit breaker state",
+ inputSchema: getProviderMetricsInput,
},
- (args) => handleGetProviderMetrics(args as any)
+ withScopeEnforcement("omniroute_get_provider_metrics", (args) =>
+ handleGetProviderMetrics(getProviderMetricsInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_best_combo_for_task",
- "Recommends the best combo for a task type based on provider fitness and constraints",
{
- taskType: {
- type: "string",
- description: "Task type: coding, review, planning, analysis, debugging, documentation",
- },
- budgetConstraint: { type: "number", description: "Max cost constraint in USD (optional)" },
- latencyConstraint: { type: "number", description: "Max latency constraint in ms (optional)" },
+ description:
+ "Recommends the best combo for a task type based on provider fitness and constraints",
+ inputSchema: bestComboForTaskInput,
},
- (args) => handleBestComboForTask(args as any)
+ withScopeEnforcement("omniroute_best_combo_for_task", (args) =>
+ handleBestComboForTask(bestComboForTaskInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_explain_route",
- "Explains why a request was routed to a specific provider, showing scoring factors and fallbacks",
{
- requestId: { type: "string", description: "Request ID from X-Request-Id header" },
+ description:
+ "Explains why a request was routed to a specific provider, showing scoring factors and fallbacks",
+ inputSchema: explainRouteInput,
},
- (args) => handleExplainRoute(args as any)
+ withScopeEnforcement("omniroute_explain_route", (args) =>
+ handleExplainRoute(explainRouteInput.parse(args))
+ )
);
- server.tool(
+ server.registerTool(
"omniroute_get_session_snapshot",
- "Returns a full snapshot of the current working session: cost, tokens, top models, errors, budget status",
- {},
- handleGetSessionSnapshot
+ {
+ description:
+ "Returns a full snapshot of the current working session: cost, tokens, top models, errors, budget status",
+ inputSchema: getSessionSnapshotInput,
+ },
+ withScopeEnforcement("omniroute_get_session_snapshot", async (args) => {
+ getSessionSnapshotInput.parse(args ?? {});
+ return handleGetSessionSnapshot();
+ })
);
return server;
diff --git a/open-sse/translator/bootstrap.ts b/open-sse/translator/bootstrap.ts
new file mode 100644
index 0000000000..6a89341ab5
--- /dev/null
+++ b/open-sse/translator/bootstrap.ts
@@ -0,0 +1,27 @@
+/**
+ * Explicit translator bootstrap module.
+ * Importing this file initializes all translator adapters via side-effect registration.
+ */
+
+import "./request/claude-to-openai.ts";
+import "./request/openai-to-claude.ts";
+import "./request/gemini-to-openai.ts";
+import "./request/openai-to-gemini.ts";
+import "./request/antigravity-to-openai.ts";
+import "./request/openai-responses.ts";
+import "./request/openai-to-kiro.ts";
+import "./request/openai-to-cursor.ts";
+import "./request/claude-to-gemini.ts";
+
+import "./response/claude-to-openai.ts";
+import "./response/openai-to-claude.ts";
+import "./response/gemini-to-openai.ts";
+import "./response/gemini-to-claude.ts";
+import "./response/openai-to-antigravity.ts";
+import "./response/openai-responses.ts";
+import "./response/kiro-to-openai.ts";
+import "./response/cursor-to-openai.ts";
+
+export function bootstrapTranslatorRegistry() {
+ // no-op by design; importing this module triggers translator self-registration once
+}
diff --git a/open-sse/translator/index.ts b/open-sse/translator/index.ts
index 20ba2d906d..ce3f353f60 100644
--- a/open-sse/translator/index.ts
+++ b/open-sse/translator/index.ts
@@ -2,25 +2,14 @@ import { FORMATS } from "./formats.ts";
import { ensureToolCallIds, fixMissingToolResponses } from "./helpers/toolCallHelper.ts";
import { prepareClaudeRequest } from "./helpers/claudeHelper.ts";
import { filterToOpenAIFormat } from "./helpers/openaiHelper.ts";
+import { getRequestTranslator, getResponseTranslator } from "./registry.ts";
+import { bootstrapTranslatorRegistry } from "./bootstrap.ts";
import { normalizeThinkingConfig } from "../services/provider.ts";
import { applyThinkingBudget } from "../services/thinkingBudget.ts";
import { normalizeRoles } from "../services/roleNormalizer.ts";
-// Registry for translators.
-// NOTE: translator modules import this file and call register() at module-load time.
-// Using `var` + lazy init avoids TDZ/circular-init crashes under bundlers.
-var requestRegistry;
-var responseRegistry;
-
-function getRequestRegistry() {
- if (!requestRegistry) requestRegistry = new Map();
- return requestRegistry;
-}
-
-function getResponseRegistry() {
- if (!responseRegistry) responseRegistry = new Map();
- return responseRegistry;
-}
+bootstrapTranslatorRegistry();
+export { register } from "./registry.ts";
function normalizeResponsesInputItem(item) {
if (typeof item === "string") {
@@ -77,37 +66,6 @@ function normalizeOpenAIResponsesRequest(body) {
return normalized;
}
-// Register translator (called by each translator module on import)
-export function register(from, to, requestFn, responseFn) {
- const key = `${from}:${to}`;
- if (requestFn) {
- getRequestRegistry().set(key, requestFn);
- }
- if (responseFn) {
- getResponseRegistry().set(key, responseFn);
- }
-}
-
-// Translator modules self-register via register() on import
-import "./request/claude-to-openai.ts";
-import "./request/openai-to-claude.ts";
-import "./request/gemini-to-openai.ts";
-import "./request/openai-to-gemini.ts";
-import "./request/antigravity-to-openai.ts";
-import "./request/openai-responses.ts";
-import "./request/openai-to-kiro.ts";
-import "./request/openai-to-cursor.ts";
-import "./request/claude-to-gemini.ts";
-
-import "./response/claude-to-openai.ts";
-import "./response/openai-to-claude.ts";
-import "./response/gemini-to-openai.ts";
-import "./response/gemini-to-claude.ts";
-import "./response/openai-to-antigravity.ts";
-import "./response/openai-responses.ts";
-import "./response/kiro-to-openai.ts";
-import "./response/cursor-to-openai.ts";
-
// Translate request: source -> openai -> target
export function translateRequest(
sourceFormat,
@@ -141,15 +99,14 @@ export function translateRequest(
// If same format, skip translation steps
if (sourceFormat !== targetFormat) {
// Check for direct translation path first (e.g., Claude → Gemini)
- const directKey = `${sourceFormat}:${targetFormat}`;
- const directTranslator = getRequestRegistry().get(directKey);
+ const directTranslator = getRequestTranslator(sourceFormat, targetFormat);
if (directTranslator && sourceFormat !== FORMATS.OPENAI && targetFormat !== FORMATS.OPENAI) {
result = directTranslator(model, result, stream, credentials);
} else {
// Fallback: hub-and-spoke via OpenAI
// Step 1: source -> openai (if source is not openai)
if (sourceFormat !== FORMATS.OPENAI) {
- const toOpenAI = getRequestRegistry().get(`${sourceFormat}:${FORMATS.OPENAI}`);
+ const toOpenAI = getRequestTranslator(sourceFormat, FORMATS.OPENAI);
if (toOpenAI) {
result = toOpenAI(model, result, stream, credentials);
// Log OpenAI intermediate format
@@ -159,7 +116,7 @@ export function translateRequest(
// Step 2: openai -> target (if target is not openai)
if (targetFormat !== FORMATS.OPENAI) {
- const fromOpenAI = getRequestRegistry().get(`${FORMATS.OPENAI}:${targetFormat}`);
+ const fromOpenAI = getRequestTranslator(FORMATS.OPENAI, targetFormat);
if (fromOpenAI) {
result = fromOpenAI(model, result, stream, credentials);
}
@@ -197,8 +154,7 @@ export function translateResponse(targetFormat, sourceFormat, chunk, state) {
let openaiResults = null; // Store OpenAI intermediate results
// Check for direct translation path first (e.g., Gemini → Claude)
- const directKey = `${targetFormat}:${sourceFormat}`;
- const directTranslator = getResponseRegistry().get(directKey);
+ const directTranslator = getResponseTranslator(targetFormat, sourceFormat);
if (directTranslator && targetFormat !== FORMATS.OPENAI && sourceFormat !== FORMATS.OPENAI) {
const converted = directTranslator(chunk, state);
if (converted) {
@@ -212,7 +168,7 @@ export function translateResponse(targetFormat, sourceFormat, chunk, state) {
// Fallback: hub-and-spoke via OpenAI
// Step 1: target -> openai (if target is not openai)
if (targetFormat !== FORMATS.OPENAI) {
- const toOpenAI = getResponseRegistry().get(`${targetFormat}:${FORMATS.OPENAI}`);
+ const toOpenAI = getResponseTranslator(targetFormat, FORMATS.OPENAI);
if (toOpenAI) {
results = [];
const converted = toOpenAI(chunk, state);
@@ -225,7 +181,7 @@ export function translateResponse(targetFormat, sourceFormat, chunk, state) {
// Step 2: openai -> source (if source is not openai)
if (sourceFormat !== FORMATS.OPENAI) {
- const fromOpenAI = getResponseRegistry().get(`${FORMATS.OPENAI}:${sourceFormat}`);
+ const fromOpenAI = getResponseTranslator(FORMATS.OPENAI, sourceFormat);
if (fromOpenAI) {
const finalResults = [];
for (const r of results) {
@@ -240,7 +196,7 @@ export function translateResponse(targetFormat, sourceFormat, chunk, state) {
// Attach OpenAI intermediate results for logging
if (openaiResults && sourceFormat !== FORMATS.OPENAI && targetFormat !== FORMATS.OPENAI) {
- (results as any)._openaiIntermediate = openaiResults;
+ (results as { _openaiIntermediate?: unknown })._openaiIntermediate = openaiResults;
}
return results;
@@ -299,4 +255,6 @@ export function initState(sourceFormat) {
}
// Initialize all translators (no-op, kept for backward compatibility)
-export function initTranslators() {}
+export function initTranslators() {
+ bootstrapTranslatorRegistry();
+}
diff --git a/open-sse/translator/registry.ts b/open-sse/translator/registry.ts
new file mode 100644
index 0000000000..f35371b0da
--- /dev/null
+++ b/open-sse/translator/registry.ts
@@ -0,0 +1,41 @@
+type RequestTranslator = (
+ model: string,
+ body: Record<string, unknown>,
+ stream?: boolean,
+ credentials?: Record<string, unknown> | null
+) => unknown;
+
+type ResponseTranslator = (
+ chunk: Record<string, unknown>,
+ state: Record<string, unknown>
+) => unknown;
+
+const requestRegistry = new Map<string, RequestTranslator>();
+const responseRegistry = new Map<string, ResponseTranslator>();
+
+function makeKey(from: string, to: string) {
+ return `${from}:${to}`;
+}
+
+export function register(
+ from: string,
+ to: string,
+ requestFn?: RequestTranslator,
+ responseFn?: ResponseTranslator
+) {
+ const key = makeKey(from, to);
+ if (requestFn) {
+ requestRegistry.set(key, requestFn);
+ }
+ if (responseFn) {
+ responseRegistry.set(key, responseFn);
+ }
+}
+
+export function getRequestTranslator(from: string, to: string) {
+ return requestRegistry.get(makeKey(from, to));
+}
+
+export function getResponseTranslator(from: string, to: string) {
+ return responseRegistry.get(makeKey(from, to));
+}
diff --git a/open-sse/translator/request/antigravity-to-openai.ts b/open-sse/translator/request/antigravity-to-openai.ts
index e90f572fa8..8fe9e24b33 100644
--- a/open-sse/translator/request/antigravity-to-openai.ts
+++ b/open-sse/translator/request/antigravity-to-openai.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
import { adjustMaxTokens } from "../helpers/maxTokensHelper.ts";
diff --git a/open-sse/translator/request/claude-to-gemini.ts b/open-sse/translator/request/claude-to-gemini.ts
index 7ac3cf4d9a..e02f2ceb28 100644
--- a/open-sse/translator/request/claude-to-gemini.ts
+++ b/open-sse/translator/request/claude-to-gemini.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
import { DEFAULT_SAFETY_SETTINGS, tryParseJSON } from "../helpers/geminiHelper.ts";
import { DEFAULT_THINKING_GEMINI_SIGNATURE } from "../../config/defaultThinkingSignature.ts";
diff --git a/open-sse/translator/request/claude-to-openai.ts b/open-sse/translator/request/claude-to-openai.ts
index 7cd43602d7..d511dca6bc 100644
--- a/open-sse/translator/request/claude-to-openai.ts
+++ b/open-sse/translator/request/claude-to-openai.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
import { adjustMaxTokens } from "../helpers/maxTokensHelper.ts";
diff --git a/open-sse/translator/request/gemini-to-openai.ts b/open-sse/translator/request/gemini-to-openai.ts
index c10d8c0533..751cbca654 100644
--- a/open-sse/translator/request/gemini-to-openai.ts
+++ b/open-sse/translator/request/gemini-to-openai.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
import { adjustMaxTokens } from "../helpers/maxTokensHelper.ts";
diff --git a/open-sse/translator/request/openai-responses.ts b/open-sse/translator/request/openai-responses.ts
index c0d433c53f..6c6d2522af 100644
--- a/open-sse/translator/request/openai-responses.ts
+++ b/open-sse/translator/request/openai-responses.ts
@@ -4,7 +4,7 @@
* Responses API uses: { input: [...], instructions: "..." }
* Chat API uses: { messages: [...] }
*/
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
/**
diff --git a/open-sse/translator/request/openai-to-claude.ts b/open-sse/translator/request/openai-to-claude.ts
index cec2430ef2..4c0f2fb14f 100644
--- a/open-sse/translator/request/openai-to-claude.ts
+++ b/open-sse/translator/request/openai-to-claude.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
import { CLAUDE_SYSTEM_PROMPT } from "../../config/constants.ts";
import { adjustMaxTokens } from "../helpers/maxTokensHelper.ts";
diff --git a/open-sse/translator/request/openai-to-cursor.ts b/open-sse/translator/request/openai-to-cursor.ts
index 0d04356b4b..28164bd94d 100644
--- a/open-sse/translator/request/openai-to-cursor.ts
+++ b/open-sse/translator/request/openai-to-cursor.ts
@@ -2,7 +2,7 @@
* OpenAI to Cursor Request Translator
* Converts OpenAI messages to Cursor simple format
*/
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
/**
@@ -80,9 +80,7 @@ function convertMessages(messages) {
result.push(assistantMsg);
} else if (content || pendingToolResults.length > 0) {
- const msgObj: Record<string, any> = { role: msg.role,
- content: content || "",
- };
+ const msgObj: Record<string, any> = { role: msg.role, content: content || "" };
// Attach pending tool results to this message
if (pendingToolResults.length > 0) {
diff --git a/open-sse/translator/request/openai-to-gemini.ts b/open-sse/translator/request/openai-to-gemini.ts
index 6f5a0365c7..0694e52719 100644
--- a/open-sse/translator/request/openai-to-gemini.ts
+++ b/open-sse/translator/request/openai-to-gemini.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
import { DEFAULT_THINKING_GEMINI_SIGNATURE } from "../../config/defaultThinkingSignature.ts";
import { ANTIGRAVITY_DEFAULT_SYSTEM } from "../../config/constants.ts";
diff --git a/open-sse/translator/request/openai-to-kiro.ts b/open-sse/translator/request/openai-to-kiro.ts
index 26db5f916e..2697bd8813 100644
--- a/open-sse/translator/request/openai-to-kiro.ts
+++ b/open-sse/translator/request/openai-to-kiro.ts
@@ -2,7 +2,7 @@
* OpenAI to Kiro Request Translator
* Converts OpenAI Chat Completions format to Kiro/AWS CodeWhisperer format
*/
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
import { v4 as uuidv4 } from "uuid";
diff --git a/open-sse/translator/response/claude-to-openai.ts b/open-sse/translator/response/claude-to-openai.ts
index 84e87cbf9f..373f5be51b 100644
--- a/open-sse/translator/response/claude-to-openai.ts
+++ b/open-sse/translator/response/claude-to-openai.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
// Create OpenAI chunk helper
diff --git a/open-sse/translator/response/cursor-to-openai.ts b/open-sse/translator/response/cursor-to-openai.ts
index d330f76007..289fccf8b4 100644
--- a/open-sse/translator/response/cursor-to-openai.ts
+++ b/open-sse/translator/response/cursor-to-openai.ts
@@ -2,7 +2,7 @@
* Cursor to OpenAI Response Translator
* CursorExecutor already emits OpenAI format - this is a passthrough
*/
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
/**
diff --git a/open-sse/translator/response/gemini-to-claude.ts b/open-sse/translator/response/gemini-to-claude.ts
index f0e598be9f..ba1034fe27 100644
--- a/open-sse/translator/response/gemini-to-claude.ts
+++ b/open-sse/translator/response/gemini-to-claude.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
/**
diff --git a/open-sse/translator/response/gemini-to-openai.ts b/open-sse/translator/response/gemini-to-openai.ts
index 08a49c2268..9d6a470090 100644
--- a/open-sse/translator/response/gemini-to-openai.ts
+++ b/open-sse/translator/response/gemini-to-openai.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
// Convert Gemini response chunk to OpenAI format
diff --git a/open-sse/translator/response/kiro-to-openai.ts b/open-sse/translator/response/kiro-to-openai.ts
index b299d2f493..c8fad48d11 100644
--- a/open-sse/translator/response/kiro-to-openai.ts
+++ b/open-sse/translator/response/kiro-to-openai.ts
@@ -2,7 +2,7 @@
* Kiro to OpenAI Response Translator
* Converts Kiro/AWS CodeWhisperer streaming events to OpenAI SSE format
*/
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
/**
diff --git a/open-sse/translator/response/openai-responses.ts b/open-sse/translator/response/openai-responses.ts
index d72b6d20bb..016d73851e 100644
--- a/open-sse/translator/response/openai-responses.ts
+++ b/open-sse/translator/response/openai-responses.ts
@@ -2,7 +2,7 @@
* Translator: OpenAI Chat Completions → OpenAI Responses API (response)
* Converts streaming chunks from Chat Completions to Responses API events
*/
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
/**
diff --git a/open-sse/translator/response/openai-to-antigravity.ts b/open-sse/translator/response/openai-to-antigravity.ts
index 36e3050965..a8a7d85957 100644
--- a/open-sse/translator/response/openai-to-antigravity.ts
+++ b/open-sse/translator/response/openai-to-antigravity.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
// Convert OpenAI SSE chunk to Antigravity SSE format
diff --git a/open-sse/translator/response/openai-to-claude.ts b/open-sse/translator/response/openai-to-claude.ts
index 21904e6c19..82bbab4987 100644
--- a/open-sse/translator/response/openai-to-claude.ts
+++ b/open-sse/translator/response/openai-to-claude.ts
@@ -1,4 +1,4 @@
-import { register } from "../index.ts";
+import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
// Prefix for Claude OAuth tool names (must match request translator)