one-model-router 0.0.13 → 0.0.14
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.
- package/README.md +11 -6
- package/bin/omr.js +90 -11
- package/package.json +2 -1
- package/src/admin.js +131 -7
- package/src/boot.js +10 -1
- package/src/bun-bootstrap.js +115 -0
- package/src/channels/index.js +8 -4
- package/src/channels/lingxi-browser-login.js +231 -0
- package/src/channels/lingxi-cred.js +448 -0
- package/src/channels/lingxi.js +1481 -0
- package/src/channels/loomy.js +140 -31
- package/src/default-group.js +142 -0
- package/src/free-models.js +9 -0
- package/src/probe.js +55 -25
- package/src/providers/opencode/bun-fetch.js +6 -26
- package/src/sync/index.js +150 -19
- package/src/sync/qr-mobile.js +141 -0
- package/src/sync/remote-login.js +28 -130
- package/src/sync/snapshot.js +2 -0
- package/src/update.js +7 -2
- package/web/app.js +472 -77
- package/web/index.html +2 -2
- package/web/style.css +26 -6
package/src/channels/loomy.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Loomy(讯飞办公助手)渠道 ——
|
|
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
|
|
8
|
-
*
|
|
9
|
-
* HTTP 200 + {"code":"100002","desc":"缺少 token"}。
|
|
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
|
-
*
|
|
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
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
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
|
-
/**
|
|
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-
|
|
102
|
-
* ⚠️ 只用于 complete()
|
|
103
|
-
*
|
|
104
|
-
* ⚠️
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
* ⚠️
|
|
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: '
|
|
111
|
-
{ id: '
|
|
112
|
-
{ id: '
|
|
113
|
-
{ id: '
|
|
114
|
-
{ id: 'GLM-5.3-Flash', name: 'GLM 5.3 Flash
|
|
115
|
-
{ id: 'qwen3.8-flash', name: '
|
|
116
|
-
|
|
117
|
-
{ id: '
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
-
|
|
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
|
+
}
|
package/src/free-models.js
CHANGED
|
@@ -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)
|
package/src/probe.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* - 全轮 rate_limit → 指数退避(30→60→120 分钟封顶),退避期跳过普通轮
|
|
6
6
|
* - 保守判据:探测失败只记录状态,不进请求冷却(网关抖动/限流 ≠ 模型死亡);
|
|
7
7
|
* 探测成功 → 清除该模型现有冷却,尽快回到路由链头
|
|
8
|
-
* - omr/
|
|
8
|
+
* - omr/ 虚拟组不探测(没有自己的端点);「测试组内模型」是把组展开成成员逐个探
|
|
9
9
|
* - 停用渠道不探测:目录缓存可能滞后(启动预热快照 / SWR 旧目录),探测前按
|
|
10
10
|
* 实时启用状态过滤(免密渠道看 settings、转发渠道看 channels.json、自定义提供商看 enabled)
|
|
11
11
|
* 单轮结果(延迟/状态)在内存;lastProbeAt 持久化到 settings.json,
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { completeOnModel, buildCatalog } from './providers/index.js'
|
|
16
|
-
import { loadSettings, saveSettings, emitRuntimeEvent, DATA_DIR, loadChannels, loadProviders } from './store.js'
|
|
16
|
+
import { loadSettings, saveSettings, emitRuntimeEvent, DATA_DIR, loadChannels, loadProviders, loadGroups } from './store.js'
|
|
17
17
|
import { slugify } from './util.js'
|
|
18
18
|
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
19
19
|
import { join } from 'node:path'
|
|
@@ -59,8 +59,8 @@ export function primeProbeState() {
|
|
|
59
59
|
let timer = null
|
|
60
60
|
/** 全局探测轮进行中(「探测全部」/周期轮)。单渠道测试不占用此标记,避免影响 UI 的探测提示。 */
|
|
61
61
|
let running = false
|
|
62
|
-
/**
|
|
63
|
-
const
|
|
62
|
+
/** 正在批量测试的范围键集合(渠道 / 模型组):各范围互不阻塞,可并行执行。 */
|
|
63
|
+
const scopeRunning = new Map()
|
|
64
64
|
let throttleStreak = 0
|
|
65
65
|
let backoffUntil = 0
|
|
66
66
|
let log = () => {}
|
|
@@ -122,7 +122,7 @@ async function probeOne(row) {
|
|
|
122
122
|
publish(row.id, { state: 'available', detail: '', latencyMs, probedAt: Date.now() })
|
|
123
123
|
// 探测通过 → 清请求冷却(模型恢复后尽快回到链头)
|
|
124
124
|
health.markSuccess(row.id)
|
|
125
|
-
return { ok: true, kind: '' }
|
|
125
|
+
return { ok: true, kind: '', detail: '' }
|
|
126
126
|
} catch (error) {
|
|
127
127
|
const kind = error?.kind ?? 'unknown'
|
|
128
128
|
const message = String(error?.message ?? error).slice(0, 300)
|
|
@@ -138,7 +138,7 @@ async function probeOne(row) {
|
|
|
138
138
|
})
|
|
139
139
|
// 判死 → 长冷却殿后(组路由自动跳过);其余失败不进冷却,防探针误伤
|
|
140
140
|
if (dead) health.markFailure(row.id, 30 * 60_000)
|
|
141
|
-
return { ok: false, kind }
|
|
141
|
+
return { ok: false, kind, detail: message }
|
|
142
142
|
} finally {
|
|
143
143
|
probing.delete(row.id)
|
|
144
144
|
clearTimeout(timer)
|
|
@@ -181,29 +181,48 @@ function collectEnabledKeys(settings) {
|
|
|
181
181
|
return enabled
|
|
182
182
|
}
|
|
183
183
|
|
|
184
|
+
/**
|
|
185
|
+
* 模型组「测试组内模型」的目标集合:组内参与轮询的候选(跳过组内停用项与嵌套组引用,
|
|
186
|
+
* 组不允许套娃,omr/ 成员本身没有可直连的端点)。组不存在返回 null,交由调用方报错。
|
|
187
|
+
*/
|
|
188
|
+
function groupProbeTargets(gid) {
|
|
189
|
+
const g = (loadGroups().groups ?? []).find(x => x.id === gid)
|
|
190
|
+
if (!g) return null
|
|
191
|
+
const disabled = new Set(Array.isArray(g.disabled) ? g.disabled : [])
|
|
192
|
+
return new Set((Array.isArray(g.models) ? g.models : [])
|
|
193
|
+
.filter(id => typeof id === 'string' && id !== '' && !disabled.has(id) && !id.startsWith('omr/')))
|
|
194
|
+
}
|
|
195
|
+
|
|
184
196
|
/**
|
|
185
197
|
* 跑一轮探测。force=true 穿透退避与开关(UI 手动按钮)。
|
|
186
|
-
* channel
|
|
187
|
-
* -
|
|
198
|
+
* 定向轮(channel / group 二选一非空,UI 的「测试本渠道」「测试组内模型」):
|
|
199
|
+
* - 不同范围可并行跑,互不阻塞(同一范围单飞);
|
|
188
200
|
* - 不写 running / 不写 lastProbeAt / 不牵动退避,因此不影响「探测全部」旁的全局探测提示。
|
|
189
|
-
*
|
|
190
|
-
*
|
|
191
|
-
* 返回 { skipped?, reason?, total, ok, throttled }
|
|
201
|
+
* 全局轮与定向轮之间仍互斥(全局轮本来就会覆盖所有目标)。
|
|
202
|
+
* 未启用的渠道一律不探测(手动测试对停用渠道同样返回无可探测模型)。
|
|
203
|
+
* 返回 { skipped?, reason?, total, ok, throttled, channel, group, results };
|
|
204
|
+
* results 为逐模型明细 [{ id, ok, detail }],供 UI 汇总失败项。
|
|
192
205
|
*/
|
|
193
|
-
export async function runProbeRound({ force = false, channel = '' } = {}) {
|
|
194
|
-
const
|
|
195
|
-
|
|
206
|
+
export async function runProbeRound({ force = false, channel = '', group = '' } = {}) {
|
|
207
|
+
const scoped = channel !== '' || group !== ''
|
|
208
|
+
const scopeKey = group !== '' ? `group:${group}` : channel !== '' ? `channel:${channel}` : ''
|
|
209
|
+
const scopeName = group !== '' ? `模型组 omr/${group}` : channel !== '' ? `渠道「${channel}」` : ''
|
|
210
|
+
if (scoped) {
|
|
196
211
|
if (running) return { skipped: true, reason: '全局探测进行中' }
|
|
197
|
-
if (
|
|
198
|
-
} else if (running ||
|
|
212
|
+
if (scopeRunning.has(scopeKey)) return { skipped: true, reason: `${scopeName} 测试进行中` }
|
|
213
|
+
} else if (running || scopeRunning.size > 0) {
|
|
199
214
|
return { skipped: true, reason: '上一轮仍在进行' }
|
|
200
215
|
}
|
|
201
216
|
if (!force && Date.now() < backoffUntil) return { skipped: true, reason: '限流退避中' }
|
|
202
217
|
const settings = loadSettings()
|
|
203
218
|
if (settings.probe?.enabled === false && !force) return { skipped: true, reason: '探测已关闭' }
|
|
204
219
|
|
|
205
|
-
|
|
206
|
-
|
|
220
|
+
// 组轮先解析成员:组不存在 / 组内没有可探测的候选时直接返回,不出网也不占车道
|
|
221
|
+
const memberIds = group !== '' ? groupProbeTargets(group) : null
|
|
222
|
+
if (group !== '' && memberIds === null) return { skipped: true, reason: `模型组 omr/${group} 不存在` }
|
|
223
|
+
|
|
224
|
+
if (scoped) {
|
|
225
|
+
scopeRunning.set(scopeKey, scopeName)
|
|
207
226
|
} else {
|
|
208
227
|
running = true
|
|
209
228
|
emitRuntimeEvent('probe-meta', probeMeta())
|
|
@@ -216,18 +235,22 @@ export async function runProbeRound({ force = false, channel = '' } = {}) {
|
|
|
216
235
|
const targets = catalog.filter(r =>
|
|
217
236
|
!r.offline
|
|
218
237
|
&& (channel === '' || r.channel === channel)
|
|
238
|
+
&& (memberIds === null || memberIds.has(r.id))
|
|
219
239
|
&& enabledKeys.has(r.channelId ?? r.provider))
|
|
220
240
|
if (targets.length === 0) {
|
|
221
|
-
|
|
241
|
+
const emptyReason = group !== ''
|
|
242
|
+
? `模型组 omr/${group} 没有可探测的候选(组内为空 / 全部停用 / 所属渠道未启用)`
|
|
243
|
+
: channel !== '' ? `渠道「${channel}」没有可探测的模型` : '目录为空'
|
|
244
|
+
return { skipped: true, reason: emptyReason }
|
|
222
245
|
}
|
|
223
|
-
log(`探测开始:${targets.length} 个模型(并发 ${CONCURRENCY})${
|
|
246
|
+
log(`探测开始:${targets.length} 个模型(并发 ${CONCURRENCY})${scopeName === '' ? '' : ` · ${scopeName}`}`)
|
|
224
247
|
|
|
225
248
|
const results = await pool(targets, CONCURRENCY, probeOne)
|
|
226
249
|
const ok = results.filter(r => r.ok).length
|
|
227
250
|
const throttled = results.filter(r => !r.ok && r.kind === 'rate_limit').length
|
|
228
251
|
|
|
229
|
-
// 全轮限流 → 指数退避(30→60→120
|
|
230
|
-
if (
|
|
252
|
+
// 全轮限流 → 指数退避(30→60→120 分钟封顶);定向轮不牵动全局退避与「上次探测」时间
|
|
253
|
+
if (!scoped) {
|
|
231
254
|
if (results.length > 0 && throttled === results.length) {
|
|
232
255
|
throttleStreak += 1
|
|
233
256
|
const minutes = Math.min(30 * 2 ** (throttleStreak - 1), 120)
|
|
@@ -242,10 +265,17 @@ export async function runProbeRound({ force = false, channel = '' } = {}) {
|
|
|
242
265
|
}
|
|
243
266
|
log(`探测完成:${ok}/${results.length} 可用`)
|
|
244
267
|
saveProbeCache()
|
|
245
|
-
return {
|
|
268
|
+
return {
|
|
269
|
+
total: results.length,
|
|
270
|
+
ok,
|
|
271
|
+
throttled,
|
|
272
|
+
channel,
|
|
273
|
+
group,
|
|
274
|
+
results: targets.map((r, i) => ({ id: r.id, ok: results[i].ok, detail: results[i].detail ?? '' })),
|
|
275
|
+
}
|
|
246
276
|
} finally {
|
|
247
|
-
if (
|
|
248
|
-
|
|
277
|
+
if (scoped) {
|
|
278
|
+
scopeRunning.delete(scopeKey)
|
|
249
279
|
} else {
|
|
250
280
|
running = false
|
|
251
281
|
emitRuntimeEvent('probe-meta', probeMeta())
|