/* default-gen-model.js —— 「新建配置节点默认模型」的纯函数(2026-11-25) * * 配置顶层 defaultGen = { providerId, model, keyGroup },决定新建 gen 节点预选的服务商 / 模型 / 密钥组。 * 本模块只算值、不碰 I/O、不碰 DOM;宿主把结果同步到 DEFAULTS.gen 模板即可让三条建节点路径统一生效。 * * 关键约定: * ① 生效值始终可算(未配置也回退主服务首个可见模型),保证「默认」标识与新建节点取值一致; * 一个可用模型都没有时才返回 null,宿主保留 DEFAULTS.gen 硬编码兜底。 * ② 已配置但指向的模型被删 / 关闭可见 ⇒ 同样回退,不会让新建节点失去模型。 * ③ 与 LLM 渠道的 defaultModel 完全隔离,不读不写 llm.*。 */ ;(function (global) { 'use strict' const norm = (v) => String(v == null ? '' : v).trim() // 生成候选列表: [{ providerId, model, keyGroup, label }],仅收可见模型(visible !== false)。 function wDefaultGenOptions (cfg) { const providers = (cfg && Array.isArray(cfg.providers)) ? cfg.providers : [] const out = [] const seen = new Set() for (const p of providers) { const pid = norm(p && p.id) if (!pid) continue const group = ((p.keys || [])[0] || {}).id || '' for (const m of (p.models || [])) { const name = norm(m && (typeof m === 'string' ? m : m.name)) if (!name || (m && typeof m === 'object' && m.visible === false)) continue const key = pid + '::' + name if (seen.has(key)) continue seen.add(key) out.push({ providerId: pid, model: name, keyGroup: norm(group), label: ((p && p.name) || pid) + ' · ' + name }) } } return out } // 解析生效值:始终给出「新建节点会用的那个模型」,让设置页与新建行为一致、可解释。 // ① 有效配置 ⇒ 原样用(密钥组缺省时取该服务第一个分组) // ② 未配置 / 配置的模型被删或被关闭 ⇒ 回退主服务(providers[0])第一个可见模型 // ③ 一个可用模型都没有 ⇒ null(宿主保留 DEFAULTS.gen 的硬编码兜底) function wResolveDefaultGen (cfg) { const opts = wDefaultGenOptions(cfg) if (!opts.length) return null const d = (cfg && cfg.defaultGen) || {} const pid = norm(d.providerId) const model = norm(d.model) if (pid && model) { const hit = opts.find((o) => o.providerId === pid && o.model === model) if (hit) return { providerId: hit.providerId, model: hit.model, keyGroup: norm(d.keyGroup) || hit.keyGroup } } const firstPid = norm((((cfg || {}).providers || [])[0] || {}).id) const fb = (firstPid && opts.find((o) => o.providerId === firstPid)) || opts[0] return { providerId: fb.providerId, model: fb.model, keyGroup: fb.keyGroup } } // 配置保存前的校验/归一化:只接受候选里的有效项;失效项不写入,让读取侧走回退。 function wNormalizeDefaultGen (cfg, incoming) { const d = (incoming && typeof incoming === 'object') ? incoming : {} const pid = norm(d.providerId) const model = norm(d.model) if (!pid || !model) return null const opts = wDefaultGenOptions(cfg) const hit = opts.find((o) => o.providerId === pid && o.model === model) return hit ? { providerId: hit.providerId, model: hit.model, keyGroup: norm(d.keyGroup) || hit.keyGroup } : null } global.IWBDefaultGenModel = { wResolveDefaultGen, wDefaultGenOptions, wNormalizeDefaultGen } })(typeof window !== 'undefined' ? window : globalThis)