mirror of
https://github.com/Nezumi-2711/9router.git
synced 2026-09-22 20:00:47 +00:00
refactor: streamline provider interactions and enhance error handling
This commit is contained in:
@@ -102,7 +102,7 @@ export default function PricingSettingsPage() {
|
||||
<div className="space-y-3 text-sm text-text-muted">
|
||||
<p>
|
||||
<strong>Cost Calculation:</strong> Costs are calculated based on token usage and pricing rates.
|
||||
Each request's cost is determined by: (input_tokens × input_rate) + (output_tokens × output_rate) + (cached_tokens × cached_rate)
|
||||
Each request's cost is determined by: (input_tokens × input_rate) + (output_tokens × output_rate) + (cached_tokens × cached_rate)
|
||||
</p>
|
||||
<p>
|
||||
<strong>Pricing Format:</strong> All rates are in <strong>dollars per million tokens</strong> ($/1M tokens).
|
||||
|
||||
+19
-5
@@ -4,6 +4,9 @@ import { v4 as uuidv4 } from "uuid";
|
||||
import path from "path";
|
||||
import os from "os";
|
||||
import fs from "fs";
|
||||
|
||||
const isCloud = typeof caches !== 'undefined' || typeof caches === 'object';
|
||||
|
||||
// Get app name - fixed constant to avoid Windows path issues in standalone build
|
||||
function getAppName() {
|
||||
return "9router";
|
||||
@@ -11,10 +14,12 @@ function getAppName() {
|
||||
|
||||
// Get user data directory based on platform
|
||||
function getUserDataDir() {
|
||||
if (isCloud) return "/tmp"; // Fallback for Workers
|
||||
|
||||
const platform = process.platform;
|
||||
const homeDir = os.homedir();
|
||||
const appName = getAppName();
|
||||
|
||||
|
||||
if (platform === "win32") {
|
||||
return path.join(process.env.APPDATA || path.join(homeDir, "AppData", "Roaming"), appName);
|
||||
} else {
|
||||
@@ -25,10 +30,10 @@ function getUserDataDir() {
|
||||
|
||||
// Data file path - stored in user home directory
|
||||
const DATA_DIR = getUserDataDir();
|
||||
const DB_FILE = path.join(DATA_DIR, "db.json");
|
||||
const DB_FILE = isCloud ? null : path.join(DATA_DIR, "db.json");
|
||||
|
||||
// Ensure data directory exists
|
||||
if (!fs.existsSync(DATA_DIR)) {
|
||||
if (!isCloud && !fs.existsSync(DATA_DIR)) {
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
@@ -52,10 +57,19 @@ let dbInstance = null;
|
||||
* Get database instance (singleton)
|
||||
*/
|
||||
export async function getDb() {
|
||||
if (isCloud) {
|
||||
// Return in-memory DB for Workers
|
||||
if (!dbInstance) {
|
||||
dbInstance = new Low({ read: async () => {}, write: async () => {} }, defaultData);
|
||||
dbInstance.data = defaultData;
|
||||
}
|
||||
return dbInstance;
|
||||
}
|
||||
|
||||
if (!dbInstance) {
|
||||
const adapter = new JSONFile(DB_FILE);
|
||||
dbInstance = new Low(adapter, defaultData);
|
||||
|
||||
|
||||
// Try to read DB with error recovery for corrupt JSON
|
||||
try {
|
||||
await dbInstance.read();
|
||||
@@ -68,7 +82,7 @@ export async function getDb() {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Initialize with default data if empty
|
||||
if (!dbInstance.data) {
|
||||
dbInstance.data = defaultData;
|
||||
|
||||
@@ -77,7 +77,10 @@ export const ANTIGRAVITY_CONFIG = {
|
||||
"https://www.googleapis.com/auth/experimentsandconfigs",
|
||||
],
|
||||
// Antigravity specific
|
||||
apiEndpoint: "https://cloudcode-pa.googleapis.com",
|
||||
apiVersion: "v1internal",
|
||||
loadCodeAssistEndpoint: "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist",
|
||||
onboardUserEndpoint: "https://cloudcode-pa.googleapis.com/v1internal:onboardUser",
|
||||
loadCodeAssistUserAgent: "google-api-nodejs-client/9.15.1",
|
||||
loadCodeAssistApiClient: "google-cloud-sdk vscode_cloudshelleditor/0.1",
|
||||
loadCodeAssistClientMetadata: `{"ideType":"IDE_UNSPECIFIED","platform":"PLATFORM_UNSPECIFIED","pluginType":"GEMINI"}`,
|
||||
|
||||
+54
-15
@@ -245,34 +245,73 @@ const PROVIDERS = {
|
||||
return await response.json();
|
||||
},
|
||||
postExchange: async (tokens) => {
|
||||
const headers = {
|
||||
Authorization: `Bearer ${tokens.access_token}`,
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": ANTIGRAVITY_CONFIG.loadCodeAssistUserAgent,
|
||||
"X-Goog-Api-Client": ANTIGRAVITY_CONFIG.loadCodeAssistApiClient,
|
||||
"Client-Metadata": ANTIGRAVITY_CONFIG.loadCodeAssistClientMetadata,
|
||||
};
|
||||
const metadata = { ideType: "IDE_UNSPECIFIED", platform: "PLATFORM_UNSPECIFIED", pluginType: "GEMINI" };
|
||||
|
||||
// Fetch user info
|
||||
const userInfoRes = await fetch(`${ANTIGRAVITY_CONFIG.userInfoUrl}?alt=json`, {
|
||||
headers: { Authorization: `Bearer ${tokens.access_token}` },
|
||||
});
|
||||
const userInfo = userInfoRes.ok ? await userInfoRes.json() : {};
|
||||
|
||||
// Fetch project ID from loadCodeAssist
|
||||
// Load Code Assist to get project ID and tier
|
||||
let projectId = "";
|
||||
let tierId = "legacy-tier";
|
||||
try {
|
||||
const projectRes = await fetch(ANTIGRAVITY_CONFIG.loadCodeAssistEndpoint, {
|
||||
const loadRes = await fetch(ANTIGRAVITY_CONFIG.loadCodeAssistEndpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokens.access_token}`,
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": ANTIGRAVITY_CONFIG.loadCodeAssistUserAgent,
|
||||
"X-Goog-Api-Client": ANTIGRAVITY_CONFIG.loadCodeAssistApiClient,
|
||||
"Client-Metadata": ANTIGRAVITY_CONFIG.loadCodeAssistClientMetadata,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
metadata: { ideType: "IDE_UNSPECIFIED", platform: "PLATFORM_UNSPECIFIED", pluginType: "GEMINI" },
|
||||
}),
|
||||
headers,
|
||||
body: JSON.stringify({ metadata }),
|
||||
});
|
||||
if (projectRes.ok) {
|
||||
const data = await projectRes.json();
|
||||
if (loadRes.ok) {
|
||||
const data = await loadRes.json();
|
||||
projectId = data.cloudaicompanionProject?.id || data.cloudaicompanionProject || "";
|
||||
// Extract tier ID
|
||||
if (Array.isArray(data.allowedTiers)) {
|
||||
for (const tier of data.allowedTiers) {
|
||||
if (tier.isDefault && tier.id) {
|
||||
tierId = tier.id.trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Failed to fetch project ID:", e);
|
||||
console.log("Failed to load code assist:", e);
|
||||
}
|
||||
|
||||
// Onboard user to enable Gemini Code Assist
|
||||
if (projectId) {
|
||||
try {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const onboardRes = await fetch(ANTIGRAVITY_CONFIG.onboardUserEndpoint, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({ tierId, metadata, cloudaicompanionProject: projectId }),
|
||||
});
|
||||
if (onboardRes.ok) {
|
||||
const result = await onboardRes.json();
|
||||
if (result.done === true) {
|
||||
// Extract final project ID from response
|
||||
if (result.response?.cloudaicompanionProject) {
|
||||
const respProject = result.response.cloudaicompanionProject;
|
||||
projectId = typeof respProject === 'string' ? respProject.trim() : (respProject.id || projectId);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Wait 5 seconds before retry
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Failed to onboard user:", e);
|
||||
}
|
||||
}
|
||||
|
||||
return { userInfo, projectId };
|
||||
|
||||
@@ -78,45 +78,124 @@ export class AntigravityService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch Project ID from loadCodeAssist API
|
||||
* Get common headers for Antigravity API calls
|
||||
*/
|
||||
async fetchProjectId(accessToken) {
|
||||
const loadReqBody = {
|
||||
metadata: {
|
||||
ideType: "IDE_UNSPECIFIED",
|
||||
platform: "PLATFORM_UNSPECIFIED",
|
||||
pluginType: "GEMINI",
|
||||
},
|
||||
getApiHeaders(accessToken) {
|
||||
return {
|
||||
"Authorization": `Bearer ${accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": this.config.loadCodeAssistUserAgent,
|
||||
"X-Goog-Api-Client": this.config.loadCodeAssistApiClient,
|
||||
"Client-Metadata": this.config.loadCodeAssistClientMetadata,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get metadata object for API calls
|
||||
*/
|
||||
getMetadata() {
|
||||
return {
|
||||
ideType: "IDE_UNSPECIFIED",
|
||||
platform: "PLATFORM_UNSPECIFIED",
|
||||
pluginType: "GEMINI",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch Project ID and Tier from loadCodeAssist API
|
||||
*/
|
||||
async loadCodeAssist(accessToken) {
|
||||
const response = await fetch(this.config.loadCodeAssistEndpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": this.config.loadCodeAssistUserAgent,
|
||||
"X-Goog-Api-Client": this.config.loadCodeAssistApiClient,
|
||||
"Client-Metadata": this.config.loadCodeAssistClientMetadata,
|
||||
},
|
||||
body: JSON.stringify(loadReqBody),
|
||||
headers: this.getApiHeaders(accessToken),
|
||||
body: JSON.stringify({ metadata: this.getMetadata() }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Failed to fetch project ID: ${errorText}`);
|
||||
throw new Error(`Failed to load code assist: ${errorText}`);
|
||||
}
|
||||
|
||||
const loadResp = await response.json();
|
||||
let projectId = loadResp.cloudaicompanionProject;
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Extract project ID
|
||||
let projectId = data.cloudaicompanionProject;
|
||||
if (typeof projectId === 'object' && projectId !== null && projectId.id) {
|
||||
projectId = projectId.id;
|
||||
}
|
||||
|
||||
// Extract tier ID (default to legacy-tier)
|
||||
let tierId = "legacy-tier";
|
||||
if (Array.isArray(data.allowedTiers)) {
|
||||
for (const tier of data.allowedTiers) {
|
||||
if (tier.isDefault && tier.id) {
|
||||
tierId = tier.id.trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { projectId, tierId, raw: data };
|
||||
}
|
||||
|
||||
/**
|
||||
* Onboard user to enable Gemini Code Assist for the project
|
||||
*/
|
||||
async onboardUser(accessToken, projectId, tierId) {
|
||||
const response = await fetch(this.config.onboardUserEndpoint, {
|
||||
method: "POST",
|
||||
headers: this.getApiHeaders(accessToken),
|
||||
body: JSON.stringify({
|
||||
tierId,
|
||||
metadata: this.getMetadata(),
|
||||
cloudaicompanionProject: projectId,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Failed to onboard user: ${errorText}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete onboarding flow with retry
|
||||
*/
|
||||
async completeOnboarding(accessToken, projectId, tierId, maxRetries = 10) {
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
const result = await this.onboardUser(accessToken, projectId, tierId);
|
||||
|
||||
if (result.done === true) {
|
||||
// Extract final project ID from response
|
||||
let finalProjectId = projectId;
|
||||
if (result.response?.cloudaicompanionProject) {
|
||||
const respProject = result.response.cloudaicompanionProject;
|
||||
if (typeof respProject === 'string') {
|
||||
finalProjectId = respProject.trim();
|
||||
} else if (respProject.id) {
|
||||
finalProjectId = respProject.id.trim();
|
||||
}
|
||||
}
|
||||
return { success: true, projectId: finalProjectId };
|
||||
}
|
||||
|
||||
// Wait 5 seconds before retry
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
}
|
||||
|
||||
throw new Error("Onboarding timeout - please try again");
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch Project ID from loadCodeAssist API (legacy method for compatibility)
|
||||
*/
|
||||
async fetchProjectId(accessToken) {
|
||||
const { projectId } = await this.loadCodeAssist(accessToken);
|
||||
if (!projectId) {
|
||||
throw new Error("No cloudaicompanionProject found in response");
|
||||
}
|
||||
|
||||
return projectId;
|
||||
}
|
||||
|
||||
@@ -218,17 +297,27 @@ export class AntigravityService {
|
||||
// Get user info
|
||||
const userInfo = await this.getUserInfo(tokens.access_token);
|
||||
|
||||
spinner.text = "Fetching Google Cloud Project ID...";
|
||||
spinner.text = "Loading Code Assist configuration...";
|
||||
|
||||
// Fetch Project ID
|
||||
const projectId = await this.fetchProjectId(tokens.access_token);
|
||||
// Load Code Assist to get project ID and tier
|
||||
const { projectId, tierId } = await this.loadCodeAssist(tokens.access_token);
|
||||
|
||||
if (!projectId) {
|
||||
throw new Error("No Google Cloud Project found. Please ensure you have a GCP project with Gemini Code Assist enabled.");
|
||||
}
|
||||
|
||||
spinner.text = "Onboarding to Gemini Code Assist...";
|
||||
|
||||
// Complete onboarding to enable Gemini Code Assist
|
||||
const onboardResult = await this.completeOnboarding(tokens.access_token, projectId, tierId);
|
||||
const finalProjectId = onboardResult.projectId || projectId;
|
||||
|
||||
spinner.text = "Saving tokens to server...";
|
||||
|
||||
// Save tokens to server
|
||||
await this.saveTokens(tokens, userInfo, projectId);
|
||||
await this.saveTokens(tokens, userInfo, finalProjectId);
|
||||
|
||||
spinner.succeed(`Antigravity connected successfully! (${userInfo.email}, Project: ${projectId})`);
|
||||
spinner.succeed(`Antigravity connected successfully! (${userInfo.email}, Project: ${finalProjectId})`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
spinner.fail(`Failed: ${error.message}`);
|
||||
|
||||
+23
-3
@@ -5,8 +5,12 @@ import os from "os";
|
||||
import fs from "fs";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const isCloud = typeof caches !== 'undefined' || typeof caches === 'object';
|
||||
|
||||
// Get app name from root package.json config
|
||||
function getAppName() {
|
||||
if (isCloud) return "9router"; // Skip file system access in Workers
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
// Look for root package.json (monorepo root)
|
||||
const rootPkgPath = path.resolve(__dirname, "../../../package.json");
|
||||
@@ -20,6 +24,8 @@ function getAppName() {
|
||||
|
||||
// Get user data directory based on platform
|
||||
function getUserDataDir() {
|
||||
if (isCloud) return "/tmp"; // Fallback for Workers
|
||||
|
||||
const platform = process.platform;
|
||||
const homeDir = os.homedir();
|
||||
const appName = getAppName();
|
||||
@@ -34,11 +40,11 @@ function getUserDataDir() {
|
||||
|
||||
// Data file path - stored in user home directory
|
||||
const DATA_DIR = getUserDataDir();
|
||||
const DB_FILE = path.join(DATA_DIR, "usage.json");
|
||||
const LOG_FILE = path.join(DATA_DIR, "log.txt");
|
||||
const DB_FILE = isCloud ? null : path.join(DATA_DIR, "usage.json");
|
||||
const LOG_FILE = isCloud ? null : path.join(DATA_DIR, "log.txt");
|
||||
|
||||
// Ensure data directory exists
|
||||
if (!fs.existsSync(DATA_DIR)) {
|
||||
if (!isCloud && !fs.existsSync(DATA_DIR)) {
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
@@ -83,6 +89,15 @@ export function trackPendingRequest(model, provider, connectionId, started) {
|
||||
* Get usage database instance (singleton)
|
||||
*/
|
||||
export async function getUsageDb() {
|
||||
if (isCloud) {
|
||||
// Return in-memory DB for Workers
|
||||
if (!dbInstance) {
|
||||
dbInstance = new Low({ read: async () => {}, write: async () => {} }, defaultData);
|
||||
dbInstance.data = defaultData;
|
||||
}
|
||||
return dbInstance;
|
||||
}
|
||||
|
||||
if (!dbInstance) {
|
||||
const adapter = new JSONFile(DB_FILE);
|
||||
dbInstance = new Low(adapter, defaultData);
|
||||
@@ -114,6 +129,8 @@ export async function getUsageDb() {
|
||||
* @param {object} entry - Usage entry { provider, model, tokens: { prompt_tokens, completion_tokens, ... }, connectionId? }
|
||||
*/
|
||||
export async function saveRequestUsage(entry) {
|
||||
if (isCloud) return; // Skip saving in Workers
|
||||
|
||||
try {
|
||||
const db = await getUsageDb();
|
||||
|
||||
@@ -187,6 +204,8 @@ function formatLogDate(date = new Date()) {
|
||||
* Format: datetime(dd-mm-yyyy h:m:s) | model | provider | account | tokens sent | tokens received | status
|
||||
*/
|
||||
export async function appendRequestLog({ model, provider, connectionId, tokens, status }) {
|
||||
if (isCloud) return; // Skip logging in Workers
|
||||
|
||||
try {
|
||||
const timestamp = formatLogDate();
|
||||
const p = provider?.toUpperCase() || "-";
|
||||
@@ -218,6 +237,7 @@ export async function appendRequestLog({ model, provider, connectionId, tokens,
|
||||
* Get last N lines of log.txt
|
||||
*/
|
||||
export async function getRecentLogs(limit = 200) {
|
||||
if (isCloud) return []; // Skip in Workers
|
||||
if (!fs.existsSync(LOG_FILE)) return [];
|
||||
try {
|
||||
const content = fs.readFileSync(LOG_FILE, "utf-8");
|
||||
|
||||
Reference in New Issue
Block a user