fix: 平台 type 放开校验;模型唯一键改为 平台名/模型id

- type 仅决定余额适配器,未知值合法(查不了余额而已),不再报非法
- 打平视图 cfg.models:id = 内部唯一键「平台名/模型id」(池/会话/用量/前端按它认模型,调用处字段名不变),
  mid = 发给上游的原始模型名(callModel body.model 用它)
- 同平台内模型 id 必须唯一;不同平台允许同 id(旧版直接报错的问题)
- 旧 models[] 迁移时平台名自动去重,避免唯一键碰撞
- 前端:卡片/编辑器展示 mid(原始名),编辑弹窗新增时按 平台+id 查重
- concurrency 仍仅解析记录,调度保持每模型 1 会话
This commit is contained in:
2026-09-02 23:09:04 +08:00
parent 7e046e5bbe
commit e3bfe0a1d5
9 changed files with 302 additions and 99 deletions
+17 -9
View File
@@ -809,19 +809,27 @@ networks:
## 十四、配置文件示例 ## 十四、配置文件示例
```yaml ```yaml
models: # 模型池:平台(platforms) → Key → 模型 三层。url/type 配在平台,api_key/concurrency 配在 Key,
# 模型只声明 {id, display_name, vision}。加载时打平成全局模型列表。
platforms:
- name: proxy-a
url: "https://proxy-a.example.com/v1"
type: openai # openai/deepseek/custom,决定余额查询适配器(预留)
keys:
- api_key: "sk-..."
concurrency: 1 # 该 Key 并发会话数,默认 1(当前仅记录,未参与调度)
models:
- id: ds1 - id: ds1
display_name: "AMD DeepSeek 1" display_name: "AMD DeepSeek 1"
url: "https://proxy-a.example.com/v1" # vision: true # 选填,默认 false
api_key: "sk-..." - name: proxy-c
- id: ds2 url: "https://proxy-c.example.com/v1"
display_name: "AMD DeepSeek 2" type: custom
url: "https://proxy-b.example.com/v1" keys:
api_key: "sk-..." - api_key: "sk-..."
models:
- id: ds3 - id: ds3
display_name: "AMD DeepSeek 3" display_name: "AMD DeepSeek 3"
url: "https://proxy-c.example.com/v1"
api_key: "sk-..."
workspace_root: "/workspace/tasks" workspace_root: "/workspace/tasks"
+22 -10
View File
@@ -1,22 +1,34 @@
# 自用通用 Agent 系统配置示例 # 自用通用 Agent 系统配置示例
# 复制为 config.yml 后按需修改;容器内通过 AGENT_CONFIG 指定路径。 # 复制为 config.yml 后按需修改;容器内通过 AGENT_CONFIG 指定路径。
# 模型池:每个模型独立配置上游 url 与 api_key(互不共用,可指向不同代理/账号)。 # 模型池:平台(platforms) → Key → 模型 三层层级。url/type 配在平台,api_key/concurrency 配在 Key,
# 同时活跃会话数上限 = 模型数量。 # 模型只声明 {id, display_name, vision}。加载时自动打平成全局模型列表。
models: # 暂按每模型 1 会话调度;concurrency 已解析入库,多会话并发后续再接调度。
- id: ds1 platforms:
display_name: "AMD DeepSeek 1" - name: proxy-a # 平台名;留空取 url 主机名首段。注意:它是模型唯一键的一部分,改名等于重建其下所有模型(历史会话回绑失效、用量统计分家)
url: "https://proxy-a.example.com/v1" # 独立的 OpenAI 兼容 /v1 地址 url: "https://proxy-a.example.com/v1" # OpenAI 兼容 /v1 地址,该平台下所有模型共用
api_key: "sk-..." # 各模型可不同,留空则不带鉴权头 type: openai # openai/deepseek/custom,决定余额查询适配器(预留)
keys:
- api_key: "sk-..." # 各 Key 独立(同平台不同账号/额度),留空则不带鉴权头
concurrency: 1 # 该 Key 并发会话数,默认 1(当前仅记录,未参与调度)
models:
- id: ds1 # 上游模型名;只需同平台内唯一(不同平台可同名),内部唯一键 = 平台名/模型id,历史会话按它绑定,页面不可改
display_name: "AMD DeepSeek 1" # 显示名,缺省同 id
# vision: true # 选填,默认 false;支持时 read_file 读图会压缩回传(长边≤2000px JPEG),会话上下文会告知 AI # vision: true # 选填,默认 false;支持时 read_file 读图会压缩回传(长边≤2000px JPEG),会话上下文会告知 AI
- id: ds2 - id: ds2
display_name: "AMD DeepSeek 2" display_name: "AMD DeepSeek 2"
url: "https://proxy-b.example.com/v1" - api_key: "sk-..." # 同平台的第二个 Key
api_key: "sk-..." models:
- id: ds3 - id: ds3
display_name: "AMD DeepSeek 3" display_name: "AMD DeepSeek 3"
- name: proxy-c
url: "https://proxy-c.example.com/v1" url: "https://proxy-c.example.com/v1"
api_key: "" type: custom
keys:
- api_key: ""
models:
- id: ds4
display_name: "No Auth Model"
workspace_root: "./data/tasks" workspace_root: "./data/tasks"
# db_path: "/data/.agent.db" # db_path: "/data/.agent.db"
+98 -16
View File
@@ -22,7 +22,7 @@ const DEFAULTS = {
model_hold: { idle_release_ms: 180000, active_max_ms: 1800000, sweep_ms: 10000 }, model_hold: { idle_release_ms: 180000, active_max_ms: 1800000, sweep_ms: 10000 },
// 日志等级:debug < info < warn < error < none,只输出 >= 阈值等级的日志;none=全部静默。 // 日志等级:debug < info < warn < error < none,只输出 >= 阈值等级的日志;none=全部静默。
log_level: 'info', log_level: 'info',
models: [], platforms: [],
// 登录认证:{ users: [{user, password}], secret?, ttl_ms? },密码明文存配置(自用场景)。 // 登录认证:{ users: [{user, password}], secret?, ttl_ms? },密码明文存配置(自用场景)。
// users 为空则不启用认证(可交给前置 nginx-proxy,但手机浏览器原生下载不带 Basic 头,不推荐)。 // users 为空则不启用认证(可交给前置 nginx-proxy,但手机浏览器原生下载不带 Basic 头,不推荐)。
auth: null, auth: null,
@@ -43,23 +43,99 @@ function deepMerge(base, extra) {
return out; 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 仅记录来源,可为空。 // 校验原始配置文本(启动读文件与网页编辑共用)。configPath 仅记录来源,可为空。
function parseAndValidate(rawText, configPath) { function parseAndValidate(rawText, configPath) {
const raw = YAML.parse(rawText || '') || {}; let raw = YAML.parse(rawText || '') || {};
const cfg = deepMerge(DEFAULTS, raw); const cfg = deepMerge(DEFAULTS, raw);
if (!Array.isArray(cfg.models) || cfg.models.length === 0) { // ---------- 模型配置:platforms 层级(platforms[].keys[].models[])----------
throw new Error('配置缺少 models:至少需要一个模型 {id, url, display_name}') // 旧版扁平 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 选填(留空则不带鉴权头) if (!Array.isArray(raw.platforms) || !raw.platforms.length) {
for (const m of cfg.models) { throw new Error('配置缺少 platforms:至少需要一个平台 {name, url, keys:[{api_key, models:[{id}]}]}')
if (!m || !m.id) throw new Error('models 中每项必须有 id'); }
if (!m.url) throw new Error('models.' + m.id + ' 缺少 url(每个模型独立配置上游 /v1 地址)'); cfg.platforms = normalizePlatforms(raw.platforms);
if (!m.display_name) m.display_name = m.id; cfg.models = [];
m.url = String(m.url).replace(/\/+$/, ''); cfg.platforms.forEach((p, pi) => p.keys.forEach((k, ki) => k.models.forEach((m, mi) => {
m.api_key = m.api_key || ''; cfg.models.push({
// 模型是否支持 vision(图片内容回传);默认 false,会话上下文中会告知 AI // id = 内部唯一键「平台名/模型id」(池/会话/用量/前端均按它认模型,调用处无需区分);
m.vision = m.vision === true; // 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); cfg.workspace_root = path.resolve(cfg.workspace_root);
@@ -137,15 +213,21 @@ function readConfigText(cfg) {
return fs.readFileSync(p, 'utf8'); return fs.readFileSync(p, 'utf8');
} }
// 单项编辑:[{path:[...], value}] 或 [{path:[...], delete:true}]。 // 单项编辑:[{path:[...], value}] 或 [{path:[...], delete:true}] 或 [{path:[...], value, append:true}]。
// 用 YAML Document 写回,保留注释与排版;路径段为纯数字时按数组下标处理(如 ["models",0,"url"])。 // 用 YAML Document 写回,保留注释与排版;路径段为纯数字时按数组下标处理(如 ["platforms",0,"keys",1,"models",0])。
// append:向目标数组追加一项(新增平台/Key/模型用);目标不存在时创建新数组。
function applyEditsToText(text, edits) { function applyEditsToText(text, edits) {
const doc = YAML.parseDocument(text || ''); const doc = YAML.parseDocument(text || '');
for (const e of edits || []) { for (const e of edits || []) {
if (!e || !Array.isArray(e.path) || !e.path.length) throw new Error('配置项 path 必须是非空数组'); 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); const docPath = e.path.map(s => (typeof s === 'string' && /^\d+$/.test(s)) ? Number(s) : s);
if (e.delete) doc.deleteIn(docPath); 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(); return doc.toString();
} }
+3 -2
View File
@@ -108,11 +108,12 @@ async function callModel(cfg, modelId, messages, tools, options) {
if (opts.signal.aborted) controller.abort(); if (opts.signal.aborted) controller.abort();
else opts.signal.addEventListener('abort', () => controller.abort()); else opts.signal.addEventListener('abort', () => controller.abort());
} }
// modelId = 内部唯一键「平台名/模型id」;发给上游的模型名用 mid(原始 id)。
const modelCfg = (cfg.models || []).find(m => m.id === modelId); 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 = { const body = {
model: modelId, model: modelCfg.mid || modelCfg.id,
messages, messages,
stream: true, stream: true,
stream_options: { include_usage: true }, stream_options: { include_usage: true },
+18 -3
View File
@@ -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> <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> </button>
<h3 id="moe-title">编辑模型</h3> <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-name" placeholder="显示名(留空同 id)" style="width:100%">
<input type="text" id="moe-id" 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%">
<label class="del-dir"><input type="checkbox" id="moe-vision">支持图片输入(vision)</label> <label class="del-dir"><input type="checkbox" id="moe-vision">支持图片输入(vision)</label>
<div class="btn-row"> <div class="btn-row">
<button class="ghost-btn danger hidden" id="moe-del-btn" onclick="modelsUI.del()">删除</button> <button class="ghost-btn danger hidden" id="moe-del-btn" onclick="modelsUI.del()">删除</button>
+98 -35
View File
@@ -1,19 +1,22 @@
// 模型 Tab(阶段 5):模型池状态 + 增 / 改 / 删(仅写 config.yml,到「设置」页重启才生效)。 // 模型 Tab(阶段 5):模型池状态 + 模型增 / 改 / 删(仅写 config.yml,到「设置」页重启才生效)。
// 卡片默认只展示:名称 / id / 运行状态 + 余额占位 + 今日/累计 token 用量(model_usage 表统计)。 // 配置为 platforms 层级(平台 → Key → 模型):url/type 在平台层,api_key/concurrency 在 Key 层,
// 编辑走统一弹窗(新增复用同一弹窗);id 不可页面修改(会话按 id 绑定,改 id 走配置文件原文)。 // 模型项只有 {id, display_name, vision};id 只需同平台内唯一(内部唯一键 = 平台名/模型id,
// effective.models 的 id 即该键、mid 为原始模型名)。页面 PATCH 用 platforms[i].keys[j].models[k] 嵌套下标定位;
// 新增一律走 append(只动目标数组,脱敏 key 绝不整体回写文件);已有 Key 的 api_key 修改请走配置原文编辑器。
'use strict'; 'use strict';
window.tabModules = window.tabModules || {}; 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 runtimeById = {}; // 运行池状态,按 id 关联
let modelsPendingRestart = false; let modelsPendingRestart = false;
let moeIdx = -1; // 当前编辑弹窗对应的下标;-1 = 新增 let moeIdx = -1; // 当前编辑弹窗对应的打平下标;-1 = 新增
let moeOrigKey = ''; // 打开编辑弹窗时的原始 api_key;未改动(显示仍含***)则保留原值
// api_key 脱敏显示:sk-***1234 样式。含 *** 作为「未改动」哨兵,保存时据此还原原 key。 // api_key 脱敏显示:sk-***1234 样式。后端 GET effective 已脱敏,这里仅兜底(幂等)。
function maskKey(k) { function maskKey(k) {
k = k || ''; k = k || '';
if (k.includes('***')) return k;
if (k.length > 8) return k.slice(0, 3) + '***' + k.slice(-4); if (k.length > 8) return k.slice(0, 3) + '***' + k.slice(-4);
if (k.length > 0) return '***' + k.slice(-2); if (k.length > 0) return '***' + k.slice(-2);
return ''; return '';
@@ -36,6 +39,7 @@ async function loadModelCards() {
const [rt, cg] = await Promise.all([req('GET', '/api/models'), req('GET', '/api/config')]); const [rt, cg] = await Promise.all([req('GET', '/api/models'), req('GET', '/api/config')]);
runtimeById = {}; runtimeById = {};
for (const m of rt || []) runtimeById[m.id] = m; for (const m of rt || []) runtimeById[m.id] = m;
cfgPlatforms = (cg.effective && cg.effective.platforms) || [];
cfgModels = (cg.effective && cg.effective.models) || []; cfgModels = (cg.effective && cg.effective.models) || [];
if (!cfgModels.length) { if (!cfgModels.length) {
el.innerHTML = '<div class="empty-tip">尚未配置模型,点右上角 + 添加。</div>'; el.innerHTML = '<div class="empty-tip">尚未配置模型,点右上角 + 添加。</div>';
@@ -49,10 +53,10 @@ async function loadModelCards() {
: '<span class="model-card-state pending">待重启</span>'; : '<span class="model-card-state pending">待重启</span>';
return '<div class="model-card">' + return '<div class="model-card">' +
'<div class="model-card-head">' + '<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 + stateHtml +
'</div>' + '</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>' + (run && run.is_busy && run.current_session_id ? ' · 会话 ' + esc(run.current_session_id) : '') + '</div>' +
'<div class="cfg-kv"><label>余额</label><b>--</b></div>' + '<div class="cfg-kv"><label>余额</label><b>--</b></div>' +
// token 紧凑显示:输入 / 输出 // 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) { function openModelEditor(rawId) {
const add = rawId == null; const add = rawId == null;
moeIdx = add ? -1 : idxOf(decodeURIComponent(rawId)); moeIdx = add ? -1 : idxOf(decodeURIComponent(rawId));
if (!add && moeIdx < 0) return toast('模型不存在'); 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-title').textContent = add ? '添加模型' : '编辑模型';
$('moe-name').value = m.display_name || '';
const idIn = $('moe-id'); const idIn = $('moe-id');
idIn.value = m.id || ''; idIn.value = m ? (m.mid || m.id) : '';
idIn.disabled = !add; // 编辑时禁改 id(历史会话按 id 绑定) idIn.disabled = !add; // 编辑时禁改 id(历史会话按「平台名/模型id」绑定,改 id 等于换模型)
$('moe-url').value = m.url || ''; $('moe-name').value = m ? (m.display_name || '') : '';
moeOrigKey = m.api_key || ''; $('moe-vision').checked = m ? !!m.vision : false;
const keyIn = $('moe-key'); const tgt = $('moe-target');
keyIn.value = maskKey(moeOrigKey); if (add) {
keyIn.placeholder = add ? 'sk-...' : '不改则保留原 key(清空将保存为空)'; tgt.disabled = false;
$('moe-vision').checked = !!m.vision; 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); $('moe-del-btn').classList.toggle('hidden', add);
$('model-edit-modal').classList.remove('hidden'); $('model-edit-modal').classList.remove('hidden');
} }
function closeModelEditor() { $('model-edit-modal').classList.add('hidden'); } function closeModelEditor() { $('model-edit-modal').classList.add('hidden'); }
async function saveModelEditor() { async function saveModelEditor() {
const add = moeIdx < 0;
const id = $('moe-id').value.trim(); const id = $('moe-id').value.trim();
const url = $('moe-url').value.trim().replace(/\/+$/, '');
if (!id) return toast('请填写 id'); if (!id) return toast('请填写 id');
if (!url) return toast('请填写上游地址'); // 模型项本身只含 id/display_name/vision;url/key/concurrency 在平台/Key 层,这里不动。
// 显示值含 *** = 未改动,还原原 key;否则按用户输入(支持改为新 key 或清空) const model = {
const keyVal = $('moe-key').value.trim();
const api_key = keyVal.includes('***') ? moeOrigKey : keyVal;
const obj = {
id, id,
display_name: $('moe-name').value.trim() || id, display_name: $('moe-name').value.trim() || id,
url,
api_key,
vision: $('moe-vision').checked, vision: $('moe-vision').checked,
}; };
const add = moeIdx < 0;
let body; let body;
if (add) { if (!add) {
if (idxOf(id) >= 0) return toast('id 已存在:' + id); // 编辑:精确改到 platforms[pi].keys[ki].models[mi]
body = { path: 'models', value: cfgModels.concat([obj]) }; const m = cfgModels[moeIdx];
body = { path: ['platforms', m.platform_index, 'keys', m.key_index, 'models', m.model_index], value: model };
} else { } else {
// 整项替换;key 顺序固定,保持配置文件观感一致 const t = $('moe-target').value;
body = { path: ['models', moeIdx], value: obj }; // 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 { try {
await req('PATCH', '/api/config', body); await req('PATCH', '/api/config', body);
@@ -136,10 +197,11 @@ async function delModelFromModal() {
const m = cfgModels[moeIdx]; const m = cfgModels[moeIdx];
closeModelEditor(); closeModelEditor();
if (cfgModels.length <= 1) return toast('至少要保留一个模型'); 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; if (!ok) return;
try { 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(); afterWrite();
} catch (e) { toast('删除失败:' + e.message); } } catch (e) { toast('删除失败:' + e.message); }
} }
@@ -150,6 +212,7 @@ window.modelsUI = {
close: closeModelEditor, close: closeModelEditor,
save: saveModelEditor, save: saveModelEditor,
del: delModelFromModal, del: delModelFromModal,
onTargetChange: onTargetChange,
}; };
tabModules.models = { tabModules.models = {
+19 -8
View File
@@ -43,10 +43,10 @@ function maskKey(k) {
return ''; return '';
} }
// 逐行掩码 config.yml 原文里的 api_key 值(设置页原文编辑器展示用)。 // 逐行掩码配置原文里的 api_key 值(设置页原文编辑器展示用)。
// 行格式如 ` api_key: sk-xxx` 或 ` api_key: "sk-xxx"`(双/单引号)。 // 行格式如 ` api_key: sk-xxx` / ` api_key: "sk-xxx"` / ` - api_key: sk-xxx`(platforms.keys 列表项写法)。
// 记录每行是否掩码,便于 restore 时按顺序还原未改动项。 // 记录每行是否掩码,便于 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) { function maskApiKeys(text) {
if (!text) return text; if (!text) return text;
return text.split('\n').map(function (line) { return text.split('\n').map(function (line) {
@@ -76,13 +76,23 @@ function restoreApiKeys(submitted, orig) {
}).join('\n'); }).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) => { router.get('/', wrap((req, res) => {
const cfg = cfgOf(); const cfg = cfgOf();
const text = readConfigText(cfg); const text = readConfigText(cfg);
const shown = text === null ? '' : maskApiKeys(text); 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 } // 干跑校验(编辑器保存前预检):body { text }
@@ -115,8 +125,9 @@ router.put('/', wrap((req, res) => {
res.json({ ok: true, changed: diffTop(cfg, next), restart_required: true }); res.json({ ok: true, changed: diffTop(cfg, next), restart_required: true });
})); }));
// 单项修改:body { path: "agent.temperature" | ["models",0,"url"], value, op?: "delete" } // 单项修改:body { path: "agent.temperature" | ["platforms",0,"keys",0,"models",1], value, op?: "delete"|"append" }
// 用 YAML Document 写回,保留文件注释与排版;数组可整体替换,也可按数字下标改元素。 // 用 YAML Document 写回,保留文件注释与排版;数组可整体替换,可按数字下标改/删元素,
// 也可 append 向数组追加一项(新增平台/Key/模型;前端只持有脱敏 key,绝不能整体替换含 key 的数组)。
router.patch('/', wrap((req, res) => { router.patch('/', wrap((req, res) => {
const cfg = cfgOf(); const cfg = cfgOf();
const text = readConfigText(cfg); const text = readConfigText(cfg);
@@ -129,7 +140,7 @@ router.patch('/', wrap((req, res) => {
if (!pathArr.length) return badRequest(res, new Error('body.path 为空')); if (!pathArr.length) return badRequest(res, new Error('body.path 为空'));
let nextText; let nextText;
try { 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); } } catch (e) { return badRequest(res, e); }
let next; let next;
try { next = loadConfigFromText(nextText, cfg.config_path); } catch (e) { return badRequest(res, e); } try { next = loadConfigFromText(nextText, cfg.config_path); } catch (e) { return badRequest(res, e); }
+14 -3
View File
@@ -1,13 +1,24 @@
# 冒烟测试用配置:上游指向本地 mock # 冒烟测试用配置:上游指向本地 mock
# 两个模型都开 vision:让「读图」端到端测试与绑定哪个模型无关(非 vision 分支由单测覆盖) # 两个模型都开 vision:让「读图」端到端测试与绑定哪个模型无关(非 vision 分支由单测覆盖)
models: platforms:
- name: mock-a
url: "http://127.0.0.1:9999/v1"
type: openai
keys:
- api_key: ""
models:
- id: ds1 - id: ds1
display_name: "Mock Model 1" display_name: "Mock Model 1"
url: "http://127.0.0.1:9999/v1"
vision: true vision: true
- name: mock-b
url: "http://127.0.0.1:9999/v1"
type: custom
keys:
- api_key: ""
concurrency: 1
models:
- id: ds2 - id: ds2
display_name: "Mock Model 2" display_name: "Mock Model 2"
url: "http://127.0.0.1:9999/v1"
vision: true vision: true
workspace_root: "./test/tmp/tasks" workspace_root: "./test/tmp/tasks"
+2 -2
View File
@@ -256,9 +256,9 @@ async function main() {
try { await api('PUT', '/api/config', { text: 'models: [unclosed' }); } catch (e) { bad400 = /400/.test(e.message); } try { await api('PUT', '/api/config', { text: 'models: [unclosed' }); } catch (e) { bad400 = /400/.test(e.message); }
ok(bad400, 'PUT 非法配置被 400 拒绝'); ok(bad400, 'PUT 非法配置被 400 拒绝');
ok(fs.readFileSync(cfgPath, 'utf8') === afterPatch.text, '非法写入未动文件'); ok(fs.readFileSync(cfgPath, 'utf8') === afterPatch.text, '非法写入未动文件');
const mpatch = await api('PATCH', '/api/config', { path: 'models.0.display_name', value: '改名模型' }); const mpatch = await api('PATCH', '/api/config', { path: 'platforms.0.keys.0.models.0.display_name', value: '改名模型' });
const mtext = (await api('GET', '/api/config')).text; const mtext = (await api('GET', '/api/config')).text;
ok(mpatch.ok && mtext.includes('改名模型'), 'PATCH 支持 models[i] 数组下标'); ok(mpatch.ok && mtext.includes('改名模型'), 'PATCH 支持 platforms 嵌套数组下标');
const restored = await api('PUT', '/api/config', { text: origText }); const restored = await api('PUT', '/api/config', { text: origText });
ok(restored.ok && fs.readFileSync(cfgPath, 'utf8') === origText, 'PUT 整文件恢复原配置'); ok(restored.ok && fs.readFileSync(cfgPath, 'utf8') === origText, 'PUT 整文件恢复原配置');