2026-02-27 22:11:53 -05:00
|
|
|
import "open-sse/index.js";
|
|
|
|
|
|
2026-02-08 04:45:31 -05:00
|
|
|
import {
|
|
|
|
|
getProviderCredentials,
|
|
|
|
|
markAccountUnavailable,
|
|
|
|
|
clearAccountError,
|
|
|
|
|
extractApiKey,
|
|
|
|
|
isValidApiKey,
|
|
|
|
|
} from "../services/auth.js";
|
2026-03-25 05:57:26 -04:00
|
|
|
import { cacheClaudeHeaders } from "open-sse/utils/claudeHeaderCache.js";
|
2026-02-18 01:46:14 -05:00
|
|
|
import { getSettings } from "@/lib/localDb";
|
2026-01-04 21:58:59 -05:00
|
|
|
import { getModelInfo, getComboModels } from "../services/model.js";
|
|
|
|
|
import { handleChatCore } from "open-sse/handlers/chatCore.js";
|
2026-02-06 23:17:06 -05:00
|
|
|
import { errorResponse, unavailableResponse } from "open-sse/utils/error.js";
|
2026-01-04 21:58:59 -05:00
|
|
|
import { handleComboChat } from "open-sse/services/combo.js";
|
2026-03-12 05:20:46 -04:00
|
|
|
import { HTTP_STATUS } from "open-sse/config/runtimeConfig.js";
|
2026-03-01 03:35:41 -05:00
|
|
|
import { detectFormatByEndpoint } from "open-sse/translator/formats.js";
|
2026-01-04 21:58:59 -05:00
|
|
|
import * as log from "../utils/logger.js";
|
|
|
|
|
import { updateProviderCredentials, checkAndRefreshToken } from "../services/tokenRefresh.js";
|
2026-02-21 11:15:18 -05:00
|
|
|
import { getProjectIdForConnection } from "open-sse/services/projectId.js";
|
2026-01-04 21:58:59 -05:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Handle chat completion request
|
|
|
|
|
* Supports: OpenAI, Claude, Gemini, OpenAI Responses API formats
|
|
|
|
|
* Format detection and translation handled by translator
|
|
|
|
|
*/
|
|
|
|
|
export async function handleChat(request, clientRawRequest = null) {
|
|
|
|
|
let body;
|
|
|
|
|
try {
|
|
|
|
|
body = await request.json();
|
|
|
|
|
} catch {
|
|
|
|
|
log.warn("CHAT", "Invalid JSON body");
|
2026-02-06 23:17:06 -05:00
|
|
|
return errorResponse(HTTP_STATUS.BAD_REQUEST, "Invalid JSON body");
|
2026-01-04 21:58:59 -05:00
|
|
|
}
|
2026-02-24 23:40:50 -05:00
|
|
|
|
2026-01-04 21:58:59 -05:00
|
|
|
// Build clientRawRequest for logging (if not provided)
|
|
|
|
|
if (!clientRawRequest) {
|
|
|
|
|
const url = new URL(request.url);
|
|
|
|
|
clientRawRequest = {
|
|
|
|
|
endpoint: url.pathname,
|
|
|
|
|
body,
|
|
|
|
|
headers: Object.fromEntries(request.headers.entries())
|
|
|
|
|
};
|
|
|
|
|
}
|
2026-03-25 05:57:26 -04:00
|
|
|
cacheClaudeHeaders(clientRawRequest.headers);
|
2026-01-04 21:58:59 -05:00
|
|
|
|
2026-01-09 05:14:51 -05:00
|
|
|
// Log request endpoint and model
|
|
|
|
|
const url = new URL(request.url);
|
|
|
|
|
const modelStr = body.model;
|
2026-02-24 23:40:50 -05:00
|
|
|
|
2026-01-04 21:58:59 -05:00
|
|
|
// Count messages (support both messages[] and input[] formats)
|
|
|
|
|
const msgCount = body.messages?.length || body.input?.length || 0;
|
|
|
|
|
const toolCount = body.tools?.length || 0;
|
2026-02-05 21:44:41 -05:00
|
|
|
const effort = body.reasoning_effort || body.reasoning?.effort || null;
|
|
|
|
|
log.request("POST", `${url.pathname} | ${modelStr} | ${msgCount} msgs${toolCount ? ` | ${toolCount} tools` : ""}${effort ? ` | effort=${effort}` : ""}`);
|
2026-01-09 05:14:51 -05:00
|
|
|
|
|
|
|
|
// Log API key (masked)
|
2026-02-08 04:45:31 -05:00
|
|
|
const authHeader = request.headers.get("Authorization");
|
|
|
|
|
const apiKey = extractApiKey(request);
|
|
|
|
|
if (authHeader && apiKey) {
|
|
|
|
|
const masked = log.maskKey(apiKey);
|
2026-01-09 05:14:51 -05:00
|
|
|
log.debug("AUTH", `API Key: ${masked}`);
|
|
|
|
|
} else {
|
|
|
|
|
log.debug("AUTH", "No API key provided (local mode)");
|
|
|
|
|
}
|
2026-01-04 21:58:59 -05:00
|
|
|
|
2026-02-18 01:46:14 -05:00
|
|
|
// Enforce API key if enabled in settings
|
|
|
|
|
const settings = await getSettings();
|
|
|
|
|
if (settings.requireApiKey) {
|
2026-02-08 04:45:31 -05:00
|
|
|
if (!apiKey) {
|
2026-02-18 01:46:14 -05:00
|
|
|
log.warn("AUTH", "Missing API key (requireApiKey=true)");
|
2026-02-08 04:45:31 -05:00
|
|
|
return errorResponse(HTTP_STATUS.UNAUTHORIZED, "Missing API key");
|
|
|
|
|
}
|
|
|
|
|
const valid = await isValidApiKey(apiKey);
|
|
|
|
|
if (!valid) {
|
2026-02-18 01:46:14 -05:00
|
|
|
log.warn("AUTH", "Invalid API key (requireApiKey=true)");
|
2026-02-08 04:45:31 -05:00
|
|
|
return errorResponse(HTTP_STATUS.UNAUTHORIZED, "Invalid API key");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-04 21:58:59 -05:00
|
|
|
if (!modelStr) {
|
|
|
|
|
log.warn("CHAT", "Missing model");
|
2026-02-06 23:17:06 -05:00
|
|
|
return errorResponse(HTTP_STATUS.BAD_REQUEST, "Missing model");
|
2026-01-04 21:58:59 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if model is a combo (has multiple models with fallback)
|
|
|
|
|
const comboModels = await getComboModels(modelStr);
|
|
|
|
|
if (comboModels) {
|
2026-03-22 23:08:24 -04:00
|
|
|
// Check for combo-specific strategy first, fallback to global
|
|
|
|
|
const comboStrategies = settings.comboStrategies || {};
|
|
|
|
|
const comboSpecificStrategy = comboStrategies[modelStr]?.fallbackStrategy;
|
|
|
|
|
const comboStrategy = comboSpecificStrategy || settings.comboStrategy || "fallback";
|
|
|
|
|
|
2026-03-22 22:52:31 -04:00
|
|
|
log.info("CHAT", `Combo "${modelStr}" with ${comboModels.length} models (strategy: ${comboStrategy})`);
|
2026-01-04 21:58:59 -05:00
|
|
|
return handleComboChat({
|
|
|
|
|
body,
|
|
|
|
|
models: comboModels,
|
2026-02-11 03:44:08 -05:00
|
|
|
handleSingleModel: (b, m) => handleSingleModelChat(b, m, clientRawRequest, request, apiKey),
|
2026-03-22 22:52:31 -04:00
|
|
|
log,
|
|
|
|
|
comboName: modelStr,
|
|
|
|
|
comboStrategy
|
2026-01-04 21:58:59 -05:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Single model request
|
2026-02-11 03:44:08 -05:00
|
|
|
return handleSingleModelChat(body, modelStr, clientRawRequest, request, apiKey);
|
2026-01-04 21:58:59 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Handle single model chat request
|
|
|
|
|
*/
|
2026-02-11 03:44:08 -05:00
|
|
|
async function handleSingleModelChat(body, modelStr, clientRawRequest = null, request = null, apiKey = null) {
|
2026-01-04 21:58:59 -05:00
|
|
|
const modelInfo = await getModelInfo(modelStr);
|
2026-02-24 23:40:50 -05:00
|
|
|
|
|
|
|
|
// If provider is null, this might be a combo name - check and handle
|
2026-01-04 21:58:59 -05:00
|
|
|
if (!modelInfo.provider) {
|
2026-02-24 23:40:50 -05:00
|
|
|
const comboModels = await getComboModels(modelStr);
|
|
|
|
|
if (comboModels) {
|
2026-03-22 22:52:31 -04:00
|
|
|
const chatSettings = await getSettings();
|
2026-03-22 23:08:24 -04:00
|
|
|
// Check for combo-specific strategy first, fallback to global
|
|
|
|
|
const comboStrategies = chatSettings.comboStrategies || {};
|
|
|
|
|
const comboSpecificStrategy = comboStrategies[modelStr]?.fallbackStrategy;
|
|
|
|
|
const comboStrategy = comboSpecificStrategy || chatSettings.comboStrategy || "fallback";
|
|
|
|
|
|
2026-03-22 22:52:31 -04:00
|
|
|
log.info("CHAT", `Combo "${modelStr}" with ${comboModels.length} models (strategy: ${comboStrategy})`);
|
2026-02-24 23:40:50 -05:00
|
|
|
return handleComboChat({
|
|
|
|
|
body,
|
|
|
|
|
models: comboModels,
|
2026-03-13 22:37:29 -04:00
|
|
|
handleSingleModel: (b, m) => handleSingleModelChat(b, m, clientRawRequest, request, apiKey),
|
2026-03-22 22:52:31 -04:00
|
|
|
log,
|
|
|
|
|
comboName: modelStr,
|
|
|
|
|
comboStrategy
|
2026-02-24 23:40:50 -05:00
|
|
|
});
|
|
|
|
|
}
|
2026-01-04 21:58:59 -05:00
|
|
|
log.warn("CHAT", "Invalid model format", { model: modelStr });
|
2026-02-06 23:17:06 -05:00
|
|
|
return errorResponse(HTTP_STATUS.BAD_REQUEST, "Invalid model format");
|
2026-01-04 21:58:59 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const { provider, model } = modelInfo;
|
|
|
|
|
|
2026-01-09 05:14:51 -05:00
|
|
|
// Log model routing (alias → actual model)
|
|
|
|
|
if (modelStr !== `${provider}/${model}`) {
|
|
|
|
|
log.info("ROUTING", `${modelStr} → ${provider}/${model}`);
|
|
|
|
|
} else {
|
|
|
|
|
log.info("ROUTING", `Provider: ${provider}, Model: ${model}`);
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-14 03:42:38 -05:00
|
|
|
// Extract userAgent from request
|
|
|
|
|
const userAgent = request?.headers?.get("user-agent") || "";
|
|
|
|
|
|
2026-01-04 21:58:59 -05:00
|
|
|
// Try with available accounts (fallback on errors)
|
2026-03-13 22:37:29 -04:00
|
|
|
const excludeConnectionIds = new Set();
|
2026-01-04 21:58:59 -05:00
|
|
|
let lastError = null;
|
2026-02-06 23:17:06 -05:00
|
|
|
let lastStatus = null;
|
2026-01-04 21:58:59 -05:00
|
|
|
|
|
|
|
|
while (true) {
|
2026-03-13 22:37:29 -04:00
|
|
|
const credentials = await getProviderCredentials(provider, excludeConnectionIds, model);
|
2026-02-06 23:17:06 -05:00
|
|
|
|
|
|
|
|
// All accounts unavailable
|
|
|
|
|
if (!credentials || credentials.allRateLimited) {
|
|
|
|
|
if (credentials?.allRateLimited) {
|
|
|
|
|
const errorMsg = lastError || credentials.lastError || "Unavailable";
|
|
|
|
|
const status = lastStatus || Number(credentials.lastErrorCode) || HTTP_STATUS.SERVICE_UNAVAILABLE;
|
|
|
|
|
log.warn("CHAT", `[${provider}/${model}] ${errorMsg} (${credentials.retryAfterHuman})`);
|
|
|
|
|
return unavailableResponse(status, `[${provider}/${model}] ${errorMsg}`, credentials.retryAfter, credentials.retryAfterHuman);
|
|
|
|
|
}
|
2026-03-13 22:37:29 -04:00
|
|
|
if (excludeConnectionIds.size === 0) {
|
2026-03-22 23:25:35 -04:00
|
|
|
log.warn("AUTH", `No active credentials for provider: ${provider}`);
|
|
|
|
|
return errorResponse(HTTP_STATUS.NOT_FOUND, `No active credentials for provider: ${provider}`);
|
2026-01-04 21:58:59 -05:00
|
|
|
}
|
|
|
|
|
log.warn("CHAT", "No more accounts available", { provider });
|
2026-02-06 23:17:06 -05:00
|
|
|
return errorResponse(lastStatus || HTTP_STATUS.SERVICE_UNAVAILABLE, lastError || "All accounts unavailable");
|
2026-01-04 21:58:59 -05:00
|
|
|
}
|
|
|
|
|
|
2026-01-09 05:14:51 -05:00
|
|
|
// Log account selection
|
2026-03-11 07:04:38 -04:00
|
|
|
log.info("AUTH", `\x1b[32mUsing ${provider} account: ${credentials.connectionName}\x1b[0m`);
|
2026-01-04 21:58:59 -05:00
|
|
|
|
|
|
|
|
const refreshedCredentials = await checkAndRefreshToken(provider, credentials);
|
2026-02-21 11:15:18 -05:00
|
|
|
|
|
|
|
|
// Ensure real project ID is available for providers that need it (P0 fix: cold miss)
|
|
|
|
|
if ((provider === "antigravity" || provider === "gemini-cli") && !refreshedCredentials.projectId) {
|
|
|
|
|
const pid = await getProjectIdForConnection(credentials.connectionId, refreshedCredentials.accessToken);
|
|
|
|
|
if (pid) {
|
|
|
|
|
refreshedCredentials.projectId = pid;
|
|
|
|
|
// Persist to DB in background so subsequent requests have it immediately
|
|
|
|
|
updateProviderCredentials(credentials.connectionId, { projectId: pid }).catch(() => { });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-04 21:58:59 -05:00
|
|
|
// Use shared chatCore
|
2026-03-12 22:41:40 -04:00
|
|
|
const chatSettings = await getSettings();
|
2026-01-04 21:58:59 -05:00
|
|
|
const result = await handleChatCore({
|
|
|
|
|
body: { ...body, model: `${provider}/${model}` },
|
|
|
|
|
modelInfo: { provider, model },
|
|
|
|
|
credentials: refreshedCredentials,
|
|
|
|
|
log,
|
|
|
|
|
clientRawRequest,
|
2026-01-06 09:44:14 -05:00
|
|
|
connectionId: credentials.connectionId,
|
2026-01-14 03:42:38 -05:00
|
|
|
userAgent,
|
2026-02-11 03:44:08 -05:00
|
|
|
apiKey,
|
2026-03-12 22:41:40 -04:00
|
|
|
ccFilterNaming: !!chatSettings.ccFilterNaming,
|
2026-03-01 06:40:55 -05:00
|
|
|
// Detect source format by endpoint + body
|
|
|
|
|
sourceFormatOverride: request?.url ? detectFormatByEndpoint(new URL(request.url).pathname, body) : null,
|
2026-01-04 21:58:59 -05:00
|
|
|
onCredentialsRefreshed: async (newCreds) => {
|
|
|
|
|
await updateProviderCredentials(credentials.connectionId, {
|
|
|
|
|
accessToken: newCreds.accessToken,
|
|
|
|
|
refreshToken: newCreds.refreshToken,
|
|
|
|
|
providerSpecificData: newCreds.providerSpecificData,
|
|
|
|
|
testStatus: "active"
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
onRequestSuccess: async () => {
|
2026-02-27 22:04:57 -05:00
|
|
|
await clearAccountError(credentials.connectionId, credentials, model);
|
2026-01-04 21:58:59 -05:00
|
|
|
}
|
|
|
|
|
});
|
2026-02-24 23:40:50 -05:00
|
|
|
|
2026-01-04 21:58:59 -05:00
|
|
|
if (result.success) return result.response;
|
|
|
|
|
|
2026-02-06 23:17:06 -05:00
|
|
|
// Mark account unavailable (auto-calculates cooldown with exponential backoff)
|
2026-02-14 23:35:13 -05:00
|
|
|
const { shouldFallback } = await markAccountUnavailable(credentials.connectionId, result.status, result.error, provider, model);
|
2026-02-24 23:40:50 -05:00
|
|
|
|
2026-01-04 21:58:59 -05:00
|
|
|
if (shouldFallback) {
|
2026-03-11 07:04:38 -04:00
|
|
|
log.warn("AUTH", `Account ${credentials.connectionName} unavailable (${result.status}), trying fallback`);
|
2026-03-13 22:37:29 -04:00
|
|
|
excludeConnectionIds.add(credentials.connectionId);
|
2026-01-04 21:58:59 -05:00
|
|
|
lastError = result.error;
|
2026-02-06 23:17:06 -05:00
|
|
|
lastStatus = result.status;
|
2026-01-04 21:58:59 -05:00
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result.response;
|
|
|
|
|
}
|
|
|
|
|
}
|