diff --git a/README.md b/README.md index 7b263ff..bdcf741 100644 --- a/README.md +++ b/README.md @@ -809,19 +809,27 @@ networks: ## 十四、配置文件示例 ```yaml -models: - - id: ds1 - display_name: "AMD DeepSeek 1" +# 模型池:平台(platforms) → Key → 模型 三层。url/type 配在平台,api_key/concurrency 配在 Key, +# 模型只声明 {id, display_name, vision}。加载时打平成全局模型列表。 +platforms: + - name: proxy-a url: "https://proxy-a.example.com/v1" - api_key: "sk-..." - - id: ds2 - display_name: "AMD DeepSeek 2" - url: "https://proxy-b.example.com/v1" - api_key: "sk-..." - - id: ds3 - display_name: "AMD DeepSeek 3" + type: openai # openai/deepseek/custom,决定余额查询适配器(预留) + keys: + - api_key: "sk-..." + concurrency: 1 # 该 Key 并发会话数,默认 1(当前仅记录,未参与调度) + models: + - id: ds1 + display_name: "AMD DeepSeek 1" + # vision: true # 选填,默认 false + - name: proxy-c url: "https://proxy-c.example.com/v1" - api_key: "sk-..." + type: custom + keys: + - api_key: "sk-..." + models: + - id: ds3 + display_name: "AMD DeepSeek 3" workspace_root: "/workspace/tasks" diff --git a/app/config.example.yml b/app/config.example.yml index 6170236..580548d 100644 --- a/app/config.example.yml +++ b/app/config.example.yml @@ -1,22 +1,34 @@ # 自用通用 Agent 系统配置示例 # 复制为 config.yml 后按需修改;容器内通过 AGENT_CONFIG 指定路径。 -# 模型池:每个模型独立配置上游 url 与 api_key(互不共用,可指向不同代理/账号)。 -# 同时活跃会话数上限 = 模型数量。 -models: - - id: ds1 - display_name: "AMD DeepSeek 1" - url: "https://proxy-a.example.com/v1" # 独立的 OpenAI 兼容 /v1 地址 - api_key: "sk-..." # 各模型可不同,留空则不带鉴权头 - # vision: true # 选填,默认 false;支持时 read_file 读图会压缩回传(长边≤2000px JPEG),会话上下文会告知 AI - - id: ds2 - display_name: "AMD DeepSeek 2" - url: "https://proxy-b.example.com/v1" - api_key: "sk-..." - - id: ds3 - display_name: "AMD DeepSeek 3" +# 模型池:平台(platforms) → Key → 模型 三层层级。url/type 配在平台,api_key/concurrency 配在 Key, +# 模型只声明 {id, display_name, vision}。加载时自动打平成全局模型列表。 +# 暂按每模型 1 会话调度;concurrency 已解析入库,多会话并发后续再接调度。 +platforms: + - name: proxy-a # 平台名;留空取 url 主机名首段。注意:它是模型唯一键的一部分,改名等于重建其下所有模型(历史会话回绑失效、用量统计分家) + url: "https://proxy-a.example.com/v1" # OpenAI 兼容 /v1 地址,该平台下所有模型共用 + 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 + - id: ds2 + display_name: "AMD DeepSeek 2" + - api_key: "sk-..." # 同平台的第二个 Key + models: + - id: ds3 + display_name: "AMD DeepSeek 3" + - name: proxy-c 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" # db_path: "/data/.agent.db" diff --git a/app/server/config.js b/app/server/config.js index 8e1dbf3..4388711 100644 --- a/app/server/config.js +++ b/app/server/config.js @@ -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(); } diff --git a/app/server/llm.js b/app/server/llm.js index 5eed3ac..c343ccb 100644 --- a/app/server/llm.js +++ b/app/server/llm.js @@ -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 }, diff --git a/app/server/public/index.html b/app/server/public/index.html index bdc160d..d26e6cf 100644 --- a/app/server/public/index.html +++ b/app/server/public/index.html @@ -243,10 +243,25 @@

编辑模型

+ + + - - - +
diff --git a/app/server/public/js/models.js b/app/server/public/js/models.js index 4ae8695..d930692 100644 --- a/app/server/public/js/models.js +++ b/app/server/public/js/models.js @@ -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 = '
尚未配置模型,点右上角 + 添加。
'; @@ -49,10 +53,10 @@ async function loadModelCards() { : '待重启'; return '
' + '
' + - '' + esc(m.display_name || m.id) + '' + + '' + esc(m.display_name || m.mid || m.id) + '' + stateHtml + '
' + - '
' + esc(m.id) + + '
' + esc(m.mid || m.id) + ' · 平台 ' + esc(m.platform || '') + (run && run.is_busy && run.current_session_id ? ' · 会话 ' + esc(run.current_session_id) : '') + '
' + '
--
' + // 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 += ''; + })); + html += ''; + html += ''; + 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) => + '').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 = ''; + 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 = { diff --git a/app/server/routes/config.js b/app/server/routes/config.js index 5b4a548..30283d5 100644 --- a/app/server/routes/config.js +++ b/app/server/routes/config.js @@ -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); } diff --git a/app/test/config.test.yml b/app/test/config.test.yml index ee30d71..5a46aa5 100644 --- a/app/test/config.test.yml +++ b/app/test/config.test.yml @@ -1,14 +1,25 @@ # 冒烟测试用配置:上游指向本地 mock # 两个模型都开 vision:让「读图」端到端测试与绑定哪个模型无关(非 vision 分支由单测覆盖) -models: - - id: ds1 - display_name: "Mock Model 1" +platforms: + - name: mock-a url: "http://127.0.0.1:9999/v1" - vision: true - - id: ds2 - display_name: "Mock Model 2" + type: openai + keys: + - api_key: "" + models: + - id: ds1 + display_name: "Mock Model 1" + vision: true + - name: mock-b url: "http://127.0.0.1:9999/v1" - vision: true + type: custom + keys: + - api_key: "" + concurrency: 1 + models: + - id: ds2 + display_name: "Mock Model 2" + vision: true workspace_root: "./test/tmp/tasks" diff --git a/app/test/smoke.js b/app/test/smoke.js index 0412c68..2c4b4fc 100644 --- a/app/test/smoke.js +++ b/app/test/smoke.js @@ -256,9 +256,9 @@ async function main() { try { await api('PUT', '/api/config', { text: 'models: [unclosed' }); } catch (e) { bad400 = /400/.test(e.message); } ok(bad400, 'PUT 非法配置被 400 拒绝'); 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; - ok(mpatch.ok && mtext.includes('改名模型'), 'PATCH 支持 models[i] 数组下标'); + ok(mpatch.ok && mtext.includes('改名模型'), 'PATCH 支持 platforms 嵌套数组下标'); const restored = await api('PUT', '/api/config', { text: origText }); ok(restored.ok && fs.readFileSync(cfgPath, 'utf8') === origText, 'PUT 整文件恢复原配置');