Files
Kelx/AgentWorker/provider-settings.js
T
2026-11-30 16:32:37 +00:00

106 lines
5.5 KiB
JavaScript

"use strict";
const fs = require("node:fs");
const dotenv = require("dotenv");
const { PANEL_ENV_PATH } = require("./feature-config");
const { getAiProviderConfig, normalizeAiSecretValue, normalizeOpenAiCompatibleBaseUrl } = require("./provider-config");
const { AgentRpcError } = require("./private-rpc");
const MAX_MANUAL_MODELS = 32;
const MAX_MANUAL_MODEL_BYTES = 4096;
function normalizeManualModelId(value) {
if (typeof value !== "string" || value.length > 255 || /[\u0000-\u001f\u007f-\u009f\u2028\u2029\p{Cs}]/u.test(value)) {
throw new AgentRpcError(400, "agent_invalid_manual_model");
}
return value.trim();
}
function normalizeManualModelIds(values) {
if (!Array.isArray(values) || values.length > MAX_MANUAL_MODELS) throw new AgentRpcError(400, "agent_invalid_manual_model");
const ids = [...new Set(Array.from(values, normalizeManualModelId).filter(Boolean))];
if (Buffer.byteLength(JSON.stringify(ids)) > MAX_MANUAL_MODEL_BYTES) throw new AgentRpcError(400, "agent_invalid_manual_model");
return ids;
}
function readManualModelIds(config, source, fallback) {
if (!config?.modelIdsEnv) return [];
const encoded = source[config.modelIdsEnv] ?? fallback[config.modelIdsEnv];
try {
if (encoded === undefined) return normalizeManualModelIds([source[config.modelEnv] ?? fallback[config.modelEnv] ?? ""]);
if (!encoded || encoded.length > Math.ceil(MAX_MANUAL_MODEL_BYTES * 4 / 3) || !/^[A-Za-z0-9_-]+$/.test(encoded)) return [];
return normalizeManualModelIds(JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")));
} catch { return []; }
}
function resolveProviderSettings(provider, source, fallback = {}) {
const config = getAiProviderConfig(provider);
const modelIds = readManualModelIds(config, source, fallback);
return {
apiKey: config?.keyEnv ? normalizeAiSecretValue(source[config.keyEnv] ?? fallback[config.keyEnv]) : "",
baseUrl: config?.baseUrlEnv ? normalizeAiSecretValue(source[config.baseUrlEnv] ?? fallback[config.baseUrlEnv]) : "",
modelIds,
modelId: modelIds[0] || "",
};
}
function readProviderSettings(provider) {
return resolveProviderSettings(provider, dotenv.parse(fs.readFileSync(PANEL_ENV_PATH)));
}
function normalizeAiProviderId(value) {
return String(value || "").trim().toLowerCase().slice(0, 64);
}
function sanitizeAiModelId(value) {
return normalizeAiSecretValue(value).slice(0, 255);
}
function assertAiProviderReady(provider, model, readSettings = readProviderSettings) {
const providerId = normalizeAiProviderId(provider);
const modelId = sanitizeAiModelId(model);
const config = getAiProviderConfig(providerId);
if (!config) throw Object.assign(new Error("invalid AI provider"), { status: 400 });
if (!modelId) throw Object.assign(new Error("model is required"), { status: 400 });
const settings = readSettings(providerId);
if (config.requiresKey !== false && !settings.apiKey) {
throw Object.assign(new Error("API key not configured for this provider"), { status: 400 });
}
if (config.requiresBaseUrl && !settings.baseUrl) {
throw Object.assign(new Error("Base URL not configured for this provider"), { status: 400 });
}
return { provider: providerId, model: modelId, settings };
}
function providerEnvUpdates(config, settings = {}) {
return Object.fromEntries([[config.keyEnv, settings.apiKey], [config.baseUrlEnv, settings.baseUrl],
[config.modelEnv, ""], [config.modelIdsEnv, settings.modelIds?.length && Buffer.from(JSON.stringify(settings.modelIds)).toString("base64url")],
].filter(([key]) => key).map(([key, value]) => [key, value || ""]));
}
async function prepareAgentProviderConnection(config, input, stored, discover) {
const baseUrl = config.requiresBaseUrl ? normalizeOpenAiCompatibleBaseUrl(normalizeAiSecretValue(input.baseUrl) || stored.baseUrl) : "";
if (config.requiresBaseUrl && !baseUrl) throw new Error("Please enter a valid Base URL.");
let reuseKey = !config.requiresBaseUrl;
if (baseUrl && stored.baseUrl) {
// adpanel:provider-key-origin - changing an API origin must not forward the previous provider's secret.
try { reuseKey = new URL(baseUrl).origin === new URL(stored.baseUrl).origin; } catch { }
}
const apiKey = normalizeAiSecretValue(input.key) || (reuseKey ? stored.apiKey || "" : "");
if (config.requiresKey !== false && !apiKey) throw new Error(`Please enter a valid ${config.name} API key.`);
const previousModels = stored.modelIds || (stored.modelId ? [stored.modelId] : []);
const modelIds = config.modelIdsEnv ? normalizeManualModelIds(input.modelIds !== undefined ? input.modelIds :
input.modelId !== undefined && previousModels.length <= 1 ? [input.modelId] : previousModels) : [];
const settings = { apiKey, baseUrl, modelIds, modelId: modelIds[0] || "" };
const modelToValidate = modelIds.find((model) => !previousModels.includes(model)) || modelIds[0];
const discovery = await discover({ ...settings, modelToValidate });
if (!Array.isArray(discovery?.models) || !discovery.models.length) throw new AgentRpcError(422, "agent_discovery_empty");
return { settings: { ...settings, baseUrl: discovery.resolvedBaseUrl || baseUrl }, models: discovery.models };
}
function formatAiMessageModelLabel(provider, model) {
return `${normalizeAiProviderId(provider)}:${sanitizeAiModelId(model)}`.slice(0, 255);
}
module.exports = { resolveProviderSettings, readProviderSettings, normalizeAiProviderId, sanitizeAiModelId, assertAiProviderReady, formatAiMessageModelLabel,
normalizeManualModelIds, providerEnvUpdates, prepareAgentProviderConnection };