- Speech-to-Text: full pipeline with sttCore handler, /v1/audio/transcriptions endpoint, sttConfig for OpenAI, Gemini, Groq, Deepgram, AssemblyAI, HuggingFace, NVIDIA Parakeet; new 9router-stt skill - Gemini TTS: add gemini provider with 30 prebuilt voices and TTS_PROVIDER_CONFIG - Usage: implement GLM (intl/cn) and MiniMax (intl/cn) quota fetchers; refactor Gemini CLI usage to use retrieveUserQuota with per-model buckets - Disabled models: lowdb-backed disabledModelsDb + /api/models/disabled route - Header search: reusable Zustand store (headerSearchStore) wired into Header - CLI tools: add Claude Cowork tool card and cowork-settings API - Providers: introduce mediaPriority sorting in getProvidersByKind, add Kimi K2.6, reorder hermes, drop qwen STT kind - UI: expand media-providers/[kind]/[id] page (+314), enhance OAuthModal, ModelSelectModal, ProviderTopology, ProxyPools, ProviderLimits - Assets: refresh provider PNGs (alicode, byteplus, cloudflare-ai, nvidia, ollama, vertex, volcengine-ark) and add aws-polly, fal-ai, jina-ai, recraft, runwayml, stability-ai, topaz, black-forest-labs
172 lines
6.1 KiB
JavaScript
172 lines
6.1 KiB
JavaScript
// Ensure proxyFetch is loaded to patch globalThis.fetch
|
|
import "open-sse/index.js";
|
|
|
|
import { getProviderConnectionById, updateProviderConnection } from "@/lib/localDb";
|
|
import { getUsageForProvider } from "open-sse/services/usage.js";
|
|
import { getExecutor } from "open-sse/executors/index.js";
|
|
import { resolveConnectionProxyConfig } from "@/lib/network/connectionProxy";
|
|
import { USAGE_APIKEY_PROVIDERS } from "@/shared/constants/providers";
|
|
|
|
// Detect auth-expired messages returned by usage providers instead of throwing
|
|
const AUTH_EXPIRED_PATTERNS = ["expired", "authentication", "unauthorized", "401", "re-authorize"];
|
|
function isAuthExpiredMessage(usage) {
|
|
if (!usage?.message) return false;
|
|
const msg = usage.message.toLowerCase();
|
|
return AUTH_EXPIRED_PATTERNS.some((p) => msg.includes(p));
|
|
}
|
|
|
|
/**
|
|
* Refresh credentials using executor and update database
|
|
* @param {boolean} force - Skip needsRefresh check and always attempt refresh
|
|
* @returns Promise<{ connection, refreshed: boolean }>
|
|
*/
|
|
async function refreshAndUpdateCredentials(connection, force = false, proxyOptions = null) {
|
|
const executor = getExecutor(connection.provider);
|
|
|
|
// Build credentials object from connection
|
|
const credentials = {
|
|
accessToken: connection.accessToken,
|
|
refreshToken: connection.refreshToken,
|
|
expiresAt: connection.expiresAt || connection.tokenExpiresAt,
|
|
providerSpecificData: connection.providerSpecificData,
|
|
// For GitHub
|
|
copilotToken: connection.providerSpecificData?.copilotToken,
|
|
copilotTokenExpiresAt: connection.providerSpecificData?.copilotTokenExpiresAt,
|
|
};
|
|
|
|
// Check if refresh is needed (skip when force=true)
|
|
const needsRefresh = force || executor.needsRefresh(credentials);
|
|
|
|
if (!needsRefresh) {
|
|
return { connection, refreshed: false };
|
|
}
|
|
|
|
// Use executor's refreshCredentials method (with optional proxy)
|
|
const refreshResult = await executor.refreshCredentials(credentials, console, proxyOptions);
|
|
|
|
if (!refreshResult) {
|
|
// Refresh failed but we still have an accessToken — try with existing token
|
|
if (connection.accessToken) {
|
|
return { connection, refreshed: false };
|
|
}
|
|
throw new Error("Failed to refresh credentials. Please re-authorize the connection.");
|
|
}
|
|
|
|
// Build update object
|
|
const now = new Date().toISOString();
|
|
const updateData = {
|
|
updatedAt: now,
|
|
};
|
|
|
|
// Update accessToken if present
|
|
if (refreshResult.accessToken) {
|
|
updateData.accessToken = refreshResult.accessToken;
|
|
}
|
|
|
|
// Update refreshToken if present
|
|
if (refreshResult.refreshToken) {
|
|
updateData.refreshToken = refreshResult.refreshToken;
|
|
}
|
|
|
|
// Update token expiry
|
|
if (refreshResult.expiresIn) {
|
|
updateData.expiresAt = new Date(Date.now() + refreshResult.expiresIn * 1000).toISOString();
|
|
} else if (refreshResult.expiresAt) {
|
|
updateData.expiresAt = refreshResult.expiresAt;
|
|
}
|
|
|
|
// Handle provider-specific data (copilotToken for GitHub, etc.)
|
|
if (refreshResult.copilotToken || refreshResult.copilotTokenExpiresAt) {
|
|
updateData.providerSpecificData = {
|
|
...connection.providerSpecificData,
|
|
copilotToken: refreshResult.copilotToken,
|
|
copilotTokenExpiresAt: refreshResult.copilotTokenExpiresAt,
|
|
};
|
|
}
|
|
|
|
// Update database
|
|
await updateProviderConnection(connection.id, updateData);
|
|
|
|
// Return updated connection
|
|
const updatedConnection = {
|
|
...connection,
|
|
...updateData,
|
|
};
|
|
|
|
return {
|
|
connection: updatedConnection,
|
|
refreshed: true,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* GET /api/usage/[connectionId] - Get usage data for a specific connection
|
|
*/
|
|
export async function GET(request, { params }) {
|
|
let connection;
|
|
try {
|
|
const { connectionId } = await params;
|
|
|
|
|
|
// Get connection from database
|
|
connection = await getProviderConnectionById(connectionId);
|
|
if (!connection) {
|
|
return Response.json({ error: "Connection not found" }, { status: 404 });
|
|
}
|
|
|
|
// Allow OAuth connections, plus whitelisted apikey providers (glm/minimax/...)
|
|
const isOAuth = connection.authType === "oauth";
|
|
const isApikeyEligible =
|
|
connection.authType === "apikey" &&
|
|
USAGE_APIKEY_PROVIDERS.includes(connection.provider);
|
|
|
|
if (!isOAuth && !isApikeyEligible) {
|
|
return Response.json({ message: "Usage not available for this connection" });
|
|
}
|
|
|
|
// Resolve connection proxy config; force strictProxy=false so quota/refresh fall back to direct on failure
|
|
const proxyConfig = await resolveConnectionProxyConfig(connection.providerSpecificData);
|
|
const proxyOptions = {
|
|
connectionProxyEnabled: proxyConfig.connectionProxyEnabled === true,
|
|
connectionProxyUrl: proxyConfig.connectionProxyUrl || "",
|
|
connectionNoProxy: proxyConfig.connectionNoProxy || "",
|
|
vercelRelayUrl: proxyConfig.vercelRelayUrl || "",
|
|
strictProxy: false,
|
|
};
|
|
|
|
// Refresh credentials only for OAuth connections (apikey has no token refresh)
|
|
if (isOAuth) {
|
|
try {
|
|
const result = await refreshAndUpdateCredentials(connection, false, proxyOptions);
|
|
connection = result.connection;
|
|
} catch (refreshError) {
|
|
console.error("[Usage API] Credential refresh failed:", refreshError);
|
|
return Response.json({
|
|
error: `Credential refresh failed: ${refreshError.message}`
|
|
}, { status: 401 });
|
|
}
|
|
}
|
|
|
|
// Fetch usage from provider API
|
|
let usage = await getUsageForProvider(connection, proxyOptions);
|
|
|
|
// If provider returned an auth-expired message instead of throwing,
|
|
// force-refresh token and retry once (OAuth only)
|
|
if (isOAuth && isAuthExpiredMessage(usage) && connection.refreshToken) {
|
|
try {
|
|
const retryResult = await refreshAndUpdateCredentials(connection, true, proxyOptions);
|
|
connection = retryResult.connection;
|
|
usage = await getUsageForProvider(connection, proxyOptions);
|
|
} catch (retryError) {
|
|
console.warn(`[Usage] ${connection.provider}: force refresh failed: ${retryError.message}`);
|
|
}
|
|
}
|
|
|
|
return Response.json(usage);
|
|
} catch (error) {
|
|
const provider = connection?.provider ?? "unknown";
|
|
console.warn(`[Usage] ${provider}: ${error.message}`);
|
|
return Response.json({ error: error.message }, { status: 500 });
|
|
}
|
|
}
|