one-model-router 0.0.11 → 0.0.12

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
@@ -23,7 +23,13 @@
23
23
  winget install OneModelRouter.OneModelRouter
24
24
 
25
25
  # 或一行安装脚本(自动取最新版并校验 sha256)
26
- powershell -c "irm https://bothua111.github.io/OneModelRouter/install.ps1 | iex"
26
+ powershell -c "irm https://one-model-router.traesite.cn/install.ps1 | iex"
27
+
28
+ # 网络不好时用 githubusercontent 备用
29
+ powershell -c "irm https://raw.githubusercontent.com/bothua111/OneModelRouter/gh-pages/install.ps1 | iex"
30
+
31
+ # 原生安装包不可用时,脚本会自动回退 npm 安装网页版;也可强制:
32
+ # powershell -c "& ([scriptblock]::Create((irm https://one-model-router.traesite.cn/install.ps1))) -Npm"
27
33
  ```
28
34
 
29
35
  也可直接从 [Releases](https://github.com/bothua111/OneModelRouter/releases/latest) 下载
@@ -36,7 +42,10 @@ powershell -c "irm https://bothua111.github.io/OneModelRouter/install.ps1 | iex"
36
42
  brew tap bothua111/cask && brew install --cask onemodelrouter
37
43
 
38
44
  # 或一行安装脚本(curl 下载不带隔离标记,可直接打开)
39
- curl -fsSL https://bothua111.github.io/OneModelRouter/install.sh | sh
45
+ curl -fsSL https://one-model-router.traesite.cn/install.sh | sh
46
+
47
+ # 网络不好时用 githubusercontent 备用
48
+ curl -fsSL https://raw.githubusercontent.com/bothua111/OneModelRouter/gh-pages/install.sh | sh
40
49
  ```
41
50
 
42
51
  Apple Silicon 与 Intel 分别有 `arm64` / `x64` 包。当前发布链是**无证书 ad-hoc 签名**,
@@ -46,7 +55,10 @@ Apple Silicon 与 Intel 分别有 `arm64` / `x64` 包。当前发布链是**无
46
55
 
47
56
  ```bash
48
57
  # 一行安装脚本(默认装 AppImage 到 ~/.local/bin)
49
- curl -fsSL https://bothua111.github.io/OneModelRouter/install.sh | sh
58
+ curl -fsSL https://one-model-router.traesite.cn/install.sh | sh
59
+
60
+ # 网络不好时用 githubusercontent 备用
61
+ curl -fsSL https://raw.githubusercontent.com/bothua111/OneModelRouter/gh-pages/install.sh | sh
50
62
 
51
63
  # 或用系统包(Releases 里下载)
52
64
  sudo dpkg -i OneModelRouter-<版本>-amd64.deb # Debian / Ubuntu
@@ -62,6 +74,8 @@ npm i -g one-model-router # 或:npx one-model-router start --detach
62
74
  omr start --detach
63
75
  ```
64
76
 
77
+ npm 版是**网页版**:管理界面在浏览器 <http://127.0.0.1:18681/admin>,数据目录与桌面端共用。
78
+
65
79
  ### Docker
66
80
 
67
81
  ```bash
@@ -107,6 +121,9 @@ curl http://127.0.0.1:18682/v1/models
107
121
  | `omr stop` / `omr restart` | 停止 / 重启后台实例 |
108
122
  | `omr status` | 查看进程、端口与 `/health` 探针 |
109
123
  | `omr portal` | 用系统浏览器打开管理面板 |
124
+ | `omr update` | 检查并升级到最新版(按当前系统优先装对应安装包,失败回退 npm 升级) |
125
+ | `omr update --check` | 只检查是否有新版本 |
126
+ | `omr update --npm` | 强制走 npm 全局升级 |
110
127
  | `omr version` | 版本 |
111
128
 
112
129
  通用选项:`--port`(网关,默认 18682)、`--admin-port`(管理面,默认 18681)、`--data-dir`。
@@ -120,6 +137,7 @@ curl http://127.0.0.1:18682/v1/models
120
137
  | `OMR_ADMIN_PORT` | `18681` | 管理面板端口 |
121
138
  | `OMR_GATEWAY_HOST` | `127.0.0.1` | 网关监听地址(容器内需设 `0.0.0.0`) |
122
139
  | `OMR_ADMIN_HOST` | `127.0.0.1` | 管理面监听地址 |
140
+ | `OMR_NO_UPDATE_CHECK` | — | 设为 `1` 关闭网页版后台自动检查更新 |
123
141
 
124
142
  桌面端与 CLI / Docker **共用同一份数据目录**,凭据不需要重复配置。
125
143
 
@@ -129,12 +147,16 @@ curl http://127.0.0.1:18682/v1/models
129
147
 
130
148
  | 渠道 | 方式 |
131
149
  | --- | --- |
132
- | Windows / macOS / Linux 桌面端 | 管理面板右上角「升级」按钮,内置自更新(优先 Gitee 源) |
150
+ | Windows / macOS / Linux 桌面端 | 管理面板右上角「升级」按钮,内置自更新(源顺序:TRAE 站点 → githubusercontent → Gitee → GitHub → 镜像) |
133
151
  | winget | `winget upgrade OneModelRouter.OneModelRouter` |
134
152
  | Homebrew | `brew upgrade --cask onemodelrouter` |
135
- | npm | `npm update -g one-model-router` |
153
+ | npm(网页版) | `omr update`(按当前系统优先装对应安装包,失败自动回退 `npm i -g one-model-router@latest`) |
154
+ | npm(网页版,手动) | `npm update -g one-model-router` |
136
155
  | Docker | `docker pull` 新 tag 后重建容器 |
137
156
 
157
+ 升级 feed 源顺序统一为:**TRAE 站点 → raw.githubusercontent.com → Gitee raw → GitHub Release → 加速镜像**,
158
+ 客户端并行探测取「版本最高且可达」的一份,避免首选源缓存陈旧导致漏升级。
159
+
138
160
  ---
139
161
 
140
162
  ## 常见问题
@@ -153,6 +175,11 @@ curl http://127.0.0.1:18682/v1/models
153
175
  用官网的 `install.sh` 安装(curl 下载不带隔离标记),或在终端执行
154
176
  `xattr -dr com.apple.quarantine /Applications/OneModelRouter.app` 后再打开。
155
177
 
178
+ **npm 版怎么升级?**
179
+ `omr update`:按当前系统优先装对应原生安装包(Windows 用 Setup、macOS 用 dmg/zip、Linux 用 AppImage),
180
+ 失败时自动回退 `npm i -g one-model-router@latest`;升级完执行 `omr restart` 生效。
181
+ 只想检查不升级:`omr update --check`。管理面板右上角「升级」按钮也是同一套逻辑。
182
+
156
183
  **Linux AppImage 双击没反应?**
157
184
  缺 `libfuse2`:`sudo apt install libfuse2`,或直接 `./OneModelRouter --appimage-extract-and-run`。
158
185
 
package/bin/omr.js CHANGED
@@ -17,6 +17,7 @@ import { spawn } from 'node:child_process'
17
17
  import { closeSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
18
18
  import { dirname, join } from 'node:path'
19
19
  import { fileURLToPath, pathToFileURL } from 'node:url'
20
+ import { runUpdate, checkForUpdate, cleanupStaged } from '../src/update.js'
20
21
 
21
22
  const ROOT = dirname(dirname(fileURLToPath(import.meta.url)))
22
23
  const PKG = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'))
@@ -42,6 +43,8 @@ function parseArgs(argv) {
42
43
  else if (a === '--port') args.port = rest.shift()
43
44
  else if (a === '--admin-port') args.adminPort = rest.shift()
44
45
  else if (a === '--data-dir') args.dataDir = rest.shift()
46
+ else if (a === '--npm') args.npm = true
47
+ else if (a === '--check') args.check = true
45
48
  else if (a === '-h' || a === '--help') args.command = 'help'
46
49
  else if (a === '-v' || a === '--version') args.command = 'version'
47
50
  else die(`未知参数 ${a}(omr help 看用法)`)
@@ -257,6 +260,40 @@ function portal() {
257
260
  } catch { /* 打不开就让用户手点,地址已经打在上一行 */ }
258
261
  }
259
262
 
263
+ /**
264
+ * omr update:自更新(与桌面版同一套 feed/产物逻辑)。
265
+ * - 默认 auto:按当前系统优先装对应原生安装包,失败自动回退 npm 全局升级;
266
+ * - --npm:强制走 npm i -g one-model-router@latest;
267
+ * - --check:只检查是否有新版本,不下载安装。
268
+ * 升级完成后需要重启服务使其生效(omr restart)。
269
+ */
270
+ async function update() {
271
+ const log = (...a) => console.log(...a)
272
+ const mode = args.npm ? 'npm' : 'auto'
273
+ if (args.check) {
274
+ const info = await checkForUpdate()
275
+ if (!info.hasUpdate) log(`已是最新版本 v${info.current}`)
276
+ else {
277
+ log(`可升级:v${info.current} → v${info.latest}(更新源:${info.source})`)
278
+ if (info.notes) log(`更新说明:${info.notes}`)
279
+ log(`执行 omr update 升级${info.asset ? '' : '(本平台无原生包,将走 npm 升级)'}`)
280
+ }
281
+ return
282
+ }
283
+ const pid = runningPid()
284
+ if (pid) log(`检测到正在运行的实例(PID ${pid});升级完成后请执行 omr restart 重启使其生效`)
285
+ try {
286
+ const result = await runUpdate({ mode, log })
287
+ if (!result.updated) {
288
+ log(`已是最新版本 v${result.current ?? ''}`)
289
+ }
290
+ } catch (error) {
291
+ die(`升级失败:${error?.message ?? error}`)
292
+ } finally {
293
+ cleanupStaged()
294
+ }
295
+ }
296
+
260
297
  function version() {
261
298
  log(`${PKG.name} ${PKG.version}(node ${process.version})`)
262
299
  }
@@ -272,6 +309,9 @@ function help() {
272
309
  log(' restart 停止后重新后台启动')
273
310
  log(' status 查看运行状态与健康探针')
274
311
  log(' portal 打印并用系统浏览器打开管理面板')
312
+ log(' update 检查并升级到最新版(按系统优先装原生包,失败回退 npm 升级)')
313
+ log(' update --check 只检查是否有新版本')
314
+ log(' update --npm 强制走 npm 全局升级(npm i -g one-model-router@latest)')
275
315
  log(' version 显示版本')
276
316
  log('')
277
317
  log('选项:')
@@ -291,6 +331,12 @@ const commands = {
291
331
  },
292
332
  status,
293
333
  portal,
334
+ update,
335
+ upgrade: update,
336
+ 'check-update': async () => {
337
+ args.check = true
338
+ await update()
339
+ },
294
340
  version,
295
341
  help,
296
342
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "one-model-router",
3
- "version": "0.0.11",
3
+ "version": "0.0.12",
4
4
  "description": "本地模型路由网关:聚合免费/自有模型通道,OpenAI 兼容转发,模型组自动轮询切换,自动签到领积分",
5
5
  "author": {
6
6
  "name": "OneModelRouter",
@@ -32,7 +32,8 @@
32
32
  "dist:linux": "electron-builder --linux",
33
33
  "dist:all": "electron-builder -mwl",
34
34
  "gen:feed": "node scripts/gen-feed.cjs",
35
- "gen:winget": "node scripts/gen-winget.cjs"
35
+ "gen:winget": "node scripts/gen-winget.cjs",
36
+ "sync:site-feed": "node scripts/sync-site-feed.cjs"
36
37
  },
37
38
  "engines": {
38
39
  "node": ">=18.0.0"
package/src/admin.js CHANGED
@@ -23,6 +23,7 @@ import { freeModelsState } from './free-models.js'
23
23
  import { syncState, updateSyncSettings, generatePairCode, latestPair, startRelayBrowserLogin, relayBrowserLoginState, cancelRelayBrowserLogin } from './sync/index.js'
24
24
  import { json, openAiError, slugify, shortId, generateApiKey } from './util.js'
25
25
  import { BUILTIN_PROVIDERS, BUILTIN_IDS } from './providers/builtin.js'
26
+ import { checkForUpdate, runUpdate, applyUpdate, getUpdateState, onUpdateEvent } from './update.js'
26
27
 
27
28
  const WEB_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'web')
28
29
  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' }
@@ -46,11 +47,34 @@ export function createAdminServer({ log = () => {} } = {}) {
46
47
  })
47
48
  })
48
49
 
50
+ // 网页版:更新状态变化经 SSE 'update' 事件推给管理面板(Electron 端由 preload 自带事件流)
51
+ if (!process.versions.electron) {
52
+ onUpdateEvent(next => emitRuntimeEvent('update', next))
53
+ }
54
+
49
55
  async function handle(req, res) {
50
56
  const url = new URL(req.url ?? '/', 'http://localhost')
51
57
  const path = url.pathname.replace(/\/+$/, '') || '/'
52
58
 
53
59
  if (path === '/admin/api/version' && req.method === 'GET') return json(res, 200, { version: appVersionText() })
60
+ // 网页版自更新接口(Electron 桌面端经 preload IPC 更新,不走这里,避免双更新器)
61
+ if (!process.versions.electron) {
62
+ if (path === '/admin/api/update' && req.method === 'GET') return json(res, 200, getUpdateState())
63
+ if (path === '/admin/api/update/check' && req.method === 'POST') {
64
+ try { await checkForUpdate(); return json(res, 200, { ok: true }) }
65
+ catch (error) { return json(res, 200, { ok: false, error: error?.message ?? String(error) }) }
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
+ }
77
+ }
54
78
  if (path === '/admin/api/state' && req.method === 'GET') return apiState(res)
55
79
  if (path === '/admin/api/settings' && req.method === 'PUT') return apiUpdateSettings(req, res)
56
80
  if (path === '/admin/api/opencode/probe' && req.method === 'POST') return apiProbeOpencode(res)
package/src/server.js CHANGED
@@ -9,14 +9,30 @@
9
9
 
10
10
  import { startAll } from './boot.js'
11
11
  import { utc8Stamp } from './util.js'
12
+ import { checkForUpdate } from './update.js'
12
13
 
13
14
  const log = (...args) => console.log(utc8Stamp(), ...args)
14
15
 
16
+ /**
17
+ * 网页版后台自动检查更新(与桌面端同源同逻辑):首查 10s 后,之后每 6 小时一轮。
18
+ * 仅更新状态机,Web 面板经 SSE 感知「有新版本」;实际升级由 `omr update` 或面板按钮触发。
19
+ * 设 OMR_NO_UPDATE_CHECK=1 可关闭。
20
+ */
21
+ function startUpdateChecker() {
22
+ if (process.env.OMR_NO_UPDATE_CHECK === '1') return
23
+ const tick = () => checkForUpdate().catch(error => log(`更新检查失败: ${error?.message ?? error}`))
24
+ const first = setTimeout(tick, 10_000)
25
+ first.unref?.()
26
+ const timer = setInterval(tick, 6 * 60 * 60_000)
27
+ timer.unref?.()
28
+ }
29
+
15
30
  async function main() {
16
31
  const { stop } = await startAll({ log })
17
32
 
18
33
  log(' 自动签到: 启动后按需执行(间隔见设置页)')
19
34
  log(' 后台探测: 周期检测模型可用性(设置页可关/调间隔)')
35
+ startUpdateChecker()
20
36
  log(' 按 Ctrl+C 停止')
21
37
 
22
38
  const shutdown = async () => {
package/src/update.js ADDED
@@ -0,0 +1,458 @@
1
+ /**
2
+ * 网页版(npm 包)自更新引擎。
3
+ *
4
+ * 只依赖 Node 内置模块(不含 Electron),供 bin/omr.js(CLI)与 src/admin.js(Web 面板)共用。
5
+ *
6
+ * 设计对齐桌面端(electron/self-update.js):
7
+ * 1. feed(latest.json)源顺序:TRAE 站点 → GitHub raw(githubusercontent) → Gitee raw → GitHub Release → 加速镜像;
8
+ * 并行拉取所有可用源,取「版本最高且可达」的一份,避免首选源缓存陈旧导致漏升级。
9
+ * 2. 按 process.platform / process.arch 选载体:
10
+ * win32 → windows-<arch>.file(NSIS Setup):静默 /S 安装,安装器自行处理旧实例。
11
+ * darwin → macos-<arch>-zip.file(无 zip 退回 dmg):解压/挂载后整包换入 /Applications。
12
+ * linux → linux-appimage-<arch>.file:AppImage 运行态原子覆盖自身;否则装到 ~/.local/bin。
13
+ * 3. 下载流式校验 sha512(缺失退 sha256),不符即删并报错。
14
+ * 4. 原生路径不可用/失败 → 兜底 `npm i -g one-model-router@latest`。
15
+ */
16
+
17
+ import { accessSync, chmodSync, constants, cpSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync } from 'node:fs'
18
+ import { createHash } from 'node:crypto'
19
+ import { spawn } from 'node:child_process'
20
+ import { basename, dirname, join, resolve } from 'node:path'
21
+ import { homedir, tmpdir } from 'node:os'
22
+ import { fileURLToPath } from 'node:url'
23
+ import { Readable } from 'node:stream'
24
+ import { pipeline } from 'node:stream/promises'
25
+
26
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
27
+
28
+ function readPkg() {
29
+ try { return JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')) } catch { return {} }
30
+ }
31
+ const PKG = readPkg()
32
+ const PKG_NAME = String(PKG.name || 'one-model-router')
33
+
34
+ /** 官网(TRAE 站点)根地址:一行安装脚本与 feed 的首选源。 */
35
+ export const SITE = 'https://one-model-router.traesite.cn'
36
+ const GITHUB = PKG.omrRepos?.github || 'bothua111/OneModelRouter'
37
+ const GITEE = PKG.omrRepos?.gitee || 'laojiaogroup/OneModelRouter'
38
+ const GITHUB_MIRRORS = ['https://ghproxy.net/', 'https://gh-proxy.com/']
39
+
40
+ export function getCurrentVersion() {
41
+ return String(PKG.version || '0.0.0')
42
+ }
43
+
44
+ /** feed 源(顺序即优先级):TRAE 站点 → githubusercontent → Gitee raw → GitHub Release → 加速镜像。 */
45
+ export function feedSources() {
46
+ // 测试钩子:本地 mock feed 验证自更新链路(与 electron/self-update.js 的同名约定一致)
47
+ const override = process.env.OMR_UPDATE_FEED_URL
48
+ if (override) return [{ label: '环境变量覆盖', url: override, base: '' }]
49
+ return [
50
+ { label: 'TRAE 站点', url: `${SITE}/latest.json`, base: '' },
51
+ { label: 'GitHub raw', url: `https://raw.githubusercontent.com/${GITHUB}/gh-pages/latest.json`, base: '' },
52
+ { label: 'Gitee raw', url: `https://gitee.com/${GITEE}/raw/master/update/latest.json`, base: '' },
53
+ { label: 'GitHub Release', url: `https://github.com/${GITHUB}/releases/latest/download/latest.json`, base: '' },
54
+ ...GITHUB_MIRRORS.map(m => ({ label: `镜像 ${m}`, url: `${m}https://github.com/${GITHUB}/releases/latest/download/latest.json`, base: m })),
55
+ ]
56
+ }
57
+
58
+ /** 语义化版本比较:a 大于 b 返回 1,小于返回 -1,相等返回 0。 */
59
+ export function compareVersions(a, b) {
60
+ const pa = String(a).split('.').map(Number)
61
+ const pb = String(b).split('.').map(Number)
62
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
63
+ const va = pa[i] || 0
64
+ const vb = pb[i] || 0
65
+ if (va !== vb) return va > vb ? 1 : -1
66
+ }
67
+ return 0
68
+ }
69
+
70
+ async function getJson(url, timeoutMs) {
71
+ const res = await fetch(url, {
72
+ signal: AbortSignal.timeout(timeoutMs),
73
+ headers: { 'User-Agent': 'OneModelRouter-Update' },
74
+ cache: 'no-store',
75
+ })
76
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
77
+ return await res.json()
78
+ }
79
+
80
+ /**
81
+ * 拉取 feed:并行请求所有源,取「版本最高且可达」的一份。
82
+ * @returns {{ feed:any, base:string, label:string }}
83
+ */
84
+ export async function fetchFeed({ timeoutMs = 8000 } = {}) {
85
+ const sources = feedSources()
86
+ const settled = await Promise.allSettled(sources.map(async src => {
87
+ const feed = await getJson(src.url, timeoutMs)
88
+ if (!feed?.version || !feed?.platforms || typeof feed.platforms !== 'object') {
89
+ throw new Error('feed 结构不完整(缺少 version/platforms)')
90
+ }
91
+ return { feed, base: src.base, label: src.label }
92
+ }))
93
+ let best = null
94
+ settled.forEach((r, i) => {
95
+ if (r.status !== 'fulfilled') return
96
+ if (!best || compareVersions(r.value.feed.version, best.feed.version) > 0) best = r.value
97
+ })
98
+ if (!best) {
99
+ const tried = settled.map((r, i) => `${sources[i].label}:${r.reason?.message ?? r.reason}`).join(' / ')
100
+ throw new Error(`所有 feed 源均不可达(${tried})`)
101
+ }
102
+ return best
103
+ }
104
+
105
+ /** 本平台在 feed.platforms 里的候选 key(按优先级)。 */
106
+ function platformKeys() {
107
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
108
+ if (process.platform === 'darwin') return [`macos-${arch}-zip`, `macos-${arch}`]
109
+ if (process.platform === 'linux') return [`linux-appimage-${arch}`]
110
+ return [`windows-${arch}`, 'windows']
111
+ }
112
+
113
+ function applyMirror(url, base) {
114
+ if (base && typeof url === 'string' && url.startsWith('https://github.com/')) return base + url
115
+ return url
116
+ }
117
+
118
+ /** 选出本平台要下载的产物及候选 URL(gitee 直链 → 命中镜像 → github 直链 → 其余镜像)。 */
119
+ function pickAsset(feed, base) {
120
+ const platforms = feed.platforms || {}
121
+ for (const key of platformKeys()) {
122
+ const info = platforms[key]
123
+ if (!info?.file || !(info.url || info.giteeUrl)) continue
124
+ const urls = []
125
+ const push = u => { u = String(u ?? '').trim(); if (u && !urls.includes(u)) urls.push(u) }
126
+ push(info.giteeUrl)
127
+ push(applyMirror(info.url, base))
128
+ push(info.url)
129
+ for (const m of GITHUB_MIRRORS) push(applyMirror(info.url, m))
130
+ const kind = info.kind || (key.startsWith('windows') ? 'setup' : key.includes('zip') ? 'zip' : key.includes('appimage') ? 'appimage' : 'dmg')
131
+ return {
132
+ key,
133
+ kind,
134
+ name: info.file,
135
+ urls,
136
+ size: Number(info.size) || 0,
137
+ sha256: String(info.sha256 || '').toLowerCase(),
138
+ sha512: String(info.sha512 || '').toLowerCase(),
139
+ }
140
+ }
141
+ throw new Error(`更新源里没有本平台(${process.platform}/${process.arch})可自更新的产物`)
142
+ }
143
+
144
+ // ── 状态机(供 CLI 打印 / Web 面板 SSE 推送)──────────────────────────────
145
+
146
+ let state = {
147
+ status: 'idle', // idle / checking / available / downloading / downloaded / installing / done / not-available / error
148
+ current: getCurrentVersion(),
149
+ latest: null,
150
+ notes: null,
151
+ progress: null,
152
+ error: null,
153
+ source: null,
154
+ via: null,
155
+ downloadPage: null,
156
+ }
157
+ /** 最近一次检查命中的待安装信息(不对外暴露,供 download/install 阶段使用)。 */
158
+ let pending = null
159
+
160
+ const listeners = new Set()
161
+ export function onUpdateEvent(fn) {
162
+ listeners.add(fn)
163
+ return () => listeners.delete(fn)
164
+ }
165
+ function setState(patch) {
166
+ state = { ...state, ...patch }
167
+ for (const fn of listeners) {
168
+ try { fn({ ...state }) } catch { /* 单个订阅者异常不影响其余 */ }
169
+ }
170
+ }
171
+ export function getUpdateState() {
172
+ return { ...state }
173
+ }
174
+
175
+ /**
176
+ * 检查更新(不下载)。成功返回详情;失败抛出。
177
+ */
178
+ export async function checkForUpdate({ timeoutMs } = {}) {
179
+ setState({ status: 'checking', error: null })
180
+ let feed, base, label
181
+ try {
182
+ ({ feed, base, label } = await fetchFeed({ timeoutMs }))
183
+ } catch (error) {
184
+ setState({ status: 'error', error: error.message })
185
+ throw error
186
+ }
187
+ const latest = String(feed.version)
188
+ const current = getCurrentVersion()
189
+ const hasUpdate = compareVersions(latest, current) > 0
190
+ let asset = null
191
+ let assetError = ''
192
+ if (hasUpdate) {
193
+ try { asset = pickAsset(feed, base) } catch (e) { assetError = e.message }
194
+ }
195
+ pending = asset ? { feed, base, asset } : null
196
+ setState({
197
+ status: hasUpdate ? 'available' : 'not-available',
198
+ current,
199
+ latest,
200
+ notes: feed.notes || '',
201
+ source: label,
202
+ downloadPage: feed.url || SITE,
203
+ error: null,
204
+ progress: null,
205
+ })
206
+ return { hasUpdate, current, latest, notes: feed.notes || '', source: label, downloadPage: feed.url || SITE, asset, assetError }
207
+ }
208
+
209
+ function stagedPath(kind) {
210
+ const dir = mkdtempSync(join(tmpdir(), 'omr-update-'))
211
+ const ext = kind === 'zip' ? '.zip' : kind === 'dmg' ? '.dmg' : kind === 'appimage' ? '.AppImage' : '.exe'
212
+ return join(dir, `OneModelRouter-update${ext}`)
213
+ }
214
+
215
+ /** 下载到 dest,边写边算 sha512/sha256,实时回报进度;校验不过即删。 */
216
+ async function downloadTo(url, dest, asset, onProgress) {
217
+ const res = await fetch(url, {
218
+ signal: AbortSignal.timeout(600_000),
219
+ headers: { 'User-Agent': 'OneModelRouter-Update', Accept: '*/*' },
220
+ })
221
+ if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}:${url}`)
222
+ const total = asset.size || Number(res.headers.get('content-length')) || 0
223
+ const sha512 = createHash('sha512')
224
+ const sha256 = createHash('sha256')
225
+ let received = 0
226
+ let lastPct = -1
227
+ const nodeStream = Readable.fromWeb(res.body)
228
+ nodeStream.on('data', chunk => {
229
+ received += chunk.length
230
+ sha512.update(chunk)
231
+ sha256.update(chunk)
232
+ if (total > 0) {
233
+ const pct = Math.min(100, Math.round((received / total) * 100))
234
+ if (pct !== lastPct) { lastPct = pct; onProgress?.(pct) }
235
+ }
236
+ })
237
+ try {
238
+ await pipeline(nodeStream, createWriteStream(dest))
239
+ } catch (error) {
240
+ rmSync(dest, { force: true })
241
+ throw error
242
+ }
243
+ const actual512 = sha512.digest('hex')
244
+ const actual256 = sha256.digest('hex')
245
+ if (asset.sha512 && actual512 !== asset.sha512) {
246
+ rmSync(dest, { force: true })
247
+ throw new Error('sha512 校验不匹配,下载被拒绝(疑似被篡改或下载不完整)')
248
+ }
249
+ if (!asset.sha512 && asset.sha256 && actual256 !== asset.sha256) {
250
+ rmSync(dest, { force: true })
251
+ throw new Error('sha256 校验不匹配,下载被拒绝(疑似被篡改或下载不完整)')
252
+ }
253
+ return { size: received }
254
+ }
255
+
256
+ /** 下载当前待安装产物。 */
257
+ export async function downloadUpdate() {
258
+ try {
259
+ if (!pending?.asset) throw new Error('当前没有可下载的更新')
260
+ const asset = pending.asset
261
+ const dest = stagedPath(asset.kind)
262
+ setState({ status: 'downloading', progress: 0, error: null })
263
+ let lastError = null
264
+ for (const url of asset.urls) {
265
+ try {
266
+ await downloadTo(url, dest, asset, p => setState({ progress: p }))
267
+ pending.stagedPath = dest
268
+ setState({ status: 'downloaded', progress: 100, error: null })
269
+ return true
270
+ } catch (error) {
271
+ lastError = error
272
+ rmSync(dest, { force: true })
273
+ }
274
+ }
275
+ throw lastError ?? new Error('所有下载源均不可达')
276
+ } catch (error) {
277
+ setState({ status: 'error', error: error.message })
278
+ return false
279
+ }
280
+ }
281
+
282
+ function run(cmd, args, timeoutMs = 120_000) {
283
+ return new Promise((resolveP, reject) => {
284
+ let child
285
+ try { child = spawn(cmd, args, { stdio: ['ignore', 'ignore', 'pipe'] }) } catch (error) { reject(error); return }
286
+ let stderr = ''
287
+ child.stderr.on('data', chunk => { stderr = (stderr + chunk.toString()).slice(-2000) })
288
+ const timer = setTimeout(() => {
289
+ try { child.kill('SIGKILL') } catch { /* ignore */ }
290
+ reject(new Error(`${basename(cmd)} 执行超时`))
291
+ }, timeoutMs)
292
+ child.on('error', error => { clearTimeout(timer); reject(error) })
293
+ child.on('close', code => {
294
+ clearTimeout(timer)
295
+ if (code === 0) resolveP()
296
+ else reject(new Error(`${basename(cmd)} 退出码 ${code}${stderr.trim() ? ':' + stderr.trim() : ''}`))
297
+ })
298
+ })
299
+ }
300
+
301
+ function findAppUnder(dir) {
302
+ const hit = base => {
303
+ try {
304
+ return readdirSync(base)
305
+ .map(name => join(base, name))
306
+ .find(p => p.toLowerCase().endsWith('.app') && existsSync(join(p, 'Contents', 'Info.plist'))) || ''
307
+ } catch { return '' }
308
+ }
309
+ const direct = hit(dir)
310
+ if (direct) return direct
311
+ try {
312
+ for (const name of readdirSync(dir)) {
313
+ const nested = hit(join(dir, name))
314
+ if (nested) return nested
315
+ }
316
+ } catch { /* 目录不可读当作没找到 */ }
317
+ return ''
318
+ }
319
+
320
+ function writableDir(dir) {
321
+ try { accessSync(dir, constants.W_OK); return true } catch { return false }
322
+ }
323
+
324
+ /** Windows:静默运行 NSIS 安装器(安装器自带关闭旧实例/装回原目录/装完拉起新版)。 */
325
+ function installWindows(file) {
326
+ const child = spawn(file, ['/S'], { detached: true, stdio: 'ignore' })
327
+ child.on('error', () => { /* 异步 spawn 失败只能记日志,由调用方兜底 */ })
328
+ if (!child.pid) throw new Error('安装器进程创建失败')
329
+ child.unref()
330
+ }
331
+
332
+ /** macOS:解压/挂载更新包,整包换入 /Applications(不可写则 ~/Applications)。 */
333
+ async function installMacos(asset, file) {
334
+ const work = mkdtempSync(join(tmpdir(), 'omr-mac-'))
335
+ let mount = ''
336
+ try {
337
+ let appSrc = ''
338
+ if (asset.kind === 'dmg') {
339
+ mount = join(work, 'mnt')
340
+ mkdirSync(mount, { recursive: true })
341
+ await run('/usr/bin/hdiutil', ['attach', '-quiet', '-nobrowse', '-readonly', '-mountpoint', mount, file])
342
+ appSrc = findAppUnder(mount)
343
+ if (!appSrc) throw new Error('dmg 内未找到 OneModelRouter.app')
344
+ } else {
345
+ await run('/usr/bin/ditto', ['-x', '-k', file, work])
346
+ appSrc = findAppUnder(work)
347
+ if (!appSrc) throw new Error('更新包内没有 OneModelRouter.app')
348
+ }
349
+ const apps = writableDir('/Applications') ? '/Applications' : join(homedir(), 'Applications')
350
+ mkdirSync(apps, { recursive: true })
351
+ const target = join(apps, 'OneModelRouter.app')
352
+ if (existsSync(target)) rmSync(target, { recursive: true, force: true })
353
+ cpSync(appSrc, target, { recursive: true })
354
+ } finally {
355
+ if (mount) await run('/usr/bin/hdiutil', ['detach', '-quiet', mount]).catch(() => {})
356
+ rmSync(work, { recursive: true, force: true })
357
+ }
358
+ }
359
+
360
+ /** Linux:AppImage 运行态原子覆盖自身;非 AppImage(npm/服务端)装到 ~/.local/bin。 */
361
+ async function installLinux(file) {
362
+ const current = process.env.APPIMAGE
363
+ if (current) {
364
+ const next = `${current}.new`
365
+ try {
366
+ cpSync(file, next)
367
+ chmodSync(next, 0o755)
368
+ renameSync(next, current)
369
+ } catch (error) {
370
+ rmSync(next, { force: true })
371
+ throw new Error(`覆盖 AppImage 失败(${error.message})`)
372
+ }
373
+ return
374
+ }
375
+ const bin = process.env.OMR_BIN_DIR || join(homedir(), '.local', 'bin')
376
+ mkdirSync(bin, { recursive: true })
377
+ const target = join(bin, 'OneModelRouter')
378
+ cpSync(file, target)
379
+ chmodSync(target, 0o755)
380
+ }
381
+
382
+ /** 按当前系统执行与桌面端一致的安装动作。 */
383
+ async function installArtifact(asset, file) {
384
+ if (process.platform === 'win32') return installWindows(file)
385
+ if (process.platform === 'darwin') return installMacos(asset, file)
386
+ if (process.platform === 'linux') return installLinux(file)
387
+ throw new Error(`当前系统不支持内置自更新(${process.platform}),请从官网重新安装`)
388
+ }
389
+
390
+ /** 兜底:npm 全局升级到最新版。 */
391
+ export function npmUpgrade(log = () => {}) {
392
+ log(`执行 npm 兜底升级:npm i -g ${PKG_NAME}@latest`)
393
+ return new Promise((resolveP, reject) => {
394
+ const child = spawn('npm', ['i', '-g', `${PKG_NAME}@latest`], { stdio: 'inherit', shell: true })
395
+ child.on('error', reject)
396
+ child.on('close', code => (code === 0 ? resolveP() : reject(new Error(`npm 退出码 ${code}`))))
397
+ })
398
+ }
399
+
400
+ /** 安装已下载的更新;原生失败自动回退 npm 升级。 */
401
+ export async function applyUpdate({ log = () => {} } = {}) {
402
+ try {
403
+ if (!pending?.stagedPath) throw new Error('暂无已下载的更新包')
404
+ setState({ status: 'installing', error: null })
405
+ await installArtifact(pending.asset, pending.stagedPath)
406
+ setState({ status: 'done', via: 'native' })
407
+ return true
408
+ } catch (error) {
409
+ log(`原生安装不可用/失败:${error.message},改用 npm 兜底升级`)
410
+ try {
411
+ setState({ status: 'installing', error: null, via: 'npm' })
412
+ await npmUpgrade(log)
413
+ setState({ status: 'done', via: 'npm' })
414
+ return true
415
+ } catch (npmError) {
416
+ setState({ status: 'error', error: `原生升级失败:${error.message};npm 兜底也失败:${npmError.message}` })
417
+ return false
418
+ }
419
+ }
420
+ }
421
+
422
+ /**
423
+ * 一键更新:检查 → 下载 → 安装(原生优先,npm 兜底)。
424
+ * @param {{ mode?: 'auto'|'npm', log?: (...a:any[])=>void }} [options]
425
+ */
426
+ export async function runUpdate({ mode = 'auto', log = () => {} } = {}) {
427
+ if (mode !== 'npm') {
428
+ const info = await checkForUpdate()
429
+ log(`更新源:${info.source};当前 v${info.current},最新 v${info.latest}`)
430
+ if (!info.hasUpdate) { log('已是最新版本'); return { updated: false, via: null, ...info } }
431
+ if (info.asset) {
432
+ log(`发现新版本 v${info.latest},下载 ${info.asset.name} …`)
433
+ const downloaded = await downloadUpdate()
434
+ if (downloaded) {
435
+ log('下载完成并通过校验,开始安装…')
436
+ const installed = await applyUpdate({ log })
437
+ if (installed) {
438
+ const via = getUpdateState().via
439
+ log(`升级完成(${via === 'npm' ? 'npm 兜底' : '原生安装包'})。请重启服务使其生效。`)
440
+ return { updated: true, via, ...info }
441
+ }
442
+ log(`升级失败:${getUpdateState().error}`)
443
+ return { updated: false, via: null, error: getUpdateState().error, ...info }
444
+ }
445
+ log(`下载失败:${getUpdateState().error},改用 npm 兜底升级`)
446
+ } else {
447
+ log(`本平台无原生安装包(${info.assetError || '无'}),改用 npm 兜底升级`)
448
+ }
449
+ }
450
+ await npmUpgrade(log)
451
+ log(`npm 升级完成。请重启服务使其生效(omr restart)。`)
452
+ return { updated: true, via: 'npm' }
453
+ }
454
+
455
+ /** 关闭时清理下载残留(进程退出调用)。 */
456
+ export function cleanupStaged() {
457
+ try { if (pending?.stagedPath) rmSync(dirname(pending.stagedPath), { recursive: true, force: true }) } catch { /* ignore */ }
458
+ }
package/web/app.js CHANGED
@@ -360,6 +360,14 @@ function recentTableHtml(recent) {
360
360
 
361
361
  const events = new EventSource('/admin/api/events')
362
362
 
363
+ // 网页版自更新:更新状态经 SSE 'update' 事件推送,供浏览器版更新胶囊订阅
364
+ const updateSubs = new Set()
365
+ events.addEventListener('update', e => {
366
+ let s
367
+ try { s = JSON.parse(e.data) } catch { return }
368
+ for (const fn of updateSubs) { try { fn(s) } catch { /* ignore */ } }
369
+ })
370
+
363
371
  events.addEventListener('request', e => {
364
372
  if (!state) return
365
373
  let data
@@ -3794,10 +3802,30 @@ setInterval(() => {
3794
3802
  refresh()
3795
3803
  }, 30000)
3796
3804
 
3797
- // ── 桌面端自动升级 UI(仅 Electron:window.omrUpdater 由 preload 注入)───────
3798
- // 纯浏览器访问 /admin 时 omrUpdater 为 undefined,整块跳过,Web 端零影响。
3799
- // 面板关闭时状态也持续缓存到模块级变量,事件推送照常更新,重新打开即最新。
3800
- if (window.omrUpdater) {
3805
+ // ── 自动升级 UI ──────────────────────────────────────────────────────────────
3806
+ // 桌面端:window.omrUpdater(preload IPC,桌面版自更新);
3807
+ // 网页版(npm 安装):走 /admin/api/update/* HTTP 接口,行为与桌面版一致。
3808
+ // 纯浏览器/桌面端均由同一个 updater 抽象驱动,UI 零差异。
3809
+ const webUpdater = window.omrUpdater ? null : (function createWebUpdater() {
3810
+ const post = path => fetch(path, { method: 'POST' })
3811
+ .then(r => r.json().catch(() => ({})))
3812
+ .then(d => (d && d.ok === false ? { ok: false, error: d.error ?? '未知错误' } : { ok: true }))
3813
+ .catch(e => ({ ok: false, error: String(e?.message ?? e) }))
3814
+ return {
3815
+ getState: () => fetch('/admin/api/update').then(r => r.json()).catch(() => null),
3816
+ check: () => post('/admin/api/update/check'),
3817
+ // 网页版点「升级」= 服务端一次完成 下载 + 安装(原生优先,npm 兜底)
3818
+ download: () => post('/admin/api/update/run').then(r => {
3819
+ if (r.ok) toast('升级完成,请执行 omr restart 重启服务使其生效')
3820
+ return r
3821
+ }),
3822
+ install: () => post('/admin/api/update/install'),
3823
+ onEvent: cb => { updateSubs.add(cb); return () => updateSubs.delete(cb) },
3824
+ }
3825
+ })()
3826
+
3827
+ const updater = window.omrUpdater || webUpdater
3828
+ if (updater) {
3801
3829
  let updaterState = null // 最新升级状态缓存(结构同 getState 返回值)
3802
3830
  let updaterOpen = false // 下拉面板当前是否展开
3803
3831
  let promptedVersion = null // 已提示过的版本号:同一版本只自动展开提示一次
@@ -3867,6 +3895,16 @@ if (window.omrUpdater) {
3867
3895
  <div class="omr-update-title">${esc(v)} 下载完成</div>
3868
3896
  <div class="omr-update-line">正在安装并重启,请稍候…</div>`
3869
3897
  break
3898
+ case 'installing':
3899
+ $panel.innerHTML = `
3900
+ <div class="omr-update-title">${esc(v)} 正在安装</div>
3901
+ <div class="omr-update-line">正在按当前系统安装更新,请稍候…</div>`
3902
+ break
3903
+ case 'done':
3904
+ $panel.innerHTML = `
3905
+ <div class="omr-update-title">${esc(v)} 升级完成</div>
3906
+ <div class="omr-update-line">请执行 omr restart 重启服务使其生效</div>`
3907
+ break
3870
3908
  case 'error':
3871
3909
  $panel.innerHTML = `
3872
3910
  <div class="omr-update-title err">更新失败</div>
@@ -3893,11 +3931,11 @@ if (window.omrUpdater) {
3893
3931
  // 下载/安装失败(error)时若本轮已发现过新版本,仍保留按钮,否则用户会连重试入口都看不到。
3894
3932
  let seenUpdate = false
3895
3933
 
3896
- const btnVisible = s => !!s && (['available', 'downloading', 'downloaded'].includes(s.status)
3934
+ const btnVisible = s => !!s && (['available', 'downloading', 'downloaded', 'installing', 'done'].includes(s.status)
3897
3935
  || (s.status === 'error' && seenUpdate))
3898
3936
 
3899
3937
  function renderAll() {
3900
- if (['available', 'downloading', 'downloaded'].includes(updaterState?.status)) seenUpdate = true
3938
+ if (['available', 'downloading', 'downloaded', 'installing', 'done'].includes(updaterState?.status)) seenUpdate = true
3901
3939
  if (!btnVisible(updaterState)) {
3902
3940
  // 隐藏按钮的同时收起面板,避免留下悬空浮层
3903
3941
  $wrap.hidden = true
@@ -3908,7 +3946,7 @@ if (window.omrUpdater) {
3908
3946
  $wrap.hidden = false
3909
3947
  const status = updaterState?.status ?? 'idle'
3910
3948
  // 照 magpie:下载/重启中胶囊置灰并禁用点击,文字与 title 跟随状态
3911
- $btn.classList.toggle('busy', ['downloading', 'downloaded'].includes(status))
3949
+ $btn.classList.toggle('busy', ['downloading', 'downloaded', 'installing'].includes(status))
3912
3950
  $btn.title = btnTitle(updaterState)
3913
3951
  $label.textContent = btnLabel(updaterState)
3914
3952
  renderPanel(updaterState)
@@ -3933,7 +3971,7 @@ if (window.omrUpdater) {
3933
3971
  $panel.hidden = false
3934
3972
  }
3935
3973
  try {
3936
- const res = await window.omrUpdater[action]()
3974
+ const res = await updater[action]()
3937
3975
  if (res && res.ok === false) toast(`操作失败:${res.error ?? '未知错误'}`, 'err')
3938
3976
  } catch (e) {
3939
3977
  toast(`操作失败:${e?.message ?? e}`, 'err')
@@ -3959,12 +3997,12 @@ if (window.omrUpdater) {
3959
3997
  $panel.hidden = true
3960
3998
  })
3961
3999
 
3962
- window.omrUpdater.onEvent(s => {
4000
+ updater.onEvent(s => {
3963
4001
  updaterState = s
3964
4002
  renderAll()
3965
4003
  promptIfAvailable(s)
3966
4004
  })
3967
- window.omrUpdater.getState().then(s => {
4005
+ updater.getState().then(s => {
3968
4006
  updaterState = s
3969
4007
  renderAll()
3970
4008
  promptIfAvailable(s)