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 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 # 或:npx one-model-router start --detach
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`;升级完执行 `omr restart` 生效。
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(` 管理面板 http://127.0.0.1:${adm}/admin`)
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 ? `管理面板:${url}` : `管理面板:${url}(当前未在运行,先 omr start)`)
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,42 @@ 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
311
  * - 默认 auto:按当前系统优先装对应原生安装包,失败自动回退 npm 全局升级;
266
312
  * - --npm:强制走 npm i -g one-model-router@latest;
267
313
  * - --check:只检查是否有新版本,不下载安装。
268
- * 升级完成后需要重启服务使其生效(omr restart)。
314
+ * 升级完成后自动重启服务使其生效,并打印登录地址。
269
315
  */
270
316
  async function update() {
271
317
  const log = (...a) => console.log(...a)
@@ -280,18 +326,43 @@ async function update() {
280
326
  }
281
327
  return
282
328
  }
283
- const pid = runningPid()
284
- if (pid) log(`检测到正在运行的实例(PID ${pid});升级完成后请执行 omr restart 重启使其生效`)
329
+ const instance = readInstance()
330
+ if (instance.pid) log(`检测到正在运行的实例(PID ${instance.pid}),升级完成后自动重启`)
331
+ // 嵌套的 npm i -g 会触发本包 postinstall;关掉它,重启统一由 restartAfterUpgrade 负责,避免停两次
332
+ process.env.OMR_NO_POSTINSTALL_START = '1'
333
+ let result = null
285
334
  try {
286
- const result = await runUpdate({ mode, log })
287
- if (!result.updated) {
288
- log(`已是最新版本 v${result.current ?? ''}`)
289
- }
335
+ result = await runUpdate({ mode, log })
290
336
  } catch (error) {
291
337
  die(`升级失败:${error?.message ?? error}`)
292
338
  } finally {
293
339
  cleanupStaged()
294
340
  }
341
+ if (!result?.updated) {
342
+ log(`已是最新版本 v${result?.current ?? ''}`)
343
+ if (instance.pid) printEndpoints(instance)
344
+ return
345
+ }
346
+ await restartAfterUpgrade(instance, result.via === 'native')
347
+ }
348
+
349
+ /**
350
+ * 升级后自动重启,让新代码接管端口并打印登录地址。
351
+ * 原生安装包路径下桌面端可能由安装器自己拉起,先等它接管(最多 30 秒),
352
+ * 等不到再回退用本机 node 起后台实例。
353
+ */
354
+ async function restartAfterUpgrade(instance, viaNative) {
355
+ await stop()
356
+ if (viaNative && instance.pid) {
357
+ log('原生安装包已更新,等待新版服务接管端口…')
358
+ if (await waitHealthy(instance.gatewayPort, 30_000)) {
359
+ log('新版服务已就绪')
360
+ printEndpoints(instance)
361
+ return
362
+ }
363
+ log('未检测到新版服务,改用本机 node 后台实例启动')
364
+ }
365
+ await startDetached()
295
366
  }
296
367
 
297
368
  function version() {
@@ -308,17 +379,23 @@ function help() {
308
379
  log(' stop 停止后台实例')
309
380
  log(' restart 停止后重新后台启动')
310
381
  log(' status 查看运行状态与健康探针')
311
- log(' portal 打印并用系统浏览器打开管理面板')
382
+ log(' portal 打印并用系统浏览器打开管理面板(登录地址)')
312
383
  log(' update 检查并升级到最新版(按系统优先装原生包,失败回退 npm 升级)')
313
384
  log(' update --check 只检查是否有新版本')
314
385
  log(' update --npm 强制走 npm 全局升级(npm i -g one-model-router@latest)')
315
386
  log(' version 显示版本')
316
387
  log('')
388
+ log(' 安装 / 升级 / 启动 / 重启 完成后都会自动打印登录地址;')
389
+ log(' npm 安装或升级结束后还会自动把服务拉起来(postinstall)。')
390
+ log('')
317
391
  log('选项:')
318
392
  log(' --port <n> 网关端口(默认 18682,等同 OMR_GATEWAY_PORT)')
319
393
  log(' --admin-port <n> 管理面端口(默认 18681,等同 OMR_ADMIN_PORT)')
320
394
  log(' --data-dir <path> 数据目录(默认 ~/.OneModelRouter/data,等同 OMR_DATA_DIR)')
321
395
  log('')
396
+ log('环境变量:')
397
+ log(' OMR_NO_POSTINSTALL_START=1 关闭 npm 安装 / 升级后的自动启动')
398
+ log('')
322
399
  log('Agent 侧接入:baseURL 填 http://127.0.0.1:' + GATEWAY_PORT + '/v1')
323
400
  }
324
401
 
@@ -339,6 +416,8 @@ const commands = {
339
416
  },
340
417
  version,
341
418
  help,
419
+ // npm 生命周期钩子(package.json: postinstall → node bin/omr.js postinstall)
420
+ postinstall,
342
421
  }
343
422
 
344
423
  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.13",
3
+ "version": "0.0.14",
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,11 +16,12 @@ 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'
@@ -111,6 +112,14 @@ export function createAdminServer({ log = () => {} } = {}) {
111
112
  if (path === '/admin/api/sync/login' && req.method === 'POST') return json(res, 200, await startRelayBrowserLogin())
112
113
  if (path === '/admin/api/sync/login/status' && req.method === 'GET') return json(res, 200, relayBrowserLoginState())
113
114
  if (path === '/admin/api/sync/login/cancel' && req.method === 'POST') return json(res, 200, await cancelRelayBrowserLogin())
115
+ // 站点托管扫码登录:起步出二维码,轮询拿令牌自动注册(令牌不进返回值)
116
+ if (path === '/admin/api/sync/login/qr/start' && req.method === 'POST') {
117
+ const body = await readBody(req)
118
+ return json(res, 200, await startRelayQrLogin(body.provider, body.mode === 'mobile' ? 'mobile' : 'direct'))
119
+ }
120
+ if (path === '/admin/api/sync/login/qr/poll' && req.method === 'GET') {
121
+ return json(res, 200, await pollRelayQrLogin(url.searchParams.get('qrId')))
122
+ }
114
123
  if (path === '/admin/api/sync/pair-code' && req.method === 'POST') {
115
124
  const pair = await generatePairCode()
116
125
  return json(res, pair.ok === false ? 400 : 200, pair)
@@ -376,11 +385,12 @@ export function createAdminServer({ log = () => {} } = {}) {
376
385
  json(res, 200, { ok: true, count: catalog.filter(r => !r.offline).length })
377
386
  }
378
387
 
379
- /** 手动触发一轮探测(force 穿透退避与开关);body.channel 非空时只探测该渠道下的模型(可多渠道并行)。 */
388
+ /** 手动触发一轮探测(force 穿透退避与开关);body.channel / body.group 非空时只探测该范围内的模型(可多范围并行)。 */
380
389
  async function apiRunProbe(req, res) {
381
390
  const body = await readBody(req).catch(() => ({}))
382
391
  const channel = String(body.channel ?? '').trim()
383
- const result = await probe.runProbeRound({ force: true, channel })
392
+ const group = String(body.group ?? '').trim()
393
+ const result = await probe.runProbeRound({ force: true, channel, group })
384
394
  json(res, 200, { ok: !result.skipped, ...result })
385
395
  }
386
396
 
@@ -578,16 +588,58 @@ export function createAdminServer({ log = () => {} } = {}) {
578
588
  const body = await readBody(req)
579
589
  const name = String(body.name ?? '').trim()
580
590
  const models = [...new Set((Array.isArray(body.models) ? body.models : []).map(v => String(v ?? '').trim()).filter(v => v !== ''))]
591
+ const doc = loadGroups()
592
+ doc.groups ??= []
593
+ // 新建 vs 编辑:新建时前端不传 id(或传空串),id 由名称 slugify 派生。
594
+ const isCreate = body.id === undefined || body.id === null || body.id === ''
595
+ const id = body.id ?? slugify(name)
596
+ const prev = doc.groups.find(g => g.id === id)
597
+ // 内置默认组(omr/default):成员集合由小时扫描维护,手动保存只能调序,不能增删。
598
+ if (isDefaultGroup(id)) {
599
+ // 新建时撞上保留字:直接拒绝,别把内置组覆盖掉
600
+ if (isCreate) {
601
+ openAiError(res, 400, 'invalid_request_error', `模型组 ID「default」为内置默认组保留字,请换一个名称`)
602
+ return
603
+ }
604
+ // 自建的同名组(id=default 但不是内置组)不该被当成内置组覆盖:让出 default 给内置组
605
+ if (prev && prev.builtin !== true) {
606
+ openAiError(res, 400, 'invalid_request_error', `模型组 ID「default」为内置默认组保留字,请换一个名称`)
607
+ return
608
+ }
609
+ const kept = Array.isArray(prev?.models) ? prev.models : []
610
+ if (kept.length === 0) {
611
+ openAiError(res, 400, 'invalid_request_error', `内置模型组 omr/${id} 的成员由系统维护,请稍候扫描完成`)
612
+ return
613
+ }
614
+ // 成员集合由扫描维护,这里只接受重排(增删会被丢弃,排序由用户决定)
615
+ const nextModels = builtinGroupMembers(kept, body.models)
616
+ const rawDisabled = Array.isArray(body.disabled) ? body.disabled : (Array.isArray(prev?.disabled) ? prev.disabled : [])
617
+ // 内置组的停用清单不做「成员仍在组内」过滤:模型被上游下架后重新上架时,
618
+ // 用户的停用意图依然生效。
619
+ const disabled = [...new Set(rawDisabled.map(v => String(v ?? '').trim()))].filter(v => v !== '')
620
+ const row = {
621
+ id,
622
+ name: name === '' ? (prev?.name ?? id) : name,
623
+ models: nextModels,
624
+ strategy: body.strategy === 'round-robin' ? 'round-robin' : (prev?.strategy === 'round-robin' ? 'round-robin' : 'fallback'),
625
+ stickyLimit: Math.max(1, Math.trunc(Number(body.stickyLimit) || prev?.stickyLimit || 3)),
626
+ enabled: body.enabled !== undefined ? body.enabled !== false : prev?.enabled !== false,
627
+ disabled,
628
+ builtin: true,
629
+ }
630
+ doc.groups[doc.groups.indexOf(prev)] = row
631
+ saveGroups(doc)
632
+ pruneRotation(doc.groups.map(g => g.id))
633
+ emitRuntimeEvent('groups', loadGroups().groups) // 通知多端同步
634
+ json(res, 200, { ok: true, group: row, builtin: true })
635
+ return
636
+ }
581
637
  if (name === '' || models.length === 0) {
582
638
  openAiError(res, 400, 'invalid_request_error', 'name 与至少一个成员模型必填')
583
639
  return
584
640
  }
585
- const doc = loadGroups()
586
- doc.groups ??= []
587
- const id = body.id ?? slugify(name)
588
641
  // disabled:成员仍留在组里(保序),仅不参与轮询/故障切换;仅保留仍在 models 内的 id。
589
642
  // 未携带 disabled(其他写入口/旧客户端)时沿用原停用清单,避免静默把停用项全部恢复启用。
590
- const prev = doc.groups.find(g => g.id === id)
591
643
  const rawDisabled = Array.isArray(body.disabled) ? body.disabled : (Array.isArray(prev?.disabled) ? prev.disabled : [])
592
644
  const disabled = [...new Set(rawDisabled.map(v => String(v ?? '').trim()))].filter(v => models.includes(v))
593
645
  const row = {
@@ -608,6 +660,10 @@ export function createAdminServer({ log = () => {} } = {}) {
608
660
 
609
661
  async function apiDeleteGroup(req, res) {
610
662
  const id = decodeURIComponent(req.url.split('/').pop() ?? '')
663
+ if (isDefaultGroup(id)) {
664
+ openAiError(res, 400, 'invalid_request_error', `内置模型组 omr/${id} 不可删除`)
665
+ return
666
+ }
611
667
  const doc = loadGroups()
612
668
  doc.groups = (doc.groups ?? []).filter(g => g.id !== id)
613
669
  saveGroups(doc)
@@ -691,6 +747,8 @@ export function createAdminServer({ log = () => {} } = {}) {
691
747
 
692
748
  /** 进行中的在线登录流程:channelId -> { loginUrl, status, error, startedAt }。 */
693
749
  const pendingLogins = new Map()
750
+ /** 「添加账号」的浏览器登录流程:channelId -> { status, message, error, startedAt }。 */
751
+ const localAccountLogins = new Map()
694
752
 
695
753
  function apiChannels(res) {
696
754
  const channels = CHANNELS.map(ch => {
@@ -703,6 +761,7 @@ export function createAdminServer({ log = () => {} } = {}) {
703
761
  repo: ch.meta.repo ?? '',
704
762
  loginMode: ch.meta.loginMode ?? 'credential',
705
763
  localLogin: ch.meta.localLogin === true,
764
+ localAccount: ch.meta.localAccount === true,
706
765
  anonymousModels: ch.meta.anonymousModels === true,
707
766
  enabled: state.enabled,
708
767
  models: state.models,
@@ -739,6 +798,8 @@ export function createAdminServer({ log = () => {} } = {}) {
739
798
  if (sub === 'login' && req.method === 'POST') return apiChannelLoginStart(req, res, id)
740
799
  if (sub === 'login' && req.method === 'GET') return apiChannelLoginStatus(res, id)
741
800
  if (sub === 'credential' && req.method === 'POST') return apiChannelAddCredential(req, res, id)
801
+ if (sub === 'local-account' && req.method === 'POST') return apiChannelAddLocalAccount(req, res, id)
802
+ if (sub === 'local-account' && req.method === 'GET') return apiChannelLocalAccountStatus(res, id)
742
803
  if (sub === 'accounts' && rest.length >= 3) return apiChannelAccount(req, res, id, decodeURIComponent(rest[2]), req.method)
743
804
  openAiError(res, 404, 'not_found_error', `no channel route: ${req.method} ${path}`)
744
805
  }
@@ -863,6 +924,69 @@ export function createAdminServer({ log = () => {} } = {}) {
863
924
  }
864
925
  }
865
926
 
927
+ /**
928
+ * 「添加账号」:不接收任何凭据,由渠道自行从本机读取(如灵犀读取本机客户端
929
+ * Cookie 库)。读取/校验失败时把可读原因带回 UI,不要求手工粘贴。
930
+ */
931
+ async function apiChannelAddLocalAccount(req, res, id) {
932
+ const ch = channelById(id)
933
+ if (typeof ch.addLocalAccount !== 'function') {
934
+ openAiError(res, 400, 'invalid_request_error', '该渠道不支持从本机自动读取账号')
935
+ return
936
+ }
937
+ const existing = localAccountLogins.get(id)
938
+ if (existing?.status === 'pending') {
939
+ json(res, 200, { ok: false, pending: true, message: existing.message })
940
+ return
941
+ }
942
+ const body = await readBody(req).catch(() => ({}))
943
+ const entry = { status: 'pending', message: '正在读取本机灵犀登录态…', startedAt: Date.now() }
944
+ localAccountLogins.set(id, entry)
945
+ let credential
946
+ try {
947
+ credential = await ch.addLocalAccount()
948
+ } catch (error) {
949
+ // 账号已被上游风控拦截时,换浏览器登录同一账号也无济于事,直接报错。
950
+ if (error?.code === 'blocked' || typeof ch.startBrowserLogin !== 'function') {
951
+ localAccountLogins.delete(id)
952
+ openAiError(res, 400, 'invalid_request_error', String(error?.message ?? error))
953
+ return
954
+ }
955
+ let flow
956
+ try {
957
+ flow = ch.startBrowserLogin()
958
+ } catch (browserError) {
959
+ localAccountLogins.delete(id)
960
+ openAiError(res, 400, 'invalid_request_error', `${error.brief || error.message};${browserError.message}`)
961
+ return
962
+ }
963
+ entry.message = `${error.brief || error.message};已打开浏览器登录窗口,请在窗口中完成 WPS 登录`
964
+ flow.then(browserCredential => {
965
+ entry.status = 'done'
966
+ addAccount(id, browserCredential)
967
+ invalidateCatalog()
968
+ emitRuntimeEvent('channels', { channelId: id })
969
+ log(`channel ${id} 浏览器登录成功`)
970
+ }).catch(browserError => {
971
+ entry.status = 'error'
972
+ entry.error = String(browserError?.message ?? browserError)
973
+ log(`channel ${id} 浏览器登录失败: ${entry.error}`)
974
+ })
975
+ json(res, 200, { ok: false, pending: true, message: entry.message })
976
+ return
977
+ }
978
+ const accountId = addAccount(id, credential, typeof body.label === 'string' ? body.label : '')
979
+ localAccountLogins.delete(id)
980
+ invalidateCatalog()
981
+ emitRuntimeEvent('channels', { channelId: id })
982
+ json(res, 200, { ok: true, accountId, described: ch.describeCredential(credential) })
983
+ }
984
+
985
+ function apiChannelLocalAccountStatus(res, id) {
986
+ const entry = localAccountLogins.get(id)
987
+ json(res, 200, entry ?? { status: 'idle' })
988
+ }
989
+
866
990
  async function apiChannelAccount(req, res, id, accountId, method) {
867
991
  const ch = channelById(id)
868
992
  if (method === 'DELETE') {
package/src/boot.js CHANGED
@@ -11,6 +11,7 @@ import { startAdmin } from './admin.js'
11
11
  import { startSmartScheduler } from './checkin.js'
12
12
  import { startProber, primeProbeState } from './probe.js'
13
13
  import { startFreeModelWatcher } from './free-models.js'
14
+ import { syncDefaultGroup } from './default-group.js'
14
15
  import { startSyncIfEnabled, stopSync } from './sync/index.js'
15
16
  import { runtime, flushRecentRequestsNow } from './store.js'
16
17
  import { invalidateCatalog, primeCatalogCache, buildCatalog } from './providers/index.js'
@@ -58,6 +59,14 @@ export async function startAll({
58
59
  } = {}) {
59
60
  runtime.startedAt = Date.now()
60
61
  invalidateCatalog()
62
+ // 内置默认组(omr/default):不存在则建,并按当前免密渠道的选用清单填入成员
63
+ // (小时扫描每轮会再同步一次;这里先建好,避免首屏还没有 omr/default)
64
+ try {
65
+ const groupSync = syncDefaultGroup({ log })
66
+ if (groupSync.changed) invalidateCatalog()
67
+ } catch (error) {
68
+ log(`默认模型组初始化失败:${error?.message ?? error}`)
69
+ }
61
70
  // 上次运行的目录快照预热缓存:管理页首屏立即出内容,出网重建在后台完成后经 SSE 换新
62
71
  primeCatalogCache()
63
72
  // 上次探测快照预热:模型组排序能立即用上「哪些候选真的可用」,不必等本轮探测跑完
@@ -92,7 +101,7 @@ export async function startAll({
92
101
  firstSweep.unref?.()
93
102
 
94
103
  log('OneModelRouter 已启动')
95
- log(` 管理界面: http://${admin.host}:${admin.port}/admin`)
104
+ log(` 登录地址: http://${admin.host}:${admin.port}/admin`)
96
105
  log(` 网关地址: http://${gateway.host}:${gateway.port}/v1 (agent 的 baseURL 填这里)`)
97
106
 
98
107
  let stopping = null
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Bun 引导:检测本机 Bun(OpenCode 免费车道推理依赖,见 src/providers/opencode/bun-fetch.js),
3
+ * 缺失时以分离进程自动补装。对齐官网安装方法(https://bun.sh/docs/installation):
4
+ * Windows powershell -c "irm bun.sh/install.ps1 | iex"(装到 %USERPROFILE%\.bun\bin 并写入用户 PATH)
5
+ * macOS/Linux curl -fsSL https://bun.sh/install | bash(装到 ~/.bun/bin)
6
+ * 兜底 npm install -g bun
7
+ *
8
+ * 只依赖 Node 内置模块,供网页版升级(src/update.js)与桌面端升级(electron/self-update.js)共用。
9
+ * ensureBunDetached 在升级完成后调用:检测在本进程内做(口径与运行时 findBunExecutable 一致),
10
+ * 缺失才拉起分离的平台 shell 子进程安装(不 import 本模块——打包态 electron 的 asar 路径在
11
+ * ELECTRON_RUN_AS_NODE 下不可读),安装不阻塞升级流程与服务重启;输出追加到
12
+ * <数据目录>/logs/bun-install.log。装完后运行时按路径候选自动识别,无需重启服务。
13
+ * 安装失败不影响本体(仅 OpenCode 免费车道不可用)。
14
+ *
15
+ * @module src/bun-bootstrap
16
+ */
17
+
18
+ import { accessSync, closeSync, constants, mkdirSync, openSync, statSync } from 'node:fs'
19
+ import { homedir } from 'node:os'
20
+ import { delimiter, join, resolve } from 'node:path'
21
+ import { spawn } from 'node:child_process'
22
+
23
+ /** 定位原生 Bun 可执行文件(永不执行 .cmd/.ps1 壳)。不安装、不下载。 */
24
+ export function findBunExecutable() {
25
+ const name = process.platform === 'win32' ? 'bun.exe' : 'bun'
26
+ const candidates = [
27
+ process.env.OMR_OPENCODE_BUN,
28
+ process.env.OUR_FREE_MODEL_BUN,
29
+ process.env.BUN_INSTALL && join(process.env.BUN_INSTALL, 'bin', name),
30
+ join(homedir(), '.bun', 'bin', name),
31
+ ...(process.env.PATH || '').split(delimiter).filter(Boolean).map(p => join(p.replace(/^"|"$/g, ''), name)),
32
+ process.env.APPDATA && join(process.env.APPDATA, 'npm', 'node_modules', 'bun', 'bin', name),
33
+ ]
34
+ for (const candidate of candidates.filter(Boolean)) {
35
+ try {
36
+ const path = resolve(candidate)
37
+ if (process.platform === 'win32' && !path.toLowerCase().endsWith('.exe')) continue
38
+ if (!statSync(path).isFile()) continue
39
+ accessSync(path, constants.X_OK)
40
+ return path
41
+ } catch { /* 试下一个候选 */ }
42
+ }
43
+ return undefined
44
+ }
45
+
46
+ /**
47
+ * Windows 补装脚本:官方 install.ps1(经 scriptblock 执行,与官网 irm|iex 等效)→ npm 兜底。
48
+ * 只认官方脚本的落盘位置(BUN_INSTALL 覆盖时同规则),装不上不影响本体。
49
+ */
50
+ const INSTALL_PS1 = [
51
+ '$ProgressPreference = "SilentlyContinue"',
52
+ '$bun = Join-Path $env:USERPROFILE ".bun\\bin\\bun.exe"',
53
+ 'if ($env:BUN_INSTALL) { $bun = Join-Path $env:BUN_INSTALL "bin\\bun.exe" }',
54
+ 'if (-not (Test-Path -LiteralPath $bun -PathType Leaf)) {',
55
+ ' Write-Host "[bun] 官方脚本安装:https://bun.sh/install.ps1"',
56
+ ' try { & ([scriptblock]::Create((Invoke-WebRequest -UseBasicParsing -Uri "https://bun.sh/install.ps1").Content)) } catch { Write-Host "[bun] 官方脚本失败:$($_.Exception.Message)" }',
57
+ '}',
58
+ 'if (-not (Test-Path -LiteralPath $bun -PathType Leaf) -and Get-Command npm -ErrorAction SilentlyContinue) {',
59
+ ' Write-Host "[bun] 改用 npm i -g bun"',
60
+ ' npm i -g bun',
61
+ '}',
62
+ 'if (Test-Path -LiteralPath $bun -PathType Leaf) { Write-Host "[bun] 安装完成:$bun" } else { Write-Host "[bun] 自动安装失败,请手动安装:https://bun.sh" }',
63
+ ].join('\n')
64
+
65
+ /** macOS / Linux 补装脚本:官方 install(bash)→ npm 兜底;与 INSTALL_PS1 同口径。 */
66
+ const INSTALL_SH = [
67
+ 'if [ ! -x "$HOME/.bun/bin/bun" ] && ! command -v bun >/dev/null 2>&1; then',
68
+ ' echo "[bun] 官方脚本安装:https://bun.sh/install"',
69
+ ' curl -fsSL https://bun.sh/install | bash || echo "[bun] 官方脚本失败"',
70
+ 'fi',
71
+ 'if [ ! -x "$HOME/.bun/bin/bun" ] && ! command -v bun >/dev/null 2>&1 && command -v npm >/dev/null 2>&1; then',
72
+ ' echo "[bun] 改用 npm i -g bun"',
73
+ ' npm i -g bun || echo "[bun] npm 安装失败"',
74
+ 'fi',
75
+ 'if [ -x "$HOME/.bun/bin/bun" ] || command -v bun >/dev/null 2>&1; then echo "[bun] 安装完成"; else echo "[bun] 自动安装失败,请手动安装:https://bun.sh"; fi',
76
+ ].join('\n')
77
+
78
+ /** 安装日志路径:<数据目录>/logs/bun-install.log(数据目录约定与 src/paths.js / electron/data-dir.cjs 一致)。 */
79
+ function bunInstallLogFile() {
80
+ const dataDir = process.env.OMR_DATA_DIR || join(homedir(), '.OneModelRouter', 'data')
81
+ return join(dataDir, 'logs', 'bun-install.log')
82
+ }
83
+
84
+ /**
85
+ * 升级完成后的 Bun 检查与补装(分离进程,不阻塞调用方)。
86
+ * 已安装则只记日志返回 already;缺失则拉起平台 shell 子进程安装并立即返回 started。
87
+ * 任何异常都消化在返回值/日志里,绝不影响升级流程本身。
88
+ */
89
+ export function ensureBunDetached({ log = () => {} } = {}) {
90
+ try {
91
+ const found = findBunExecutable()
92
+ if (found) {
93
+ log(`Bun 已安装(${found}),OpenCode 免费车道可用`)
94
+ return { status: 'already', path: found }
95
+ }
96
+ let logFile = ''
97
+ let fd = 'ignore'
98
+ try {
99
+ logFile = bunInstallLogFile()
100
+ mkdirSync(join(logFile, '..'), { recursive: true })
101
+ fd = openSync(logFile, 'a')
102
+ } catch { /* 日志目录不可写:子进程输出丢弃 */ }
103
+ const child = process.platform === 'win32'
104
+ ? spawn('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', INSTALL_PS1], { detached: true, stdio: ['ignore', fd, fd], windowsHide: true })
105
+ : spawn('/bin/sh', ['-c', INSTALL_SH], { detached: true, stdio: ['ignore', fd, fd] })
106
+ child.on('error', error => log(`Bun 后台安装进程启动失败:${error?.message ?? error}`))
107
+ child.unref()
108
+ if (typeof fd === 'number') closeSync(fd)
109
+ log(`未检测到 Bun(OpenCode 免费车道依赖),已后台开始安装${logFile ? `,日志:${logFile}` : ''}`)
110
+ return { status: 'started', logFile }
111
+ } catch (error) {
112
+ log(`Bun 检查/补装异常(不影响本体):${error?.message ?? error}`)
113
+ return { status: 'failed', error: String(error?.message ?? error) }
114
+ }
115
+ }
@@ -39,6 +39,7 @@ import * as tabbit from './tabbit.js'
39
39
  import * as doubaowork from './doubaowork.js'
40
40
  import * as miaoshou from './miaoshou.js'
41
41
  import { joycodeChannel } from './joycode.js'
42
+ import * as lingxi from './lingxi.js'
42
43
 
43
44
  /** 账号轮换游标:catalogRowId -> cursor(按模型记忆,同 opencode 槽轮换)。 */
44
45
  const cursors = new Map()
@@ -69,6 +70,7 @@ export const CHANNELS = [
69
70
  doubaowork.meta && doubaowork,
70
71
  miaoshou.meta && miaoshou,
71
72
  joycodeChannel.meta && joycodeChannel,
73
+ lingxi.meta && lingxi,
72
74
  ].filter(Boolean)
73
75
 
74
76
  export function channelById(id) {
@@ -248,12 +250,14 @@ export async function sweepRefresh() {
248
250
  // 只对已启用的渠道做后台续期:停用的渠道不刷新凭据,避免无谓出网与记账噪音。
249
251
  if (!state.enabled) continue
250
252
  for (const account of state.accounts) {
251
- // 旧版本曾把「上游无 refresh 端点」误判终态(lastError 含「不可自动续期」)。
252
- // 若渠道现在声明可续期,先解除终态并清掉旧错误,让本轮巡检自动校验/续期。
253
- if (account.refreshable === false && /不可自动续期/.test(account.lastError ?? '') &&
254
- ch.describeCredential?.(account.credential)?.refreshable === true) {
253
+ // 渠道新增/恢复自动续期能力后,旧账号可能在上一版本被标成 refreshable=false。
254
+ // 以渠道当前声明为准:只有「明确不可续期」或鉴权已终态时才允许自愈。
255
+ const described = ch.describeCredential?.(account.credential)
256
+ if (account.refreshable === false && described?.refreshable === true &&
257
+ (account.authDead === true || /不可自动续期|自动续期不可用|不支持自动续期/.test(account.lastError ?? ''))) {
255
258
  account.refreshable = true
256
259
  account.lastError = ''
260
+ account.authDead = false
257
261
  account.updatedAt = Date.now()
258
262
  saveChannelState(id, state)
259
263
  }