one-model-router 0.0.13 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
1
  /**
2
- * Loomy(讯飞办公助手)渠道 —— oauth-callback 登录。
2
+ * Loomy(讯飞办公助手)渠道 —— 微信扫码登录。
3
3
  *
4
- * 协议要点:
4
+ * 协议要点(2026-12-03 用本机客户端真实 session 复核):
5
5
  * - 端点:业务/推理 https://loomyad.xunfei.cn/api/v1;账号(CAccount)
6
6
  * https://account.xfinfr.com(HMAC-SHA1 签名 `account {ak}:{sig}`)。
7
- * - 两套认证头:/chat/completions 只认 `Authorization: Bearer`(无前缀同样判失败),
8
- * /models、/points/* 只认小写 `token` 头。带错的那个 →
9
- * HTTP 200 + {"code":"100002","desc":"缺少 token"}。chat 头两个都发
7
+ * - 两套认证头:/chat/completions 认 `Authorization: Bearer`(官方客户端同时再发
8
+ * 一个小写 `token`),/models、/points/* 只认小写 `token` 头。带错 →
9
+ * HTTP 200 + {"code":"100002","desc":"缺少 token"}。
10
10
  * - 业务失败**恒 HTTP 200**,成败只能读 body 的 code:000000 成功 / 100002 登录失效
11
11
  * (不得重试,凭据终态)/ 100001 参数错误
12
12
  * - 登录:微信扫码(OMR 侧渲染二维码,不起本地登录页)——
@@ -32,19 +32,30 @@
32
32
  * (GET /points/records?pageNo=1&pageSize=1 是最便宜的只读端点),100002 → 终态;
33
33
  * describeCredential 恒 refreshable:false(诚实标记,不是遗漏)
34
34
  * - 登录后 best-effort POST /points/first-login 初始化每日赠送额度(登录后即触发,
35
- * 失败不影响登录;⚠️ dailyQuota 只在该响应里,绝不硬编码 5000)
35
+ * 失败不影响登录)。响应实测:{ alreadyProcessed, currentBalance, permanentBalance,
36
+ * dailyBalance, dailyQuota, dailyConsumed, dailyCycleDate, registerReward,
37
+ * inviteeReward, inviterReward, invitationCodes }。⚠️ dailyQuota 只在该响应里,
38
+ * 绝不硬编码 5000
39
+ * - 积分查询(只读):GET /points/records?recordType=all|earned|consumed 返回
40
+ * balance(永久)/ dailyBalance(每日剩余)/ availableBalance(总可用)与流水
41
+ * (direction=credit|debit、pointsActual、description…)。另存在 /points/balance
42
+ * 只返回三个余额字段,但官方客户端统一走 /points/records,本渠道跟随官方口径。
43
+ * 「已领取」= recordType=earned 流水的 pointsActual 之和(与当前余额是两回事)
36
44
  * - 对话:POST {api}/chat/completions 标准 OpenAI 兼容 + 标准 SSE(data: 帧 + 空 data:
37
45
  * 终止帧,思考在 delta.reasoning_content,无加密无信封)+ 恒 stream:true 本地聚合;
46
+ * ⚠️ 必须带 W3C `traceparent`(官方客户端注明缺它会挂死到超时)+ `loomy-version`;
38
47
  * reasoning_effort 仅当落在模型声明的 efforts 内才下发(off/disabled → none;服务端对
39
48
  * 未知字段静默忽略回 200,不能靠状态码判断生效;未知模型不编造档位)
40
- * - 模型:GET {api}/models(需 token 头)只留 type==='chat'(⚠️ 不能看 input_modalities,
41
- * 5 个 chat 模型的输入模态含 image,那是能看图不是生图);倍率在 name 末尾括号里且
42
- * 全角/半角/无空格三种风格混用,拆成数值 `rate` 字段交给 UI 渲染倍率徽章
43
- * (名称不再拼接 x{n});只认实时清单,远端失败/空结果直接抛错,不回落兜底表
49
+ * - 模型:GET {api}/models(需 token 头)只留「文本输出」的 chat 模型:判据是
50
+ * type==='chat' **且** capabilities.output_modalities 含 text。⚠️ 不能只看 type:
51
+ * 远端把 seedance-2-0/2-5 等视频模型也标成 chat(output=[video]、streaming=false);
52
+ * ⚠️ 也不能看 input_modalities:真正的 chat 模型输入也含 image(能看图 ≠ 会生图)。
53
+ * 远端 name 已不带倍率(早期 `x{n}` 括号格式已消失),故 rate 通常为空;
54
+ * 只认实时清单,远端失败/空结果直接抛错,不回落兜底表
44
55
  * - 默认思考档:本插件选 `high`(远端 default_reasoning_effort 声明的是 low,有意不沿用)
45
56
  */
46
57
 
47
- import { createHash, createHmac, randomUUID } from 'node:crypto'
58
+ import { createHash, createHmac, randomBytes, randomUUID } from 'node:crypto'
48
59
  import { httpFetch, readBodyText, readSseData, mergeSseChunks } from '../util.js'
49
60
 
50
61
  // ── 产品常量 ────────────────────────────────────────────────────────────────
@@ -66,6 +77,12 @@ const LOOMY_WECHAT_APP_ID = 'wx18d60be432287cf8'
66
77
  /** ⚠️ 必须是官方地址:微信校验 redirect_uri 域名白名单;它实测 404 但链路不依赖它。 */
67
78
  const LOOMY_WECHAT_REDIRECT_URI = 'https://loomy.xunfei.cn/oauth/wechat/callback'
68
79
 
80
+ /**
81
+ * 官方客户端版本:chat 端点会带 `loomy-version` 头(可选,但官方客户端恒发)。
82
+ * 版本可用环境变量覆盖,避免客户端升级后立刻失效。
83
+ */
84
+ const LOOMY_CLIENT_VERSION = process.env.OMR_LOOMY_VERSION || '0.9.39'
85
+
69
86
  const REQUEST_TIMEOUT_MS = 60_000
70
87
  const MODELS_TIMEOUT_MS = 20_000
71
88
  const BODY_READ_TIMEOUT_MS = 15_000
@@ -82,7 +99,7 @@ const REFRESH_LEAD_MS = 60 * 60_000
82
99
  /** 登录会话有效期(秒)= 14 天;只是向服务端的声明,expires_at 由本地推算。 */
83
100
  const LOOMY_SESSION_TTL_SECONDS = 1_209_600
84
101
 
85
- /** 实测思考档位(8 个 chat 模型完全一致)。 */
102
+ /** 实测思考档位(所有文本 chat 模型一致)。 */
86
103
  const LOOMY_EFFORTS = ['none', 'low', 'medium', 'high', 'xhigh']
87
104
  /** 本插件选用的默认档位。 */
88
105
  const LOOMY_DEFAULT_EFFORT = 'high'
@@ -98,26 +115,32 @@ const CREDIT_MARKERS = [
98
115
  const RATE_LIMIT_MARKERS = ['rate limit', 'too many requests', '频率限制']
99
116
 
100
117
  /**
101
- * 静态元数据表(2026-09-26 实测 GET /models 的 8 条 type==='chat',顺序与远端一致)。
102
- * ⚠️ 只用于 complete() 的思考档位校验,**不参与模型清单**:清单只认实时 /models,
103
- * 拉不到直接抛错(见 fetchModels)。
104
- * ⚠️ name 已规范化成 `{name} · x{n}`(远端原值三种括号风格混用)。
105
- * ⚠️ contextWindow 用远端 context_length。spark-x 是已知分歧:远端声明 1048576,
106
- * 客户端本地表强制降到 262144 —— 先采信远端。
107
- * ⚠️ 兜底表不声明图片能力(supportsImage:false):宁可少报,不报服务端可能不认的模态。
118
+ * 静态元数据表(2026-12-03 实测 GET /models 中 7 条「文本输出」的 chat 模型)。
119
+ * ⚠️ 只用于 complete() 的思考档位校验(fetchModels 成功后还会用远端 efforts 动态覆盖),
120
+ * **不参与模型清单**:清单只认实时 /models,拉不到直接抛错(见 fetchModels)。
121
+ * ⚠️ 远端 type==='chat' 里还混有 seedance-2-0 / seedance-2-5 等视频模型
122
+ * (output_modalities=['video']、streaming=false),不能当对话模型发布,已由
123
+ * isLoomyChatModel 按 output_modalities 过滤掉。
124
+ * ⚠️ 远端 name 已不再带倍率(早期括号倍率格式已消失),故这里不再声明 rate。
125
+ * ⚠️ contextWindow 取远端 context_length;maxTokens 取 max_output_tokens。
108
126
  */
109
127
  export const fallbackModels = [
110
- { id: 'deepseek-v4-flash-0731', name: 'DeepSeek V4 Flash 0731 · x3.0', contextWindow: 1_048_576, supportsImage: false, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
111
- { id: 'MiniMax-M3', name: 'MiniMax M3 · x4.0', contextWindow: 1_048_576, supportsImage: false, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
112
- { id: 'Kimi-k2.6', name: 'Kimi k2.6 · x6.5', contextWindow: 262_144, supportsImage: false, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
113
- { id: 'qwen-3.8-max', name: 'Qwen 3.8 Max · x12.0', contextWindow: 1_000_000, supportsImage: false, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
114
- { id: 'GLM-5.3-Flash', name: 'GLM 5.3 Flash · x0.8', contextWindow: 1_048_576, supportsImage: false, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
115
- { id: 'qwen3.8-flash', name: 'qwen 3.8 flash · x0.8', contextWindow: 1_000_000, supportsImage: false, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
116
- { id: 'spark-x', name: 'Spark X2.5 · x0.1', contextWindow: 1_048_576, supportsImage: false, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
117
- { id: 'mimo-v2.5', name: 'MiMo V2.5 · x3.3', contextWindow: 1_048_576, supportsImage: false, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
128
+ { id: 'spark-x2.6', name: 'Spark X2.6', contextWindow: 1_048_576, maxTokens: 131_072, supportsImage: false, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
129
+ { id: 'DeepSeek-V4.1-Flash', name: 'DeepSeek V4.1 Flash', contextWindow: 1_048_576, maxTokens: 384_000, supportsImage: true, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
130
+ { id: 'deepseek-v4.1-flash-1017', name: 'DeepSeek V4.1 Flash 1017', contextWindow: 1_048_576, maxTokens: 384_000, supportsImage: true, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
131
+ { id: 'Hy4-Flash', name: 'Hy4 Flash', contextWindow: 1_000_000, maxTokens: 64_000, supportsImage: true, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
132
+ { id: 'GLM-5.3-Flash', name: 'GLM 5.3 Flash', contextWindow: 1_048_576, maxTokens: 131_072, supportsImage: true, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
133
+ { id: 'qwen3.8-flash', name: 'Qwen 3.8 Flash', contextWindow: 1_000_000, maxTokens: 131_072, supportsImage: true, efforts: [...LOOMY_EFFORTS], defaultEffort: LOOMY_DEFAULT_EFFORT },
134
+ // ⚠️ auto(自动路由)远端未声明 reasoning_efforts:不编造档位,交回服务端默认。
135
+ { id: 'auto', name: '自动', contextWindow: 1_048_576, maxTokens: 384_000, supportsImage: true },
118
136
  ]
119
137
 
120
138
  const fallbackIndex = new Map(fallbackModels.map(m => [m.id, m]))
139
+ /**
140
+ * 远端 /models 声明的思考档位(model id → efforts)。列表会随账号权益变化,
141
+ * 静态表只能覆盖「已知模型」;远端拉到后以远端为准,避免新模型被静默丢弃档位。
142
+ */
143
+ const remoteEfforts = new Map()
121
144
 
122
145
  export const meta = { id: 'loomy', label: 'Loomy (讯飞)', loginMode: 'qr' }
123
146
 
@@ -223,6 +246,15 @@ function looksLikeBilling(text) {
223
246
  return CREDIT_MARKERS.some(m => lower.includes(m))
224
247
  }
225
248
 
249
+ /**
250
+ * W3C traceparent(`00-<32hex>-<16hex>-01`)。
251
+ * ⚠️ 官方客户端注明:Loomy iModel 缺 traceparent 时 chat/completions 会挂死到超时,
252
+ * 故每个对话请求都必须带。
253
+ */
254
+ function buildTraceparent() {
255
+ return `00-${randomBytes(16).toString('hex')}-${randomBytes(8).toString('hex')}-01`
256
+ }
257
+
226
258
  // ── 凭据形态 ────────────────────────────────────────────────────────────────
227
259
 
228
260
  /** 解析 expires_at(毫秒时间戳字符串);缺失或非法返回 undefined。 */
@@ -633,12 +665,62 @@ export async function claimCredits(credential) {
633
665
  return { kind: 'claimed', credit: granted }
634
666
  }
635
667
 
668
+ /**
669
+ * 累计「已领取」积分:把获得流水(recordType=earned)逐页加总。
670
+ * 官方客户端的分页上限是 100,这里同样按 100 翻页;超过安全页数(2000 条)时
671
+ * 宁可返回 undefined 也不返回一个偏小的和(不编造/不误报)。
672
+ * 单页失败同样返回 undefined —— 余额本身仍可展示,只是不显示累计领取。
673
+ */
674
+ const EARNED_PAGE_SIZE = 100
675
+ const MAX_EARNED_PAGES = 20
676
+
677
+ async function fetchEarnedTotal(token) {
678
+ let sum = 0
679
+ let complete = false
680
+ for (let page = 1; page <= MAX_EARNED_PAGES; page++) {
681
+ let response
682
+ try {
683
+ response = await httpFetch(
684
+ `${API_BASE}/points/records?pageNo=${page}&pageSize=${EARNED_PAGE_SIZE}&recordType=earned`,
685
+ { method: 'GET', headers: { Accept: 'application/json', token } },
686
+ REQUEST_TIMEOUT_MS,
687
+ )
688
+ } catch {
689
+ return undefined
690
+ }
691
+ let parsed
692
+ try {
693
+ parsed = JSON.parse(await readBodyText(response, BODY_READ_TIMEOUT_MS))
694
+ } catch {
695
+ return undefined
696
+ }
697
+ const envelope = parseEnvelope(parsed)
698
+ if (!envelope.ok) return undefined
699
+ const data = envelope.data ?? {}
700
+ const list = Array.isArray(data.list) ? data.list : []
701
+ for (const item of list) {
702
+ if (item?.direction !== 'credit') continue
703
+ const points = readNumber(item.pointsActual)
704
+ if (points !== undefined) sum += points
705
+ }
706
+ const total = readNumber(data.total)
707
+ if (list.length < EARNED_PAGE_SIZE || (total !== undefined && page * EARNED_PAGE_SIZE >= total)) {
708
+ complete = true
709
+ break
710
+ }
711
+ }
712
+ return complete ? sum : undefined
713
+ }
714
+
636
715
  /**
637
716
  * 查询积分余额(**只读**)。
638
717
  * ⚠️ 用 points/records 而不是 first-login:后者是写端点,在「打开面板」这类
639
718
  * 高频路径上调用会意外触发签到。
719
+ * ⚠️ 服务端另有 /points/balance(同样返回 balance/dailyBalance/availableBalance),
720
+ * 但官方客户端统一走 /points/records;这里跟随官方口径,避免依赖未公开端点。
640
721
  * 两个池各作一个 package,让用户看出「永久」与「每日」分开计算;
641
722
  * total 用 availableBalance(两者之和口径)。
723
+ * 另附 earnedTotal = 获得流水 pointsActual 之和(「已领取」累计,非当前余额)。
642
724
  * @returns 查不到(凭据失效 / 响应异常)返回 null,与「余额为 0」严格区分。
643
725
  */
644
726
  export async function fetchCreditBalance(credential) {
@@ -667,12 +749,15 @@ export async function fetchCreditBalance(credential) {
667
749
  if (permanent === undefined) return null
668
750
  const daily = readNumber(data.dailyBalance) ?? 0
669
751
  const available = readNumber(data.availableBalance)
752
+ // 累计领取是附加信息:查不到就不带这个字段,不影响余额展示。
753
+ const earnedTotal = await fetchEarnedTotal(token)
670
754
  return {
671
755
  total: available ?? (permanent + daily),
672
756
  packages: [
673
757
  makeCreditPackage('永久积分', permanent),
674
758
  makeCreditPackage('每日赠送', daily),
675
759
  ],
760
+ ...(earnedTotal !== undefined ? { earnedTotal } : {}),
676
761
  expiredTotal: 0,
677
762
  }
678
763
  }
@@ -817,11 +902,29 @@ function readInputModalities(entry) {
817
902
  return raw.filter(item => typeof item === 'string').map(item => item.toLowerCase())
818
903
  }
819
904
 
820
- /** 是否可对话的 chat 模型:判据是 type==='chat',不能看 input_modalities(那是输入模态)。 */
905
+ /** 把 capabilities.output_modalities 读成小写字符串数组。 */
906
+ function readOutputModalities(entry) {
907
+ const capabilities = entry.capabilities
908
+ if (capabilities === null || typeof capabilities !== 'object') return []
909
+ const raw = capabilities.output_modalities
910
+ if (!Array.isArray(raw)) return []
911
+ return raw.filter(item => typeof item === 'string').map(item => item.toLowerCase())
912
+ }
913
+
914
+ /**
915
+ * 是否可对话的 chat 模型:type 必须是 'chat',且输出模态必须包含文本。
916
+ * ⚠️ 不能只看 type:远端把 seedance-2-0 / seedance-2-5 等视频模型也标成 type==='chat',
917
+ * 但它们 output_modalities=['video']、streaming=false,发 /chat/completions 得不到文本回复。
918
+ * ⚠️ 也不能看 input_modalities:6 个真正的 chat 模型输入都含 image(那是能看图,不是生图)。
919
+ * 远端缺 output_modalities 时退回「type + streaming!=false」(向前兼容旧版清单)。
920
+ */
821
921
  function isLoomyChatModel(entry) {
822
922
  if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return false
823
923
  const id = typeof entry.id === 'string' ? entry.id.trim() : ''
824
- return id.length > 0 && entry.type === 'chat'
924
+ if (id.length === 0 || entry.type !== 'chat') return false
925
+ const outputs = readOutputModalities(entry)
926
+ if (outputs.length === 0) return entry.capabilities?.streaming !== false
927
+ return outputs.includes('text')
825
928
  }
826
929
 
827
930
  /** 解析 GET /models 响应(数组或 {data:[...]}),只留 chat 条目。 */
@@ -839,12 +942,15 @@ function parseRemoteModels(payload) {
839
942
  const { name: displayName, rate: rateText } = splitLoomyRate(rawName)
840
943
  const rate = parseRateValue(rateText)
841
944
  const contextWindow = Number(item.context_length)
945
+ const maxTokens = Number(item.max_output_tokens)
842
946
  const efforts = readReasoningEfforts(item)
947
+ if (efforts.length > 0) remoteEfforts.set(id, efforts)
843
948
  out.push({
844
949
  id,
845
950
  name: displayName.length > 0 ? displayName : id,
846
951
  ...(rate !== undefined ? { rate } : {}),
847
952
  ...(Number.isFinite(contextWindow) && contextWindow > 0 ? { contextWindow } : {}),
953
+ ...(Number.isFinite(maxTokens) && maxTokens > 0 ? { maxTokens } : {}),
848
954
  supportsImage: readInputModalities(item).includes('image'),
849
955
  // ⚠️ 默认档不采信远端(声明的是 low):与本插件兜底表口径一致,声明 efforts 含 high 才给
850
956
  ...(efforts.length > 0 ? { efforts } : {}),
@@ -886,7 +992,8 @@ export async function fetchModels(credential) {
886
992
  function normalizeEffort(value, model) {
887
993
  if (typeof value !== 'string' || value.length === 0) return undefined
888
994
  const mapped = value === 'off' || value === 'disabled' ? 'none' : value
889
- const efforts = fallbackIndex.get(model)?.efforts
995
+ // 远端清单优先(新模型/权益变化以远端为准),静态表只覆盖「还没拉过清单」的已知模型。
996
+ const efforts = remoteEfforts.get(model) ?? fallbackIndex.get(model)?.efforts
890
997
  if (efforts === undefined) return undefined
891
998
  return efforts.includes(mapped) ? mapped : undefined
892
999
  }
@@ -947,12 +1054,14 @@ export async function complete(credential, body, { signal, onData, headerTimeout
947
1054
  try {
948
1055
  response = await httpFetch(`${API_BASE}/chat/completions`, {
949
1056
  method: 'POST',
950
- // ⚠️ chat 端点只认 Bearer(业务端点才认 token),两个都发
1057
+ // ⚠️ chat 端点只认 Bearer(业务端点才认 token),两个都发;traceparent 必带
951
1058
  headers: {
952
1059
  Accept: 'text/event-stream',
953
1060
  'Content-Type': 'application/json',
954
1061
  Authorization: `Bearer ${token}`,
955
1062
  token,
1063
+ traceparent: buildTraceparent(),
1064
+ 'loomy-version': LOOMY_CLIENT_VERSION,
956
1065
  },
957
1066
  body: payload,
958
1067
  signal,
@@ -0,0 +1,142 @@
1
+ /**
2
+ * 内置默认模型组(omr/default)。
3
+ *
4
+ * 成员由小时扫描自动维护:每次采集完各渠道可用模型后,本模块把「免密渠道」
5
+ * (kilo / opencode)的可用模型并入本组——成员 ID 采用目录形式 `kilo/<id>` /
6
+ * `opencode/<id>`,与 providers/index.js 产出的目录行一致。上游下架的模型会自动
7
+ * 从组里摘除,新上线的追加到链尾;已有成员的组内顺序保持不变(用户的拖拽排序不被
8
+ * 扫描覆盖)。
9
+ *
10
+ * 组本身是内置的:
11
+ * - 不存在时自动创建(服务启动即建);
12
+ * - 不允许删除;
13
+ * - 成员集合由扫描维护,手动保存只能调序、不能增删(见 builtinGroupMembers),
14
+ * 但展示名、策略、组内停用(disabled)仍由用户维护。
15
+ */
16
+
17
+ import { loadSettings, loadGroups, saveGroups, emitRuntimeEvent } from './store.js'
18
+
19
+ /** 内置默认组的固定 id(对外模型名 omr/default)。 */
20
+ export const DEFAULT_GROUP_ID = 'default'
21
+ /** 内置默认组的默认展示名。 */
22
+ export const DEFAULT_GROUP_NAME = '默认免费组'
23
+ /** 免密渠道 key(kilo / opencode)→ 成员 ID 前缀。 */
24
+ const NOKEY_PROVIDERS = ['kilo', 'opencode']
25
+
26
+ /** 是否为内置默认组 id。 */
27
+ export function isDefaultGroup(id) {
28
+ return id === DEFAULT_GROUP_ID
29
+ }
30
+
31
+ /**
32
+ * 免密渠道当前可用的模型 ID(目录形式:kilo/<id> / opencode/<id>)。
33
+ *
34
+ * 取自「选用清单」(settings.kilo.models / settings.opencode.models)——小时扫描后
35
+ * 这两份清单就是免密渠道最近一次扫描到的免费可用模型;停用的渠道不产出目录模型,
36
+ * 故不计入。字段既兼容 { id } 对象也兼容裸字符串。
37
+ */
38
+ export function defaultGroupMemberIds(settings = loadSettings()) {
39
+ const out = []
40
+ const seen = new Set()
41
+ for (const key of NOKEY_PROVIDERS) {
42
+ const seg = settings?.[key]
43
+ if (!seg || seg.enabled === false) continue
44
+ for (const model of Array.isArray(seg.models) ? seg.models : []) {
45
+ const id = typeof model === 'string'
46
+ ? model
47
+ : (model && typeof model.id === 'string' ? model.id : '')
48
+ if (id === '') continue
49
+ const full = `${key}/${id}`
50
+ if (seen.has(full)) continue
51
+ seen.add(full)
52
+ out.push(full)
53
+ }
54
+ }
55
+ return out
56
+ }
57
+
58
+ /**
59
+ * 内置组成员保存:只接受「重排」,不接受增删。
60
+ *
61
+ * 内置组的成员集合由小时扫描维护,但组内顺序(fallback 优先级 / 轮询环)由用户决定,
62
+ * 且用户的排序必须在下一轮扫描后保留。因此:
63
+ * - 提交里不在现有成员集合中的 id 一律丢弃(增删交给扫描);
64
+ * - 现有成员按提交的顺序重排;
65
+ * - 提交没提到的旧成员按原顺序补回(成员集合始终不变)。
66
+ * submitted 不是数组(未携带)时沿用现有成员。
67
+ */
68
+ export function builtinGroupMembers(current, submitted) {
69
+ const cur = (Array.isArray(current) ? current : []).filter(id => typeof id === 'string' && id !== '')
70
+ if (!Array.isArray(submitted)) return cur
71
+ const curSet = new Set(cur)
72
+ const next = []
73
+ for (const id of submitted) {
74
+ if (typeof id !== 'string' || !curSet.has(id) || next.includes(id)) continue
75
+ next.push(id)
76
+ }
77
+ for (const id of cur) if (!next.includes(id)) next.push(id)
78
+ return next
79
+ }
80
+
81
+ /**
82
+ * 同步内置默认组:不存在则创建,成员清单整表同步为免密渠道当前可用模型。
83
+ * 顺序:先按上一轮的成员顺序保留仍可用的(用户的排序不被覆盖),新模型追加到链尾。
84
+ * 返回 { created, changed, members }。
85
+ */
86
+ export function syncDefaultGroup({ log = () => {} } = {}) {
87
+ const settings = loadSettings()
88
+ const available = defaultGroupMemberIds(settings)
89
+ const availableSet = new Set(available)
90
+ const doc = loadGroups()
91
+ doc.groups ??= []
92
+ let index = doc.groups.findIndex(g => g && g.id === DEFAULT_GROUP_ID)
93
+ const prev = index >= 0 ? doc.groups[index] : null
94
+
95
+ // 撞名处理:用户此前自建过 id 为 default 的组(不是内置组),把它挪到 default-2 / default-3…
96
+ // 让出 default 给内置组(用户数据不丢,只改 id;改后的 id 会在日志里给出)。
97
+ let renamed = false
98
+ if (prev && prev.builtin !== true) {
99
+ const taken = new Set(doc.groups.map(g => g && g.id))
100
+ let suffix = 2
101
+ while (taken.has(`${DEFAULT_GROUP_ID}-${suffix}`)) suffix += 1
102
+ const moved = `${DEFAULT_GROUP_ID}-${suffix}`
103
+ doc.groups[index] = { ...prev, id: moved }
104
+ renamed = true
105
+ log(`已存在同 id 的自建模型组,已将其改名为 omr/${moved},omr/${DEFAULT_GROUP_ID} 留给内置默认组`)
106
+ index = doc.groups.findIndex(g => g && g.id === DEFAULT_GROUP_ID)
107
+ }
108
+ const base = index >= 0 ? doc.groups[index] : null
109
+ const created = !base
110
+
111
+ const models = []
112
+ for (const id of Array.isArray(base?.models) ? base.models : []) {
113
+ if (typeof id !== 'string' || !availableSet.has(id) || models.includes(id)) continue
114
+ models.push(id)
115
+ }
116
+ for (const id of available) if (!models.includes(id)) models.push(id)
117
+
118
+ const row = {
119
+ id: DEFAULT_GROUP_ID,
120
+ name: typeof base?.name === 'string' && base.name !== '' ? base.name : DEFAULT_GROUP_NAME,
121
+ models,
122
+ strategy: base?.strategy === 'round-robin' ? 'round-robin' : 'fallback',
123
+ stickyLimit: Math.max(1, Math.trunc(Number(base?.stickyLimit) || 3)),
124
+ enabled: base?.enabled !== false,
125
+ // 停用清单原样保留:上游临时下架又恢复时用户的停用意图依然生效
126
+ disabled: Array.isArray(base?.disabled) ? base.disabled.filter(id => typeof id === 'string' && id !== '') : [],
127
+ builtin: true,
128
+ }
129
+
130
+ const sameModels = !created && Array.isArray(base.models)
131
+ && base.models.length === row.models.length
132
+ && base.models.every((id, i) => id === row.models[i])
133
+ const changed = created || renamed || !sameModels
134
+ if (changed) {
135
+ if (index >= 0) doc.groups[index] = row
136
+ else doc.groups.push(row)
137
+ saveGroups(doc)
138
+ emitRuntimeEvent('groups', doc.groups) // 通知多端同步
139
+ log(`内置默认组 omr/${DEFAULT_GROUP_ID} 已同步:${row.models.length} 个免密渠道模型`)
140
+ }
141
+ return { created, changed, members: row.models }
142
+ }
@@ -41,6 +41,7 @@ import * as opencode from './providers/opencode.js'
41
41
  import * as openaiCompat from './providers/openai-compat.js'
42
42
  import { withLastGoodFallback } from './providers/last-good.js'
43
43
  import * as modelsdev from './providers/modelsdev.js'
44
+ import { syncDefaultGroup } from './default-group.js'
44
45
  import { utc8Date } from './util.js'
45
46
 
46
47
  const HOUR_MS = 60 * 60_000
@@ -576,6 +577,14 @@ export async function refreshFreeModels() {
576
577
  log(`免费模型自动选用失败(${target.label}):${error?.message ?? error}`)
577
578
  }
578
579
  }
580
+ // 内置默认组(omr/default):把免密渠道(kilo / opencode)本轮可用模型并入组内
581
+ // (免密渠道的选用清单在本轮扫描中已刷新,故此刻同步即为最新结果)
582
+ try {
583
+ const groupSync = syncDefaultGroup({ log })
584
+ if (groupSync.changed) invalidateCatalog()
585
+ } catch (error) {
586
+ log(`默认模型组同步失败:${error?.message ?? error}`)
587
+ }
579
588
  // 失败或本轮未采集的渠道也一并裁剪,确保落盘只有基线与当天最新两份
580
589
  for (const entry of Object.values(doc.channels)) {
581
590
  if (Array.isArray(entry?.samples)) entry.samples = pruneSamples(entry.samples, now)