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.
Files changed (80) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +32 -5
  3. package/bin/omr.js +46 -0
  4. package/package.json +3 -2
  5. package/src/admin.js +965 -941
  6. package/src/balances.js +61 -61
  7. package/src/boot.js +117 -117
  8. package/src/channels/buddy.js +2031 -2031
  9. package/src/channels/cline.js +753 -753
  10. package/src/channels/codearts.js +2051 -2051
  11. package/src/channels/comate.js +830 -830
  12. package/src/channels/doubaowork.js +1784 -1784
  13. package/src/channels/freebuff.js +1316 -1316
  14. package/src/channels/gemini.js +1721 -1721
  15. package/src/channels/index.js +270 -270
  16. package/src/channels/joycode.js +936 -936
  17. package/src/channels/kimi.js +572 -572
  18. package/src/channels/lobsterai.js +1226 -1226
  19. package/src/channels/loomy.js +1032 -1032
  20. package/src/channels/miaoshou.js +1396 -1396
  21. package/src/channels/mimo.js +474 -474
  22. package/src/channels/minimax.js +1451 -1451
  23. package/src/channels/qoder-wasm.js +434 -434
  24. package/src/channels/qoder.js +1619 -1619
  25. package/src/channels/raccoon.js +1842 -1842
  26. package/src/channels/tabbit.js +1457 -1457
  27. package/src/channels/trae.js +1405 -1405
  28. package/src/channels/zcode-global.js +35 -35
  29. package/src/channels/zcode.js +2085 -2085
  30. package/src/checkin.js +496 -496
  31. package/src/credits.js +464 -464
  32. package/src/crypto.js +132 -132
  33. package/src/free-models.js +683 -683
  34. package/src/gateway.js +596 -578
  35. package/src/health.js +86 -86
  36. package/src/model-key.js +35 -35
  37. package/src/paths.js +96 -96
  38. package/src/probe.js +318 -318
  39. package/src/providers/builtin.js +626 -626
  40. package/src/providers/index.js +483 -457
  41. package/src/providers/kilo.js +111 -111
  42. package/src/providers/last-good.js +69 -69
  43. package/src/providers/modelsdev.js +242 -242
  44. package/src/providers/openai-compat.js +312 -312
  45. package/src/providers/opencode/bun-fetch.js +226 -226
  46. package/src/providers/opencode/lane.js +186 -186
  47. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  48. package/src/providers/opencode/o2a/asset-source.js +43 -43
  49. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  50. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  51. package/src/providers/opencode/o2a/entry.js +17 -17
  52. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  53. package/src/providers/opencode/o2a/headers.js +133 -133
  54. package/src/providers/opencode/o2a/identity.js +148 -148
  55. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  56. package/src/providers/opencode/o2a/official-tools.js +110 -110
  57. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  58. package/src/providers/opencode/o2a/toolshape.js +418 -418
  59. package/src/providers/opencode/o2a/version.js +37 -37
  60. package/src/providers/opencode/upstream.js +403 -403
  61. package/src/providers/opencode/wire.js +496 -496
  62. package/src/providers/opencode.js +652 -652
  63. package/src/router.js +629 -629
  64. package/src/server.js +49 -33
  65. package/src/store.js +467 -467
  66. package/src/sync/index.js +1529 -1529
  67. package/src/sync/login-preload.cjs +52 -52
  68. package/src/sync/noise.js +141 -141
  69. package/src/sync/relay-http.js +176 -176
  70. package/src/sync/remote-host.js +818 -818
  71. package/src/sync/remote-http.js +112 -112
  72. package/src/sync/remote-login.js +657 -657
  73. package/src/sync/remote-pairing.js +204 -204
  74. package/src/sync/remote-protocol.js +321 -321
  75. package/src/sync/snapshot.js +211 -211
  76. package/src/update.js +458 -0
  77. package/src/util.js +334 -334
  78. package/web/app.js +4010 -3972
  79. package/web/index.html +32 -32
  80. package/web/style.css +971 -971
@@ -1,204 +1,204 @@
1
- /**
2
- * 桌面端配对:二维码带外下发「Client 设备级凭据 + Host 指纹」。
3
- *
4
- * 为什么必须带凭据:小程序要连 WSS 必须先有已注册设备身份,而公共 Server
5
- * 没有「短码换凭据」端点(§8.1 只有 register / register-owned-role / refresh),
6
- * 8 位短码也装不下凭据 —— 鸡生蛋。方案文档 §4.3 因此改为二维码带外交付。
7
- *
8
- * 载荷 `omr1:<base64url(JSON)>`:
9
- * h hostDeviceId c clientDeviceId
10
- * a clientAccessToken r clientRefreshToken
11
- * ck client 公钥 cp client 私钥 ← 方案初稿遗漏:Noise 握手需要 Client 静态密钥对,
12
- * k host 公钥 f host 指纹 设备注册时 identityKey 已固定到 Server,
13
- * e expiresAt s 8 位短码 私钥必须随二维码一起交付,否则小程序无法握手
14
- * u relayUrl o apiOrigin
15
- *
16
- * 凭据分层:站点账号 token 只在桌面首次注册 Host 时用一次、用完即弃;
17
- * 手机只拿设备级凭据,自行 refresh;账号级 token 永不下发。
18
- */
19
-
20
- import { randomBytes } from 'node:crypto'
21
- import {
22
- newDeviceId, generateIdentityKeyPair, identityFingerprint,
23
- CLIENT_VERSION, DEFAULT_RELAY_URL, DEFAULT_API_ORIGIN,
24
- } from './remote-protocol.js'
25
- import { makeDeviceDescriptor, normalizeTokenPair } from './remote-http.js'
26
-
27
- const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
28
- export const PAIR_TTL_MS = 10 * 60_000
29
- const PAIR_MAX = 3
30
-
31
- function shortCode() {
32
- return Array.from(randomBytes(8)).map(b => ALPHABET[b % ALPHABET.length]).join('')
33
- }
34
-
35
- /** 二维码载荷编码/解码(B2 小程序端复用同一格式)。 */
36
- export function encodePairPayload(obj) {
37
- return `omr1:${Buffer.from(JSON.stringify(obj), 'utf8').toString('base64url')}`
38
- }
39
-
40
- export function decodePairPayload(text) {
41
- const raw = String(text ?? '').trim()
42
- if (!raw.startsWith('omr1:')) throw new Error('配对串格式不正确(应以 omr1: 开头)')
43
- let obj
44
- try { obj = JSON.parse(Buffer.from(raw.slice(5), 'base64url').toString('utf8')) } catch {
45
- throw new Error('配对串无法解析')
46
- }
47
- for (const key of ['h', 'c', 'a', 'r', 'ck', 'cp', 'k', 'f']) {
48
- if (typeof obj[key] !== 'string' || obj[key] === '') throw new Error(`配对串缺少字段 ${key}`)
49
- }
50
- if (Number(obj.e) <= Date.now()) throw new Error('配对串已过期,请在桌面端重新生成')
51
- return obj
52
- }
53
-
54
- /**
55
- * @param {object} deps
56
- * @param {object} deps.api createRemoteApi() 实例
57
- * @param {Function} deps.getHost () => {deviceId, accessToken, identityPublicKey, refreshToken}
58
- * @param {Function} deps.getEndpoints () => {relayUrl, apiOrigin}
59
- * @param {Function} deps.onBound (record) => void —— 落盘已绑定 Client
60
- * @param {Function} deps.onRevoked (deviceId) => void —— 从落盘配置移除
61
- * @param {Function} deps.getInitialBound () => record[] —— 启动时恢复
62
- */
63
- export function createPairing({ api, getHost, getEndpoints, onBound = () => {}, onRevoked = () => {}, getInitialBound = () => [], log = () => {} } = {}) {
64
- const pending = new Map() // code -> {expiresAt, deviceId, consumed}
65
- const bound = new Map() // clientDeviceId -> record
66
-
67
- for (const record of getInitialBound() ?? []) {
68
- if (record?.deviceId) bound.set(record.deviceId, record)
69
- }
70
-
71
- function prune() {
72
- const now = Date.now()
73
- for (const [code, entry] of pending) {
74
- if (entry.expiresAt <= now && !entry.consumed) pending.delete(code)
75
- }
76
- }
77
-
78
- /** 生成 8 位短码 + 注册 Client 设备 + 产出二维码载荷。 */
79
- async function createPair() {
80
- prune()
81
- const host = getHost()
82
- if (!host?.deviceId || !host?.accessToken || !host?.identityPublicKey) {
83
- throw new Error('Host 设备尚未注册:请先在管理页填入站点令牌完成一次性注册')
84
- }
85
- const endpoints = getEndpoints?.() ?? {}
86
- const relayUrl = endpoints.relayUrl || DEFAULT_RELAY_URL
87
- const apiOrigin = endpoints.apiOrigin || DEFAULT_API_ORIGIN
88
-
89
- const keys = generateIdentityKeyPair()
90
- const clientDeviceId = newDeviceId()
91
- const code = shortCode()
92
- const expiresAt = Date.now() + PAIR_TTL_MS
93
- const device = makeDeviceDescriptor({
94
- deviceId: clientDeviceId,
95
- role: 'client',
96
- identityKey: keys.publicKey,
97
- name: `OMR-MP-${code.slice(0, 4)}`,
98
- platform: 'miniprogram',
99
- clientVersion: CLIENT_VERSION,
100
- })
101
- const pair = normalizeTokenPair(await api.registerOwnedRole(host.accessToken, device))
102
- if (!pair.accessToken) throw new Error('注册 Client 设备失败:服务端未返回 accessToken')
103
-
104
- // 未消费记录超过上限时丢弃最早的
105
- while (pending.size >= PAIR_MAX) pending.delete(pending.keys().next().value)
106
- pending.set(code, { expiresAt, deviceId: clientDeviceId, consumed: false })
107
-
108
- const record = {
109
- deviceId: clientDeviceId,
110
- identityPublicKey: keys.publicKey,
111
- accessToken: pair.accessToken,
112
- refreshToken: pair.refreshToken,
113
- accessTokenExpiresAt: pair.accessTokenExpiresAt,
114
- createdAt: Date.now(),
115
- code,
116
- }
117
- bound.set(clientDeviceId, record)
118
- onBound(record)
119
-
120
- const payload = encodePairPayload({
121
- v: 1,
122
- h: host.deviceId,
123
- c: clientDeviceId,
124
- a: pair.accessToken,
125
- r: pair.refreshToken,
126
- ck: keys.publicKey,
127
- cp: keys.privateKey,
128
- k: host.identityPublicKey,
129
- f: identityFingerprint(host.identityPublicKey),
130
- e: expiresAt,
131
- s: code,
132
- u: relayUrl,
133
- o: apiOrigin,
134
- })
135
-
136
- log(`配对已生成(短码 ${code},Client ${clientDeviceId.slice(0, 8)}…)`)
137
- return {
138
- code,
139
- expiresAt,
140
- payload,
141
- fingerprint: identityFingerprint(host.identityPublicKey),
142
- hostFingerprint: identityFingerprint(host.identityPublicKey),
143
- clientDeviceId,
144
- relayUrl,
145
- }
146
- }
147
-
148
- /** 该 Client 首次成功连上时,把短码作废(单次消费)。 */
149
- function markUsed(deviceId) {
150
- for (const entry of pending.values()) {
151
- if (entry.deviceId === deviceId) entry.consumed = true
152
- }
153
- prune()
154
- }
155
-
156
- function getBoundClient(deviceId) {
157
- return bound.get(deviceId) ?? null
158
- }
159
-
160
- function listBound() {
161
- return [...bound.values()].map(r => ({
162
- deviceId: r.deviceId,
163
- identityPublicKey: r.identityPublicKey,
164
- createdAt: r.createdAt,
165
- code: r.code ?? '',
166
- }))
167
- }
168
-
169
- function pendingCount() {
170
- prune()
171
- return [...pending.values()].filter(e => !e.consumed && e.expiresAt > Date.now()).length
172
- }
173
-
174
- /** 主动撤销 Client 设备(解绑);凭据过期时先 refresh 再撤销。 */
175
- async function revoke(deviceId) {
176
- const record = bound.get(deviceId)
177
- if (!record) return { ok: false, message: '未找到该设备' }
178
- const attempt = async token => api.revokeDevice(token)
179
- try {
180
- await attempt(record.accessToken)
181
- } catch (error) {
182
- if (!record.refreshToken) {
183
- return { ok: false, message: `撤销失败:${error.message}` }
184
- }
185
- try {
186
- const fresh = normalizeTokenPair(await api.refreshDevice(deviceId, record.refreshToken))
187
- await attempt(fresh.accessToken)
188
- } catch (e2) {
189
- return { ok: false, message: `撤销失败:${e2.message}` }
190
- }
191
- }
192
- bound.delete(deviceId)
193
- for (const [code, entry] of pending) if (entry.deviceId === deviceId) pending.delete(code)
194
- onRevoked(deviceId)
195
- log(`Client 设备已撤销(${deviceId.slice(0, 8)}…)`)
196
- return { ok: true, message: '设备已撤销' }
197
- }
198
-
199
- return {
200
- createPair, markUsed, getBoundClient, listBound, pendingCount, revoke,
201
- /** 供 Host 侧做 identity pinning:已配对 Client 的带外公钥。 */
202
- pinnedPublicKey: deviceId => bound.get(deviceId)?.identityPublicKey ?? '',
203
- }
204
- }
1
+ /**
2
+ * 桌面端配对:二维码带外下发「Client 设备级凭据 + Host 指纹」。
3
+ *
4
+ * 为什么必须带凭据:小程序要连 WSS 必须先有已注册设备身份,而公共 Server
5
+ * 没有「短码换凭据」端点(§8.1 只有 register / register-owned-role / refresh),
6
+ * 8 位短码也装不下凭据 —— 鸡生蛋。方案文档 §4.3 因此改为二维码带外交付。
7
+ *
8
+ * 载荷 `omr1:<base64url(JSON)>`:
9
+ * h hostDeviceId c clientDeviceId
10
+ * a clientAccessToken r clientRefreshToken
11
+ * ck client 公钥 cp client 私钥 ← 方案初稿遗漏:Noise 握手需要 Client 静态密钥对,
12
+ * k host 公钥 f host 指纹 设备注册时 identityKey 已固定到 Server,
13
+ * e expiresAt s 8 位短码 私钥必须随二维码一起交付,否则小程序无法握手
14
+ * u relayUrl o apiOrigin
15
+ *
16
+ * 凭据分层:站点账号 token 只在桌面首次注册 Host 时用一次、用完即弃;
17
+ * 手机只拿设备级凭据,自行 refresh;账号级 token 永不下发。
18
+ */
19
+
20
+ import { randomBytes } from 'node:crypto'
21
+ import {
22
+ newDeviceId, generateIdentityKeyPair, identityFingerprint,
23
+ CLIENT_VERSION, DEFAULT_RELAY_URL, DEFAULT_API_ORIGIN,
24
+ } from './remote-protocol.js'
25
+ import { makeDeviceDescriptor, normalizeTokenPair } from './remote-http.js'
26
+
27
+ const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
28
+ export const PAIR_TTL_MS = 10 * 60_000
29
+ const PAIR_MAX = 3
30
+
31
+ function shortCode() {
32
+ return Array.from(randomBytes(8)).map(b => ALPHABET[b % ALPHABET.length]).join('')
33
+ }
34
+
35
+ /** 二维码载荷编码/解码(B2 小程序端复用同一格式)。 */
36
+ export function encodePairPayload(obj) {
37
+ return `omr1:${Buffer.from(JSON.stringify(obj), 'utf8').toString('base64url')}`
38
+ }
39
+
40
+ export function decodePairPayload(text) {
41
+ const raw = String(text ?? '').trim()
42
+ if (!raw.startsWith('omr1:')) throw new Error('配对串格式不正确(应以 omr1: 开头)')
43
+ let obj
44
+ try { obj = JSON.parse(Buffer.from(raw.slice(5), 'base64url').toString('utf8')) } catch {
45
+ throw new Error('配对串无法解析')
46
+ }
47
+ for (const key of ['h', 'c', 'a', 'r', 'ck', 'cp', 'k', 'f']) {
48
+ if (typeof obj[key] !== 'string' || obj[key] === '') throw new Error(`配对串缺少字段 ${key}`)
49
+ }
50
+ if (Number(obj.e) <= Date.now()) throw new Error('配对串已过期,请在桌面端重新生成')
51
+ return obj
52
+ }
53
+
54
+ /**
55
+ * @param {object} deps
56
+ * @param {object} deps.api createRemoteApi() 实例
57
+ * @param {Function} deps.getHost () => {deviceId, accessToken, identityPublicKey, refreshToken}
58
+ * @param {Function} deps.getEndpoints () => {relayUrl, apiOrigin}
59
+ * @param {Function} deps.onBound (record) => void —— 落盘已绑定 Client
60
+ * @param {Function} deps.onRevoked (deviceId) => void —— 从落盘配置移除
61
+ * @param {Function} deps.getInitialBound () => record[] —— 启动时恢复
62
+ */
63
+ export function createPairing({ api, getHost, getEndpoints, onBound = () => {}, onRevoked = () => {}, getInitialBound = () => [], log = () => {} } = {}) {
64
+ const pending = new Map() // code -> {expiresAt, deviceId, consumed}
65
+ const bound = new Map() // clientDeviceId -> record
66
+
67
+ for (const record of getInitialBound() ?? []) {
68
+ if (record?.deviceId) bound.set(record.deviceId, record)
69
+ }
70
+
71
+ function prune() {
72
+ const now = Date.now()
73
+ for (const [code, entry] of pending) {
74
+ if (entry.expiresAt <= now && !entry.consumed) pending.delete(code)
75
+ }
76
+ }
77
+
78
+ /** 生成 8 位短码 + 注册 Client 设备 + 产出二维码载荷。 */
79
+ async function createPair() {
80
+ prune()
81
+ const host = getHost()
82
+ if (!host?.deviceId || !host?.accessToken || !host?.identityPublicKey) {
83
+ throw new Error('Host 设备尚未注册:请先在管理页填入站点令牌完成一次性注册')
84
+ }
85
+ const endpoints = getEndpoints?.() ?? {}
86
+ const relayUrl = endpoints.relayUrl || DEFAULT_RELAY_URL
87
+ const apiOrigin = endpoints.apiOrigin || DEFAULT_API_ORIGIN
88
+
89
+ const keys = generateIdentityKeyPair()
90
+ const clientDeviceId = newDeviceId()
91
+ const code = shortCode()
92
+ const expiresAt = Date.now() + PAIR_TTL_MS
93
+ const device = makeDeviceDescriptor({
94
+ deviceId: clientDeviceId,
95
+ role: 'client',
96
+ identityKey: keys.publicKey,
97
+ name: `OMR-MP-${code.slice(0, 4)}`,
98
+ platform: 'miniprogram',
99
+ clientVersion: CLIENT_VERSION,
100
+ })
101
+ const pair = normalizeTokenPair(await api.registerOwnedRole(host.accessToken, device))
102
+ if (!pair.accessToken) throw new Error('注册 Client 设备失败:服务端未返回 accessToken')
103
+
104
+ // 未消费记录超过上限时丢弃最早的
105
+ while (pending.size >= PAIR_MAX) pending.delete(pending.keys().next().value)
106
+ pending.set(code, { expiresAt, deviceId: clientDeviceId, consumed: false })
107
+
108
+ const record = {
109
+ deviceId: clientDeviceId,
110
+ identityPublicKey: keys.publicKey,
111
+ accessToken: pair.accessToken,
112
+ refreshToken: pair.refreshToken,
113
+ accessTokenExpiresAt: pair.accessTokenExpiresAt,
114
+ createdAt: Date.now(),
115
+ code,
116
+ }
117
+ bound.set(clientDeviceId, record)
118
+ onBound(record)
119
+
120
+ const payload = encodePairPayload({
121
+ v: 1,
122
+ h: host.deviceId,
123
+ c: clientDeviceId,
124
+ a: pair.accessToken,
125
+ r: pair.refreshToken,
126
+ ck: keys.publicKey,
127
+ cp: keys.privateKey,
128
+ k: host.identityPublicKey,
129
+ f: identityFingerprint(host.identityPublicKey),
130
+ e: expiresAt,
131
+ s: code,
132
+ u: relayUrl,
133
+ o: apiOrigin,
134
+ })
135
+
136
+ log(`配对已生成(短码 ${code},Client ${clientDeviceId.slice(0, 8)}…)`)
137
+ return {
138
+ code,
139
+ expiresAt,
140
+ payload,
141
+ fingerprint: identityFingerprint(host.identityPublicKey),
142
+ hostFingerprint: identityFingerprint(host.identityPublicKey),
143
+ clientDeviceId,
144
+ relayUrl,
145
+ }
146
+ }
147
+
148
+ /** 该 Client 首次成功连上时,把短码作废(单次消费)。 */
149
+ function markUsed(deviceId) {
150
+ for (const entry of pending.values()) {
151
+ if (entry.deviceId === deviceId) entry.consumed = true
152
+ }
153
+ prune()
154
+ }
155
+
156
+ function getBoundClient(deviceId) {
157
+ return bound.get(deviceId) ?? null
158
+ }
159
+
160
+ function listBound() {
161
+ return [...bound.values()].map(r => ({
162
+ deviceId: r.deviceId,
163
+ identityPublicKey: r.identityPublicKey,
164
+ createdAt: r.createdAt,
165
+ code: r.code ?? '',
166
+ }))
167
+ }
168
+
169
+ function pendingCount() {
170
+ prune()
171
+ return [...pending.values()].filter(e => !e.consumed && e.expiresAt > Date.now()).length
172
+ }
173
+
174
+ /** 主动撤销 Client 设备(解绑);凭据过期时先 refresh 再撤销。 */
175
+ async function revoke(deviceId) {
176
+ const record = bound.get(deviceId)
177
+ if (!record) return { ok: false, message: '未找到该设备' }
178
+ const attempt = async token => api.revokeDevice(token)
179
+ try {
180
+ await attempt(record.accessToken)
181
+ } catch (error) {
182
+ if (!record.refreshToken) {
183
+ return { ok: false, message: `撤销失败:${error.message}` }
184
+ }
185
+ try {
186
+ const fresh = normalizeTokenPair(await api.refreshDevice(deviceId, record.refreshToken))
187
+ await attempt(fresh.accessToken)
188
+ } catch (e2) {
189
+ return { ok: false, message: `撤销失败:${e2.message}` }
190
+ }
191
+ }
192
+ bound.delete(deviceId)
193
+ for (const [code, entry] of pending) if (entry.deviceId === deviceId) pending.delete(code)
194
+ onRevoked(deviceId)
195
+ log(`Client 设备已撤销(${deviceId.slice(0, 8)}…)`)
196
+ return { ok: true, message: '设备已撤销' }
197
+ }
198
+
199
+ return {
200
+ createPair, markUsed, getBoundClient, listBound, pendingCount, revoke,
201
+ /** 供 Host 侧做 identity pinning:已配对 Client 的带外公钥。 */
202
+ pinnedPublicKey: deviceId => bound.get(deviceId)?.identityPublicKey ?? '',
203
+ }
204
+ }