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.
- package/README.md +11 -6
- package/bin/omr.js +96 -14
- package/package.json +2 -1
- package/src/admin.js +200 -31
- package/src/boot.js +14 -3
- 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/install-forms.js +238 -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 +134 -59
- package/web/app.js +494 -81
- package/web/index.html +2 -2
- package/web/style.css +26 -6
package/README.md
CHANGED
|
@@ -67,11 +67,13 @@ AppImage 需要 `libfuse2`(Ubuntu 22.04+ 可加 `--appimage-extract-and-run`
|
|
|
67
67
|
### npm(无桌面壳,适合服务器 / 无 GUI 环境)
|
|
68
68
|
|
|
69
69
|
```bash
|
|
70
|
-
npm i -g one-model-router #
|
|
71
|
-
omr start --detach
|
|
70
|
+
npm i -g one-model-router # 装完自动启动并打印登录地址
|
|
72
71
|
```
|
|
73
72
|
|
|
74
73
|
npm 版是**网页版**:管理界面在浏览器 <http://127.0.0.1:18681/admin>,数据目录与桌面端共用。
|
|
74
|
+
安装 / 升级结束会自动启动服务(已在跑则自动重启),启动、重启后同样会打印登录地址;
|
|
75
|
+
不想自动启动就设 `OMR_NO_POSTINSTALL_START=1`(CI、容器、`npx` 已自动跳过),
|
|
76
|
+
需要手动起:`omr start --detach`。
|
|
75
77
|
|
|
76
78
|
### Docker
|
|
77
79
|
|
|
@@ -93,6 +95,8 @@ docker run -d --name omr \
|
|
|
93
95
|
1. 启动后打开管理面板:<http://127.0.0.1:18681/admin>
|
|
94
96
|
2. 在「渠道」页勾选要用的免费通道,需要登录的按提示扫码 / 粘贴令牌
|
|
95
97
|
3. 在「模型组」页把可用模型编成一组(自动轮询 + 故障切换)
|
|
98
|
+
- 内置默认组 `omr/default` 开箱即用:成员每小时自动扫描免密渠道(Kilo / OpenCode Zen)
|
|
99
|
+
的可用模型并整表同步,可直接当模型名用
|
|
96
100
|
4. 把 AI 工具的 API 地址指向网关:
|
|
97
101
|
|
|
98
102
|
```
|
|
@@ -118,7 +122,7 @@ curl http://127.0.0.1:18682/v1/models
|
|
|
118
122
|
| `omr stop` / `omr restart` | 停止 / 重启后台实例 |
|
|
119
123
|
| `omr status` | 查看进程、端口与 `/health` 探针 |
|
|
120
124
|
| `omr portal` | 用系统浏览器打开管理面板 |
|
|
121
|
-
| `omr update` | 检查并升级到最新版(按当前系统优先装对应安装包,失败回退 npm
|
|
125
|
+
| `omr update` | 检查并升级到最新版(按当前系统优先装对应安装包,失败回退 npm 升级,完成后自动重启) |
|
|
122
126
|
| `omr update --check` | 只检查是否有新版本 |
|
|
123
127
|
| `omr update --npm` | 强制走 npm 全局升级 |
|
|
124
128
|
| `omr version` | 版本 |
|
|
@@ -134,7 +138,8 @@ curl http://127.0.0.1:18682/v1/models
|
|
|
134
138
|
| `OMR_ADMIN_PORT` | `18681` | 管理面板端口 |
|
|
135
139
|
| `OMR_GATEWAY_HOST` | `127.0.0.1` | 网关监听地址(容器内需设 `0.0.0.0`) |
|
|
136
140
|
| `OMR_ADMIN_HOST` | `127.0.0.1` | 管理面监听地址 |
|
|
137
|
-
| `OMR_NO_UPDATE_CHECK` | — | 设为 `1` 关闭网页版后台自动检查更新 |
|
|
141
|
+
| `OMR_NO_UPDATE_CHECK` | — | 设为 `1` 关闭网页版后台自动检查更新 |
|
|
142
|
+
| `OMR_NO_POSTINSTALL_START` | — | 设为 `1` 关闭 npm 安装 / 升级后的自动启动 |
|
|
138
143
|
|
|
139
144
|
桌面端与 CLI / Docker **共用同一份数据目录**,凭据不需要重复配置。
|
|
140
145
|
|
|
@@ -146,7 +151,7 @@ curl http://127.0.0.1:18682/v1/models
|
|
|
146
151
|
| --- | --- |
|
|
147
152
|
| Windows / macOS / Linux 桌面端 | 管理面板右上角「升级」按钮,内置自更新(源顺序:TRAE 站点 → githubusercontent → Gitee → GitHub → 镜像) |
|
|
148
153
|
| winget | `winget upgrade OneModelRouter.OneModelRouter` |
|
|
149
|
-
| npm(网页版) | `omr update`(按当前系统优先装对应安装包,失败自动回退 `npm i -g one-model-router@latest
|
|
154
|
+
| npm(网页版) | `omr update`(按当前系统优先装对应安装包,失败自动回退 `npm i -g one-model-router@latest`,升级完自动重启并打印登录地址) |
|
|
150
155
|
| npm(网页版,手动) | `npm update -g one-model-router` |
|
|
151
156
|
| Docker | `docker pull` 新 tag 后重建容器 |
|
|
152
157
|
|
|
@@ -173,7 +178,7 @@ curl http://127.0.0.1:18682/v1/models
|
|
|
173
178
|
|
|
174
179
|
**npm 版怎么升级?**
|
|
175
180
|
`omr update`:按当前系统优先装对应原生安装包(Windows 用 Setup、macOS 用 dmg/zip、Linux 用 AppImage),
|
|
176
|
-
失败时自动回退 `npm i -g one-model-router@latest
|
|
181
|
+
失败时自动回退 `npm i -g one-model-router@latest`;升级完自动重启服务并打印登录地址。
|
|
177
182
|
只想检查不升级:`omr update --check`。管理面板右上角「升级」按钮也是同一套逻辑。
|
|
178
183
|
|
|
179
184
|
**Linux AppImage 双击没反应?**
|
package/bin/omr.js
CHANGED
|
@@ -5,6 +5,10 @@
|
|
|
5
5
|
* omr start [--detach] [--port <n>] [--admin-port <n>] [--data-dir <path>]
|
|
6
6
|
* omr stop | restart | status | portal | version | help
|
|
7
7
|
*
|
|
8
|
+
* 安装 / 升级(`npm i -g one-model-router`、`omr update`)完成后会自动把服务拉起来,
|
|
9
|
+
* 并在安装、启动、重启、升级四类动作后统一打印登录地址(管理面板)。
|
|
10
|
+
* 不想自动启动:设 `OMR_NO_POSTINSTALL_START=1`(CI、容器、npx 临时缓存已自动跳过)。
|
|
11
|
+
*
|
|
8
12
|
* 与桌面端共用同一套服务与数据目录,不含 Electron:管理面仍走浏览器
|
|
9
13
|
* (http://127.0.0.1:18681/admin)。
|
|
10
14
|
*
|
|
@@ -14,7 +18,7 @@
|
|
|
14
18
|
*/
|
|
15
19
|
|
|
16
20
|
import { spawn } from 'node:child_process'
|
|
17
|
-
import { closeSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
21
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
18
22
|
import { dirname, join } from 'node:path'
|
|
19
23
|
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
20
24
|
import { runUpdate, checkForUpdate, cleanupStaged } from '../src/update.js'
|
|
@@ -24,9 +28,20 @@ const PKG = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'))
|
|
|
24
28
|
const SERVER = join(ROOT, 'src', 'server.js')
|
|
25
29
|
const KEEP_LOGS = 5
|
|
26
30
|
|
|
31
|
+
/**
|
|
32
|
+
* npm 生命周期钩子模式(package.json 的 postinstall 会调 `omr postinstall`):
|
|
33
|
+
* 这里任何失败都只提示、不以非 0 退出,否则 npm 会把整场安装判为失败。
|
|
34
|
+
*/
|
|
35
|
+
const IS_POSTINSTALL = process.argv[2] === 'postinstall'
|
|
36
|
+
|
|
27
37
|
const log = (...args) => console.log(...args)
|
|
28
38
|
const die = message => {
|
|
29
39
|
console.error(`omr: ${message}`)
|
|
40
|
+
if (IS_POSTINSTALL) {
|
|
41
|
+
console.error('omr: 自动启动未完成,稍后可手动执行 omr start --detach')
|
|
42
|
+
process.exitCode = 0
|
|
43
|
+
return
|
|
44
|
+
}
|
|
30
45
|
process.exit(1)
|
|
31
46
|
}
|
|
32
47
|
|
|
@@ -136,10 +151,11 @@ async function waitHealthy(gatewayPort, timeoutMs) {
|
|
|
136
151
|
return false
|
|
137
152
|
}
|
|
138
153
|
|
|
154
|
+
/** 统一的收尾输出:安装 / 启动 / 重启 / 升级后都靠它打印登录地址。 */
|
|
139
155
|
function printEndpoints(instance) {
|
|
140
156
|
const gw = instance?.gatewayPort ?? GATEWAY_PORT
|
|
141
157
|
const adm = instance?.adminPort ?? ADMIN_PORT
|
|
142
|
-
log(`
|
|
158
|
+
log(` 登录地址 http://127.0.0.1:${adm}/admin`)
|
|
143
159
|
log(` 网关地址 http://127.0.0.1:${gw}/v1`)
|
|
144
160
|
log(` 数据目录 ${DATA_DIR}`)
|
|
145
161
|
}
|
|
@@ -246,7 +262,7 @@ async function status() {
|
|
|
246
262
|
function portal() {
|
|
247
263
|
const instance = readInstance()
|
|
248
264
|
const url = `http://127.0.0.1:${instance.adminPort}/admin`
|
|
249
|
-
log(instance.pid ?
|
|
265
|
+
log(instance.pid ? `登录地址:${url}` : `登录地址:${url}(当前未在运行,先 omr start)`)
|
|
250
266
|
const opener =
|
|
251
267
|
process.platform === 'win32'
|
|
252
268
|
? { cmd: 'cmd', args: ['/c', 'start', '', url] }
|
|
@@ -260,12 +276,43 @@ function portal() {
|
|
|
260
276
|
} catch { /* 打不开就让用户手点,地址已经打在上一行 */ }
|
|
261
277
|
}
|
|
262
278
|
|
|
279
|
+
/** 自动启动的跳过场景,返回跳过原因(空串表示可以自动启动)。 */
|
|
280
|
+
function autoStartSkipReason() {
|
|
281
|
+
const on = value => value !== undefined && value !== '' && !/^(0|false)$/i.test(String(value))
|
|
282
|
+
if (on(process.env.OMR_NO_POSTINSTALL_START)) return 'OMR_NO_POSTINSTALL_START=1'
|
|
283
|
+
if (on(process.env.CI)) return 'CI 环境'
|
|
284
|
+
if (on(process.env.npm_config_ignore_scripts)) return 'npm --ignore-scripts'
|
|
285
|
+
if (process.platform === 'linux' && existsSync('/.dockerenv')) return '容器内'
|
|
286
|
+
// npx 的一次性缓存:跑完就丢,不该留下后台实例
|
|
287
|
+
if (/[\\/]_npx[\\/]/.test(ROOT)) return 'npx 临时缓存'
|
|
288
|
+
return ''
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* package.json 的 postinstall 入口:npm 安装 / 升级(含 `omr update` 内部的
|
|
293
|
+
* `npm i -g @latest`)跑完后自动把服务拉起来并打印登录地址。
|
|
294
|
+
* 已在跑的旧实例(升级场景)先停掉,让新代码接管端口。
|
|
295
|
+
*/
|
|
296
|
+
async function postinstall() {
|
|
297
|
+
const reason = autoStartSkipReason()
|
|
298
|
+
if (reason) {
|
|
299
|
+
log(`OneModelRouter ${PKG.version} 安装完成(已跳过自动启动:${reason})`)
|
|
300
|
+
log(' 需要时手动启动:omr start --detach')
|
|
301
|
+
return
|
|
302
|
+
}
|
|
303
|
+
const scope = String(process.env.npm_config_global || '').toLowerCase() === 'true' ? '全局' : '本地'
|
|
304
|
+
log(`OneModelRouter ${PKG.version} ${scope}安装完成,正在${runningPid() ? '重启已有实例' : '自动启动'}…`)
|
|
305
|
+
if (runningPid()) await stop()
|
|
306
|
+
await startDetached()
|
|
307
|
+
}
|
|
308
|
+
|
|
263
309
|
/**
|
|
264
310
|
* omr update:自更新(与桌面版同一套 feed/产物逻辑)。
|
|
265
|
-
* - 默认 auto
|
|
311
|
+
* - 默认 auto:按本机已安装形态逐个升级——只装 npm 包就只升 npm 包,
|
|
312
|
+
* 只装桌面端就只换原生安装包,两者都装则两者都升;
|
|
266
313
|
* - --npm:强制走 npm i -g one-model-router@latest;
|
|
267
314
|
* - --check:只检查是否有新版本,不下载安装。
|
|
268
|
-
*
|
|
315
|
+
* 升级完成后自动重启服务使其生效,并打印登录地址。
|
|
269
316
|
*/
|
|
270
317
|
async function update() {
|
|
271
318
|
const log = (...a) => console.log(...a)
|
|
@@ -276,22 +323,49 @@ async function update() {
|
|
|
276
323
|
else {
|
|
277
324
|
log(`可升级:v${info.current} → v${info.latest}(更新源:${info.source})`)
|
|
278
325
|
if (info.notes) log(`更新说明:${info.notes}`)
|
|
279
|
-
log(
|
|
326
|
+
log(`已安装形态:${info.forms?.text || '未探测到'}`)
|
|
327
|
+
const scope = [info.targets?.desktop && '桌面端', info.targets?.npm && 'npm 包'].filter(Boolean).join(' + ')
|
|
328
|
+
log(`执行 omr update 升级${scope ? `(${scope})` : ''}${info.asset ? '' : '(本平台无原生包)'}`)
|
|
280
329
|
}
|
|
281
330
|
return
|
|
282
331
|
}
|
|
283
|
-
const
|
|
284
|
-
if (pid) log(`检测到正在运行的实例(PID ${pid}
|
|
332
|
+
const instance = readInstance()
|
|
333
|
+
if (instance.pid) log(`检测到正在运行的实例(PID ${instance.pid}),升级完成后自动重启`)
|
|
334
|
+
// 嵌套的 npm i -g 会触发本包 postinstall;关掉它,重启统一由 restartAfterUpgrade 负责,避免停两次
|
|
335
|
+
process.env.OMR_NO_POSTINSTALL_START = '1'
|
|
336
|
+
let result = null
|
|
285
337
|
try {
|
|
286
|
-
|
|
287
|
-
if (!result.updated) {
|
|
288
|
-
log(`已是最新版本 v${result.current ?? ''}`)
|
|
289
|
-
}
|
|
338
|
+
result = await runUpdate({ mode, log })
|
|
290
339
|
} catch (error) {
|
|
291
340
|
die(`升级失败:${error?.message ?? error}`)
|
|
292
341
|
} finally {
|
|
293
342
|
cleanupStaged()
|
|
294
343
|
}
|
|
344
|
+
if (!result?.updated) {
|
|
345
|
+
log(`已是最新版本 v${result?.current ?? ''}`)
|
|
346
|
+
if (instance.pid) printEndpoints(instance)
|
|
347
|
+
return
|
|
348
|
+
}
|
|
349
|
+
await restartAfterUpgrade(instance, result.via === 'native')
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* 升级后自动重启,让新代码接管端口并打印登录地址。
|
|
354
|
+
* 原生安装包路径下桌面端可能由安装器自己拉起,先等它接管(最多 30 秒),
|
|
355
|
+
* 等不到再回退用本机 node 起后台实例。
|
|
356
|
+
*/
|
|
357
|
+
async function restartAfterUpgrade(instance, viaNative) {
|
|
358
|
+
await stop()
|
|
359
|
+
if (viaNative && instance.pid) {
|
|
360
|
+
log('原生安装包已更新,等待新版服务接管端口…')
|
|
361
|
+
if (await waitHealthy(instance.gatewayPort, 30_000)) {
|
|
362
|
+
log('新版服务已就绪')
|
|
363
|
+
printEndpoints(instance)
|
|
364
|
+
return
|
|
365
|
+
}
|
|
366
|
+
log('未检测到新版服务,改用本机 node 后台实例启动')
|
|
367
|
+
}
|
|
368
|
+
await startDetached()
|
|
295
369
|
}
|
|
296
370
|
|
|
297
371
|
function version() {
|
|
@@ -308,17 +382,23 @@ function help() {
|
|
|
308
382
|
log(' stop 停止后台实例')
|
|
309
383
|
log(' restart 停止后重新后台启动')
|
|
310
384
|
log(' status 查看运行状态与健康探针')
|
|
311
|
-
log(' portal
|
|
312
|
-
log(' update
|
|
385
|
+
log(' portal 打印并用系统浏览器打开管理面板(登录地址)')
|
|
386
|
+
log(' update 检查并升级到最新版(按本机已安装形态:npm 包 / 桌面端,装了什么升什么)')
|
|
313
387
|
log(' update --check 只检查是否有新版本')
|
|
314
388
|
log(' update --npm 强制走 npm 全局升级(npm i -g one-model-router@latest)')
|
|
315
389
|
log(' version 显示版本')
|
|
316
390
|
log('')
|
|
391
|
+
log(' 安装 / 升级 / 启动 / 重启 完成后都会自动打印登录地址;')
|
|
392
|
+
log(' npm 安装或升级结束后还会自动把服务拉起来(postinstall)。')
|
|
393
|
+
log('')
|
|
317
394
|
log('选项:')
|
|
318
395
|
log(' --port <n> 网关端口(默认 18682,等同 OMR_GATEWAY_PORT)')
|
|
319
396
|
log(' --admin-port <n> 管理面端口(默认 18681,等同 OMR_ADMIN_PORT)')
|
|
320
397
|
log(' --data-dir <path> 数据目录(默认 ~/.OneModelRouter/data,等同 OMR_DATA_DIR)')
|
|
321
398
|
log('')
|
|
399
|
+
log('环境变量:')
|
|
400
|
+
log(' OMR_NO_POSTINSTALL_START=1 关闭 npm 安装 / 升级后的自动启动')
|
|
401
|
+
log('')
|
|
322
402
|
log('Agent 侧接入:baseURL 填 http://127.0.0.1:' + GATEWAY_PORT + '/v1')
|
|
323
403
|
}
|
|
324
404
|
|
|
@@ -339,6 +419,8 @@ const commands = {
|
|
|
339
419
|
},
|
|
340
420
|
version,
|
|
341
421
|
help,
|
|
422
|
+
// npm 生命周期钩子(package.json: postinstall → node bin/omr.js postinstall)
|
|
423
|
+
postinstall,
|
|
342
424
|
}
|
|
343
425
|
|
|
344
426
|
const run = commands[args.command]
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "one-model-router",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.15",
|
|
4
4
|
"description": "本地模型路由网关:聚合免费/自有模型通道,OpenAI 兼容转发,模型组自动轮询切换,自动签到领积分",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "OneModelRouter",
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
],
|
|
23
23
|
"scripts": {
|
|
24
24
|
"start": "node src/server.js",
|
|
25
|
+
"postinstall": "node bin/omr.js postinstall",
|
|
25
26
|
"start:bg": "powershell -NoProfile -ExecutionPolicy Bypass -File omr.ps1 start",
|
|
26
27
|
"stop": "powershell -NoProfile -ExecutionPolicy Bypass -File omr.ps1 stop",
|
|
27
28
|
"restart": "powershell -NoProfile -ExecutionPolicy Bypass -File omr.ps1 restart",
|
package/src/admin.js
CHANGED
|
@@ -16,14 +16,16 @@ import * as openaiCompat from './providers/openai-compat.js'
|
|
|
16
16
|
import { withLastGoodFallback } from './providers/last-good.js'
|
|
17
17
|
import { CHANNELS, channelById, enabledAccounts, addAccount, updateAccount, removeAccount, saveAccountCredential, markAccountError } from './channels/index.js'
|
|
18
18
|
import { pruneRotation, buildGroupCatalogRows } from './router.js'
|
|
19
|
+
import { isDefaultGroup, builtinGroupMembers } from './default-group.js'
|
|
19
20
|
import * as health from './health.js'
|
|
20
21
|
import * as checkin from './checkin.js'
|
|
21
22
|
import * as probe from './probe.js'
|
|
22
23
|
import { freeModelsState } from './free-models.js'
|
|
23
|
-
import { syncState, updateSyncSettings, generatePairCode, latestPair, startRelayBrowserLogin, relayBrowserLoginState, cancelRelayBrowserLogin } from './sync/index.js'
|
|
24
|
+
import { syncState, updateSyncSettings, generatePairCode, latestPair, startRelayBrowserLogin, startRelayQrLogin, pollRelayQrLogin, relayBrowserLoginState, cancelRelayBrowserLogin } from './sync/index.js'
|
|
24
25
|
import { json, openAiError, slugify, shortId, generateApiKey } from './util.js'
|
|
25
26
|
import { BUILTIN_PROVIDERS, BUILTIN_IDS } from './providers/builtin.js'
|
|
26
27
|
import { checkForUpdate, runUpdate, applyUpdate, getUpdateState, onUpdateEvent } from './update.js'
|
|
28
|
+
import { detectForms } from './install-forms.js'
|
|
27
29
|
|
|
28
30
|
const WEB_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'web')
|
|
29
31
|
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.json': 'application/json' }
|
|
@@ -38,7 +40,49 @@ function appVersionText() {
|
|
|
38
40
|
return appVersion
|
|
39
41
|
}
|
|
40
42
|
|
|
41
|
-
|
|
43
|
+
/**
|
|
44
|
+
* 更新引擎适配层:把「宿主自己的更新器」与「内置 npm 引擎」统一成同一套 HTTP 语义,
|
|
45
|
+
* 这样浏览器打开的管理面板,无论服务是 Electron 主进程还是 `omr start` 起的 Node 进程,
|
|
46
|
+
* 拿到的都是同一份状态与同一组动作(getState / check / run / install)。
|
|
47
|
+
*
|
|
48
|
+
* @param {{ getState:()=>any, check:()=>Promise<any>, run:()=>Promise<any>, install:()=>Promise<any> }} host
|
|
49
|
+
* 宿主注入的更新器(桌面端传 electron/updater.js 的公开态);不传则用内置引擎。
|
|
50
|
+
*/
|
|
51
|
+
function createUpdateEngine(host, log) {
|
|
52
|
+
if (host) {
|
|
53
|
+
// 宿主已经把状态、进度、错误都放进自己的状态机,这里只做异常归一
|
|
54
|
+
const wrap = async fn => {
|
|
55
|
+
try { const r = await fn(); return r && typeof r === 'object' ? r : { ok: r !== false } }
|
|
56
|
+
catch (error) { return { ok: false, error: String(error?.message ?? error) } }
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
getState: () => host.getState(),
|
|
60
|
+
check: () => wrap(() => host.check()),
|
|
61
|
+
run: () => wrap(() => host.run()),
|
|
62
|
+
install: () => wrap(() => host.install()),
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
getState: () => getUpdateState(),
|
|
67
|
+
check: async () => {
|
|
68
|
+
try { await checkForUpdate(); return { ok: true } }
|
|
69
|
+
catch (error) { return { ok: false, error: error?.message ?? String(error) } }
|
|
70
|
+
},
|
|
71
|
+
// 面板点「升级」= 一次完成全部已安装形态的升级(原生包 + npm 包)
|
|
72
|
+
run: async () => {
|
|
73
|
+
try {
|
|
74
|
+
const result = await runUpdate({ mode: 'auto', log: () => {} })
|
|
75
|
+
return { ok: !result.error && result.updated !== false, error: result.error ?? null, via: result.via ?? null }
|
|
76
|
+
} catch (error) { return { ok: false, error: error?.message ?? String(error) } }
|
|
77
|
+
},
|
|
78
|
+
install: async () => {
|
|
79
|
+
const ok = await applyUpdate({ log: () => {} })
|
|
80
|
+
return { ok, error: getUpdateState().error }
|
|
81
|
+
},
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function createAdminServer({ log = () => {}, updater = null } = {}) {
|
|
42
86
|
const server = http.createServer((req, res) => {
|
|
43
87
|
void handle(req, res).catch(error => {
|
|
44
88
|
log(`admin request failed: ${error?.message ?? error}`)
|
|
@@ -46,9 +90,11 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
46
90
|
else res.end()
|
|
47
91
|
})
|
|
48
92
|
})
|
|
93
|
+
const updateEngine = createUpdateEngine(updater, log)
|
|
49
94
|
|
|
50
|
-
//
|
|
51
|
-
|
|
95
|
+
// 内置引擎(Node 宿主):更新状态变化经 SSE 'update' 事件推给管理面板。
|
|
96
|
+
// 桌面端不订阅这里——主进程自己会把原生更新器的状态 emitRuntimeEvent('update', …)。
|
|
97
|
+
if (!updater && !process.versions.electron) {
|
|
52
98
|
onUpdateEvent(next => emitRuntimeEvent('update', next))
|
|
53
99
|
}
|
|
54
100
|
|
|
@@ -57,24 +103,16 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
57
103
|
const path = url.pathname.replace(/\/+$/, '') || '/'
|
|
58
104
|
|
|
59
105
|
if (path === '/admin/api/version' && req.method === 'GET') return json(res, 200, { version: appVersionText() })
|
|
60
|
-
//
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
if (path === '/admin/api/update/run' && req.method === 'POST') {
|
|
68
|
-
try {
|
|
69
|
-
const result = await runUpdate({ mode: 'auto', log: () => {} })
|
|
70
|
-
return json(res, 200, { ok: !result.error, error: result.error ?? null, via: result.via ?? null })
|
|
71
|
-
} catch (error) { return json(res, 200, { ok: false, error: error?.message ?? String(error) }) }
|
|
72
|
-
}
|
|
73
|
-
if (path === '/admin/api/update/install' && req.method === 'POST') {
|
|
74
|
-
const ok = await applyUpdate({ log: () => {} })
|
|
75
|
-
return json(res, 200, { ok, error: getUpdateState().error })
|
|
76
|
-
}
|
|
106
|
+
// 自更新接口:桌面宿主(Electron 注入原生更新器)与 npm 宿主(内置引擎)走同一组路由,
|
|
107
|
+
// 浏览器里打开的面板因此与桌面窗口内的面板能力完全一致。
|
|
108
|
+
if (path === '/admin/api/update' && req.method === 'GET') return json(res, 200, updateEngine.getState() ?? { status: 'idle' })
|
|
109
|
+
if (path === '/admin/api/update/forms' && req.method === 'GET') {
|
|
110
|
+
try { return json(res, 200, await detectForms({ refresh: url.searchParams.get('refresh') === '1' })) }
|
|
111
|
+
catch (error) { return json(res, 200, { desktop: { installed: false }, npm: { installed: false }, installed: [], error: error?.message ?? String(error) }) }
|
|
77
112
|
}
|
|
113
|
+
if (path === '/admin/api/update/check' && req.method === 'POST') return json(res, 200, await updateEngine.check())
|
|
114
|
+
if (path === '/admin/api/update/run' && req.method === 'POST') return json(res, 200, await updateEngine.run())
|
|
115
|
+
if (path === '/admin/api/update/install' && req.method === 'POST') return json(res, 200, await updateEngine.install())
|
|
78
116
|
if (path === '/admin/api/state' && req.method === 'GET') return apiState(res)
|
|
79
117
|
if (path === '/admin/api/settings' && req.method === 'PUT') return apiUpdateSettings(req, res)
|
|
80
118
|
if (path === '/admin/api/opencode/probe' && req.method === 'POST') return apiProbeOpencode(res)
|
|
@@ -111,6 +149,14 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
111
149
|
if (path === '/admin/api/sync/login' && req.method === 'POST') return json(res, 200, await startRelayBrowserLogin())
|
|
112
150
|
if (path === '/admin/api/sync/login/status' && req.method === 'GET') return json(res, 200, relayBrowserLoginState())
|
|
113
151
|
if (path === '/admin/api/sync/login/cancel' && req.method === 'POST') return json(res, 200, await cancelRelayBrowserLogin())
|
|
152
|
+
// 站点托管扫码登录:起步出二维码,轮询拿令牌自动注册(令牌不进返回值)
|
|
153
|
+
if (path === '/admin/api/sync/login/qr/start' && req.method === 'POST') {
|
|
154
|
+
const body = await readBody(req)
|
|
155
|
+
return json(res, 200, await startRelayQrLogin(body.provider, body.mode === 'mobile' ? 'mobile' : 'direct'))
|
|
156
|
+
}
|
|
157
|
+
if (path === '/admin/api/sync/login/qr/poll' && req.method === 'GET') {
|
|
158
|
+
return json(res, 200, await pollRelayQrLogin(url.searchParams.get('qrId')))
|
|
159
|
+
}
|
|
114
160
|
if (path === '/admin/api/sync/pair-code' && req.method === 'POST') {
|
|
115
161
|
const pair = await generatePairCode()
|
|
116
162
|
return json(res, pair.ok === false ? 400 : 200, pair)
|
|
@@ -122,6 +168,12 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
122
168
|
if (path === '/admin/api/requests' && req.method === 'GET') return json(res, 200, { stats: runtime.stats, recent: runtime.recentRequests, health: health.snapshot(), probe: probe.probeSnapshot(), probeMeta: probe.probeMeta() })
|
|
123
169
|
if (path === '/admin/api/events' && req.method === 'GET') return apiEvents(req, res)
|
|
124
170
|
|
|
171
|
+
// 未注册的 API 路径必须回 JSON 404:漏了这条会被下面的 SPA 回退吞成 index.html(200),
|
|
172
|
+
// 前端 fetch().json() 直接解析失败,表现为「功能静默不可用」而不是「接口不存在」。
|
|
173
|
+
if (path.startsWith('/admin/api/')) {
|
|
174
|
+
openAiError(res, 404, 'not_found_error', `no admin route: ${req.method} ${path}`)
|
|
175
|
+
return
|
|
176
|
+
}
|
|
125
177
|
// 静态 UI:/admin、/、以及静态资源
|
|
126
178
|
if (req.method === 'GET') return serveStatic(path, res)
|
|
127
179
|
openAiError(res, 404, 'not_found_error', `no admin route: ${req.method} ${path}`)
|
|
@@ -376,11 +428,12 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
376
428
|
json(res, 200, { ok: true, count: catalog.filter(r => !r.offline).length })
|
|
377
429
|
}
|
|
378
430
|
|
|
379
|
-
/** 手动触发一轮探测(force 穿透退避与开关);body.channel
|
|
431
|
+
/** 手动触发一轮探测(force 穿透退避与开关);body.channel / body.group 非空时只探测该范围内的模型(可多范围并行)。 */
|
|
380
432
|
async function apiRunProbe(req, res) {
|
|
381
433
|
const body = await readBody(req).catch(() => ({}))
|
|
382
434
|
const channel = String(body.channel ?? '').trim()
|
|
383
|
-
const
|
|
435
|
+
const group = String(body.group ?? '').trim()
|
|
436
|
+
const result = await probe.runProbeRound({ force: true, channel, group })
|
|
384
437
|
json(res, 200, { ok: !result.skipped, ...result })
|
|
385
438
|
}
|
|
386
439
|
|
|
@@ -578,16 +631,58 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
578
631
|
const body = await readBody(req)
|
|
579
632
|
const name = String(body.name ?? '').trim()
|
|
580
633
|
const models = [...new Set((Array.isArray(body.models) ? body.models : []).map(v => String(v ?? '').trim()).filter(v => v !== ''))]
|
|
634
|
+
const doc = loadGroups()
|
|
635
|
+
doc.groups ??= []
|
|
636
|
+
// 新建 vs 编辑:新建时前端不传 id(或传空串),id 由名称 slugify 派生。
|
|
637
|
+
const isCreate = body.id === undefined || body.id === null || body.id === ''
|
|
638
|
+
const id = body.id ?? slugify(name)
|
|
639
|
+
const prev = doc.groups.find(g => g.id === id)
|
|
640
|
+
// 内置默认组(omr/default):成员集合由小时扫描维护,手动保存只能调序,不能增删。
|
|
641
|
+
if (isDefaultGroup(id)) {
|
|
642
|
+
// 新建时撞上保留字:直接拒绝,别把内置组覆盖掉
|
|
643
|
+
if (isCreate) {
|
|
644
|
+
openAiError(res, 400, 'invalid_request_error', `模型组 ID「default」为内置默认组保留字,请换一个名称`)
|
|
645
|
+
return
|
|
646
|
+
}
|
|
647
|
+
// 自建的同名组(id=default 但不是内置组)不该被当成内置组覆盖:让出 default 给内置组
|
|
648
|
+
if (prev && prev.builtin !== true) {
|
|
649
|
+
openAiError(res, 400, 'invalid_request_error', `模型组 ID「default」为内置默认组保留字,请换一个名称`)
|
|
650
|
+
return
|
|
651
|
+
}
|
|
652
|
+
const kept = Array.isArray(prev?.models) ? prev.models : []
|
|
653
|
+
if (kept.length === 0) {
|
|
654
|
+
openAiError(res, 400, 'invalid_request_error', `内置模型组 omr/${id} 的成员由系统维护,请稍候扫描完成`)
|
|
655
|
+
return
|
|
656
|
+
}
|
|
657
|
+
// 成员集合由扫描维护,这里只接受重排(增删会被丢弃,排序由用户决定)
|
|
658
|
+
const nextModels = builtinGroupMembers(kept, body.models)
|
|
659
|
+
const rawDisabled = Array.isArray(body.disabled) ? body.disabled : (Array.isArray(prev?.disabled) ? prev.disabled : [])
|
|
660
|
+
// 内置组的停用清单不做「成员仍在组内」过滤:模型被上游下架后重新上架时,
|
|
661
|
+
// 用户的停用意图依然生效。
|
|
662
|
+
const disabled = [...new Set(rawDisabled.map(v => String(v ?? '').trim()))].filter(v => v !== '')
|
|
663
|
+
const row = {
|
|
664
|
+
id,
|
|
665
|
+
name: name === '' ? (prev?.name ?? id) : name,
|
|
666
|
+
models: nextModels,
|
|
667
|
+
strategy: body.strategy === 'round-robin' ? 'round-robin' : (prev?.strategy === 'round-robin' ? 'round-robin' : 'fallback'),
|
|
668
|
+
stickyLimit: Math.max(1, Math.trunc(Number(body.stickyLimit) || prev?.stickyLimit || 3)),
|
|
669
|
+
enabled: body.enabled !== undefined ? body.enabled !== false : prev?.enabled !== false,
|
|
670
|
+
disabled,
|
|
671
|
+
builtin: true,
|
|
672
|
+
}
|
|
673
|
+
doc.groups[doc.groups.indexOf(prev)] = row
|
|
674
|
+
saveGroups(doc)
|
|
675
|
+
pruneRotation(doc.groups.map(g => g.id))
|
|
676
|
+
emitRuntimeEvent('groups', loadGroups().groups) // 通知多端同步
|
|
677
|
+
json(res, 200, { ok: true, group: row, builtin: true })
|
|
678
|
+
return
|
|
679
|
+
}
|
|
581
680
|
if (name === '' || models.length === 0) {
|
|
582
681
|
openAiError(res, 400, 'invalid_request_error', 'name 与至少一个成员模型必填')
|
|
583
682
|
return
|
|
584
683
|
}
|
|
585
|
-
const doc = loadGroups()
|
|
586
|
-
doc.groups ??= []
|
|
587
|
-
const id = body.id ?? slugify(name)
|
|
588
684
|
// disabled:成员仍留在组里(保序),仅不参与轮询/故障切换;仅保留仍在 models 内的 id。
|
|
589
685
|
// 未携带 disabled(其他写入口/旧客户端)时沿用原停用清单,避免静默把停用项全部恢复启用。
|
|
590
|
-
const prev = doc.groups.find(g => g.id === id)
|
|
591
686
|
const rawDisabled = Array.isArray(body.disabled) ? body.disabled : (Array.isArray(prev?.disabled) ? prev.disabled : [])
|
|
592
687
|
const disabled = [...new Set(rawDisabled.map(v => String(v ?? '').trim()))].filter(v => models.includes(v))
|
|
593
688
|
const row = {
|
|
@@ -608,6 +703,10 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
608
703
|
|
|
609
704
|
async function apiDeleteGroup(req, res) {
|
|
610
705
|
const id = decodeURIComponent(req.url.split('/').pop() ?? '')
|
|
706
|
+
if (isDefaultGroup(id)) {
|
|
707
|
+
openAiError(res, 400, 'invalid_request_error', `内置模型组 omr/${id} 不可删除`)
|
|
708
|
+
return
|
|
709
|
+
}
|
|
611
710
|
const doc = loadGroups()
|
|
612
711
|
doc.groups = (doc.groups ?? []).filter(g => g.id !== id)
|
|
613
712
|
saveGroups(doc)
|
|
@@ -691,6 +790,8 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
691
790
|
|
|
692
791
|
/** 进行中的在线登录流程:channelId -> { loginUrl, status, error, startedAt }。 */
|
|
693
792
|
const pendingLogins = new Map()
|
|
793
|
+
/** 「添加账号」的浏览器登录流程:channelId -> { status, message, error, startedAt }。 */
|
|
794
|
+
const localAccountLogins = new Map()
|
|
694
795
|
|
|
695
796
|
function apiChannels(res) {
|
|
696
797
|
const channels = CHANNELS.map(ch => {
|
|
@@ -703,6 +804,7 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
703
804
|
repo: ch.meta.repo ?? '',
|
|
704
805
|
loginMode: ch.meta.loginMode ?? 'credential',
|
|
705
806
|
localLogin: ch.meta.localLogin === true,
|
|
807
|
+
localAccount: ch.meta.localAccount === true,
|
|
706
808
|
anonymousModels: ch.meta.anonymousModels === true,
|
|
707
809
|
enabled: state.enabled,
|
|
708
810
|
models: state.models,
|
|
@@ -739,6 +841,8 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
739
841
|
if (sub === 'login' && req.method === 'POST') return apiChannelLoginStart(req, res, id)
|
|
740
842
|
if (sub === 'login' && req.method === 'GET') return apiChannelLoginStatus(res, id)
|
|
741
843
|
if (sub === 'credential' && req.method === 'POST') return apiChannelAddCredential(req, res, id)
|
|
844
|
+
if (sub === 'local-account' && req.method === 'POST') return apiChannelAddLocalAccount(req, res, id)
|
|
845
|
+
if (sub === 'local-account' && req.method === 'GET') return apiChannelLocalAccountStatus(res, id)
|
|
742
846
|
if (sub === 'accounts' && rest.length >= 3) return apiChannelAccount(req, res, id, decodeURIComponent(rest[2]), req.method)
|
|
743
847
|
openAiError(res, 404, 'not_found_error', `no channel route: ${req.method} ${path}`)
|
|
744
848
|
}
|
|
@@ -863,6 +967,69 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
863
967
|
}
|
|
864
968
|
}
|
|
865
969
|
|
|
970
|
+
/**
|
|
971
|
+
* 「添加账号」:不接收任何凭据,由渠道自行从本机读取(如灵犀读取本机客户端
|
|
972
|
+
* Cookie 库)。读取/校验失败时把可读原因带回 UI,不要求手工粘贴。
|
|
973
|
+
*/
|
|
974
|
+
async function apiChannelAddLocalAccount(req, res, id) {
|
|
975
|
+
const ch = channelById(id)
|
|
976
|
+
if (typeof ch.addLocalAccount !== 'function') {
|
|
977
|
+
openAiError(res, 400, 'invalid_request_error', '该渠道不支持从本机自动读取账号')
|
|
978
|
+
return
|
|
979
|
+
}
|
|
980
|
+
const existing = localAccountLogins.get(id)
|
|
981
|
+
if (existing?.status === 'pending') {
|
|
982
|
+
json(res, 200, { ok: false, pending: true, message: existing.message })
|
|
983
|
+
return
|
|
984
|
+
}
|
|
985
|
+
const body = await readBody(req).catch(() => ({}))
|
|
986
|
+
const entry = { status: 'pending', message: '正在读取本机灵犀登录态…', startedAt: Date.now() }
|
|
987
|
+
localAccountLogins.set(id, entry)
|
|
988
|
+
let credential
|
|
989
|
+
try {
|
|
990
|
+
credential = await ch.addLocalAccount()
|
|
991
|
+
} catch (error) {
|
|
992
|
+
// 账号已被上游风控拦截时,换浏览器登录同一账号也无济于事,直接报错。
|
|
993
|
+
if (error?.code === 'blocked' || typeof ch.startBrowserLogin !== 'function') {
|
|
994
|
+
localAccountLogins.delete(id)
|
|
995
|
+
openAiError(res, 400, 'invalid_request_error', String(error?.message ?? error))
|
|
996
|
+
return
|
|
997
|
+
}
|
|
998
|
+
let flow
|
|
999
|
+
try {
|
|
1000
|
+
flow = ch.startBrowserLogin()
|
|
1001
|
+
} catch (browserError) {
|
|
1002
|
+
localAccountLogins.delete(id)
|
|
1003
|
+
openAiError(res, 400, 'invalid_request_error', `${error.brief || error.message};${browserError.message}`)
|
|
1004
|
+
return
|
|
1005
|
+
}
|
|
1006
|
+
entry.message = `${error.brief || error.message};已打开浏览器登录窗口,请在窗口中完成 WPS 登录`
|
|
1007
|
+
flow.then(browserCredential => {
|
|
1008
|
+
entry.status = 'done'
|
|
1009
|
+
addAccount(id, browserCredential)
|
|
1010
|
+
invalidateCatalog()
|
|
1011
|
+
emitRuntimeEvent('channels', { channelId: id })
|
|
1012
|
+
log(`channel ${id} 浏览器登录成功`)
|
|
1013
|
+
}).catch(browserError => {
|
|
1014
|
+
entry.status = 'error'
|
|
1015
|
+
entry.error = String(browserError?.message ?? browserError)
|
|
1016
|
+
log(`channel ${id} 浏览器登录失败: ${entry.error}`)
|
|
1017
|
+
})
|
|
1018
|
+
json(res, 200, { ok: false, pending: true, message: entry.message })
|
|
1019
|
+
return
|
|
1020
|
+
}
|
|
1021
|
+
const accountId = addAccount(id, credential, typeof body.label === 'string' ? body.label : '')
|
|
1022
|
+
localAccountLogins.delete(id)
|
|
1023
|
+
invalidateCatalog()
|
|
1024
|
+
emitRuntimeEvent('channels', { channelId: id })
|
|
1025
|
+
json(res, 200, { ok: true, accountId, described: ch.describeCredential(credential) })
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
function apiChannelLocalAccountStatus(res, id) {
|
|
1029
|
+
const entry = localAccountLogins.get(id)
|
|
1030
|
+
json(res, 200, entry ?? { status: 'idle' })
|
|
1031
|
+
}
|
|
1032
|
+
|
|
866
1033
|
async function apiChannelAccount(req, res, id, accountId, method) {
|
|
867
1034
|
const ch = channelById(id)
|
|
868
1035
|
if (method === 'DELETE') {
|
|
@@ -952,14 +1119,16 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
952
1119
|
return server
|
|
953
1120
|
}
|
|
954
1121
|
|
|
955
|
-
export async function startAdmin({ log = () => {}, port = 18681, host = '127.0.0.1' } = {}) {
|
|
956
|
-
const server = createAdminServer({ log })
|
|
1122
|
+
export async function startAdmin({ log = () => {}, port = 18681, host = '127.0.0.1', updater = null } = {}) {
|
|
1123
|
+
const server = createAdminServer({ log, updater })
|
|
957
1124
|
return new Promise((resolve, reject) => {
|
|
958
1125
|
server.once('error', reject)
|
|
959
1126
|
server.listen(port, host, () => {
|
|
960
1127
|
server.off('error', reject)
|
|
961
|
-
|
|
962
|
-
|
|
1128
|
+
// 端口传 0 时由系统分配:回填真实端口,否则调用方拿到的仍是 0
|
|
1129
|
+
const actual = server.address()?.port || port
|
|
1130
|
+
log(`admin UI listening on http://${host}:${actual}/admin`)
|
|
1131
|
+
resolve({ server, port: actual, host })
|
|
963
1132
|
})
|
|
964
1133
|
})
|
|
965
1134
|
}
|