one-model-router 0.0.10 → 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/LICENSE +21 -21
- package/README.md +32 -5
- package/bin/omr.js +46 -0
- package/package.json +3 -2
- package/src/admin.js +965 -941
- package/src/balances.js +61 -61
- package/src/boot.js +117 -117
- package/src/channels/buddy.js +2031 -2031
- package/src/channels/cline.js +753 -753
- package/src/channels/codearts.js +2051 -2051
- package/src/channels/comate.js +830 -830
- package/src/channels/doubaowork.js +1784 -1784
- package/src/channels/freebuff.js +1316 -1316
- package/src/channels/gemini.js +1721 -1721
- package/src/channels/index.js +270 -270
- package/src/channels/joycode.js +936 -936
- package/src/channels/kimi.js +572 -572
- package/src/channels/lobsterai.js +1226 -1226
- package/src/channels/loomy.js +1032 -1032
- package/src/channels/miaoshou.js +1396 -1396
- package/src/channels/mimo.js +474 -474
- package/src/channels/minimax.js +1451 -1451
- package/src/channels/qoder-wasm.js +434 -434
- package/src/channels/qoder.js +1619 -1619
- package/src/channels/raccoon.js +1842 -1842
- package/src/channels/tabbit.js +1457 -1457
- package/src/channels/trae.js +1405 -1405
- package/src/channels/zcode-global.js +35 -35
- package/src/channels/zcode.js +2085 -2085
- package/src/checkin.js +496 -496
- package/src/credits.js +464 -464
- package/src/crypto.js +132 -132
- package/src/free-models.js +683 -683
- package/src/gateway.js +596 -578
- package/src/health.js +86 -86
- package/src/model-key.js +35 -35
- package/src/paths.js +96 -96
- package/src/probe.js +318 -318
- package/src/providers/builtin.js +626 -626
- package/src/providers/index.js +483 -457
- package/src/providers/kilo.js +111 -111
- package/src/providers/last-good.js +69 -69
- package/src/providers/modelsdev.js +242 -242
- package/src/providers/openai-compat.js +312 -312
- package/src/providers/opencode/bun-fetch.js +226 -226
- package/src/providers/opencode/lane.js +186 -186
- package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
- package/src/providers/opencode/o2a/asset-source.js +43 -43
- package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
- package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
- package/src/providers/opencode/o2a/entry.js +17 -17
- package/src/providers/opencode/o2a/gateway-body.js +42 -42
- package/src/providers/opencode/o2a/headers.js +133 -133
- package/src/providers/opencode/o2a/identity.js +148 -148
- package/src/providers/opencode/o2a/official-prompt.js +191 -191
- package/src/providers/opencode/o2a/official-tools.js +110 -110
- package/src/providers/opencode/o2a/tool-renames.js +217 -217
- package/src/providers/opencode/o2a/toolshape.js +418 -418
- package/src/providers/opencode/o2a/version.js +37 -37
- package/src/providers/opencode/upstream.js +403 -403
- package/src/providers/opencode/wire.js +496 -496
- package/src/providers/opencode.js +652 -652
- package/src/router.js +629 -629
- package/src/server.js +49 -33
- package/src/store.js +467 -467
- package/src/sync/index.js +1529 -1529
- package/src/sync/login-preload.cjs +52 -52
- package/src/sync/noise.js +141 -141
- package/src/sync/relay-http.js +176 -176
- package/src/sync/remote-host.js +818 -818
- package/src/sync/remote-http.js +112 -112
- package/src/sync/remote-login.js +657 -657
- package/src/sync/remote-pairing.js +204 -204
- package/src/sync/remote-protocol.js +321 -321
- package/src/sync/snapshot.js +211 -211
- package/src/update.js +458 -0
- package/src/util.js +334 -334
- package/web/app.js +4010 -3972
- package/web/index.html +32 -32
- package/web/style.css +971 -971
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
|
+
}
|