fix: 平台 type 放开校验;模型唯一键改为 平台名/模型id
- type 仅决定余额适配器,未知值合法(查不了余额而已),不再报非法 - 打平视图 cfg.models:id = 内部唯一键「平台名/模型id」(池/会话/用量/前端按它认模型,调用处字段名不变), mid = 发给上游的原始模型名(callModel body.model 用它) - 同平台内模型 id 必须唯一;不同平台允许同 id(旧版直接报错的问题) - 旧 models[] 迁移时平台名自动去重,避免唯一键碰撞 - 前端:卡片/编辑器展示 mid(原始名),编辑弹窗新增时按 平台+id 查重 - concurrency 仍仅解析记录,调度保持每模型 1 会话
This commit is contained in:
+98
-16
@@ -22,7 +22,7 @@ const DEFAULTS = {
|
||||
model_hold: { idle_release_ms: 180000, active_max_ms: 1800000, sweep_ms: 10000 },
|
||||
// 日志等级:debug < info < warn < error < none,只输出 >= 阈值等级的日志;none=全部静默。
|
||||
log_level: 'info',
|
||||
models: [],
|
||||
platforms: [],
|
||||
// 登录认证:{ users: [{user, password}], secret?, ttl_ms? },密码明文存配置(自用场景)。
|
||||
// users 为空则不启用认证(可交给前置 nginx-proxy,但手机浏览器原生下载不带 Basic 头,不推荐)。
|
||||
auth: null,
|
||||
@@ -43,23 +43,99 @@ function deepMerge(base, extra) {
|
||||
return out;
|
||||
}
|
||||
|
||||
function hostnameOf(url) {
|
||||
try { return new URL(url).hostname.split('.')[0]; } catch (_) { return ''; }
|
||||
}
|
||||
|
||||
// 旧版扁平 models[](每模型自带 url/api_key)自动迁移为 platforms 层级:同 url+api_key 归为同一平台同一 key。
|
||||
function migrateLegacyModels(models) {
|
||||
const groups = [];
|
||||
const byKey = new Map();
|
||||
for (const m of models) {
|
||||
if (!m || !m.id) continue;
|
||||
const url = String(m.url || '').replace(/\/+$/, '');
|
||||
const apiKey = String(m.api_key || '');
|
||||
const gk = url + '\n' + apiKey;
|
||||
let p = byKey.get(gk);
|
||||
if (!p) {
|
||||
// 平台名 = 主机名首段;同名(如只 path 不同)自动加序号,避免「平台名/模型id」唯一键碰撞。
|
||||
let name = hostnameOf(url) || ('p' + (groups.length + 1));
|
||||
for (let n = 2; groups.some(g => g.name === name); n++) name = (hostnameOf(url) || 'p') + '-' + n;
|
||||
p = { name, url, type: 'openai', keys: [{ api_key: apiKey, concurrency: 1, models: [] }] };
|
||||
byKey.set(gk, p);
|
||||
groups.push(p);
|
||||
}
|
||||
p.keys[0].models.push({ id: m.id, display_name: m.display_name || m.id, vision: m.vision === true });
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
// 规范化并校验 platforms 层级:平台(name/url/type) → keys(api_key/concurrency) → models(id/display_name/vision)。
|
||||
// 内部唯一键 = 平台名/模型id:不同平台允许同模型 id,同平台内必须唯一(会话/模型池/用量均按该键认模型);
|
||||
// 允许键/列表为空(便于页面增删)。
|
||||
function normalizePlatforms(rawPlatforms) {
|
||||
const seen = new Set(); // 已用唯一键(平台名/模型id)
|
||||
const out = [];
|
||||
for (let pi = 0; pi < rawPlatforms.length; pi++) {
|
||||
const p = rawPlatforms[pi] || {};
|
||||
if (!p.url) throw new Error('platforms[' + pi + '] 缺少 url(OpenAI 兼容 /v1 地址)');
|
||||
const url = String(p.url).replace(/\/+$/, '');
|
||||
const name = String(p.name || '').trim() || (hostnameOf(url) || ('p' + (pi + 1)));
|
||||
// type 决定余额查询适配器(预留);openai/deepseek/custom 之外也允许,只是查不了余额。
|
||||
const type = String(p.type || 'openai').trim();
|
||||
const keys = [];
|
||||
for (let ki = 0; ki < (p.keys || []).length; ki++) {
|
||||
const k = p.keys[ki] || {};
|
||||
const concurrency = Math.max(1, parseInt(k.concurrency, 10) || 1);
|
||||
const models = [];
|
||||
for (let mi = 0; mi < (k.models || []).length; mi++) {
|
||||
const m = k.models[mi] || {};
|
||||
if (!m || !m.id) throw new Error('平台「' + name + '」key#' + (ki + 1) + ' 的 models[' + mi + '] 缺少 id');
|
||||
const uid = name + '/' + String(m.id);
|
||||
if (seen.has(uid)) throw new Error('模型重复:平台「' + name + '」下已有模型 id:' + m.id + '(不同平台可同名,同平台内必须唯一)');
|
||||
seen.add(uid);
|
||||
models.push({
|
||||
id: String(m.id),
|
||||
display_name: m.display_name ? String(m.display_name) : String(m.id),
|
||||
vision: m.vision === true, // 支持时 read_file 读图会回传图片,会话上下文会告知 AI
|
||||
});
|
||||
}
|
||||
keys.push({ api_key: String(k.api_key || ''), concurrency, models });
|
||||
}
|
||||
out.push({ name, url, type, keys });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 校验原始配置文本(启动读文件与网页编辑共用)。configPath 仅记录来源,可为空。
|
||||
function parseAndValidate(rawText, configPath) {
|
||||
const raw = YAML.parse(rawText || '') || {};
|
||||
let raw = YAML.parse(rawText || '') || {};
|
||||
const cfg = deepMerge(DEFAULTS, raw);
|
||||
|
||||
if (!Array.isArray(cfg.models) || cfg.models.length === 0) {
|
||||
throw new Error('配置缺少 models:至少需要一个模型 {id, url, display_name}')
|
||||
// ---------- 模型配置:platforms 层级(platforms[].keys[].models[])----------
|
||||
// 旧版扁平 models[](每模型自带 url/api_key)自动迁移;cfg.models 为打平后的运行时视图,
|
||||
// 每项继承所属平台的 url/type 与 key 的 api_key/concurrency,并携带位置下标(前端 PATCH 定位用)。
|
||||
if ((!Array.isArray(raw.platforms) || !raw.platforms.length) && Array.isArray(raw.models) && raw.models.length) {
|
||||
raw = Object.assign({}, raw, { platforms: migrateLegacyModels(raw.models) });
|
||||
log.info('[config] 检测到旧配置 models[] 扁平格式,已自动迁移为 platforms 层级;建议改写 config.yml 为 platforms 格式');
|
||||
}
|
||||
// 每个模型独立配置上游:url 必填(OpenAI 兼容 /v1 地址),api_key 选填(留空则不带鉴权头)
|
||||
for (const m of cfg.models) {
|
||||
if (!m || !m.id) throw new Error('models 中每项必须有 id');
|
||||
if (!m.url) throw new Error('models.' + m.id + ' 缺少 url(每个模型独立配置上游 /v1 地址)');
|
||||
if (!m.display_name) m.display_name = m.id;
|
||||
m.url = String(m.url).replace(/\/+$/, '');
|
||||
m.api_key = m.api_key || '';
|
||||
// 模型是否支持 vision(图片内容回传);默认 false,会话上下文中会告知 AI
|
||||
m.vision = m.vision === true;
|
||||
if (!Array.isArray(raw.platforms) || !raw.platforms.length) {
|
||||
throw new Error('配置缺少 platforms:至少需要一个平台 {name, url, keys:[{api_key, models:[{id}]}]}')
|
||||
}
|
||||
cfg.platforms = normalizePlatforms(raw.platforms);
|
||||
cfg.models = [];
|
||||
cfg.platforms.forEach((p, pi) => p.keys.forEach((k, ki) => k.models.forEach((m, mi) => {
|
||||
cfg.models.push({
|
||||
// id = 内部唯一键「平台名/模型id」(池/会话/用量/前端均按它认模型,调用处无需区分);
|
||||
// mid = 发给上游的原始模型名(请求体 body.model 用它)。
|
||||
id: p.name + '/' + m.id, mid: m.id,
|
||||
display_name: m.display_name, vision: m.vision,
|
||||
url: p.url, api_key: k.api_key, platform: p.name, type: p.type, concurrency: k.concurrency,
|
||||
platform_index: pi, key_index: ki, model_index: mi,
|
||||
});
|
||||
})));
|
||||
if (!cfg.models.length) {
|
||||
throw new Error('platforms 下没有任何可用模型:keys[].models 至少需要一个 {id}')
|
||||
}
|
||||
|
||||
cfg.workspace_root = path.resolve(cfg.workspace_root);
|
||||
@@ -137,15 +213,21 @@ function readConfigText(cfg) {
|
||||
return fs.readFileSync(p, 'utf8');
|
||||
}
|
||||
|
||||
// 单项编辑:[{path:[...], value}] 或 [{path:[...], delete:true}]。
|
||||
// 用 YAML Document 写回,保留注释与排版;路径段为纯数字时按数组下标处理(如 ["models",0,"url"])。
|
||||
// 单项编辑:[{path:[...], value}] 或 [{path:[...], delete:true}] 或 [{path:[...], value, append:true}]。
|
||||
// 用 YAML Document 写回,保留注释与排版;路径段为纯数字时按数组下标处理(如 ["platforms",0,"keys",1,"models",0])。
|
||||
// append:向目标数组追加一项(新增平台/Key/模型用);目标不存在时创建新数组。
|
||||
function applyEditsToText(text, edits) {
|
||||
const doc = YAML.parseDocument(text || '');
|
||||
for (const e of edits || []) {
|
||||
if (!e || !Array.isArray(e.path) || !e.path.length) throw new Error('配置项 path 必须是非空数组');
|
||||
const docPath = e.path.map(s => (typeof s === 'string' && /^\d+$/.test(s)) ? Number(s) : s);
|
||||
if (e.delete) doc.deleteIn(docPath);
|
||||
else doc.setIn(docPath, e.value);
|
||||
else if (e.append) {
|
||||
const target = doc.getIn(docPath, true);
|
||||
if (target && typeof target.add === 'function') target.add(e.value);
|
||||
else if (target === null || target === undefined) doc.setIn(docPath, [e.value]);
|
||||
else throw new Error('配置项 ' + docPath.join('.') + ' 不是数组,无法追加');
|
||||
} else doc.setIn(docPath, e.value);
|
||||
}
|
||||
return doc.toString();
|
||||
}
|
||||
|
||||
+3
-2
@@ -108,11 +108,12 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
||||
if (opts.signal.aborted) controller.abort();
|
||||
else opts.signal.addEventListener('abort', () => controller.abort());
|
||||
}
|
||||
// modelId = 内部唯一键「平台名/模型id」;发给上游的模型名用 mid(原始 id)。
|
||||
const modelCfg = (cfg.models || []).find(m => m.id === modelId);
|
||||
if (!modelCfg || !modelCfg.url) throw new Error('模型未在配置中定义或缺少独立 url: ' + modelId);
|
||||
if (!modelCfg || !modelCfg.url) throw new Error('模型未在配置中定义或缺少 url: ' + modelId);
|
||||
|
||||
const body = {
|
||||
model: modelId,
|
||||
model: modelCfg.mid || modelCfg.id,
|
||||
messages,
|
||||
stream: true,
|
||||
stream_options: { include_usage: true },
|
||||
|
||||
@@ -243,10 +243,25 @@
|
||||
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
||||
</button>
|
||||
<h3 id="moe-title">编辑模型</h3>
|
||||
<select id="moe-target" style="width:100%"></select>
|
||||
<div id="moe-newkey-wrap" class="hidden">
|
||||
<select id="moe-nk-plat" style="width:100%"></select>
|
||||
<input type="text" id="moe-nk-key" placeholder="api_key(留空则不带鉴权头)" style="width:100%">
|
||||
<input type="number" id="moe-nk-con" min="1" step="1" value="1" placeholder="并发数 concurrency(默认 1)" style="width:100%">
|
||||
</div>
|
||||
<div id="moe-newplat-wrap" class="hidden">
|
||||
<input type="text" id="moe-np-name" placeholder="平台名称(留空取域名主机段)" style="width:100%">
|
||||
<input type="text" id="moe-np-url" placeholder="平台上游地址(OpenAI 兼容 /v1)" style="width:100%">
|
||||
<select id="moe-np-type" style="width:100%">
|
||||
<option value="openai">openai</option>
|
||||
<option value="deepseek">deepseek</option>
|
||||
<option value="custom">custom</option>
|
||||
</select>
|
||||
<input type="text" id="moe-np-key" placeholder="api_key(留空则不带鉴权头)" style="width:100%">
|
||||
<input type="number" id="moe-np-con" min="1" step="1" value="1" placeholder="并发数 concurrency(默认 1)" style="width:100%">
|
||||
</div>
|
||||
<input type="text" id="moe-name" placeholder="显示名(留空同 id)" style="width:100%">
|
||||
<input type="text" id="moe-id" placeholder="id(唯一标识)" style="width:100%">
|
||||
<input type="text" id="moe-url" placeholder="上游地址(OpenAI 兼容 /v1)" style="width:100%">
|
||||
<input type="text" id="moe-key" placeholder="api_key(留空则不带鉴权头)" style="width:100%">
|
||||
<input type="text" id="moe-id" placeholder="id(上游模型名,全局唯一)" style="width:100%">
|
||||
<label class="del-dir"><input type="checkbox" id="moe-vision">支持图片输入(vision)</label>
|
||||
<div class="btn-row">
|
||||
<button class="ghost-btn danger hidden" id="moe-del-btn" onclick="modelsUI.del()">删除</button>
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
// 模型 Tab(阶段 5):模型池状态 + 增 / 改 / 删(仅写 config.yml,到「设置」页重启才生效)。
|
||||
// 卡片默认只展示:名称 / id / 运行状态 + 余额占位 + 今日/累计 token 用量(model_usage 表统计)。
|
||||
// 编辑走统一弹窗(新增复用同一弹窗);id 不可页面修改(会话按 id 绑定,改 id 走配置文件原文)。
|
||||
// 模型 Tab(阶段 5):模型池状态 + 模型增 / 改 / 删(仅写 config.yml,到「设置」页重启才生效)。
|
||||
// 配置为 platforms 层级(平台 → Key → 模型):url/type 在平台层,api_key/concurrency 在 Key 层,
|
||||
// 模型项只有 {id, display_name, vision};id 只需同平台内唯一(内部唯一键 = 平台名/模型id,
|
||||
// effective.models 的 id 即该键、mid 为原始模型名)。页面 PATCH 用 platforms[i].keys[j].models[k] 嵌套下标定位;
|
||||
// 新增一律走 append(只动目标数组,脱敏 key 绝不整体回写文件);已有 Key 的 api_key 修改请走配置原文编辑器。
|
||||
'use strict';
|
||||
|
||||
window.tabModules = window.tabModules || {};
|
||||
|
||||
let cfgModels = []; // 配置里的模型数组(下标即 PATCH 下标)
|
||||
let cfgPlatforms = []; // effective.platforms(服务端已对 api_key 脱敏)
|
||||
let cfgModels = []; // 打平后的 effective.models(含 platform_index/key_index/model_index)
|
||||
let runtimeById = {}; // 运行池状态,按 id 关联
|
||||
let modelsPendingRestart = false;
|
||||
let moeIdx = -1; // 当前编辑弹窗对应的下标;-1 = 新增
|
||||
let moeOrigKey = ''; // 打开编辑弹窗时的原始 api_key;未改动(显示仍含***)则保留原值
|
||||
let moeIdx = -1; // 当前编辑弹窗对应的打平下标;-1 = 新增
|
||||
|
||||
// api_key 脱敏显示:sk-***1234 样式。含 *** 作为「未改动」哨兵,保存时据此还原原 key。
|
||||
// api_key 脱敏显示:sk-***1234 样式。后端 GET effective 已脱敏,这里仅兜底(幂等)。
|
||||
function maskKey(k) {
|
||||
k = k || '';
|
||||
if (k.includes('***')) return k;
|
||||
if (k.length > 8) return k.slice(0, 3) + '***' + k.slice(-4);
|
||||
if (k.length > 0) return '***' + k.slice(-2);
|
||||
return '';
|
||||
@@ -36,6 +39,7 @@ async function loadModelCards() {
|
||||
const [rt, cg] = await Promise.all([req('GET', '/api/models'), req('GET', '/api/config')]);
|
||||
runtimeById = {};
|
||||
for (const m of rt || []) runtimeById[m.id] = m;
|
||||
cfgPlatforms = (cg.effective && cg.effective.platforms) || [];
|
||||
cfgModels = (cg.effective && cg.effective.models) || [];
|
||||
if (!cfgModels.length) {
|
||||
el.innerHTML = '<div class="empty-tip">尚未配置模型,点右上角 + 添加。</div>';
|
||||
@@ -49,10 +53,10 @@ async function loadModelCards() {
|
||||
: '<span class="model-card-state pending">待重启</span>';
|
||||
return '<div class="model-card">' +
|
||||
'<div class="model-card-head">' +
|
||||
'<span class="model-card-name" title="点击编辑" onclick="modelsUI.openEdit(\'' + encodeURIComponent(m.id) + '\')">' + esc(m.display_name || m.id) + '</span>' +
|
||||
'<span class="model-card-name" title="点击编辑" onclick="modelsUI.openEdit(\'' + encodeURIComponent(m.id) + '\')">' + esc(m.display_name || m.mid || m.id) + '</span>' +
|
||||
stateHtml +
|
||||
'</div>' +
|
||||
'<div class="model-card-meta">' + esc(m.id) +
|
||||
'<div class="model-card-meta">' + esc(m.mid || m.id) + ' · 平台 ' + esc(m.platform || '') +
|
||||
(run && run.is_busy && run.current_session_id ? ' · 会话 ' + esc(run.current_session_id) : '') + '</div>' +
|
||||
'<div class="cfg-kv"><label>余额</label><b>--</b></div>' +
|
||||
// token 紧凑显示:输入 / 输出
|
||||
@@ -79,50 +83,107 @@ function afterWrite() {
|
||||
}
|
||||
|
||||
// ---------- 编辑/新增弹窗 ----------
|
||||
// Key 标签:「平台名 · sk-***1234」;下拉里用它标识可挂模型的目标 Key。
|
||||
function keyLabel(pi, ki) {
|
||||
const p = cfgPlatforms[pi] || {};
|
||||
const k = (p.keys || [])[ki] || {};
|
||||
return (p.name || ('平台' + pi)) + ' · ' + (k.api_key ? maskKey(k.api_key) : '无 key');
|
||||
}
|
||||
|
||||
function targetOptions() {
|
||||
let html = '';
|
||||
cfgPlatforms.forEach((p, pi) => (p.keys || []).forEach((k, ki) => {
|
||||
html += '<option value="exist:' + pi + ':' + ki + '">' +
|
||||
esc(keyLabel(pi, ki)) + '(' + ((k.models || []).length) + ' 模型)</option>';
|
||||
}));
|
||||
html += '<option value="newkey">+ 在已有平台下新增 Key</option>';
|
||||
html += '<option value="newplat">+ 新增平台</option>';
|
||||
return html;
|
||||
}
|
||||
|
||||
// 切换「新增 Key / 新增平台」时显隐对应字段。
|
||||
function onTargetChange() {
|
||||
const t = $('moe-target').value || '';
|
||||
$('moe-newkey-wrap').classList.toggle('hidden', t !== 'newkey');
|
||||
$('moe-newplat-wrap').classList.toggle('hidden', t !== 'newplat');
|
||||
}
|
||||
|
||||
function fillNewKeyPlatforms() {
|
||||
$('moe-nk-plat').innerHTML = cfgPlatforms.map((p, i) =>
|
||||
'<option value="' + i + '">' + esc(p.name || ('平台' + i)) + '</option>').join('');
|
||||
}
|
||||
|
||||
function openModelEditor(rawId) {
|
||||
const add = rawId == null;
|
||||
moeIdx = add ? -1 : idxOf(decodeURIComponent(rawId));
|
||||
if (!add && moeIdx < 0) return toast('模型不存在');
|
||||
const m = add ? { display_name: '', id: '', url: '', api_key: '', vision: false } : cfgModels[moeIdx];
|
||||
const m = add ? null : cfgModels[moeIdx];
|
||||
$('moe-title').textContent = add ? '添加模型' : '编辑模型';
|
||||
$('moe-name').value = m.display_name || '';
|
||||
const idIn = $('moe-id');
|
||||
idIn.value = m.id || '';
|
||||
idIn.disabled = !add; // 编辑时禁改 id(历史会话按 id 绑定)
|
||||
$('moe-url').value = m.url || '';
|
||||
moeOrigKey = m.api_key || '';
|
||||
const keyIn = $('moe-key');
|
||||
keyIn.value = maskKey(moeOrigKey);
|
||||
keyIn.placeholder = add ? 'sk-...' : '不改则保留原 key(清空将保存为空)';
|
||||
$('moe-vision').checked = !!m.vision;
|
||||
idIn.value = m ? (m.mid || m.id) : '';
|
||||
idIn.disabled = !add; // 编辑时禁改 id(历史会话按「平台名/模型id」绑定,改 id 等于换模型)
|
||||
$('moe-name').value = m ? (m.display_name || '') : '';
|
||||
$('moe-vision').checked = m ? !!m.vision : false;
|
||||
const tgt = $('moe-target');
|
||||
if (add) {
|
||||
tgt.disabled = false;
|
||||
tgt.innerHTML = targetOptions();
|
||||
fillNewKeyPlatforms();
|
||||
} else {
|
||||
// 编辑时锁定目标为本模型所属 Key(移动模型 = 删除后重建,不支持就地挪)
|
||||
tgt.innerHTML = '<option value="exist:' + m.platform_index + ':' + m.key_index + '">' + esc(keyLabel(m.platform_index, m.key_index)) + '</option>';
|
||||
tgt.disabled = true;
|
||||
}
|
||||
tgt.onchange = onTargetChange;
|
||||
onTargetChange(); // add 模式默认 exist → 两组附加字段都隐藏
|
||||
$('moe-del-btn').classList.toggle('hidden', add);
|
||||
$('model-edit-modal').classList.remove('hidden');
|
||||
}
|
||||
function closeModelEditor() { $('model-edit-modal').classList.add('hidden'); }
|
||||
|
||||
async function saveModelEditor() {
|
||||
const add = moeIdx < 0;
|
||||
const id = $('moe-id').value.trim();
|
||||
const url = $('moe-url').value.trim().replace(/\/+$/, '');
|
||||
if (!id) return toast('请填写 id');
|
||||
if (!url) return toast('请填写上游地址');
|
||||
// 显示值含 *** = 未改动,还原原 key;否则按用户输入(支持改为新 key 或清空)
|
||||
const keyVal = $('moe-key').value.trim();
|
||||
const api_key = keyVal.includes('***') ? moeOrigKey : keyVal;
|
||||
const obj = {
|
||||
// 模型项本身只含 id/display_name/vision;url/key/concurrency 在平台/Key 层,这里不动。
|
||||
const model = {
|
||||
id,
|
||||
display_name: $('moe-name').value.trim() || id,
|
||||
url,
|
||||
api_key,
|
||||
vision: $('moe-vision').checked,
|
||||
};
|
||||
const add = moeIdx < 0;
|
||||
let body;
|
||||
if (add) {
|
||||
if (idxOf(id) >= 0) return toast('id 已存在:' + id);
|
||||
body = { path: 'models', value: cfgModels.concat([obj]) };
|
||||
if (!add) {
|
||||
// 编辑:精确改到 platforms[pi].keys[ki].models[mi]
|
||||
const m = cfgModels[moeIdx];
|
||||
body = { path: ['platforms', m.platform_index, 'keys', m.key_index, 'models', m.model_index], value: model };
|
||||
} else {
|
||||
// 整项替换;key 顺序固定,保持配置文件观感一致
|
||||
body = { path: ['models', moeIdx], value: obj };
|
||||
const t = $('moe-target').value;
|
||||
// id 唯一性只看同平台(内部键 = 平台名/模型id);不同平台可同名。
|
||||
let platName = '';
|
||||
if (t === 'newkey') platName = (cfgPlatforms[parseInt($('moe-nk-plat').value, 10)] || {}).name || '';
|
||||
else if (t.indexOf('exist:') === 0) platName = (cfgPlatforms[Number(t.split(':')[1])] || {}).name || '';
|
||||
if (platName && cfgModels.some(x => x.platform === platName && x.mid === id)) return toast('平台「' + platName + '」下已有模型 id:' + id);
|
||||
if (t === 'newplat') {
|
||||
const url = $('moe-np-url').value.trim().replace(/\/+$/, '');
|
||||
if (!url) return toast('请填写平台上游地址');
|
||||
// append 一整个新平台:含一个新 Key + 这个模型;key 明文只在此时输入一次。
|
||||
body = { op: 'append', path: ['platforms'], value: {
|
||||
name: $('moe-np-name').value.trim(),
|
||||
url,
|
||||
type: $('moe-np-type').value || 'openai',
|
||||
keys: [{ api_key: $('moe-np-key').value.trim(), concurrency: parseInt($('moe-np-con').value, 10) || 1, models: [model] }],
|
||||
} };
|
||||
} else if (t === 'newkey') {
|
||||
const pi = parseInt($('moe-nk-plat').value, 10);
|
||||
if (!(pi >= 0)) return toast('请选择平台');
|
||||
// append 一个新 Key 到已有平台;模型挂在它下面。
|
||||
body = { op: 'append', path: ['platforms', pi, 'keys'], value: {
|
||||
api_key: $('moe-nk-key').value.trim(), concurrency: parseInt($('moe-nk-con').value, 10) || 1, models: [model] } };
|
||||
} else {
|
||||
// exist:pi:ki → append 模型到已有 Key 的 models 数组
|
||||
const parts = t.split(':');
|
||||
body = { op: 'append', path: ['platforms', Number(parts[1]), 'keys', Number(parts[2]), 'models'], value: model };
|
||||
}
|
||||
}
|
||||
try {
|
||||
await req('PATCH', '/api/config', body);
|
||||
@@ -136,10 +197,11 @@ async function delModelFromModal() {
|
||||
const m = cfgModels[moeIdx];
|
||||
closeModelEditor();
|
||||
if (cfgModels.length <= 1) return toast('至少要保留一个模型');
|
||||
const ok = await confirmModal('删除模型', '删除模型「' + (m.display_name || m.id) + '」?将整体重写 models 段(注释可能丢失)。', '删除', true);
|
||||
const ok = await confirmModal('删除模型', '删除模型「' + (m.display_name || m.id) + '」?将从 platforms 中移除该模型项。', '删除', true);
|
||||
if (!ok) return;
|
||||
try {
|
||||
await req('PATCH', '/api/config', { path: 'models', value: cfgModels.filter(x => x.id !== m.id) });
|
||||
// delete 到 platforms[pi].keys[ki].models[mi];YAML 数组删项会自动收紧,不影响其他行注释。
|
||||
await req('PATCH', '/api/config', { path: ['platforms', m.platform_index, 'keys', m.key_index, 'models', m.model_index], op: 'delete' });
|
||||
afterWrite();
|
||||
} catch (e) { toast('删除失败:' + e.message); }
|
||||
}
|
||||
@@ -150,6 +212,7 @@ window.modelsUI = {
|
||||
close: closeModelEditor,
|
||||
save: saveModelEditor,
|
||||
del: delModelFromModal,
|
||||
onTargetChange: onTargetChange,
|
||||
};
|
||||
|
||||
tabModules.models = {
|
||||
|
||||
@@ -43,10 +43,10 @@ function maskKey(k) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// 逐行掩码 config.yml 原文里的 api_key 值(设置页原文编辑器展示用)。
|
||||
// 行格式如 ` api_key: sk-xxx` 或 ` api_key: "sk-xxx"`(双/单引号)。
|
||||
// 逐行掩码配置原文里的 api_key 值(设置页原文编辑器展示用)。
|
||||
// 行格式如 ` api_key: sk-xxx` / ` api_key: "sk-xxx"` / ` - api_key: sk-xxx`(platforms.keys 列表项写法)。
|
||||
// 记录每行是否掩码,便于 restore 时按顺序还原未改动项。
|
||||
const API_KEY_LINE = /^(\s*api_key:\s*)(["']?)(.+?)\2\s*$/;
|
||||
const API_KEY_LINE = /^(\s*(?:-\s+)?api_key:\s*)(["']?)(.+?)\2\s*$/;
|
||||
function maskApiKeys(text) {
|
||||
if (!text) return text;
|
||||
return text.split('\n').map(function (line) {
|
||||
@@ -76,13 +76,23 @@ function restoreApiKeys(submitted, orig) {
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
// 生效配置的脱敏副本:api_key 在前端仅展示用(模型卡片/Key 下拉标签),真值不会回写文件。
|
||||
function maskEffective(cfg) {
|
||||
const c = Object.assign({}, cfg);
|
||||
c.platforms = (cfg.platforms || []).map(p => Object.assign({}, p, {
|
||||
keys: (p.keys || []).map(k => Object.assign({}, k, { api_key: maskKey(k.api_key) })),
|
||||
}));
|
||||
c.models = (cfg.models || []).map(m => Object.assign({}, m, { api_key: maskKey(m.api_key) }));
|
||||
return c;
|
||||
}
|
||||
|
||||
// 配置原文 + 路径 + 当前生效配置(设置页表单显示当前值;注释原样保留)
|
||||
// GET 返回的原文对 models[].api_key 脱敏(避免明文外显);PUT/validate 时按顺序还原。
|
||||
// GET 返回的原文与生效配置均对 api_key 脱敏;PUT/validate 时按顺序还原。
|
||||
router.get('/', wrap((req, res) => {
|
||||
const cfg = cfgOf();
|
||||
const text = readConfigText(cfg);
|
||||
const shown = text === null ? '' : maskApiKeys(text);
|
||||
res.json({ config_path: cfg.config_path || '', exists: text !== null, text: shown, effective: cfg });
|
||||
res.json({ config_path: cfg.config_path || '', exists: text !== null, text: shown, effective: maskEffective(cfg) });
|
||||
}));
|
||||
|
||||
// 干跑校验(编辑器保存前预检):body { text }
|
||||
@@ -115,8 +125,9 @@ router.put('/', wrap((req, res) => {
|
||||
res.json({ ok: true, changed: diffTop(cfg, next), restart_required: true });
|
||||
}));
|
||||
|
||||
// 单项修改:body { path: "agent.temperature" | ["models",0,"url"], value, op?: "delete" }
|
||||
// 用 YAML Document 写回,保留文件注释与排版;数组可整体替换,也可按数字下标改元素。
|
||||
// 单项修改:body { path: "agent.temperature" | ["platforms",0,"keys",0,"models",1], value, op?: "delete"|"append" }
|
||||
// 用 YAML Document 写回,保留文件注释与排版;数组可整体替换,可按数字下标改/删元素,
|
||||
// 也可 append 向数组追加一项(新增平台/Key/模型;前端只持有脱敏 key,绝不能整体替换含 key 的数组)。
|
||||
router.patch('/', wrap((req, res) => {
|
||||
const cfg = cfgOf();
|
||||
const text = readConfigText(cfg);
|
||||
@@ -129,7 +140,7 @@ router.patch('/', wrap((req, res) => {
|
||||
if (!pathArr.length) return badRequest(res, new Error('body.path 为空'));
|
||||
let nextText;
|
||||
try {
|
||||
nextText = applyEditsToText(text, [{ path: pathArr, value: body.value, delete: body.op === 'delete' }]);
|
||||
nextText = applyEditsToText(text, [{ path: pathArr, value: body.value, delete: body.op === 'delete', append: body.op === 'append' }]);
|
||||
} catch (e) { return badRequest(res, e); }
|
||||
let next;
|
||||
try { next = loadConfigFromText(nextText, cfg.config_path); } catch (e) { return badRequest(res, e); }
|
||||
|
||||
Reference in New Issue
Block a user