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/admin.js
CHANGED
|
@@ -1,941 +1,965 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 管理面:REST API(/admin/api/*)+ 静态 Web UI(/admin 与 /)。
|
|
3
|
-
* 只绑 loopback;不做鉴权(本机使用)。
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import http from 'node:http'
|
|
7
|
-
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
8
|
-
import { join, dirname, extname } from 'node:path'
|
|
9
|
-
import { fileURLToPath } from 'node:url'
|
|
10
|
-
import { loadSettings, saveSettings, loadProviders, saveProviders, loadGroups, saveGroups, channelState, saveChannelState, runtime, onRuntimeEvent, emitRuntimeEvent } from './store.js'
|
|
11
|
-
import { claimAllProviders, claimChannel, collectAllBalances, collectChannelBalances, creditsCapabilities, claimTableRows, channelClaimState } from './credits.js'
|
|
12
|
-
import { buildCatalog, invalidateCatalog, probeOpencodeChannel } from './providers/index.js'
|
|
13
|
-
import * as kilo from './providers/kilo.js'
|
|
14
|
-
import * as opencode from './providers/opencode.js'
|
|
15
|
-
import * as openaiCompat from './providers/openai-compat.js'
|
|
16
|
-
import { withLastGoodFallback } from './providers/last-good.js'
|
|
17
|
-
import { CHANNELS, channelById, enabledAccounts, addAccount, updateAccount, removeAccount, saveAccountCredential, markAccountError } from './channels/index.js'
|
|
18
|
-
import { pruneRotation, buildGroupCatalogRows } from './router.js'
|
|
19
|
-
import * as health from './health.js'
|
|
20
|
-
import * as checkin from './checkin.js'
|
|
21
|
-
import * as probe from './probe.js'
|
|
22
|
-
import { freeModelsState } from './free-models.js'
|
|
23
|
-
import { syncState, updateSyncSettings, generatePairCode, latestPair, startRelayBrowserLogin, relayBrowserLoginState, cancelRelayBrowserLogin } from './sync/index.js'
|
|
24
|
-
import { json, openAiError, slugify, shortId, generateApiKey } from './util.js'
|
|
25
|
-
import { BUILTIN_PROVIDERS, BUILTIN_IDS } from './providers/builtin.js'
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
if (path === '/admin/api/
|
|
60
|
-
|
|
61
|
-
if (
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
if (path
|
|
79
|
-
if (path === '/admin/api/
|
|
80
|
-
|
|
81
|
-
if (path === '/admin/api/
|
|
82
|
-
if (path
|
|
83
|
-
|
|
84
|
-
if (path === '/admin/api/
|
|
85
|
-
if (path === '/admin/api/
|
|
86
|
-
|
|
87
|
-
if (path === '/admin/api/
|
|
88
|
-
if (path === '/admin/api/
|
|
89
|
-
if (path === '/admin/api/
|
|
90
|
-
if (path === '/admin/api/
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
if (path === '/admin/api/
|
|
95
|
-
|
|
96
|
-
if (path.startsWith('/admin/api/
|
|
97
|
-
|
|
98
|
-
if (path === '/admin/api/
|
|
99
|
-
if (path === '/admin/api/
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
if (req.method === 'GET') return
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
if (
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
const
|
|
219
|
-
const
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
settings.
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
async function
|
|
350
|
-
|
|
351
|
-
const
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
}
|
|
382
|
-
const
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
const
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
const
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
const
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
const
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
const
|
|
537
|
-
baseUrl,
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
const
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
const
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
json(res, 200,
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
async function
|
|
627
|
-
try {
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
json(res,
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
})
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
const
|
|
853
|
-
const
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
if (
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
1
|
+
/**
|
|
2
|
+
* 管理面:REST API(/admin/api/*)+ 静态 Web UI(/admin 与 /)。
|
|
3
|
+
* 只绑 loopback;不做鉴权(本机使用)。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import http from 'node:http'
|
|
7
|
+
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
8
|
+
import { join, dirname, extname } from 'node:path'
|
|
9
|
+
import { fileURLToPath } from 'node:url'
|
|
10
|
+
import { loadSettings, saveSettings, loadProviders, saveProviders, loadGroups, saveGroups, channelState, saveChannelState, runtime, onRuntimeEvent, emitRuntimeEvent } from './store.js'
|
|
11
|
+
import { claimAllProviders, claimChannel, collectAllBalances, collectChannelBalances, creditsCapabilities, claimTableRows, channelClaimState } from './credits.js'
|
|
12
|
+
import { buildCatalog, invalidateCatalog, probeOpencodeChannel } from './providers/index.js'
|
|
13
|
+
import * as kilo from './providers/kilo.js'
|
|
14
|
+
import * as opencode from './providers/opencode.js'
|
|
15
|
+
import * as openaiCompat from './providers/openai-compat.js'
|
|
16
|
+
import { withLastGoodFallback } from './providers/last-good.js'
|
|
17
|
+
import { CHANNELS, channelById, enabledAccounts, addAccount, updateAccount, removeAccount, saveAccountCredential, markAccountError } from './channels/index.js'
|
|
18
|
+
import { pruneRotation, buildGroupCatalogRows } from './router.js'
|
|
19
|
+
import * as health from './health.js'
|
|
20
|
+
import * as checkin from './checkin.js'
|
|
21
|
+
import * as probe from './probe.js'
|
|
22
|
+
import { freeModelsState } from './free-models.js'
|
|
23
|
+
import { syncState, updateSyncSettings, generatePairCode, latestPair, startRelayBrowserLogin, relayBrowserLoginState, cancelRelayBrowserLogin } from './sync/index.js'
|
|
24
|
+
import { json, openAiError, slugify, shortId, generateApiKey } from './util.js'
|
|
25
|
+
import { BUILTIN_PROVIDERS, BUILTIN_IDS } from './providers/builtin.js'
|
|
26
|
+
import { checkForUpdate, runUpdate, applyUpdate, getUpdateState, onUpdateEvent } from './update.js'
|
|
27
|
+
|
|
28
|
+
const WEB_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'web')
|
|
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' }
|
|
30
|
+
|
|
31
|
+
/** 应用版本:读仓库根(打包后 asar 根)的 package.json,读不到回退 unknown。 */
|
|
32
|
+
let appVersion
|
|
33
|
+
function appVersionText() {
|
|
34
|
+
if (appVersion) return appVersion
|
|
35
|
+
try {
|
|
36
|
+
appVersion = JSON.parse(readFileSync(join(WEB_DIR, '..', 'package.json'), 'utf8'))?.version ?? 'unknown'
|
|
37
|
+
} catch { appVersion = 'unknown' }
|
|
38
|
+
return appVersion
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function createAdminServer({ log = () => {} } = {}) {
|
|
42
|
+
const server = http.createServer((req, res) => {
|
|
43
|
+
void handle(req, res).catch(error => {
|
|
44
|
+
log(`admin request failed: ${error?.message ?? error}`)
|
|
45
|
+
if (!res.headersSent) json(res, 500, { error: String(error?.message ?? error) })
|
|
46
|
+
else res.end()
|
|
47
|
+
})
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
// 网页版:更新状态变化经 SSE 'update' 事件推给管理面板(Electron 端由 preload 自带事件流)
|
|
51
|
+
if (!process.versions.electron) {
|
|
52
|
+
onUpdateEvent(next => emitRuntimeEvent('update', next))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function handle(req, res) {
|
|
56
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
57
|
+
const path = url.pathname.replace(/\/+$/, '') || '/'
|
|
58
|
+
|
|
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
|
+
}
|
|
78
|
+
if (path === '/admin/api/state' && req.method === 'GET') return apiState(res)
|
|
79
|
+
if (path === '/admin/api/settings' && req.method === 'PUT') return apiUpdateSettings(req, res)
|
|
80
|
+
if (path === '/admin/api/opencode/probe' && req.method === 'POST') return apiProbeOpencode(res)
|
|
81
|
+
if (path === '/admin/api/opencode/slot-test' && req.method === 'POST') return apiOpencodeSlotTest(req, res)
|
|
82
|
+
if (path === '/admin/api/opencode/lane' && req.method === 'GET') return json(res, 200, opencode.laneStatus())
|
|
83
|
+
if (path === '/admin/api/opencode/lane/reset' && req.method === 'POST') return apiResetOpencodeLane(res)
|
|
84
|
+
if (path === '/admin/api/catalog/refresh' && req.method === 'POST') return apiRefreshCatalog(res)
|
|
85
|
+
if (path === '/admin/api/probe/run' && req.method === 'POST') return apiRunProbe(req, res)
|
|
86
|
+
|
|
87
|
+
if (path === '/admin/api/providers/custom' && req.method === 'GET') return json(res, 200, loadProviders())
|
|
88
|
+
if (path === '/admin/api/providers/custom' && req.method === 'POST') return apiUpsertCustomProvider(req, res)
|
|
89
|
+
if (path === '/admin/api/providers/custom/models' && req.method === 'POST') return apiFetchCustomModels(req, res)
|
|
90
|
+
if (path === '/admin/api/providers/kilo/models' && req.method === 'POST') return apiFetchKiloModels(req, res)
|
|
91
|
+
if (path === '/admin/api/providers/opencode/models' && req.method === 'POST') return apiFetchOpencodeModels(req, res)
|
|
92
|
+
if (path.startsWith('/admin/api/providers/custom/') && req.method === 'DELETE') return apiDeleteCustomProvider(req, res)
|
|
93
|
+
|
|
94
|
+
if (path === '/admin/api/groups' && req.method === 'GET') return json(res, 200, loadGroups())
|
|
95
|
+
if (path === '/admin/api/groups' && req.method === 'POST') return apiUpsertGroup(req, res)
|
|
96
|
+
if (path.startsWith('/admin/api/groups/') && req.method === 'DELETE') return apiDeleteGroup(req, res)
|
|
97
|
+
|
|
98
|
+
if (path === '/admin/api/credits/state' && req.method === 'GET') return json(res, 200, { auto: checkin.autoCheckinState(), capabilities: creditsCapabilities() })
|
|
99
|
+
if (path === '/admin/api/credits/claim' && req.method === 'POST') return apiClaimAll(res)
|
|
100
|
+
if (path.startsWith('/admin/api/credits/claim/') && req.method === 'POST') return apiClaimChannel(req, res, path.slice('/admin/api/credits/claim/'.length))
|
|
101
|
+
if (path === '/admin/api/credits/balances' && req.method === 'GET') return apiBalancesAll(res)
|
|
102
|
+
if (path.startsWith('/admin/api/credits/balances/') && req.method === 'GET') return apiBalancesChannel(res, path.slice('/admin/api/credits/balances/'.length))
|
|
103
|
+
if (path === '/admin/api/credits/auto-checkin/dismiss' && req.method === 'POST') return json(res, 200, checkin.dismissAutoCheckin())
|
|
104
|
+
|
|
105
|
+
if (path === '/admin/api/channels' && req.method === 'GET') return apiChannels(res)
|
|
106
|
+
if (path.startsWith('/admin/api/channels/')) return apiChannelRoutes(req, res, path)
|
|
107
|
+
|
|
108
|
+
if (path === '/admin/api/sync/state' && req.method === 'GET') return json(res, 200, syncState())
|
|
109
|
+
if (path === '/admin/api/sync/settings' && req.method === 'PUT') return apiUpdateSyncSettings(req, res)
|
|
110
|
+
// 站点账号一键登录:弹窗 → 捕获站点令牌 → 自动保存并注册 Host(令牌不进任何返回值)
|
|
111
|
+
if (path === '/admin/api/sync/login' && req.method === 'POST') return json(res, 200, await startRelayBrowserLogin())
|
|
112
|
+
if (path === '/admin/api/sync/login/status' && req.method === 'GET') return json(res, 200, relayBrowserLoginState())
|
|
113
|
+
if (path === '/admin/api/sync/login/cancel' && req.method === 'POST') return json(res, 200, await cancelRelayBrowserLogin())
|
|
114
|
+
if (path === '/admin/api/sync/pair-code' && req.method === 'POST') {
|
|
115
|
+
const pair = await generatePairCode()
|
|
116
|
+
return json(res, pair.ok === false ? 400 : 200, pair)
|
|
117
|
+
}
|
|
118
|
+
if (path === '/admin/api/sync/pair-qr' && req.method === 'GET') return apiPairQr(res)
|
|
119
|
+
|
|
120
|
+
if (path.startsWith('/admin/api/test-model') && req.method === 'POST') return apiTestModel(req, res)
|
|
121
|
+
|
|
122
|
+
if (path === '/admin/api/requests' && req.method === 'GET') return json(res, 200, { stats: runtime.stats, recent: runtime.recentRequests, health: health.snapshot(), probe: probe.probeSnapshot(), probeMeta: probe.probeMeta() })
|
|
123
|
+
if (path === '/admin/api/events' && req.method === 'GET') return apiEvents(req, res)
|
|
124
|
+
|
|
125
|
+
// 静态 UI:/admin、/、以及静态资源
|
|
126
|
+
if (req.method === 'GET') return serveStatic(path, res)
|
|
127
|
+
openAiError(res, 404, 'not_found_error', `no admin route: ${req.method} ${path}`)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function serveStatic(path, res) {
|
|
131
|
+
let file = path === '/' || path === '/admin' ? 'index.html' : path.replace(/^\/+/, '')
|
|
132
|
+
const full = join(WEB_DIR, file)
|
|
133
|
+
if (!full.startsWith(WEB_DIR) || !existsSync(full) || statSync(full).isDirectory()) {
|
|
134
|
+
// SPA 回退
|
|
135
|
+
const index = join(WEB_DIR, 'index.html')
|
|
136
|
+
if (!existsSync(index)) { res.writeHead(404); res.end('web UI not found'); return }
|
|
137
|
+
res.writeHead(200, { 'content-type': MIME['.html'] })
|
|
138
|
+
res.end(readFileSync(index))
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
res.writeHead(200, { 'content-type': MIME[extname(full)] ?? 'application/octet-stream', 'cache-control': 'no-cache' })
|
|
142
|
+
res.end(readFileSync(full))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function readBody(req) {
|
|
146
|
+
const chunks = []
|
|
147
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
148
|
+
if (chunks.length === 0) return {}
|
|
149
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** SSE 实时事件流:仅在真实事件发生时推送(request=网关请求记账,probe/probe-meta=探测状态),替代前端轮询。 */
|
|
153
|
+
function apiEvents(req, res) {
|
|
154
|
+
res.writeHead(200, {
|
|
155
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
156
|
+
'cache-control': 'no-cache',
|
|
157
|
+
connection: 'keep-alive',
|
|
158
|
+
})
|
|
159
|
+
res.write(': connected\n\n')
|
|
160
|
+
const off = onRuntimeEvent((type, payload) => {
|
|
161
|
+
try { res.write(`event: ${type}\ndata: ${JSON.stringify(payload)}\n\n`) } catch { /* 连接已断,close 时统一清理 */ }
|
|
162
|
+
})
|
|
163
|
+
const ping = setInterval(() => {
|
|
164
|
+
try { res.write(': ping\n\n') } catch { /* ignore */ }
|
|
165
|
+
}, 25_000)
|
|
166
|
+
ping.unref?.()
|
|
167
|
+
req.on('close', () => { off(); clearInterval(ping) })
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function apiState(res) {
|
|
171
|
+
const settings = loadSettings()
|
|
172
|
+
const catalog = await buildCatalog()
|
|
173
|
+
const groups = await buildGroupCatalogRows()
|
|
174
|
+
json(res, 200, {
|
|
175
|
+
settings: { ...settings, gateway: { ...settings.gateway, apiKey: mask(settings.gateway?.apiKey), apiKeyFull: settings.gateway?.apiKey ?? '' } },
|
|
176
|
+
providers: loadProviders(),
|
|
177
|
+
groups: loadGroups(),
|
|
178
|
+
checkin: checkin.autoCheckinState(),
|
|
179
|
+
// OpenCode 免密车道的车道级状态(额度窗口/伪装被拒),面板据此提示唯一有效动作
|
|
180
|
+
lane: opencode.laneStatus(),
|
|
181
|
+
catalog,
|
|
182
|
+
groupRows: groups,
|
|
183
|
+
// 渠道启用状态摘要:模型组成员据此把「所属渠道已停用」的成员显示为自动停用并拦截启用
|
|
184
|
+
channels: CHANNELS.map(ch => {
|
|
185
|
+
const st = channelState(ch.meta.id)
|
|
186
|
+
return { id: ch.meta.id, label: ch.meta.label, enabled: st.enabled === true }
|
|
187
|
+
}),
|
|
188
|
+
health: health.snapshot(),
|
|
189
|
+
probe: probe.probeSnapshot(),
|
|
190
|
+
probeMeta: probe.probeMeta(),
|
|
191
|
+
freeModels: freeModelsState(),
|
|
192
|
+
stats: runtime.stats,
|
|
193
|
+
recentRequests: runtime.recentRequests.slice(0, 500),
|
|
194
|
+
startedAt: runtime.startedAt,
|
|
195
|
+
creditCapabilities: creditsCapabilities(),
|
|
196
|
+
})
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function mask(key) {
|
|
200
|
+
if (typeof key !== 'string' || key === '') return ''
|
|
201
|
+
return key.length <= 12 ? key : `${key.slice(0, 10)}…${key.slice(-4)}`
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* 模型组成员引用同步(配置驱动的改写/摘除,不依赖上游目录在线状态):
|
|
206
|
+
* - renames: [{ from, to }] 提供商 id 变更 → 成员前缀 `from/` 改写为 `to/`(保序去重);
|
|
207
|
+
* - allow: Map<pid, Set<modelId>|null> 该提供商当前勾选的模型 id 集合 → 摘除不在集合内的
|
|
208
|
+
* `pid/<model>` 成员;null = 提供商已删除/全部取消勾选 → 摘除其全部成员。
|
|
209
|
+
* 只有发生变更才落盘。返回 { groups, renamed, pruned }(改动组数 / 改写条数 / 摘除条数)。
|
|
210
|
+
*/
|
|
211
|
+
function syncGroupMembers({ renames = [], allow = new Map() } = {}) {
|
|
212
|
+
if (renames.length === 0 && allow.size === 0) return { groups: 0, renamed: 0, pruned: 0 }
|
|
213
|
+
const renameMap = new Map(renames.map(r => [r.from, r.to]))
|
|
214
|
+
const doc = loadGroups()
|
|
215
|
+
let changedGroups = 0, renamed = 0, pruned = 0
|
|
216
|
+
for (const group of doc.groups ?? []) {
|
|
217
|
+
const models = Array.isArray(group.models) ? group.models : []
|
|
218
|
+
const seen = new Set()
|
|
219
|
+
const next = []
|
|
220
|
+
const idMap = new Map() // 旧成员 id -> 改写后的成员 id
|
|
221
|
+
let dirty = false
|
|
222
|
+
for (const id of models) {
|
|
223
|
+
if (typeof id !== 'string' || id === '') { dirty = true; continue }
|
|
224
|
+
const slash = id.indexOf('/')
|
|
225
|
+
const hasSlash = slash > 0
|
|
226
|
+
let pid = hasSlash ? id.slice(0, slash) : ''
|
|
227
|
+
const rest = hasSlash ? id.slice(slash + 1) : ''
|
|
228
|
+
if (hasSlash && renameMap.has(pid)) pid = renameMap.get(pid)
|
|
229
|
+
const allowed = hasSlash ? allow.get(pid) : undefined
|
|
230
|
+
if (hasSlash && allowed !== undefined && (allowed === null || !allowed.has(rest))) {
|
|
231
|
+
pruned += 1; dirty = true; continue
|
|
232
|
+
}
|
|
233
|
+
const out = hasSlash ? `${pid}/${rest}` : id
|
|
234
|
+
if (out !== id) { renamed += 1; dirty = true }
|
|
235
|
+
if (seen.has(out)) { dirty = true; continue } // 改写后重复:保序去重
|
|
236
|
+
seen.add(out)
|
|
237
|
+
idMap.set(id, out)
|
|
238
|
+
next.push(out)
|
|
239
|
+
}
|
|
240
|
+
// 停用清单随成员 id 一起改写 / 清理:否则前缀改写后旧 id 对不上,
|
|
241
|
+
// 已停用的成员会被当成启用(_router 按 disabled 集合匹配)。
|
|
242
|
+
const prevDisabled = Array.isArray(group.disabled) ? group.disabled : []
|
|
243
|
+
const nextDisabled = [...new Set(prevDisabled.map(id => idMap.get(id) ?? id))].filter(id => seen.has(id))
|
|
244
|
+
if (nextDisabled.length !== prevDisabled.length || nextDisabled.some((id, i) => id !== prevDisabled[i])) {
|
|
245
|
+
group.disabled = nextDisabled
|
|
246
|
+
dirty = true
|
|
247
|
+
}
|
|
248
|
+
if (dirty) { group.models = next; changedGroups += 1 }
|
|
249
|
+
}
|
|
250
|
+
if (changedGroups > 0) {
|
|
251
|
+
saveGroups(doc)
|
|
252
|
+
pruneRotation(doc.groups.map(g => g.id))
|
|
253
|
+
}
|
|
254
|
+
return { groups: changedGroups, renamed, pruned }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** 模型允许清单:[{ id, name, contextWindow }];非数组或空数组回落 null(= 未勾选,目录不出现该提供商的模型)。 */
|
|
258
|
+
function normalizeModelAllowlist(models) {
|
|
259
|
+
if (!Array.isArray(models)) return null
|
|
260
|
+
const rows = models
|
|
261
|
+
.filter(m => m && typeof m.id === 'string' && m.id.trim() !== '')
|
|
262
|
+
.map(m => ({
|
|
263
|
+
id: m.id.trim(),
|
|
264
|
+
name: String(m.name ?? m.id).trim(),
|
|
265
|
+
contextWindow: Number(m.contextWindow) > 0 ? Math.trunc(Number(m.contextWindow)) : null,
|
|
266
|
+
}))
|
|
267
|
+
return rows.length > 0 ? rows : null
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function apiUpdateSettings(req, res) {
|
|
271
|
+
const body = await readBody(req)
|
|
272
|
+
const settings = loadSettings()
|
|
273
|
+
if (body.gateway && typeof body.gateway === 'object') {
|
|
274
|
+
const g = { ...settings.gateway, ...body.gateway }
|
|
275
|
+
g.port = Math.min(Math.max(Math.trunc(Number(g.port) || 18682), 1), 65535)
|
|
276
|
+
g.headerTimeoutMs = Math.max(5000, Math.trunc(Number(g.headerTimeoutMs) || 60000))
|
|
277
|
+
g.idleTimeoutMs = Math.max(10000, Math.trunc(Number(g.idleTimeoutMs) || 120000))
|
|
278
|
+
g.candidateTimeoutMs = Math.max(0, Math.trunc(Number(g.candidateTimeoutMs ?? 45000) || 0))
|
|
279
|
+
g.hedgeDelayMs = Math.max(0, Math.trunc(Number(g.hedgeDelayMs ?? 6000) || 0))
|
|
280
|
+
g.hedgeMaxParallel = Math.min(Math.max(Math.trunc(Number(g.hedgeMaxParallel ?? 2) || 1), 1), 10)
|
|
281
|
+
if (typeof g.apiKey === 'string' && g.apiKey.includes('…')) g.apiKey = settings.gateway.apiKey
|
|
282
|
+
if (body.gateway.apiKey === '__rotate__') g.apiKey = generateApiKey()
|
|
283
|
+
settings.gateway = g
|
|
284
|
+
}
|
|
285
|
+
if (body.kilo && typeof body.kilo === 'object') settings.kilo = { ...settings.kilo, ...body.kilo }
|
|
286
|
+
settings.kilo.models = normalizeModelAllowlist(settings.kilo.models)
|
|
287
|
+
if (body.opencode && typeof body.opencode === 'object') {
|
|
288
|
+
const oc = { ...settings.opencode, ...body.opencode }
|
|
289
|
+
// 车道级出口代理(匿名清单/探测/无槽代理的对话统一走它);只接受字符串。
|
|
290
|
+
oc.proxy = typeof oc.proxy === 'string' ? oc.proxy.trim() : ''
|
|
291
|
+
if (Array.isArray(oc.slots)) {
|
|
292
|
+
oc.slots = oc.slots.filter(s => s && typeof s.apiKey === 'string' && s.apiKey !== '')
|
|
293
|
+
.map(s => ({ id: s.id ?? shortId('opencode-slot'), label: String(s.label ?? '').slice(0, 60), apiKey: s.apiKey, enabled: s.enabled !== false, proxy: typeof s.proxy === 'string' ? s.proxy : '' }))
|
|
294
|
+
}
|
|
295
|
+
oc.models = normalizeModelAllowlist(oc.models)
|
|
296
|
+
settings.opencode = oc
|
|
297
|
+
}
|
|
298
|
+
if (body.checkin && typeof body.checkin === 'object') {
|
|
299
|
+
const c = { ...settings.checkin, ...body.checkin }
|
|
300
|
+
c.enabled = c.enabled !== false
|
|
301
|
+
// ⚠️ 0 合法(启动后立刻跑),不能用 `Number(x) || 15000`(0 是 falsy 会被吞)。
|
|
302
|
+
const delay = Math.trunc(Number(c.delayMs))
|
|
303
|
+
c.delayMs = Number.isFinite(delay) ? Math.min(Math.max(delay, 0), 600000) : 15000
|
|
304
|
+
settings.checkin = c
|
|
305
|
+
}
|
|
306
|
+
if (body.probe && typeof body.probe === 'object') {
|
|
307
|
+
const p = { ...settings.probe, ...body.probe }
|
|
308
|
+
p.enabled = p.enabled !== false
|
|
309
|
+
p.intervalMinutes = Math.min(Math.max(Math.trunc(Number(p.intervalMinutes) || 15), 1), 1440)
|
|
310
|
+
// lastProbeAt 只由 probe.js 写入(探测轮完成时),UI 请求不应覆盖;缺失时补 0
|
|
311
|
+
p.lastProbeAt = Number(settings.probe?.lastProbeAt) || 0
|
|
312
|
+
settings.probe = p
|
|
313
|
+
}
|
|
314
|
+
if (body.freeModels && typeof body.freeModels === 'object') {
|
|
315
|
+
const f = { ...(settings.freeModels ?? {}), ...body.freeModels }
|
|
316
|
+
f.autoSelectAvailable = f.autoSelectAvailable !== false
|
|
317
|
+
settings.freeModels = f
|
|
318
|
+
}
|
|
319
|
+
// 网关开关变更时通知多端同步(手机端总览的网关开关与桌面端保持一致)
|
|
320
|
+
if (body.gateway && typeof body.gateway === 'object' && body.gateway.enabled !== undefined) {
|
|
321
|
+
emitRuntimeEvent('gateway', { enabled: settings.gateway?.enabled !== false })
|
|
322
|
+
}
|
|
323
|
+
// 勾选清单变更时同步组成员引用:仅当请求显式携带 models 数组才触发
|
|
324
|
+
// (停用通道不动清单不摘成员——停用是临时的,重新启用后组成员原样恢复)
|
|
325
|
+
const syncAllow = new Map()
|
|
326
|
+
if (body.kilo && typeof body.kilo === 'object' && Array.isArray(body.kilo.models)) {
|
|
327
|
+
syncAllow.set('kilo', new Set((settings.kilo.models ?? []).map(m => m.id)))
|
|
328
|
+
}
|
|
329
|
+
if (body.opencode && typeof body.opencode === 'object' && Array.isArray(body.opencode.models)) {
|
|
330
|
+
syncAllow.set('opencode', new Set((settings.opencode.models ?? []).map(m => m.id)))
|
|
331
|
+
}
|
|
332
|
+
saveSettings(settings)
|
|
333
|
+
invalidateCatalog()
|
|
334
|
+
const groupSync = syncGroupMembers({ allow: syncAllow })
|
|
335
|
+
json(res, 200, { ok: true, settings: { ...settings, gateway: { ...settings.gateway, apiKey: mask(settings.gateway.apiKey), apiKeyFull: settings.gateway.apiKey } }, groupSync, note: '端口/超时改动需重启服务生效' })
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async function apiProbeOpencode(res) {
|
|
339
|
+
const result = await probeOpencodeChannel()
|
|
340
|
+
json(res, 200, result)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** 清 OpenCode 车道熔断(顺带复查一次出口 IP:换出口后不必等额度窗口)。 */
|
|
344
|
+
async function apiResetOpencodeLane(res) {
|
|
345
|
+
json(res, 200, await opencode.resetLane({ probe: true }))
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** OpenCode Zen:用 body 里的槽位凭据(未保存的当前行值)测单槽连通性(GET /models,不落盘)。 */
|
|
349
|
+
async function apiOpencodeSlotTest(req, res) {
|
|
350
|
+
const body = await readBody(req)
|
|
351
|
+
const apiKey = String(body.apiKey ?? '').trim()
|
|
352
|
+
if (apiKey === '') { openAiError(res, 400, 'invalid_request_error', 'apiKey 必填(匿名槽填 public)'); return }
|
|
353
|
+
const proxy = typeof body.proxy === 'string' && body.proxy.trim() !== '' ? body.proxy.trim() : undefined
|
|
354
|
+
const slot = {
|
|
355
|
+
id: typeof body.id === 'string' && body.id !== '' ? body.id : shortId('opencode-slot-test'),
|
|
356
|
+
label: String(body.label ?? '').slice(0, 60),
|
|
357
|
+
apiKey,
|
|
358
|
+
anonymous: opencode.isAnonymousKey(apiKey),
|
|
359
|
+
proxy,
|
|
360
|
+
}
|
|
361
|
+
const controller = new AbortController()
|
|
362
|
+
const timer = setTimeout(() => controller.abort(), 20000)
|
|
363
|
+
try {
|
|
364
|
+
const result = await opencode.probeOpencode(loadSettings().opencode ?? {}, { signal: controller.signal, slot })
|
|
365
|
+
json(res, 200, result)
|
|
366
|
+
} catch (error) {
|
|
367
|
+
json(res, 200, { ok: false, modelCount: 0, message: String(error?.message ?? error) })
|
|
368
|
+
} finally {
|
|
369
|
+
clearTimeout(timer)
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
async function apiRefreshCatalog(res) {
|
|
374
|
+
invalidateCatalog()
|
|
375
|
+
const catalog = await buildCatalog({ force: true })
|
|
376
|
+
json(res, 200, { ok: true, count: catalog.filter(r => !r.offline).length })
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** 手动触发一轮探测(force 穿透退避与开关);body.channel 非空时只探测该渠道下的模型(可多渠道并行)。 */
|
|
380
|
+
async function apiRunProbe(req, res) {
|
|
381
|
+
const body = await readBody(req).catch(() => ({}))
|
|
382
|
+
const channel = String(body.channel ?? '').trim()
|
|
383
|
+
const result = await probe.runProbeRound({ force: true, channel })
|
|
384
|
+
json(res, 200, { ok: !result.skipped, ...result })
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async function apiUpsertCustomProvider(req, res) {
|
|
388
|
+
const body = await readBody(req)
|
|
389
|
+
const doc = loadProviders()
|
|
390
|
+
doc.custom ??= []
|
|
391
|
+
// 改名支持:previousId = 编辑前那行的 id,目标 id 始终由当前名称派生(slugify);
|
|
392
|
+
// 未携带 previousId 时兼容旧调用方,显式 body.id 仍作为目标 id。
|
|
393
|
+
const previousId = typeof body.previousId === 'string' && body.previousId.trim() !== '' ? body.previousId.trim() : null
|
|
394
|
+
const explicitId = typeof body.id === 'string' && body.id !== '' ? body.id : null
|
|
395
|
+
// 内置渠道:id 直接取既有 id(不再 slugify,避免 dots-ai → dots 之类的派生偏差),
|
|
396
|
+
// name / baseUrl 等静态字段一律以代码为准(忽略请求体)。
|
|
397
|
+
const builtinEdit = BUILTIN_IDS.has(previousId ?? explicitId ?? '')
|
|
398
|
+
? BUILTIN_PROVIDERS.find(b => b.id === (previousId ?? explicitId))
|
|
399
|
+
: null
|
|
400
|
+
const name = builtinEdit ? builtinEdit.name : String(body.name ?? '').trim()
|
|
401
|
+
const baseUrl = builtinEdit ? builtinEdit.baseUrl : String(body.baseUrl ?? '').trim().replace(/\/+$/, '')
|
|
402
|
+
if (name === '' || baseUrl === '') {
|
|
403
|
+
openAiError(res, 400, 'invalid_request_error', 'name 与 baseUrl 必填')
|
|
404
|
+
return
|
|
405
|
+
}
|
|
406
|
+
const id = previousId
|
|
407
|
+
? (builtinEdit ? previousId : slugify(name))
|
|
408
|
+
: (explicitId ?? slugify(name))
|
|
409
|
+
if (BUILTIN_IDS.has(id) && !builtinEdit) {
|
|
410
|
+
openAiError(res, 400, 'invalid_request_error', `提供商 ID「${id}」为内置渠道保留名,请换一个名称`)
|
|
411
|
+
return
|
|
412
|
+
}
|
|
413
|
+
if (id === '' || id === 'kilo' || id === 'opencode' || id === 'omr') {
|
|
414
|
+
openAiError(res, 400, 'invalid_request_error', `提供商 ID「${id}」为保留字,请换一个名称`)
|
|
415
|
+
return
|
|
416
|
+
}
|
|
417
|
+
const index = doc.custom.findIndex(p => p.id === (previousId ?? id))
|
|
418
|
+
if (previousId && index < 0) {
|
|
419
|
+
openAiError(res, 404, 'not_found_error', `要编辑的提供商 ${previousId} 不存在(可能已被删除),请刷新后重试`)
|
|
420
|
+
return
|
|
421
|
+
}
|
|
422
|
+
if (index >= 0 && doc.custom[index].id !== id && doc.custom.some((p, i) => i !== index && p.id === id)) {
|
|
423
|
+
openAiError(res, 400, 'invalid_request_error', `提供商 ID「${id}」已被其他提供商占用`)
|
|
424
|
+
return
|
|
425
|
+
}
|
|
426
|
+
const prev = index >= 0 ? doc.custom[index] : null
|
|
427
|
+
const models = Array.isArray(body.models)
|
|
428
|
+
? body.models.filter(m => m && typeof m.id === 'string' && m.id !== '').map(m => ({
|
|
429
|
+
id: m.id,
|
|
430
|
+
name: String(m.name ?? m.id),
|
|
431
|
+
contextWindow: Number(m.contextWindow) || null,
|
|
432
|
+
// 定价信息($X/M 单价 + 免费标记)随清单保留:目录倍率列与卡片徽章展示用
|
|
433
|
+
...(m.free === true ? { free: true } : {}),
|
|
434
|
+
...(typeof m.price === 'string' && m.price !== '' ? { price: m.price } : {}),
|
|
435
|
+
...(typeof m.priceOutput === 'string' && m.priceOutput !== '' ? { priceOutput: m.priceOutput } : {}),
|
|
436
|
+
}))
|
|
437
|
+
: (prev?.models ?? builtinEdit?.models ?? []) // 未携带 models = 维持原清单,防误清空
|
|
438
|
+
// 账号槽归一(写入口径与 opencode slots 一致):key 为空白的条目剔除;
|
|
439
|
+
// 未携带 slots 的调用方(脚本/旧客户端)维持原槽序列。
|
|
440
|
+
const slots = Array.isArray(body.slots)
|
|
441
|
+
? body.slots
|
|
442
|
+
.filter(s => s && typeof s.apiKey === 'string' && s.apiKey.trim() !== '')
|
|
443
|
+
.map(s => ({
|
|
444
|
+
id: typeof s.id === 'string' && s.id !== '' ? s.id : shortId('cp-slot'),
|
|
445
|
+
label: String(s.label ?? '').slice(0, 60),
|
|
446
|
+
apiKey: s.apiKey.trim(),
|
|
447
|
+
enabled: s.enabled !== false,
|
|
448
|
+
proxy: typeof s.proxy === 'string' ? s.proxy : '',
|
|
449
|
+
}))
|
|
450
|
+
: (prev?.slots ?? [])
|
|
451
|
+
const legacyKey = String(body.apiKey ?? prev?.apiKey ?? '').trim()
|
|
452
|
+
// 启用槽位数为 0 的提供商强制停用:没有可用账号槽时启用也无从轮换(免鉴权端点请勿添加槽)
|
|
453
|
+
const enabledSlots = slots.filter(s => s.enabled !== false).length
|
|
454
|
+
// 未携带 enabled 时沿用原启停状态。内置渠道的 enabled 是「有槽 + 未显式关闭」推导值:
|
|
455
|
+
// 原状态若只是「没有可用槽」导致的停用,则不算用户显式关闭,加槽后自动启用。
|
|
456
|
+
const hadEnabledSlot = (Array.isArray(prev?.slots) ? prev.slots : []).some(
|
|
457
|
+
s => s && s.enabled !== false && typeof s.apiKey === 'string' && s.apiKey !== ''
|
|
458
|
+
)
|
|
459
|
+
const keepOff = builtinEdit ? hadEnabledSlot && prev?.enabled === false : prev?.enabled === false
|
|
460
|
+
const enabled = enabledSlots > 0 && (body.enabled !== undefined ? body.enabled !== false : !keepOff)
|
|
461
|
+
const row = builtinEdit
|
|
462
|
+
? {
|
|
463
|
+
id, name: builtinEdit.name, baseUrl: builtinEdit.baseUrl,
|
|
464
|
+
apiKey: slots[0]?.apiKey ?? prev?.apiKey ?? '',
|
|
465
|
+
enabled,
|
|
466
|
+
models,
|
|
467
|
+
slots,
|
|
468
|
+
extraHeaders: builtinEdit.extraHeaders,
|
|
469
|
+
free: builtinEdit.free,
|
|
470
|
+
}
|
|
471
|
+
: {
|
|
472
|
+
id, name, baseUrl,
|
|
473
|
+
// apiKey 保留为「首个槽 key」的镜像(兼容展示与 GET {base}/models 试拉);
|
|
474
|
+
// 转发时的真实身份来源是槽序列(openaiCompat.listSlots 优先读 slots)。
|
|
475
|
+
apiKey: slots.length > 0 ? slots[0].apiKey : legacyKey,
|
|
476
|
+
enabled,
|
|
477
|
+
models,
|
|
478
|
+
slots,
|
|
479
|
+
extraHeaders: body.extraHeaders && typeof body.extraHeaders === 'object' ? body.extraHeaders : {},
|
|
480
|
+
free: body.free === true,
|
|
481
|
+
}
|
|
482
|
+
const oldId = index >= 0 ? doc.custom[index].id : null
|
|
483
|
+
if (index >= 0) doc.custom[index] = row
|
|
484
|
+
else doc.custom.push(row)
|
|
485
|
+
saveProviders(doc)
|
|
486
|
+
invalidateCatalog()
|
|
487
|
+
// 同步组成员引用:提供商 id 变更 → 前缀改写;勾选清单变化 → 摘除不再勾选的成员
|
|
488
|
+
const groupSync = syncGroupMembers({
|
|
489
|
+
renames: oldId && oldId !== id ? [{ from: oldId, to: id }] : [],
|
|
490
|
+
allow: new Map([[id, new Set(models.map(m => m.id))]]),
|
|
491
|
+
})
|
|
492
|
+
json(res, 200, { ok: true, provider: row, groupSync })
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async function apiDeleteCustomProvider(req, res) {
|
|
496
|
+
const id = decodeURIComponent(req.url.split('/').pop() ?? '')
|
|
497
|
+
if (BUILTIN_IDS.has(id)) {
|
|
498
|
+
openAiError(res, 400, 'invalid_request_error', '内置渠道不可删除,可在卡片内停用或清空槽位')
|
|
499
|
+
return
|
|
500
|
+
}
|
|
501
|
+
const doc = loadProviders()
|
|
502
|
+
doc.custom = (doc.custom ?? []).filter(p => p.id !== id)
|
|
503
|
+
saveProviders(doc)
|
|
504
|
+
invalidateCatalog()
|
|
505
|
+
// 同步组成员引用:提供商已删除 → 摘除其全部成员
|
|
506
|
+
const groupSync = syncGroupMembers({ allow: new Map([[id, null]]) })
|
|
507
|
+
json(res, 200, { ok: true, groupSync })
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** 拉取失败(网络不通/上游异常)时兜底回放上次成功清单,响应带 stale 信息。 */
|
|
511
|
+
async function respondModels(res, key, fetchFn) {
|
|
512
|
+
try {
|
|
513
|
+
const { models, stale, fetchedAt, error } = await withLastGoodFallback(key, fetchFn)
|
|
514
|
+
json(res, 200, stale ? { ok: true, models, stale: true, staleAt: fetchedAt, error } : { ok: true, models })
|
|
515
|
+
} catch (error) {
|
|
516
|
+
json(res, 200, { ok: false, error: String(error?.message ?? error) })
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* 自定义提供商的快照键:与小时扫描同键(provider:<id>),点击与扫描互相复用兜底。
|
|
522
|
+
* 新建表单里的草稿没有 id,按 baseUrl 反查已保存的提供商;都匹配不到才用地址建独立键。
|
|
523
|
+
*/
|
|
524
|
+
function customProviderKey(body, baseUrl) {
|
|
525
|
+
const pid = String(body.id ?? '').trim()
|
|
526
|
+
if (pid !== '') return `provider:${pid}`
|
|
527
|
+
const saved = (loadProviders().custom ?? []).find(p => p && String(p.baseUrl ?? '').trim().replace(/\/+$/, '') === baseUrl)
|
|
528
|
+
return saved?.id ? `provider:${saved.id}` : `custom-url:${baseUrl}`
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** 用表单里的 baseUrl/key 试拉上游 GET {base}/models,返回清单(不落盘)。 */
|
|
532
|
+
async function apiFetchCustomModels(req, res) {
|
|
533
|
+
const body = await readBody(req)
|
|
534
|
+
const baseUrl = String(body.baseUrl ?? '').trim().replace(/\/+$/, '')
|
|
535
|
+
if (baseUrl === '') { openAiError(res, 400, 'invalid_request_error', 'baseUrl 必填'); return }
|
|
536
|
+
const provider = {
|
|
537
|
+
baseUrl,
|
|
538
|
+
apiKey: String(body.apiKey ?? '').trim(),
|
|
539
|
+
extraHeaders: body.extraHeaders && typeof body.extraHeaders === 'object' ? body.extraHeaders : {},
|
|
540
|
+
}
|
|
541
|
+
// 魔搭 / OpenRouter / NVIDIA:只返回国内厂商的旗舰版与 flash 版
|
|
542
|
+
await respondModels(res, customProviderKey(body, baseUrl), () => openaiCompat.discoverProviderModels(provider))
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Kilo:用 body 里的 baseUrl 试拉免费池模型清单(不落盘)。 */
|
|
546
|
+
async function apiFetchKiloModels(req, res) {
|
|
547
|
+
const body = await readBody(req)
|
|
548
|
+
const baseUrl = String(body.baseUrl ?? '').trim().replace(/\/+$/, '')
|
|
549
|
+
if (baseUrl === '') { openAiError(res, 400, 'invalid_request_error', 'baseUrl 必填'); return }
|
|
550
|
+
const settings = { baseUrl, userAgent: body.userAgent ?? 'OneModelRouter/1.0' }
|
|
551
|
+
await respondModels(res, 'kilo', () => kilo.fetchModels(settings))
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** OpenCode Zen:用 body 里的 baseUrl 试拉匿名通道模型清单(不落盘);车道代理沿用已保存设置。 */
|
|
555
|
+
async function apiFetchOpencodeModels(req, res) {
|
|
556
|
+
const body = await readBody(req)
|
|
557
|
+
const baseUrl = String(body.baseUrl ?? '').trim().replace(/\/+$/, '')
|
|
558
|
+
if (baseUrl === '') { openAiError(res, 400, 'invalid_request_error', 'baseUrl 必填'); return }
|
|
559
|
+
const saved = loadSettings().opencode ?? {}
|
|
560
|
+
const settings = {
|
|
561
|
+
baseUrl,
|
|
562
|
+
// 未显式给 UA 时用已保存的值;两者都不是 v2 形态则由车道归一到 CLIENT_UA 常量。
|
|
563
|
+
userAgent: typeof body.userAgent === 'string' ? body.userAgent : (saved.userAgent ?? ''),
|
|
564
|
+
// 匿名清单走车道代理(本机直连被阻断时唯一可用路径);槽代理优先级更高但清单不传槽。
|
|
565
|
+
proxy: typeof saved.proxy === 'string' ? saved.proxy : '',
|
|
566
|
+
}
|
|
567
|
+
try {
|
|
568
|
+
// fetchModels 内部已带「上次成功在售快照」兜底(返回数组挂 stale 标记)
|
|
569
|
+
const models = await opencode.fetchModels(settings)
|
|
570
|
+
const stale = models.stale
|
|
571
|
+
json(res, 200, stale ? { ok: true, models, stale: true, staleAt: stale.at, error: stale.error } : { ok: true, models })
|
|
572
|
+
} catch (error) {
|
|
573
|
+
json(res, 200, { ok: false, error: String(error?.message ?? error) })
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
async function apiUpsertGroup(req, res) {
|
|
578
|
+
const body = await readBody(req)
|
|
579
|
+
const name = String(body.name ?? '').trim()
|
|
580
|
+
const models = [...new Set((Array.isArray(body.models) ? body.models : []).map(v => String(v ?? '').trim()).filter(v => v !== ''))]
|
|
581
|
+
if (name === '' || models.length === 0) {
|
|
582
|
+
openAiError(res, 400, 'invalid_request_error', 'name 与至少一个成员模型必填')
|
|
583
|
+
return
|
|
584
|
+
}
|
|
585
|
+
const doc = loadGroups()
|
|
586
|
+
doc.groups ??= []
|
|
587
|
+
const id = body.id ?? slugify(name)
|
|
588
|
+
// disabled:成员仍留在组里(保序),仅不参与轮询/故障切换;仅保留仍在 models 内的 id。
|
|
589
|
+
// 未携带 disabled(其他写入口/旧客户端)时沿用原停用清单,避免静默把停用项全部恢复启用。
|
|
590
|
+
const prev = doc.groups.find(g => g.id === id)
|
|
591
|
+
const rawDisabled = Array.isArray(body.disabled) ? body.disabled : (Array.isArray(prev?.disabled) ? prev.disabled : [])
|
|
592
|
+
const disabled = [...new Set(rawDisabled.map(v => String(v ?? '').trim()))].filter(v => models.includes(v))
|
|
593
|
+
const row = {
|
|
594
|
+
id, name, models,
|
|
595
|
+
strategy: body.strategy === 'round-robin' ? 'round-robin' : 'fallback',
|
|
596
|
+
stickyLimit: Math.max(1, Math.trunc(Number(body.stickyLimit) || 1)),
|
|
597
|
+
enabled: body.enabled !== false,
|
|
598
|
+
disabled,
|
|
599
|
+
}
|
|
600
|
+
const index = doc.groups.findIndex(g => g.id === id)
|
|
601
|
+
if (index >= 0) doc.groups[index] = row
|
|
602
|
+
else doc.groups.push(row)
|
|
603
|
+
saveGroups(doc)
|
|
604
|
+
pruneRotation(doc.groups.map(g => g.id))
|
|
605
|
+
emitRuntimeEvent('groups', loadGroups().groups) // 通知多端同步
|
|
606
|
+
json(res, 200, { ok: true, group: row })
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
async function apiDeleteGroup(req, res) {
|
|
610
|
+
const id = decodeURIComponent(req.url.split('/').pop() ?? '')
|
|
611
|
+
const doc = loadGroups()
|
|
612
|
+
doc.groups = (doc.groups ?? []).filter(g => g.id !== id)
|
|
613
|
+
saveGroups(doc)
|
|
614
|
+
pruneRotation(doc.groups.map(g => g.id))
|
|
615
|
+
emitRuntimeEvent('groups', loadGroups().groups) // 通知多端同步
|
|
616
|
+
json(res, 200, { ok: true })
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// ── 积分(credits/):一键领取 + 余额查询 + 自动签到状态 ───────────────────
|
|
620
|
+
|
|
621
|
+
async function apiClaimAll(res) {
|
|
622
|
+
const result = await claimAllProviders()
|
|
623
|
+
json(res, 200, { ok: true, ...result, rows: claimTableRows(result.providers) })
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
async function apiClaimChannel(req, res, providerId) {
|
|
627
|
+
try {
|
|
628
|
+
const result = await claimChannel(decodeURIComponent(providerId))
|
|
629
|
+
const ch = channelById(providerId)
|
|
630
|
+
json(res, 200, {
|
|
631
|
+
ok: true,
|
|
632
|
+
...result,
|
|
633
|
+
rows: claimTableRows([{
|
|
634
|
+
provider: providerId,
|
|
635
|
+
label: ch?.meta?.label ?? '',
|
|
636
|
+
ok: true,
|
|
637
|
+
state: channelClaimState(result.summary),
|
|
638
|
+
summary: result.summary,
|
|
639
|
+
}]),
|
|
640
|
+
})
|
|
641
|
+
} catch (error) {
|
|
642
|
+
json(res, error?.unsupported ? 400 : 500, { ok: false, error: error?.message ?? String(error) })
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
async function apiBalancesAll(res) {
|
|
647
|
+
json(res, 200, await collectAllBalances())
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
async function apiBalancesChannel(res, providerId) {
|
|
651
|
+
try {
|
|
652
|
+
json(res, 200, await collectChannelBalances(decodeURIComponent(providerId)))
|
|
653
|
+
} catch (error) {
|
|
654
|
+
json(res, error?.unsupported ? 400 : 500, { error: error?.message ?? String(error) })
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// ── 多端同步(sync/):状态、配置、配对码 ─────────────────────────────────
|
|
659
|
+
|
|
660
|
+
async function apiUpdateSyncSettings(req, res) {
|
|
661
|
+
const body = await readBody(req)
|
|
662
|
+
const result = await updateSyncSettings({
|
|
663
|
+
enabled: body.enabled,
|
|
664
|
+
endpoint: body.endpoint,
|
|
665
|
+
publishableKey: body.publishableKey,
|
|
666
|
+
email: body.email,
|
|
667
|
+
password: body.password,
|
|
668
|
+
transport: body.transport,
|
|
669
|
+
relayUrl: body.relayUrl,
|
|
670
|
+
apiOrigin: body.apiOrigin,
|
|
671
|
+
siteToken: body.siteToken,
|
|
672
|
+
})
|
|
673
|
+
json(res, result.ok ? 200 : 400, result)
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** 重取最近一次配对二维码(不重复注册设备;含带外凭据,仅本机管理面可见)。 */
|
|
677
|
+
function apiPairQr(res) {
|
|
678
|
+
const pair = latestPair()
|
|
679
|
+
if (!pair) return json(res, 404, { error: '没有有效配对,请先生成配对二维码' })
|
|
680
|
+
json(res, 200, {
|
|
681
|
+
code: pair.code,
|
|
682
|
+
expiresAt: pair.expiresAt,
|
|
683
|
+
payload: pair.payload,
|
|
684
|
+
fingerprint: pair.fingerprint,
|
|
685
|
+
qrDataUrl: pair.qrDataUrl ?? '',
|
|
686
|
+
transport: pair.transport,
|
|
687
|
+
})
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// ── 白嫖账号渠道(channels/)管理 ─────────────────────────────────────────
|
|
691
|
+
|
|
692
|
+
/** 进行中的在线登录流程:channelId -> { loginUrl, status, error, startedAt }。 */
|
|
693
|
+
const pendingLogins = new Map()
|
|
694
|
+
|
|
695
|
+
function apiChannels(res) {
|
|
696
|
+
const channels = CHANNELS.map(ch => {
|
|
697
|
+
const id = ch.meta.id
|
|
698
|
+
const state = channelState(id)
|
|
699
|
+
const login = pendingLogins.get(id)
|
|
700
|
+
return {
|
|
701
|
+
id,
|
|
702
|
+
label: ch.meta.label,
|
|
703
|
+
repo: ch.meta.repo ?? '',
|
|
704
|
+
loginMode: ch.meta.loginMode ?? 'credential',
|
|
705
|
+
localLogin: ch.meta.localLogin === true,
|
|
706
|
+
anonymousModels: ch.meta.anonymousModels === true,
|
|
707
|
+
enabled: state.enabled,
|
|
708
|
+
models: state.models,
|
|
709
|
+
modelRates: state.modelRates,
|
|
710
|
+
accounts: state.accounts.map(a => ({
|
|
711
|
+
id: a.id,
|
|
712
|
+
label: a.label,
|
|
713
|
+
enabled: a.enabled !== false,
|
|
714
|
+
autoCheckin: a.autoCheckin === true,
|
|
715
|
+
expiresAt: a.expiresAt ?? 0,
|
|
716
|
+
refreshable: a.refreshable === true,
|
|
717
|
+
lastError: a.lastError ?? '',
|
|
718
|
+
described: a.credential ? ch.describeCredential(a.credential) : null,
|
|
719
|
+
})),
|
|
720
|
+
login: login ? { status: login.status, loginUrl: login.loginUrl, error: login.error, startedAt: login.startedAt } : null,
|
|
721
|
+
}
|
|
722
|
+
})
|
|
723
|
+
json(res, 200, { channels })
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
async function apiChannelRoutes(req, res, path) {
|
|
727
|
+
const segs = path.split('/').filter(Boolean)
|
|
728
|
+
const rest = segs.slice(3) // 去掉 admin/api/channels
|
|
729
|
+
const id = rest[0] ?? ''
|
|
730
|
+
const ch = channelById(id)
|
|
731
|
+
if (!ch) { openAiError(res, 404, 'not_found_error', `unknown channel: ${id}`); return }
|
|
732
|
+
if (rest.length === 1) {
|
|
733
|
+
if (req.method === 'PUT') return apiChannelUpdate(req, res, id)
|
|
734
|
+
openAiError(res, 404, 'not_found_error', `no channel route: ${req.method} ${path}`)
|
|
735
|
+
return
|
|
736
|
+
}
|
|
737
|
+
const sub = rest[1]
|
|
738
|
+
if (sub === 'models' && req.method === 'POST') return apiChannelRemoteModels(res, id)
|
|
739
|
+
if (sub === 'login' && req.method === 'POST') return apiChannelLoginStart(req, res, id)
|
|
740
|
+
if (sub === 'login' && req.method === 'GET') return apiChannelLoginStatus(res, id)
|
|
741
|
+
if (sub === 'credential' && req.method === 'POST') return apiChannelAddCredential(req, res, id)
|
|
742
|
+
if (sub === 'accounts' && rest.length >= 3) return apiChannelAccount(req, res, id, decodeURIComponent(rest[2]), req.method)
|
|
743
|
+
openAiError(res, 404, 'not_found_error', `no channel route: ${req.method} ${path}`)
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
async function apiChannelUpdate(req, res, id) {
|
|
747
|
+
const body = await readBody(req)
|
|
748
|
+
const state = channelState(id)
|
|
749
|
+
if (typeof body.enabled === 'boolean') state.enabled = body.enabled
|
|
750
|
+
if (Array.isArray(body.models)) state.models = body.models.filter(m => typeof m === 'string' && m !== '')
|
|
751
|
+
// 倍率表:随勾选清单一起落盘(供卡片 chips / 目录展示),清洗在 saveChannelState 里做
|
|
752
|
+
if (body.modelRates && typeof body.modelRates === 'object' && !Array.isArray(body.modelRates)) {
|
|
753
|
+
state.modelRates = body.modelRates
|
|
754
|
+
}
|
|
755
|
+
saveChannelState(id, state)
|
|
756
|
+
invalidateCatalog()
|
|
757
|
+
emitRuntimeEvent('channels', { channelId: id }) // 通知多端同步
|
|
758
|
+
json(res, 200, { ok: true })
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* 拉上游实时模型清单(UI 勾选来源)。
|
|
763
|
+
* 有启用账号时用第一个账号的凭据;没有账号时,只有声明了 meta.anonymousModels 的渠道
|
|
764
|
+
* (上游清单接口免鉴权,见 cline / minimax / qoder / zcode / gemini)才以空凭据拉取。
|
|
765
|
+
*/
|
|
766
|
+
async function apiChannelRemoteModels(res, id) {
|
|
767
|
+
const ch = channelById(id)
|
|
768
|
+
const accounts = enabledAccounts(id)
|
|
769
|
+
if (accounts.length === 0 && ch.meta.anonymousModels !== true) {
|
|
770
|
+
json(res, 200, { models: [], error: '没有可用账号凭据,先添加账号' })
|
|
771
|
+
return
|
|
772
|
+
}
|
|
773
|
+
try {
|
|
774
|
+
// 实时失败(网络不通/上游异常)时兜底回放该渠道上次成功清单(与小时扫描同键)
|
|
775
|
+
const { models, stale, fetchedAt, error } = await withLastGoodFallback(id, () => ch.fetchModels(accounts.length > 0 ? accounts[0].credential : null))
|
|
776
|
+
// 顺手把「已勾选模型」的倍率刷新到渠道配置里:卡片 chips 与目录都靠它显示,
|
|
777
|
+
// 不必等用户点「应用」(未勾选的模型不落盘)。
|
|
778
|
+
const state = channelState(id)
|
|
779
|
+
const picked = new Set(state.models)
|
|
780
|
+
const rates = { ...state.modelRates }
|
|
781
|
+
let dirty = false
|
|
782
|
+
for (const m of models) {
|
|
783
|
+
if (!picked.has(m.id) || typeof m.rate !== 'number' || !Number.isFinite(m.rate)) continue
|
|
784
|
+
const next = typeof m.rateOriginal === 'number' && Number.isFinite(m.rateOriginal)
|
|
785
|
+
? { rate: m.rate, rateOriginal: m.rateOriginal }
|
|
786
|
+
: { rate: m.rate }
|
|
787
|
+
if (rates[m.id]?.rate === next.rate && rates[m.id]?.rateOriginal === next.rateOriginal) continue
|
|
788
|
+
rates[m.id] = next
|
|
789
|
+
dirty = true
|
|
790
|
+
}
|
|
791
|
+
if (dirty) {
|
|
792
|
+
state.modelRates = rates
|
|
793
|
+
saveChannelState(id, state)
|
|
794
|
+
invalidateCatalog()
|
|
795
|
+
}
|
|
796
|
+
json(res, 200, stale ? { models, stale: true, staleAt: fetchedAt, error } : { models })
|
|
797
|
+
} catch (error) {
|
|
798
|
+
const message = String(error?.message ?? error)
|
|
799
|
+
console.error(`[渠道模型] ${id} 实时清单获取失败:${message}`)
|
|
800
|
+
json(res, 200, { models: [], error: message })
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
async function apiChannelLoginStart(req, res, id) {
|
|
805
|
+
const ch = channelById(id)
|
|
806
|
+
if (typeof ch.startLogin !== 'function') {
|
|
807
|
+
openAiError(res, 400, 'invalid_request_error', `渠道 ${id} 不支持在线登录`)
|
|
808
|
+
return
|
|
809
|
+
}
|
|
810
|
+
const existing = pendingLogins.get(id)
|
|
811
|
+
if (existing && existing.status === 'pending') {
|
|
812
|
+
json(res, 200, { loginUrl: existing.loginUrl, qrSvg: existing.qrSvg, qrDataUrl: existing.qrDataUrl, status: 'pending' })
|
|
813
|
+
return
|
|
814
|
+
}
|
|
815
|
+
const body = await readBody(req).catch(() => ({}))
|
|
816
|
+
const flow = ch.startLogin({ port: Number(body?.port) || undefined })
|
|
817
|
+
const entry = { loginUrl: '', status: 'pending', error: '', startedAt: Date.now() }
|
|
818
|
+
pendingLogins.set(id, entry)
|
|
819
|
+
// loginUrl 通常是同步字符串;设备码渠道(Cline)第一步要先请求授权端点,
|
|
820
|
+
// URL 在 loginUrlReady 里异步就绪 —— 就绪后回填 entry,UI 轮询自然拿到。
|
|
821
|
+
// 同步字符串必须立刻回填,否则本次响应里 loginUrl 为空,前端只能在 2s 后的
|
|
822
|
+
// 轮询里打开登录页(已脱离点击手势,容易被弹窗拦截)。
|
|
823
|
+
if (typeof flow.loginUrl === 'string') entry.loginUrl = flow.loginUrl
|
|
824
|
+
void Promise.resolve(flow.loginUrlReady ?? flow.loginUrl).then(url => { entry.loginUrl = url ?? '' }).catch(() => {})
|
|
825
|
+
// 扫码渠道(Loomy):二维码内容登录会话开始后不再变化,允许同步或异步就绪
|
|
826
|
+
if (flow.qrSvg !== undefined || flow.qrDataUrl !== undefined) {
|
|
827
|
+
void Promise.resolve(flow.qrSvg ?? null).then(svg => { entry.qrSvg = svg ?? '' }).catch(() => {})
|
|
828
|
+
void Promise.resolve(flow.qrDataUrl ?? null).then(url => { entry.qrDataUrl = url ?? '' }).catch(() => {})
|
|
829
|
+
}
|
|
830
|
+
flow.promise.then(credential => {
|
|
831
|
+
entry.status = 'done'
|
|
832
|
+
addAccount(id, credential)
|
|
833
|
+
invalidateCatalog()
|
|
834
|
+
log(`channel ${id} 登录成功`)
|
|
835
|
+
}).catch(error => {
|
|
836
|
+
entry.status = 'error'
|
|
837
|
+
entry.error = String(error?.message ?? error)
|
|
838
|
+
log(`channel ${id} 登录失败: ${entry.error}`)
|
|
839
|
+
})
|
|
840
|
+
json(res, 200, { loginUrl: entry.loginUrl, qrSvg: entry.qrSvg, qrDataUrl: entry.qrDataUrl, status: 'pending' })
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
function apiChannelLoginStatus(res, id) {
|
|
844
|
+
const entry = pendingLogins.get(id)
|
|
845
|
+
json(res, 200, entry ?? { status: 'idle' })
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
async function apiChannelAddCredential(req, res, id) {
|
|
849
|
+
const ch = channelById(id)
|
|
850
|
+
const body = await readBody(req)
|
|
851
|
+
try {
|
|
852
|
+
const credential = ch.normalizeCredential(body.credential ?? body)
|
|
853
|
+
const accountId = addAccount(id, credential, typeof body.label === 'string' ? body.label : '')
|
|
854
|
+
// 若该渠道正在等待外部凭证注入的 startLogin promise(如 Comate 的
|
|
855
|
+
// external-link 模式:用户先跳转官网登录 → 再粘贴 license),把本次 normalize 结果
|
|
856
|
+
// 注入进去以收敛 pending 登录态。未发起登录的渠道没有 pending promise,
|
|
857
|
+
// 该调用是 no-op。
|
|
858
|
+
ch.resolveLoginCredential?.(credential)
|
|
859
|
+
invalidateCatalog()
|
|
860
|
+
json(res, 200, { ok: true, accountId })
|
|
861
|
+
} catch (error) {
|
|
862
|
+
openAiError(res, 400, 'invalid_request_error', String(error?.message ?? error))
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
async function apiChannelAccount(req, res, id, accountId, method) {
|
|
867
|
+
const ch = channelById(id)
|
|
868
|
+
if (method === 'DELETE') {
|
|
869
|
+
const ok = removeAccount(id, accountId)
|
|
870
|
+
invalidateCatalog()
|
|
871
|
+
emitRuntimeEvent('channels', { channelId: id }) // 通知多端同步
|
|
872
|
+
json(res, 200, { ok })
|
|
873
|
+
return
|
|
874
|
+
}
|
|
875
|
+
if (method === 'PUT') {
|
|
876
|
+
const body = await readBody(req)
|
|
877
|
+
const ok = updateAccount(id, accountId, body)
|
|
878
|
+
invalidateCatalog()
|
|
879
|
+
if (ok) emitRuntimeEvent('channels', { channelId: id }) // 通知多端同步
|
|
880
|
+
json(res, 200, { ok })
|
|
881
|
+
return
|
|
882
|
+
}
|
|
883
|
+
if (method === 'POST') { // 强制续期
|
|
884
|
+
const state = channelState(id)
|
|
885
|
+
const account = state.accounts.find(a => a.id === accountId)
|
|
886
|
+
if (!account) { openAiError(res, 404, 'not_found_error', '账号不存在'); return }
|
|
887
|
+
try {
|
|
888
|
+
const refreshed = await ch.refreshCredential(account.credential)
|
|
889
|
+
saveAccountCredential(id, accountId, refreshed)
|
|
890
|
+
json(res, 200, { ok: true, described: ch.describeCredential(refreshed) })
|
|
891
|
+
} catch (error) {
|
|
892
|
+
markAccountError(id, accountId, error?.message ?? String(error), {
|
|
893
|
+
terminal: error?.terminal === true,
|
|
894
|
+
disable: error?.disable === true,
|
|
895
|
+
})
|
|
896
|
+
openAiError(res, 502, 'upstream_error', String(error?.message ?? error))
|
|
897
|
+
}
|
|
898
|
+
return
|
|
899
|
+
}
|
|
900
|
+
openAiError(res, 404, 'not_found_error', `no channel account route: ${method}`)
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** 用一条 "你好" 探测某暴露模型(组也支持),返回首条文本或错误。 */
|
|
904
|
+
async function apiTestModel(req, res) {
|
|
905
|
+
const body = await readBody(req)
|
|
906
|
+
const modelId = String(body.model ?? '').trim()
|
|
907
|
+
if (modelId === '') { openAiError(res, 400, 'invalid_request_error', 'model 必填'); return }
|
|
908
|
+
const { resolveModel, completeOnModel } = await import('./providers/index.js')
|
|
909
|
+
const { completeOnGroup } = await import('./router.js')
|
|
910
|
+
const resolved = await resolveModel(modelId)
|
|
911
|
+
if (!resolved) { openAiError(res, 404, 'not_found_error', `unknown model: ${modelId}`); return }
|
|
912
|
+
const controller = new AbortController()
|
|
913
|
+
const timer = setTimeout(() => controller.abort(), Number(body.timeoutMs) || 30000)
|
|
914
|
+
const probeBody = {
|
|
915
|
+
// 带 system prompt:JoyCode 上游对裸 prompt 容易触发模型退化循环(重复输出),桌面端恒带 system prompt
|
|
916
|
+
messages: [{ role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: '回复两个字:正常' }],
|
|
917
|
+
max_tokens: 512,
|
|
918
|
+
stream: false,
|
|
919
|
+
}
|
|
920
|
+
let tried = []
|
|
921
|
+
try {
|
|
922
|
+
let payload
|
|
923
|
+
if (resolved.group) {
|
|
924
|
+
const result = await completeOnGroup(resolved.entry, probeBody, { signal: controller.signal })
|
|
925
|
+
payload = result.result.json ?? result.result
|
|
926
|
+
tried = result.tried
|
|
927
|
+
} else {
|
|
928
|
+
const result = await completeOnModel(resolved, probeBody, { signal: controller.signal })
|
|
929
|
+
payload = result.json ?? result
|
|
930
|
+
tried = [{ id: resolved.id, ok: true }]
|
|
931
|
+
}
|
|
932
|
+
const message = payload?.choices?.[0]?.message ?? {}
|
|
933
|
+
const audioData = typeof message.audio?.data === 'string' ? message.audio.data : ''
|
|
934
|
+
const text = typeof message.content === 'string' || typeof message.content === 'number' ? String(message.content) : ''
|
|
935
|
+
// TTS 类模型只回音频(content 为空):用音频大小作为测试结果,避免显示空回复
|
|
936
|
+
const reply = text !== ''
|
|
937
|
+
? text.slice(0, 500)
|
|
938
|
+
: audioData !== ''
|
|
939
|
+
? `[语音] 已生成音频(约 ${Math.floor(audioData.length * 3 / 4)} 字节)`
|
|
940
|
+
: JSON.stringify(payload).slice(0, 500)
|
|
941
|
+
health.markSuccess(modelId)
|
|
942
|
+
json(res, 200, { ok: true, reply, tried })
|
|
943
|
+
} catch (error) {
|
|
944
|
+
health.markFailure(modelId)
|
|
945
|
+
const failedTried = Array.isArray(error?.tried) ? error.tried : tried
|
|
946
|
+
json(res, 200, { ok: false, error: String(error?.message ?? error), kind: error?.kind, tried: failedTried.length > 0 ? failedTried : undefined })
|
|
947
|
+
} finally {
|
|
948
|
+
clearTimeout(timer)
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
return server
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
export async function startAdmin({ log = () => {}, port = 18681, host = '127.0.0.1' } = {}) {
|
|
956
|
+
const server = createAdminServer({ log })
|
|
957
|
+
return new Promise((resolve, reject) => {
|
|
958
|
+
server.once('error', reject)
|
|
959
|
+
server.listen(port, host, () => {
|
|
960
|
+
server.off('error', reject)
|
|
961
|
+
log(`admin UI listening on http://${host}:${port}/admin`)
|
|
962
|
+
resolve({ server, port, host })
|
|
963
|
+
})
|
|
964
|
+
})
|
|
965
|
+
}
|