one-model-router 0.0.0-stage → 0.0.10

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.
Files changed (81) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +172 -3
  3. package/bin/omr.js +300 -0
  4. package/package.json +214 -6
  5. package/src/admin.js +941 -0
  6. package/src/balances.js +61 -0
  7. package/src/boot.js +117 -0
  8. package/src/channels/buddy.js +2031 -0
  9. package/src/channels/cline.js +753 -0
  10. package/src/channels/codearts.js +2051 -0
  11. package/src/channels/comate.js +830 -0
  12. package/src/channels/doubaowork.js +1784 -0
  13. package/src/channels/freebuff.js +1316 -0
  14. package/src/channels/gemini.js +1721 -0
  15. package/src/channels/index.js +270 -0
  16. package/src/channels/joycode.js +936 -0
  17. package/src/channels/kimi.js +572 -0
  18. package/src/channels/lobsterai.js +1226 -0
  19. package/src/channels/loomy.js +1032 -0
  20. package/src/channels/miaoshou.js +1396 -0
  21. package/src/channels/mimo.js +474 -0
  22. package/src/channels/minimax.js +1451 -0
  23. package/src/channels/qoder-auth-wasm.wasm +0 -0
  24. package/src/channels/qoder-wasm.js +434 -0
  25. package/src/channels/qoder.js +1619 -0
  26. package/src/channels/raccoon.js +1842 -0
  27. package/src/channels/tabbit.js +1457 -0
  28. package/src/channels/trae.js +1405 -0
  29. package/src/channels/zcode-global.js +35 -0
  30. package/src/channels/zcode.js +2085 -0
  31. package/src/checkin.js +496 -0
  32. package/src/credits.js +464 -0
  33. package/src/crypto.js +132 -0
  34. package/src/free-models.js +683 -0
  35. package/src/gateway.js +578 -0
  36. package/src/health.js +86 -0
  37. package/src/model-key.js +35 -0
  38. package/src/paths.js +96 -0
  39. package/src/probe.js +318 -0
  40. package/src/providers/builtin.js +626 -0
  41. package/src/providers/index.js +457 -0
  42. package/src/providers/kilo.js +111 -0
  43. package/src/providers/last-good.js +69 -0
  44. package/src/providers/modelsdev.js +242 -0
  45. package/src/providers/openai-compat.js +312 -0
  46. package/src/providers/opencode/bun-fetch.js +226 -0
  47. package/src/providers/opencode/lane.js +186 -0
  48. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -0
  49. package/src/providers/opencode/o2a/asset-source.js +43 -0
  50. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -0
  51. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -0
  52. package/src/providers/opencode/o2a/entry.js +17 -0
  53. package/src/providers/opencode/o2a/gateway-body.js +42 -0
  54. package/src/providers/opencode/o2a/headers.js +133 -0
  55. package/src/providers/opencode/o2a/identity.js +148 -0
  56. package/src/providers/opencode/o2a/official-prompt.js +191 -0
  57. package/src/providers/opencode/o2a/official-tools.js +110 -0
  58. package/src/providers/opencode/o2a/tool-renames.js +217 -0
  59. package/src/providers/opencode/o2a/toolshape.js +418 -0
  60. package/src/providers/opencode/o2a/version.js +37 -0
  61. package/src/providers/opencode/upstream.js +403 -0
  62. package/src/providers/opencode/wire.js +496 -0
  63. package/src/providers/opencode.js +652 -0
  64. package/src/router.js +629 -0
  65. package/src/server.js +33 -0
  66. package/src/store.js +467 -0
  67. package/src/sync/index.js +1529 -0
  68. package/src/sync/login-preload.cjs +52 -0
  69. package/src/sync/noise.js +141 -0
  70. package/src/sync/relay-http.js +176 -0
  71. package/src/sync/remote-host.js +818 -0
  72. package/src/sync/remote-http.js +112 -0
  73. package/src/sync/remote-login.js +657 -0
  74. package/src/sync/remote-pairing.js +204 -0
  75. package/src/sync/remote-protocol.js +321 -0
  76. package/src/sync/snapshot.js +211 -0
  77. package/src/util.js +334 -0
  78. package/web/app.js +3972 -0
  79. package/web/index.html +32 -0
  80. package/web/logo.png +0 -0
  81. package/web/style.css +971 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OneModelRouter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,172 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # OneModelRouter
2
+
3
+ 把散落在各家的免费 / 自有大模型通道聚合成**一个 OpenAI 兼容接口**,装在自己电脑上运行,
4
+ 一个地址接给所有 AI 工具(Claude Code、Cline、Cursor、Cherry Studio 等)。
5
+
6
+ - **统一网关**:OpenAI 兼容 `/v1`,一个 baseURL 通吃
7
+ - **免费渠道聚合**:20+ 免费 / 额度通道集中管理,Web 面板勾选启用
8
+ - **模型组轮询**:多模型成组自动切换,故障 / 限流自动转移
9
+ - **多账号池**:渠道内多账号轮换,失败自动换号重试
10
+ - **自动签到**:每日自动领各渠道积分 / Token 额度
11
+ - **本地运行**:数据只在你自己机器上,管理面板仅监听 `127.0.0.1`
12
+
13
+ > 仅供个人学习与技术研究使用,请勿商用或高频滥用,详见文末[免责声明](#免责声明)。
14
+
15
+ ---
16
+
17
+ ## 安装
18
+
19
+ ### Windows
20
+
21
+ ```powershell
22
+ # 包管理器(推荐,后续 winget upgrade 一条命令升级)
23
+ winget install OneModelRouter.OneModelRouter
24
+
25
+ # 或一行安装脚本(自动取最新版并校验 sha256)
26
+ powershell -c "irm https://bothua111.github.io/OneModelRouter/install.ps1 | iex"
27
+ ```
28
+
29
+ 也可直接从 [Releases](https://github.com/bothua111/OneModelRouter/releases/latest) 下载
30
+ `OneModelRouter-Setup-<版本>-x64.exe`(支持 arm64,文件名带 `-arm64`)。
31
+
32
+ ### macOS
33
+
34
+ ```bash
35
+ # Homebrew cask(推荐)
36
+ brew tap bothua111/cask && brew install --cask onemodelrouter
37
+
38
+ # 或一行安装脚本(curl 下载不带隔离标记,可直接打开)
39
+ curl -fsSL https://bothua111.github.io/OneModelRouter/install.sh | sh
40
+ ```
41
+
42
+ Apple Silicon 与 Intel 分别有 `arm64` / `x64` 包。当前发布链是**无证书 ad-hoc 签名**,
43
+ 首次打开如遇「无法验证开发者」,在 Finder 里右键 →「打开」一次即可。
44
+
45
+ ### Linux
46
+
47
+ ```bash
48
+ # 一行安装脚本(默认装 AppImage 到 ~/.local/bin)
49
+ curl -fsSL https://bothua111.github.io/OneModelRouter/install.sh | sh
50
+
51
+ # 或用系统包(Releases 里下载)
52
+ sudo dpkg -i OneModelRouter-<版本>-amd64.deb # Debian / Ubuntu
53
+ sudo rpm -ivh OneModelRouter-<版本>-x86_64.rpm # RHEL / Fedora
54
+ ```
55
+
56
+ AppImage 需要 `libfuse2`(Ubuntu 22.04+ 可加 `--appimage-extract-and-run` 参数,安装脚本已处理)。
57
+
58
+ ### npm(无桌面壳,适合服务器 / 无 GUI 环境)
59
+
60
+ ```bash
61
+ npm i -g one-model-router # 或:npx one-model-router start --detach
62
+ omr start --detach
63
+ ```
64
+
65
+ ### Docker
66
+
67
+ ```bash
68
+ docker run -d --name omr \
69
+ -p 18682:18682 \
70
+ -p 127.0.0.1:18681:18681 \
71
+ -v omr-data:/data \
72
+ ghcr.io/<owner>/onemodelrouter:latest
73
+ ```
74
+
75
+ > 管理面板无登录鉴权且能看到模型凭据,所以管理端口刻意只映射到宿主机回环地址;
76
+ > 需要远程访问请自行加反向代理 + 鉴权。
77
+
78
+ ---
79
+
80
+ ## 快速开始
81
+
82
+ 1. 启动后打开管理面板:<http://127.0.0.1:18681/admin>
83
+ 2. 在「渠道」页勾选要用的免费通道,需要登录的按提示扫码 / 粘贴令牌
84
+ 3. 在「模型组」页把可用模型编成一组(自动轮询 + 故障切换)
85
+ 4. 把 AI 工具的 API 地址指向网关:
86
+
87
+ ```
88
+ baseURL : http://127.0.0.1:18682/v1
89
+ apiKey : 任意非空字符串(本机网关不做鉴权)
90
+ model : 你的模型组名,或具体模型 id
91
+ ```
92
+
93
+ 验证:
94
+
95
+ ```bash
96
+ curl http://127.0.0.1:18682/v1/models
97
+ ```
98
+
99
+ ---
100
+
101
+ ## 命令行(`omr`)
102
+
103
+ | 命令 | 说明 |
104
+ | --- | --- |
105
+ | `omr start` | 前台启动(Ctrl+C 停止) |
106
+ | `omr start --detach` | 后台启动,写 pid 并等健康探针就绪 |
107
+ | `omr stop` / `omr restart` | 停止 / 重启后台实例 |
108
+ | `omr status` | 查看进程、端口与 `/health` 探针 |
109
+ | `omr portal` | 用系统浏览器打开管理面板 |
110
+ | `omr version` | 版本 |
111
+
112
+ 通用选项:`--port`(网关,默认 18682)、`--admin-port`(管理面,默认 18681)、`--data-dir`。
113
+
114
+ ## 环境变量
115
+
116
+ | 变量 | 默认值 | 说明 |
117
+ | --- | --- | --- |
118
+ | `OMR_DATA_DIR` | `~/.OneModelRouter/data` | 数据目录(凭据、配置、日志) |
119
+ | `OMR_GATEWAY_PORT` | `18682` | 网关端口 |
120
+ | `OMR_ADMIN_PORT` | `18681` | 管理面板端口 |
121
+ | `OMR_GATEWAY_HOST` | `127.0.0.1` | 网关监听地址(容器内需设 `0.0.0.0`) |
122
+ | `OMR_ADMIN_HOST` | `127.0.0.1` | 管理面监听地址 |
123
+
124
+ 桌面端与 CLI / Docker **共用同一份数据目录**,凭据不需要重复配置。
125
+
126
+ ---
127
+
128
+ ## 升级
129
+
130
+ | 渠道 | 方式 |
131
+ | --- | --- |
132
+ | Windows / macOS / Linux 桌面端 | 管理面板右上角「升级」按钮,内置自更新(优先 Gitee 源) |
133
+ | winget | `winget upgrade OneModelRouter.OneModelRouter` |
134
+ | Homebrew | `brew upgrade --cask onemodelrouter` |
135
+ | npm | `npm update -g one-model-router` |
136
+ | Docker | `docker pull` 新 tag 后重建容器 |
137
+
138
+ ---
139
+
140
+ ## 常见问题
141
+
142
+ **网关起来了但调用报错?**
143
+ 先 `curl http://127.0.0.1:18682/v1/models` 看模型列表是否为空——为空通常是渠道未启用或令牌过期,
144
+ 到管理面板「渠道」页看该渠道的状态与最近错误。
145
+
146
+ **端口被占用?**
147
+ `omr start --port 19000 --admin-port 19001`,或设置 `OMR_GATEWAY_PORT` / `OMR_ADMIN_PORT`。
148
+
149
+ **数据存在哪?想备份 / 迁移?**
150
+ 整个 `~/.OneModelRouter/data` 目录复制走即可(含加密凭据,注意保管)。也可用 `OMR_DATA_DIR` 指到别处。
151
+
152
+ **macOS 提示「已损坏,无法打开」?**
153
+ 用官网的 `install.sh` 安装(curl 下载不带隔离标记),或在终端执行
154
+ `xattr -dr com.apple.quarantine /Applications/OneModelRouter.app` 后再打开。
155
+
156
+ **Linux AppImage 双击没反应?**
157
+ 缺 `libfuse2`:`sudo apt install libfuse2`,或直接 `./OneModelRouter --appimage-extract-and-run`。
158
+
159
+ ---
160
+
161
+ ## 免责声明
162
+
163
+ 本项目仅供个人学习与技术研究使用,请勿用于商业用途或任何违法违规场景。
164
+
165
+ - 转发渠道**务必使用小号 / 备用账号**,切勿使用主力账号,避免被平台风控
166
+ - 请控制调用频率,不要高频、批量或商业化滥用
167
+ - 请自行遵守各模型平台的服务条款与当地法律法规;因使用本工具产生的账号风控、
168
+ 额度变化或第三方服务问题,均由使用者自行承担,项目作者不承担任何责任
169
+
170
+ ## License
171
+
172
+ [MIT](LICENSE)
package/bin/omr.js ADDED
@@ -0,0 +1,300 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * OneModelRouter 命令行入口(npm 包发布形态:`npm i -g one-model-router` 或 `npx one-model-router`)。
4
+ *
5
+ * omr start [--detach] [--port <n>] [--admin-port <n>] [--data-dir <path>]
6
+ * omr stop | restart | status | portal | version | help
7
+ *
8
+ * 与桌面端共用同一套服务与数据目录,不含 Electron:管理面仍走浏览器
9
+ * (http://127.0.0.1:18681/admin)。
10
+ *
11
+ * pid 文件与日志命名刻意沿用 omr.ps1 的约定(<数据目录>/omr.pid、
12
+ * <数据目录>/logs/omr-<时间戳>.log,保留最近 5 份),因此本 CLI 与
13
+ * PowerShell 管理脚本、桌面端看到的是同一个实例状态,互不打架。
14
+ */
15
+
16
+ import { spawn } from 'node:child_process'
17
+ import { closeSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
18
+ import { dirname, join } from 'node:path'
19
+ import { fileURLToPath, pathToFileURL } from 'node:url'
20
+
21
+ const ROOT = dirname(dirname(fileURLToPath(import.meta.url)))
22
+ const PKG = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'))
23
+ const SERVER = join(ROOT, 'src', 'server.js')
24
+ const KEEP_LOGS = 5
25
+
26
+ const log = (...args) => console.log(...args)
27
+ const die = message => {
28
+ console.error(`omr: ${message}`)
29
+ process.exit(1)
30
+ }
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // 参数解析(先落 env,再 import src/paths.js —— 它在求值时就读取 OMR_DATA_DIR)
34
+ // ---------------------------------------------------------------------------
35
+ function parseArgs(argv) {
36
+ const args = { command: 'start', detach: false }
37
+ const rest = [...argv]
38
+ if (rest.length && !rest[0].startsWith('-')) args.command = rest.shift()
39
+ while (rest.length) {
40
+ const a = rest.shift()
41
+ if (a === '-d' || a === '--detach') args.detach = true
42
+ else if (a === '--port') args.port = rest.shift()
43
+ else if (a === '--admin-port') args.adminPort = rest.shift()
44
+ else if (a === '--data-dir') args.dataDir = rest.shift()
45
+ else if (a === '-h' || a === '--help') args.command = 'help'
46
+ else if (a === '-v' || a === '--version') args.command = 'version'
47
+ else die(`未知参数 ${a}(omr help 看用法)`)
48
+ }
49
+ return args
50
+ }
51
+
52
+ const args = parseArgs(process.argv.slice(2))
53
+ if (args.port) process.env.OMR_GATEWAY_PORT = String(args.port)
54
+ if (args.adminPort) process.env.OMR_ADMIN_PORT = String(args.adminPort)
55
+ if (args.dataDir) process.env.OMR_DATA_DIR = String(args.dataDir)
56
+
57
+ const GATEWAY_PORT = Number(process.env.OMR_GATEWAY_PORT) || 18682
58
+ const ADMIN_PORT = Number(process.env.OMR_ADMIN_PORT) || 18681
59
+ const { DATA_DIR } = await import(pathToFileURL(join(ROOT, 'src', 'paths.js')).href)
60
+
61
+ const PID_FILE = join(DATA_DIR, 'omr.pid')
62
+ const LOG_DIR = join(DATA_DIR, 'logs')
63
+
64
+ const alive = pid => {
65
+ if (!pid) return false
66
+ try {
67
+ process.kill(pid, 0)
68
+ return true
69
+ } catch {
70
+ return false
71
+ }
72
+ }
73
+
74
+ /**
75
+ * 实例登记信息。pid 文件首行是 PID(与 omr.ps1 的 `Get-Content -TotalCount 1` 兼容),
76
+ * 后两行是本实例实际监听的网关/管理面端口——否则 `omr status` 只能用 env 默认值,
77
+ * 用 --port 起的实例会被报错端口。
78
+ */
79
+ function readInstance() {
80
+ const fallback = { pid: 0, gatewayPort: GATEWAY_PORT, adminPort: ADMIN_PORT }
81
+ try {
82
+ const lines = readFileSync(PID_FILE, 'utf8').split(/\r?\n/)
83
+ const pid = Number(String(lines[0] || '').trim())
84
+ if (!alive(pid)) return fallback
85
+ return {
86
+ pid,
87
+ gatewayPort: Number(lines[1]) || GATEWAY_PORT,
88
+ adminPort: Number(lines[2]) || ADMIN_PORT,
89
+ }
90
+ } catch {
91
+ return fallback
92
+ }
93
+ }
94
+
95
+ const runningPid = () => readInstance().pid
96
+
97
+ const healthUrlOf = gatewayPort => `http://127.0.0.1:${gatewayPort}/health`
98
+
99
+ function writePid(pid, gatewayPort, adminPort) {
100
+ mkdirSync(DATA_DIR, { recursive: true })
101
+ writeFileSync(PID_FILE, `${pid}\n${gatewayPort}\n${adminPort}\n`, 'utf8')
102
+ }
103
+
104
+ function latestLog() {
105
+ try {
106
+ return readdirSync(LOG_DIR)
107
+ .filter(name => /^omr-.*\.log$/i.test(name))
108
+ .map(name => join(LOG_DIR, name))
109
+ .sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0] || ''
110
+ } catch {
111
+ return ''
112
+ }
113
+ }
114
+
115
+ function tail(file, lines = 20) {
116
+ try {
117
+ return readFileSync(file, 'utf8').split('\n').filter(Boolean).slice(-lines).join('\n')
118
+ } catch {
119
+ return ''
120
+ }
121
+ }
122
+
123
+ async function waitHealthy(gatewayPort, timeoutMs) {
124
+ const url = healthUrlOf(gatewayPort)
125
+ const deadline = Date.now() + timeoutMs
126
+ while (Date.now() < deadline) {
127
+ try {
128
+ const res = await fetch(url, { signal: AbortSignal.timeout(1500) })
129
+ if (res.ok) return true
130
+ } catch { /* 还没起来 */ }
131
+ await new Promise(resolve => setTimeout(resolve, 400))
132
+ }
133
+ return false
134
+ }
135
+
136
+ function printEndpoints(instance) {
137
+ const gw = instance?.gatewayPort ?? GATEWAY_PORT
138
+ const adm = instance?.adminPort ?? ADMIN_PORT
139
+ log(` 管理面板 http://127.0.0.1:${adm}/admin`)
140
+ log(` 网关地址 http://127.0.0.1:${gw}/v1`)
141
+ log(` 数据目录 ${DATA_DIR}`)
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // 命令实现
146
+ // ---------------------------------------------------------------------------
147
+ async function startForeground() {
148
+ const pid = runningPid()
149
+ if (pid) die(`已有实例在运行(PID ${pid})。先 omr stop,或直接 omr status 查看`)
150
+ log(`OneModelRouter ${PKG.version} 前台启动(Ctrl+C 停止)`)
151
+ // 前台也登记 pid + 端口,让另一个终端的 omr status / stop 能看到这个实例
152
+ writePid(process.pid, GATEWAY_PORT, ADMIN_PORT)
153
+ printEndpoints()
154
+ // server.js 求值即启动全部服务,并自己处理 SIGINT/SIGTERM
155
+ await import(pathToFileURL(SERVER).href)
156
+ }
157
+
158
+ async function startDetached() {
159
+ const pid = runningPid()
160
+ if (pid) die(`已有实例在运行(PID ${pid})`)
161
+ mkdirSync(LOG_DIR, { recursive: true })
162
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '').replace('T', '-')
163
+ const logFile = join(LOG_DIR, `omr-${stamp}${String(Date.now() % 1000).padStart(3, '0')}.log`)
164
+ // 与 omr.ps1 一致:只保留最近 5 份运行日志
165
+ try {
166
+ readdirSync(LOG_DIR)
167
+ .filter(name => /^omr-.*\.log$/i.test(name))
168
+ .map(name => join(LOG_DIR, name))
169
+ .sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)
170
+ .slice(KEEP_LOGS)
171
+ .forEach(old => rmSync(old, { force: true }))
172
+ } catch { /* 清日志失败不影响启动 */ }
173
+
174
+ const fd = openSync(logFile, 'a')
175
+ const child = spawn(process.execPath, [SERVER], {
176
+ detached: true,
177
+ stdio: ['ignore', fd, fd],
178
+ windowsHide: true,
179
+ env: process.env,
180
+ })
181
+ // 子进程已继承该文件句柄,父进程这边立刻关掉,避免长期占着日志文件
182
+ try {
183
+ closeSync(fd)
184
+ } catch { /* 已被关闭 */ }
185
+ if (!child.pid) die('后台进程创建失败')
186
+ writePid(child.pid, GATEWAY_PORT, ADMIN_PORT)
187
+ child.on('error', error => log(`后台进程异常: ${error.message}`))
188
+ child.unref()
189
+
190
+ if (await waitHealthy(GATEWAY_PORT, 20000)) {
191
+ log(`OneModelRouter ${PKG.version} 已启动(PID ${child.pid})`)
192
+ printEndpoints()
193
+ log(` 运行日志 ${logFile}`)
194
+ return
195
+ }
196
+
197
+ // 起不来:杀掉刚拉起的进程,把日志尾巴打出来,避免留下半死不活的孤儿
198
+ try {
199
+ process.kill(child.pid)
200
+ } catch { /* 可能已自行退出 */ }
201
+ rmSync(PID_FILE, { force: true })
202
+ const detail = tail(logFile)
203
+ die(`启动失败:20 秒内 ${healthUrlOf(GATEWAY_PORT)} 未就绪${detail ? `\n--- ${logFile} 末尾 ---\n${detail}` : ''}`)
204
+ }
205
+
206
+ async function stop() {
207
+ const pid = runningPid()
208
+ if (!pid) {
209
+ rmSync(PID_FILE, { force: true })
210
+ log('未在运行')
211
+ return
212
+ }
213
+ try {
214
+ process.kill(pid, 'SIGTERM')
215
+ } catch (error) {
216
+ die(`停止失败(PID ${pid}): ${error.message}`)
217
+ }
218
+ const deadline = Date.now() + 5000
219
+ while (Date.now() < deadline && alive(pid)) await new Promise(resolve => setTimeout(resolve, 200))
220
+ rmSync(PID_FILE, { force: true })
221
+ log(`已停止(PID ${pid})`)
222
+ }
223
+
224
+ async function status() {
225
+ const instance = readInstance()
226
+ if (!instance.pid) {
227
+ log('未在运行')
228
+ log(' 启动:omr start --detach')
229
+ return
230
+ }
231
+ log(`运行中(PID ${instance.pid})`)
232
+ printEndpoints(instance)
233
+ try {
234
+ const res = await fetch(healthUrlOf(instance.gatewayPort), { signal: AbortSignal.timeout(2500) })
235
+ log(` 健康探针 ${res.ok ? '正常' : `HTTP ${res.status}`}`)
236
+ } catch (error) {
237
+ log(` 健康探针 不可达(${error.message})`)
238
+ }
239
+ const logFile = latestLog()
240
+ if (logFile) log(` 运行日志 ${logFile}`)
241
+ }
242
+
243
+ function portal() {
244
+ const instance = readInstance()
245
+ const url = `http://127.0.0.1:${instance.adminPort}/admin`
246
+ log(instance.pid ? `管理面板:${url}` : `管理面板:${url}(当前未在运行,先 omr start)`)
247
+ const opener =
248
+ process.platform === 'win32'
249
+ ? { cmd: 'cmd', args: ['/c', 'start', '', url] }
250
+ : process.platform === 'darwin'
251
+ ? { cmd: 'open', args: [url] }
252
+ : { cmd: 'xdg-open', args: [url] }
253
+ try {
254
+ const child = spawn(opener.cmd, opener.args, { detached: true, stdio: 'ignore' })
255
+ child.on('error', () => {})
256
+ child.unref()
257
+ } catch { /* 打不开就让用户手点,地址已经打在上一行 */ }
258
+ }
259
+
260
+ function version() {
261
+ log(`${PKG.name} ${PKG.version}(node ${process.version})`)
262
+ }
263
+
264
+ function help() {
265
+ log(`${PKG.name} ${PKG.version} — ${PKG.description}`)
266
+ log('')
267
+ log('用法:omr <命令> [选项]')
268
+ log('')
269
+ log(' start 前台启动(默认,Ctrl+C 停止)')
270
+ log(' start --detach 后台启动,写 pid 文件并等健康探针就绪')
271
+ log(' stop 停止后台实例')
272
+ log(' restart 停止后重新后台启动')
273
+ log(' status 查看运行状态与健康探针')
274
+ log(' portal 打印并用系统浏览器打开管理面板')
275
+ log(' version 显示版本')
276
+ log('')
277
+ log('选项:')
278
+ log(' --port <n> 网关端口(默认 18682,等同 OMR_GATEWAY_PORT)')
279
+ log(' --admin-port <n> 管理面端口(默认 18681,等同 OMR_ADMIN_PORT)')
280
+ log(' --data-dir <path> 数据目录(默认 ~/.OneModelRouter/data,等同 OMR_DATA_DIR)')
281
+ log('')
282
+ log('Agent 侧接入:baseURL 填 http://127.0.0.1:' + GATEWAY_PORT + '/v1')
283
+ }
284
+
285
+ const commands = {
286
+ start: () => (args.detach ? startDetached() : startForeground()),
287
+ stop,
288
+ restart: async () => {
289
+ await stop()
290
+ await startDetached()
291
+ },
292
+ status,
293
+ portal,
294
+ version,
295
+ help,
296
+ }
297
+
298
+ const run = commands[args.command]
299
+ if (!run) die(`未知命令 ${args.command}(omr help 看用法)`)
300
+ Promise.resolve(run()).catch(error => die(error?.stack ?? String(error)))