dsh-qqbot-muu 0.1.20 → 0.1.21
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/CHANGELOG.md +168 -154
- package/client/qqbot-settings.js +13401 -13380
- package/dist/config.js +573 -581
- package/dist/features/contextless-store.js +247 -247
- package/dist/features/four-source.js +338 -336
- package/dist/features/group-join-request.js +289 -287
- package/dist/features/local-models.js +1494 -1467
- package/dist/features/style-layer.js +501 -498
- package/dist/features/thinking-log.js +71 -69
- package/dist/gateway/bootstrap.js +1704 -1652
- package/dist/model/settings-reader.js +193 -102
- package/dist/shared/paths.js +128 -0
- package/dist/shared/settings-io.js +79 -83
- package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
- package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -794
- package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
- package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
- package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -444
- package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
- package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
- package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
- package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
- package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
- package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
- package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
- package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
- package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
- package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
- package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
- package/package.json +119 -118
- package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
- package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
- package/scripts/ai-toolkit.py +607 -478
- package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
- package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
- package/scripts/chat-archive/build-sft-v4.py +566 -0
- package/scripts/chat-archive/build-sft.py +390 -0
- package/scripts/chat-archive/eval-sft.py +155 -0
- package/scripts/chat-archive/extract-memory.py +143 -0
- package/scripts/chat-archive/inventory.py +182 -0
- package/scripts/chat-archive/merge-sft.py +114 -0
- package/scripts/chat-archive/qce-pull.py +217 -0
- package/scripts/chat-archive/qqheader.py +110 -0
- package/scripts/chat-archive/qqkey2.py +113 -0
- package/scripts/chat-archive/qqprobe.py +153 -0
- package/scripts/chat-archive/screen-collect.py +163 -0
- package/scripts/chat-archive/sqlcipher_probe.py +444 -0
- package/scripts/episode.py +529 -0
- package/scripts/fan-curve.py +218 -0
- package/scripts/fan-guard.cmd +8 -0
- package/scripts/fan-mode.py +380 -263
- package/scripts/gen-image.py +420 -413
- package/scripts/gen-video.py +186 -178
- package/scripts/hw-profile.py +175 -0
- package/scripts/media-enhance.py +402 -0
- package/scripts/memory-audit.py +581 -0
- package/scripts/migrate-scope.mjs +140 -139
- package/scripts/qq-connect-login.py +133 -0
- package/scripts/qq-ip-sync-hidden.vbs +5 -0
- package/scripts/qq-ip-sync.py +300 -0
- package/scripts/qq-whitelist.py +71 -0
- package/scripts/release-all.mjs +636 -509
- package/scripts/release-check.mjs +244 -226
- package/scripts/secure-room/index.html +334 -0
- package/scripts/secure-room/server.py +582 -0
- package/scripts/stickers/auto-tag.mjs +161 -0
- package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
- package/scripts/train/gguf-quantize.py +92 -0
- package/scripts/train/gguf-to-hf.py +112 -0
- package/scripts/train/merge-lora.py +51 -0
- package/scripts/train/probe-mirrors.sh +12 -0
- package/scripts/train/probe-mirrors2.sh +20 -0
- package/scripts/train/setup-wsl.sh +23 -0
- package/scripts/train/setup-wsl2.sh +25 -0
- package/scripts/train/setup-wsl3.sh +22 -0
- package/scripts/train/setup-wsl4.sh +22 -0
- package/scripts/train/train-lora.py +319 -0
- package/dist/_backup_ctx_20261125_183653/dist/config.d.ts +0 -473
- package/dist/_backup_ctx_20261125_183653/dist/config.js +0 -450
- package/dist/_backup_ctx_20261125_183653/dist/features/contextless-trim.js +0 -304
- package/dist/_backup_ctx_20261125_183653/dist/session/session-manager.js +0 -1588
- package/dist/_backup_ctx_20261125_183653/dist/transport/inbound.js +0 -1567
- package/dist/_backup_ctx_20261125_183653/dist/transport/outbound.js +0 -647
- package/scripts/__pycache__/ai-mode.cpython-311.pyc +0 -0
- package/scripts/__pycache__/ai-toolkit.cpython-311.pyc +0 -0
- package/scripts/__pycache__/comfy_gen.cpython-311.pyc +0 -0
- package/scripts/__pycache__/gen-image.cpython-311.pyc +0 -0
- package/scripts/__pycache__/gen-video.cpython-311.pyc +0 -0
- package/scripts/__pycache__/model-registry.cpython-311.pyc +0 -0
- package/scripts/__pycache__/purge-standby.cpython-311.pyc +0 -0
|
@@ -1,1467 +1,1494 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* local-models.js — 本地模型能力层(2026-11-25 主人任务)
|
|
3
|
-
*
|
|
4
|
-
* 目标:把本机已有的本地能力接成 QQ 工具,且**默认全关**(主人要求「检测到需要再启用」)。
|
|
5
|
-
* ASR/OCR/TTS/LLM → localai 8188(/asr /ocr /tts /llm;/tts 由另一路在加,没上线时给结构化错误)
|
|
6
|
-
* 图像生成 → 依次探 8188/8189/7860:ComfyUI /prompt 或 SD WebUI /sdapi/v1/txt2img
|
|
7
|
-
* LLM 兜底 → Strata 8080/v1/chat/completions(enable_thinking=false)→ ollama 11434/api/generate
|
|
8
|
-
*
|
|
9
|
-
* 设计约束:
|
|
10
|
-
* - 本文件**不 import 宿主包**(@deepseek-ai/dsh-tools 等),保证 `node --check` /
|
|
11
|
-
* `node scripts/selftest-local-models.mjs` 能直接 import 做纯 node 自测。
|
|
12
|
-
* 工具定义由 buildLocalModelTools(defineTool) 在 channel-tools 里装配。
|
|
13
|
-
* - 所有能力:绝不抛异常,失败返回 { ok:false, code, error, ... }。
|
|
14
|
-
* - 所有网络调用都有超时(默认 60s;图像/视频 300s),超时单独返回 code='timeout'。
|
|
15
|
-
* - 开关关着 → 直接返回 code='disabled' / 'disabled_capability',并附「在哪开」。
|
|
16
|
-
*/
|
|
17
|
-
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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
|
-
|
|
60
|
-
*/
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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
|
-
|
|
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
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
const
|
|
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
|
-
const
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
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
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
return { ok: true,
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
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
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
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
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
if (!
|
|
441
|
-
const
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
const
|
|
464
|
-
return
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
const
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
if (
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
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
|
-
|
|
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
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
};
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
return
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
async function
|
|
656
|
-
const
|
|
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
|
-
const
|
|
685
|
-
const
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
const
|
|
707
|
-
if (
|
|
708
|
-
const
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
const
|
|
714
|
-
|
|
715
|
-
return
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
const
|
|
728
|
-
if (!
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
const
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
return
|
|
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
|
-
const
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
}
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
const
|
|
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
|
-
|
|
853
|
-
|
|
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
|
-
|
|
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
|
-
if (
|
|
919
|
-
|
|
920
|
-
}
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
const
|
|
928
|
-
if (
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
}
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
}
|
|
1007
|
-
const
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
if (
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
const
|
|
1065
|
-
if (
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
}
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
*
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
}
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
const
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
}
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
}
|
|
1303
|
-
},
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
'
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
},
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
}
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
const
|
|
1422
|
-
|
|
1423
|
-
const
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
return {
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
'
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
const
|
|
1449
|
-
|
|
1450
|
-
const
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
]
|
|
1461
|
-
return { ok: true, msg: lines.join('\n')
|
|
1462
|
-
},
|
|
1463
|
-
);
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1
|
+
/**
|
|
2
|
+
* local-models.js — 本地模型能力层(2026-11-25 主人任务)
|
|
3
|
+
*
|
|
4
|
+
* 目标:把本机已有的本地能力接成 QQ 工具,且**默认全关**(主人要求「检测到需要再启用」)。
|
|
5
|
+
* ASR/OCR/TTS/LLM → localai 8188(/asr /ocr /tts /llm;/tts 由另一路在加,没上线时给结构化错误)
|
|
6
|
+
* 图像生成 → 依次探 8188/8189/7860:ComfyUI /prompt 或 SD WebUI /sdapi/v1/txt2img
|
|
7
|
+
* LLM 兜底 → Strata 8080/v1/chat/completions(enable_thinking=false)→ ollama 11434/api/generate
|
|
8
|
+
*
|
|
9
|
+
* 设计约束:
|
|
10
|
+
* - 本文件**不 import 宿主包**(@deepseek-ai/dsh-tools 等),保证 `node --check` /
|
|
11
|
+
* `node scripts/selftest-local-models.mjs` 能直接 import 做纯 node 自测。
|
|
12
|
+
* 工具定义由 buildLocalModelTools(defineTool) 在 channel-tools 里装配。
|
|
13
|
+
* - 所有能力:绝不抛异常,失败返回 { ok:false, code, error, ... }。
|
|
14
|
+
* - 所有网络调用都有超时(默认 60s;图像/视频 300s),超时单独返回 code='timeout'。
|
|
15
|
+
* - 开关关着 → 直接返回 code='disabled' / 'disabled_capability',并附「在哪开」。
|
|
16
|
+
*/
|
|
17
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync, renameSync } from 'node:fs';
|
|
18
|
+
import { DEFAULT_TOOLKIT_PYTHON } from '../config.js';
|
|
19
|
+
import { execFileSync, spawn } from 'node:child_process';
|
|
20
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
21
|
+
import { fileURLToPath } from 'node:url';
|
|
22
|
+
|
|
23
|
+
// 包根/真仓库根/产出根统一由 shared/paths.js 提供(2026-12-04 路径中心化)
|
|
24
|
+
import { PKG_ROOT, REPO_ROOT, OUT_ROOT } from '../shared/paths.js';
|
|
25
|
+
const pyPick = (cands) => cands.find((p) => p === 'python' || existsSync(p)) || 'python';
|
|
26
|
+
/**
|
|
27
|
+
* 统一产出根(2026-11-28 主人要求):**任何形式产出的图/视频/音频/文本只落 out/ 一处**,
|
|
28
|
+
* 不再 media/outbox、data/out、media/sing 各占一块。定义已上移到 shared/paths.js。
|
|
29
|
+
*/
|
|
30
|
+
function ymNow() {
|
|
31
|
+
const d = new Date();
|
|
32
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
|
|
33
|
+
}
|
|
34
|
+
/** 某类产物的当月目录(kind: image / video / audio / text) */
|
|
35
|
+
export function outDirFor(kind) {
|
|
36
|
+
const k = String(kind || 'misc').trim() || 'misc';
|
|
37
|
+
return join(OUT_ROOT, k, ymNow());
|
|
38
|
+
}
|
|
39
|
+
const DEFAULT_OUT_DIR = outDirFor('image');
|
|
40
|
+
/** 设置页分组名(错误信息里指路用,改标题时同步这里) */
|
|
41
|
+
export const SETTINGS_HINT = '设置页 → 「⑫ 本地模型」→ 打开总开关和对应能力开关,保存后重启 qqbot';
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 网关鉴权 key(2026-11-29 安全):包里不再写死凭证。
|
|
45
|
+
* 取值顺序:设置页填的 > 环境变量 QQBOT_GATEWAY_KEY > 本机 services/gateway/clients.json 第一个 key > 空。
|
|
46
|
+
* 本机(有 gateway/clients.json)行为与以前一致;换台没网关的机器则不带鉴权头,不会误用别人的 key。
|
|
47
|
+
*/
|
|
48
|
+
let _gwKeyCache = null;
|
|
49
|
+
export function resolveGatewayKey(cfg) {
|
|
50
|
+
const own = String((cfg && cfg.gatewayKey) || '').trim();
|
|
51
|
+
if (own) return own;
|
|
52
|
+
if (_gwKeyCache !== null) return _gwKeyCache;
|
|
53
|
+
const env = String(process.env.QQBOT_GATEWAY_KEY || '').trim();
|
|
54
|
+
if (env) { _gwKeyCache = env; return env; }
|
|
55
|
+
for (const p of [join(PKG_ROOT, 'services', 'gateway', 'clients.json'), join(process.cwd(), 'services', 'gateway', 'clients.json')]) {
|
|
56
|
+
try {
|
|
57
|
+
const j = JSON.parse(readFileSync(p, 'utf8'));
|
|
58
|
+
const first = j && j.clients && Object.values(j.clients)[0];
|
|
59
|
+
if (first && first.key) { _gwKeyCache = String(first.key); return _gwKeyCache; }
|
|
60
|
+
} catch { /* 试下一个位置 */ }
|
|
61
|
+
}
|
|
62
|
+
_gwKeyCache = '';
|
|
63
|
+
return '';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const DEFAULT_CONFIG = Object.freeze({
|
|
67
|
+
enabled: false,
|
|
68
|
+
asr: false,
|
|
69
|
+
ocr: false,
|
|
70
|
+
tts: false,
|
|
71
|
+
llm: false,
|
|
72
|
+
image: false,
|
|
73
|
+
localaiUrl: 'http://127.0.0.1:8188',
|
|
74
|
+
ollamaUrl: 'http://127.0.0.1:11434',
|
|
75
|
+
strataUrl: 'http://127.0.0.1:8080/v1',
|
|
76
|
+
strataModel: 'qwen3.6-35b-a3b-ud-q4_k_xl',
|
|
77
|
+
gatewayUrl: 'http://127.0.0.1:8090/v1',
|
|
78
|
+
// 2026-11-29 安全:不再把本地网关的 key 写死在包里(发布闸门会把它当成泄漏的云密钥)。
|
|
79
|
+
// 留空 = 运行时自动读 QQBOT_GATEWAY_KEY 环境变量,或本机 services/gateway/clients.json
|
|
80
|
+
// 的第一个 key —— 本机行为与以前完全一致,但包里不再携带凭证。
|
|
81
|
+
gatewayKey: '',
|
|
82
|
+
gatewayModel: '',
|
|
83
|
+
llmBackend: 'auto',
|
|
84
|
+
llmModel: '',
|
|
85
|
+
llmTimeoutMs: 120000,
|
|
86
|
+
imagePorts: '8188,8189,7860',
|
|
87
|
+
comfyCheckpoint: 'v1-5-pruned-emaonly.safetensors',
|
|
88
|
+
imageBackend: 'auto',
|
|
89
|
+
toolkitPython: DEFAULT_TOOLKIT_PYTHON,
|
|
90
|
+
toolkitScript: join(REPO_ROOT, 'scripts', 'ai-toolkit.py'),
|
|
91
|
+
toolkitUrl: 'http://127.0.0.1:8195',
|
|
92
|
+
toolkitImageModel: 'krea',
|
|
93
|
+
toolkitTimeoutMs: 900000,
|
|
94
|
+
sdServerUrl: 'http://127.0.0.1:7861',
|
|
95
|
+
sdPython: pyPick([join(REPO_ROOT, '.venv-draw', 'Scripts', 'python.exe'), 'python']),
|
|
96
|
+
sdScript: join(REPO_ROOT, 'qqbot-mod', 'scripts', 'sd_server.py'),
|
|
97
|
+
sdModel: join(REPO_ROOT, '.models', 'counterfeit3', 'Counterfeit-V3.0_fix_fp16.safetensors'),
|
|
98
|
+
sdWidth: 768,
|
|
99
|
+
sdHeight: 768,
|
|
100
|
+
sdSteps: 24,
|
|
101
|
+
sdBootWaitMs: 180000,
|
|
102
|
+
sdPort: 7861,
|
|
103
|
+
computeUrl: 'http://127.0.0.1:8199',
|
|
104
|
+
imageNeedVramMb: 7000,
|
|
105
|
+
ttsNeedVramMb: 7000,
|
|
106
|
+
ttsIdleUnload: false,
|
|
107
|
+
timeoutMs: 60000,
|
|
108
|
+
heavyTimeoutMs: 300000,
|
|
109
|
+
vramGuardNote: '显存守卫:Strata 35B 常驻约占 20.5G;TTS 约 5.2G、SD 约 3-6G,冲突时先 /tts/unload?kill=1 或停 strata,别和 35B 抢卡',
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
const CAP_LABEL = {
|
|
113
|
+
asr: '语音转文字(ASR)',
|
|
114
|
+
ocr: '图片识别(OCR)',
|
|
115
|
+
tts: '语音合成(TTS)',
|
|
116
|
+
llm: '本地大模型(LLM)',
|
|
117
|
+
image: '文生图(Image)',
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
let CFG = { ...DEFAULT_CONFIG };
|
|
121
|
+
|
|
122
|
+
/** 数值型配置键(设置页可能传字符串,统一转正数) */
|
|
123
|
+
const NUMERIC_KEYS = new Set([
|
|
124
|
+
'timeoutMs',
|
|
125
|
+
'heavyTimeoutMs',
|
|
126
|
+
'llmTimeoutMs',
|
|
127
|
+
'sdWidth',
|
|
128
|
+
'sdHeight',
|
|
129
|
+
'sdSteps',
|
|
130
|
+
'sdBootWaitMs',
|
|
131
|
+
'sdPort',
|
|
132
|
+
'imageNeedVramMb',
|
|
133
|
+
'ttsNeedVramMb',
|
|
134
|
+
'toolkitTimeoutMs',
|
|
135
|
+
]);
|
|
136
|
+
|
|
137
|
+
/** 配置写入(bootstrap 启动时调一次;设置页保存后宿主 remount 会再调) */
|
|
138
|
+
export function configureLocalModels(partial) {
|
|
139
|
+
const p = partial && typeof partial === 'object' ? partial : {};
|
|
140
|
+
const next = { ...DEFAULT_CONFIG };
|
|
141
|
+
for (const k of Object.keys(DEFAULT_CONFIG)) {
|
|
142
|
+
if (p[k] === undefined || p[k] === null) continue;
|
|
143
|
+
if (NUMERIC_KEYS.has(k)) {
|
|
144
|
+
const n = Number(p[k]);
|
|
145
|
+
if (Number.isFinite(n) && n > 0) next[k] = n;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (typeof DEFAULT_CONFIG[k] === 'boolean') {
|
|
149
|
+
next[k] = p[k] === true || p[k] === 'true' || p[k] === 1;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
next[k] = String(p[k]);
|
|
153
|
+
}
|
|
154
|
+
// URL 末尾去掉 '/',拼接时统一 `${base}/path`
|
|
155
|
+
for (const k of ['localaiUrl', 'ollamaUrl', 'strataUrl', 'gatewayUrl', 'sdServerUrl', 'computeUrl', 'toolkitUrl']) next[k] = next[k].replace(/\/+$/, '');
|
|
156
|
+
if (!next.strataUrl.endsWith('/v1')) {
|
|
157
|
+
// 允许只填 http://127.0.0.1:8080,自动补 /v1
|
|
158
|
+
next.strataUrl = next.strataUrl + '/v1';
|
|
159
|
+
}
|
|
160
|
+
if (!next.gatewayUrl.endsWith('/v1')) {
|
|
161
|
+
// 允许只填 http://127.0.0.1:8090,自动补 /v1
|
|
162
|
+
next.gatewayUrl = next.gatewayUrl + '/v1';
|
|
163
|
+
}
|
|
164
|
+
const be = String(next.llmBackend || 'auto').toLowerCase();
|
|
165
|
+
next.llmBackend = ['auto', 'localai', 'strata', 'gateway', 'ollama'].includes(be) ? be : 'auto';
|
|
166
|
+
const ib = String(next.imageBackend || 'auto').toLowerCase();
|
|
167
|
+
next.imageBackend = ['toolkit', 'sdserver', 'auto', 'sdwebui', 'comfyui'].includes(ib) ? ib : 'auto';
|
|
168
|
+
CFG = next;
|
|
169
|
+
return { ...CFG };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function getLocalModelsConfig() {
|
|
173
|
+
return { ...CFG };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function err(code, error, extra) {
|
|
177
|
+
return { ok: false, code, error, ...(extra || {}) };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 开关裁决:总开关 → 分开关 */
|
|
181
|
+
export function localCapabilityState(cap) {
|
|
182
|
+
if (CFG.enabled !== true) {
|
|
183
|
+
return err('disabled', `本地模型总开关关着(localModels.enabled=false)。${SETTINGS_HINT}`);
|
|
184
|
+
}
|
|
185
|
+
if (cap && CFG[cap] !== true) {
|
|
186
|
+
return err('disabled_capability', `「${CAP_LABEL[cap] || cap}」分开关关着(localModels.${cap}=false)。${SETTINGS_HINT}`);
|
|
187
|
+
}
|
|
188
|
+
return { ok: true };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function listImagePorts() {
|
|
192
|
+
const raw = Array.isArray(CFG.imagePorts) ? CFG.imagePorts.join(',') : String(CFG.imagePorts || '');
|
|
193
|
+
const ports = raw.split(/[,\s]+/).map((s) => parseInt(s, 10)).filter((n) => Number.isFinite(n) && n > 0);
|
|
194
|
+
return ports.length > 0 ? ports : [8188, 8189, 7860];
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function absPath(p) {
|
|
198
|
+
const s = String(p || '').trim();
|
|
199
|
+
if (!s) return '';
|
|
200
|
+
return isAbsolute(s) ? s : resolve(PKG_ROOT, s);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function ensureFile(p) {
|
|
204
|
+
const f = absPath(p);
|
|
205
|
+
if (!f) return err('bad_arg', '缺少文件路径');
|
|
206
|
+
if (!existsSync(f)) return err('bad_arg', `文件不存在:${f}`);
|
|
207
|
+
try {
|
|
208
|
+
if (!statSync(f).isFile()) return err('bad_arg', `不是文件:${f}`);
|
|
209
|
+
} catch (e) {
|
|
210
|
+
return err('bad_arg', `读不到文件:${f}(${e instanceof Error ? e.message : String(e)})`);
|
|
211
|
+
}
|
|
212
|
+
return { ok: true, path: f };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function ensureOutDir(dir, kind) {
|
|
216
|
+
const d = dir ? absPath(dir) : (kind ? outDirFor(kind) : DEFAULT_OUT_DIR);
|
|
217
|
+
try {
|
|
218
|
+
mkdirSync(d, { recursive: true });
|
|
219
|
+
} catch { /* 目录可能已存在/只读,写的时候会报 */ }
|
|
220
|
+
return d;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function stamp() {
|
|
224
|
+
const d = new Date();
|
|
225
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
226
|
+
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* 统一请求:超时 + 结构化错误。
|
|
231
|
+
* @returns {Promise<{ok:true,ms:number,res?:Response,json?:any,buffer?:Buffer,contentType?:string}|{ok:false,code:string,error:string,url:string,ms:number}>}
|
|
232
|
+
*/
|
|
233
|
+
async function request(url, opts = {}) {
|
|
234
|
+
const { method = 'GET', body, headers, timeoutMs = CFG.timeoutMs, as = 'json' } = opts;
|
|
235
|
+
const started = Date.now();
|
|
236
|
+
const ctrl = new AbortController();
|
|
237
|
+
const timer = setTimeout(() => {
|
|
238
|
+
try {
|
|
239
|
+
ctrl.abort(new Error('timeout'));
|
|
240
|
+
} catch { /* ignore */ }
|
|
241
|
+
}, Math.max(500, Number(timeoutMs) || CFG.timeoutMs));
|
|
242
|
+
try {
|
|
243
|
+
const res = await fetch(url, { method, headers, body, signal: ctrl.signal });
|
|
244
|
+
const ms = Date.now() - started;
|
|
245
|
+
if (as === 'buffer') {
|
|
246
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
247
|
+
if (!res.ok) {
|
|
248
|
+
return err('http_error', `${method} ${url} → HTTP ${res.status}`, { status: res.status, url, ms, bodyText: buf.toString('utf8').slice(0, 300) });
|
|
249
|
+
}
|
|
250
|
+
return { ok: true, ms, res, buffer: buf, contentType: String(res.headers.get('content-type') || '') };
|
|
251
|
+
}
|
|
252
|
+
const text = await res.text();
|
|
253
|
+
let json;
|
|
254
|
+
try {
|
|
255
|
+
json = text ? JSON.parse(text) : undefined;
|
|
256
|
+
} catch { /* 非 JSON */ }
|
|
257
|
+
if (!res.ok) {
|
|
258
|
+
return err('http_error', `${method} ${url} → HTTP ${res.status}`, { status: res.status, url, ms, bodyText: text.slice(0, 300) });
|
|
259
|
+
}
|
|
260
|
+
if (json === undefined) {
|
|
261
|
+
return err('bad_response', `${method} ${url} 返回的不是 JSON`, { url, ms, bodyText: text.slice(0, 300) });
|
|
262
|
+
}
|
|
263
|
+
return { ok: true, ms, res, json };
|
|
264
|
+
} catch (e) {
|
|
265
|
+
const ms = Date.now() - started;
|
|
266
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
267
|
+
const isTimeout = e?.name === 'AbortError' || /abort|timeout/i.test(msg);
|
|
268
|
+
if (isTimeout) {
|
|
269
|
+
return err('timeout', `${method} ${url} 超时(>${timeoutMs}ms)`, { url, ms, timeoutMs });
|
|
270
|
+
}
|
|
271
|
+
return err('endpoint_unreachable', `${method} ${url} 连不上:${msg}`, { url, ms });
|
|
272
|
+
} finally {
|
|
273
|
+
clearTimeout(timer);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function jsonBody(obj) {
|
|
278
|
+
return {
|
|
279
|
+
headers: { 'content-type': 'application/json; charset=utf-8' },
|
|
280
|
+
body: Buffer.from(JSON.stringify(obj), 'utf8'),
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, Math.max(0, Number(ms) || 0)));
|
|
285
|
+
|
|
286
|
+
// ─────────────────────────────────────────────────────────────
|
|
287
|
+
// 0. 显存 / 算力面板 / SD 服务 小工具
|
|
288
|
+
// ─────────────────────────────────────────────────────────────
|
|
289
|
+
|
|
290
|
+
/** 从 nvidia-smi 的 `memory.free` 输出里取第一个数字(MiB);解析不了返回 null */
|
|
291
|
+
export function parseVramFreeMb(text) {
|
|
292
|
+
const m = String(text || '').match(/(\d+(?:\.\d+)?)/);
|
|
293
|
+
if (!m) return null;
|
|
294
|
+
const n = Number(m[1]);
|
|
295
|
+
return Number.isFinite(n) ? Math.round(n) : null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** 读当前空闲显存(MiB);没有 nvidia-smi 时返回 null(调用方按「未知」处理) */
|
|
299
|
+
export function readFreeVramMb() {
|
|
300
|
+
// 自测/演示用:QQBOT_FAKE_VRAM_FREE_MB=100 可伪造「卡快满了」,不影响真实环境
|
|
301
|
+
const fake = process.env.QQBOT_FAKE_VRAM_FREE_MB;
|
|
302
|
+
if (fake !== undefined && String(fake).trim() !== '') {
|
|
303
|
+
const n = Number(fake);
|
|
304
|
+
return Number.isFinite(n) ? Math.round(n) : null;
|
|
305
|
+
}
|
|
306
|
+
try {
|
|
307
|
+
const out = execFileSync('nvidia-smi', ['--query-gpu=memory.free', '--format=csv,noheader,nounits'], {
|
|
308
|
+
encoding: 'utf8',
|
|
309
|
+
timeout: 5000,
|
|
310
|
+
windowsHide: true,
|
|
311
|
+
});
|
|
312
|
+
return parseVramFreeMb(out);
|
|
313
|
+
} catch {
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** 调算力面板:POST /api/backend/{name}/{start|stop|release} */
|
|
319
|
+
export async function computeBackendAction(name, action, opts = {}) {
|
|
320
|
+
const url = `${CFG.computeUrl}/api/backend/${encodeURIComponent(name)}/${encodeURIComponent(action)}`;
|
|
321
|
+
const r = await request(url, { method: 'POST', timeoutMs: Number(opts.timeoutMs) || 15000 });
|
|
322
|
+
if (!r.ok) return { ...r, action: `${name}:${action}` };
|
|
323
|
+
return { ok: true, action: `${name}:${action}`, json: r.json, ms: r.ms };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** POST /tts/unload?kill=1 —— 杀掉 8189 worker,把 5.2G 显存还回去 */
|
|
327
|
+
export async function unloadTtsWorker() {
|
|
328
|
+
const url = `${CFG.localaiUrl}/tts/unload?kill=1`;
|
|
329
|
+
const r = await request(url, { method: 'POST', timeoutMs: 15000 });
|
|
330
|
+
if (!r.ok) return { ...r, backend: 'localai' };
|
|
331
|
+
return { ok: true, backend: 'localai', json: r.json, ms: r.ms };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* 需要显存时腾退:先看空闲,不够就停 strata(算力面板),等最多 ~12s 再看一次。
|
|
336
|
+
* @returns {{ok:true, freeMb:number|null, stopped:string[], tried:any[]}|{ok:false, code:string, error:string, freeMb:number|null, tried:any[]}}
|
|
337
|
+
*/
|
|
338
|
+
export async function ensureVram(needMb, opts = {}) {
|
|
339
|
+
const need = Number(needMb) || 0;
|
|
340
|
+
const tried = [];
|
|
341
|
+
const stopped = [];
|
|
342
|
+
let free = readFreeVramMb();
|
|
343
|
+
const before = free;
|
|
344
|
+
if (free === null || need <= 0 || free >= need) return { ok: true, freeMb: free, before, stopped, tried };
|
|
345
|
+
const targets = Array.isArray(opts.stop) ? opts.stop : ['strata'];
|
|
346
|
+
for (const name of targets) {
|
|
347
|
+
const r = await computeBackendAction(name, 'stop');
|
|
348
|
+
tried.push({ target: name, ok: r.ok, code: r.code, error: r.error });
|
|
349
|
+
if (r.ok) stopped.push(name);
|
|
350
|
+
}
|
|
351
|
+
for (let i = 0; i < 12 && stopped.length > 0; i++) {
|
|
352
|
+
await sleep(1000);
|
|
353
|
+
free = readFreeVramMb();
|
|
354
|
+
if (free === null || free >= need) break;
|
|
355
|
+
}
|
|
356
|
+
if (free !== null && free < need) {
|
|
357
|
+
return {
|
|
358
|
+
ok: false,
|
|
359
|
+
code: 'vram_insufficient',
|
|
360
|
+
error: `空闲显存 ${free}MB < 需要 ${need}MB(已尝试腾退:${stopped.join(',') || '无'})`,
|
|
361
|
+
freeMb: free,
|
|
362
|
+
before,
|
|
363
|
+
stopped,
|
|
364
|
+
tried,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
return { ok: true, freeMb: free, before, stopped, tried };
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** 探 sd_server:GET /health → { ok, loaded, health } */
|
|
371
|
+
export async function probeSdServer(base) {
|
|
372
|
+
const url = `${String(base || CFG.sdServerUrl).replace(/\/+$/, '')}/health`;
|
|
373
|
+
const r = await request(url, { timeoutMs: 3000 });
|
|
374
|
+
if (!r.ok) return { ok: false, code: r.code, error: r.error, url };
|
|
375
|
+
const health = r.json || {};
|
|
376
|
+
return { ok: true, loaded: health.loaded === true, health, ms: r.ms, url };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** 等 sd_server 就绪(轮询 /health.loaded);超时或加载报错返回结构化错误 */
|
|
380
|
+
export async function waitSdServer(deadlineMs) {
|
|
381
|
+
const t0 = Date.now();
|
|
382
|
+
let last = null;
|
|
383
|
+
while (Date.now() - t0 < Math.max(1000, Number(deadlineMs) || 1000)) {
|
|
384
|
+
const p = await probeSdServer();
|
|
385
|
+
last = p;
|
|
386
|
+
if (!p.ok) {
|
|
387
|
+
await sleep(1200);
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
if (p.health?.error) return { ok: false, code: 'sd_load_failed', error: `sd_server 加载失败:${p.health.error}`, health: p.health, waitedMs: Date.now() - t0 };
|
|
391
|
+
if (p.loaded) return { ok: true, health: p.health, waitedMs: Date.now() - t0 };
|
|
392
|
+
await sleep(1200);
|
|
393
|
+
}
|
|
394
|
+
return { ok: false, code: 'sd_boot_timeout', error: `sd_server 在 ${deadlineMs}ms 内没就绪(最后:${last?.error || (last?.ok ? 'loaded=false' : '连不上')})`, last };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** 起 sd_server(detached,不阻塞 qqbot;日志丢弃,失败在 /health.error 里看) */
|
|
398
|
+
export function spawnSdServer() {
|
|
399
|
+
const py = absPath(CFG.sdPython);
|
|
400
|
+
const script = absPath(CFG.sdScript);
|
|
401
|
+
const model = absPath(CFG.sdModel);
|
|
402
|
+
if (!py || !existsSync(py)) return err('sd_python_missing', `sd_server 的 python 不存在:${py || '(空)'}`);
|
|
403
|
+
if (!script || !existsSync(script)) return err('sd_script_missing', `sd_server 脚本不存在:${script || '(空)'}`);
|
|
404
|
+
if (!model || !existsSync(model)) return err('sd_model_missing', `SD 权重不存在:${model || '(空)'}`);
|
|
405
|
+
try {
|
|
406
|
+
const child = spawn(py, [script, '--model', model, '--port', String(CFG.sdPort)], {
|
|
407
|
+
detached: true,
|
|
408
|
+
stdio: 'ignore',
|
|
409
|
+
windowsHide: true,
|
|
410
|
+
env: {
|
|
411
|
+
...process.env,
|
|
412
|
+
HF_HOME: process.env.HF_HOME || join(REPO_ROOT, '.hf'),
|
|
413
|
+
HF_HUB_OFFLINE: '1',
|
|
414
|
+
TRANSFORMERS_OFFLINE: '1',
|
|
415
|
+
PYTHONIOENCODING: 'utf-8',
|
|
416
|
+
},
|
|
417
|
+
});
|
|
418
|
+
child.unref();
|
|
419
|
+
return { ok: true, pid: child.pid, python: py, script, model, port: CFG.sdPort };
|
|
420
|
+
} catch (e) {
|
|
421
|
+
return err('sd_spawn_failed', `起 sd_server 失败:${e instanceof Error ? e.message : String(e)}`);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** 从 PNG 的 IHDR 读宽高(不依赖图像库);不是 PNG 返回 null */
|
|
426
|
+
export function pngSize(buf) {
|
|
427
|
+
if (!buf || buf.length < 24) return null;
|
|
428
|
+
const sig = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
|
429
|
+
for (let i = 0; i < sig.length; i++) if (buf[i] !== sig[i]) return null;
|
|
430
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// ─────────────────────────────────────────────────────────────
|
|
434
|
+
// 1. ASR / OCR / TTS
|
|
435
|
+
// ─────────────────────────────────────────────────────────────
|
|
436
|
+
|
|
437
|
+
/** 语音转文字:localai POST /asr {path} */
|
|
438
|
+
export async function localAsr(file, opts = {}) {
|
|
439
|
+
const gate = localCapabilityState('asr');
|
|
440
|
+
if (!gate.ok) return gate;
|
|
441
|
+
const f = ensureFile(file);
|
|
442
|
+
if (!f.ok) return f;
|
|
443
|
+
const url = `${CFG.localaiUrl}/asr`;
|
|
444
|
+
const r = await request(url, {
|
|
445
|
+
method: 'POST',
|
|
446
|
+
...jsonBody({ path: f.path, lang: opts.lang || 'zh' }),
|
|
447
|
+
timeoutMs: opts.timeoutMs || CFG.timeoutMs,
|
|
448
|
+
});
|
|
449
|
+
if (!r.ok) return { ...r, backend: 'localai' };
|
|
450
|
+
const j = r.json || {};
|
|
451
|
+
return {
|
|
452
|
+
ok: true,
|
|
453
|
+
backend: 'localai',
|
|
454
|
+
text: String(j.text ?? ''),
|
|
455
|
+
lang: String(j.lang ?? opts.lang ?? ''),
|
|
456
|
+
duration: Number(j.duration ?? 0),
|
|
457
|
+
ms: r.ms,
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** 图片 OCR:localai POST /ocr {path} */
|
|
462
|
+
export async function localOcr(file, opts = {}) {
|
|
463
|
+
const gate = localCapabilityState('ocr');
|
|
464
|
+
if (!gate.ok) return gate;
|
|
465
|
+
const f = ensureFile(file);
|
|
466
|
+
if (!f.ok) return f;
|
|
467
|
+
const url = `${CFG.localaiUrl}/ocr`;
|
|
468
|
+
const r = await request(url, {
|
|
469
|
+
method: 'POST',
|
|
470
|
+
...jsonBody({ path: f.path }),
|
|
471
|
+
timeoutMs: opts.timeoutMs || CFG.timeoutMs,
|
|
472
|
+
});
|
|
473
|
+
if (!r.ok) return { ...r, backend: 'localai' };
|
|
474
|
+
const j = r.json || {};
|
|
475
|
+
const lines = Array.isArray(j.lines) ? j.lines : [];
|
|
476
|
+
const texts = lines.map((l) => (typeof l === 'string' ? l : String(l?.text ?? ''))).filter(Boolean);
|
|
477
|
+
return {
|
|
478
|
+
ok: true,
|
|
479
|
+
backend: 'localai',
|
|
480
|
+
text: texts.join('\n'),
|
|
481
|
+
lines,
|
|
482
|
+
count: lines.length,
|
|
483
|
+
ms: r.ms,
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* 语音合成:localai POST /tts
|
|
489
|
+
* body: {text, voice, speed, format:'wav'} → audio/* 二进制,或 JSON {path|url|base64}
|
|
490
|
+
*
|
|
491
|
+
* 显存策略(2026-11-26):Strata 35B 常驻约 20.5G,8189 TTS worker 约 5.2G。
|
|
492
|
+
* 1) 默认先 POST /tts/unload?kill=1 把旧 worker 杀掉(冷启动一次,避免叠加占卡);
|
|
493
|
+
* 2) 空闲显存 < ttsNeedVramMb 时,经算力面板停 strata(POST /api/backend/strata/stop);
|
|
494
|
+
* 3) 合成完若 ttsIdleUnload=true 再 kill 一次,把显存还给下一个后端。
|
|
495
|
+
* 这些动作和数字写进返回的 note(policy 数组也回,便于排查)。
|
|
496
|
+
*/
|
|
497
|
+
export async function localTts(text, opts = {}) {
|
|
498
|
+
const gate = localCapabilityState('tts');
|
|
499
|
+
if (!gate.ok) return gate;
|
|
500
|
+
const t = String(text || '').trim();
|
|
501
|
+
if (!t) return err('bad_arg', 'text 不能为空');
|
|
502
|
+
const url = `${CFG.localaiUrl}/tts`;
|
|
503
|
+
const policy = [];
|
|
504
|
+
const notes = [];
|
|
505
|
+
const t0 = Date.now();
|
|
506
|
+
|
|
507
|
+
// 1) 先杀旧 worker(默认开;opts.unloadFirst=false 可跳过,测试/热缓存用)
|
|
508
|
+
if (opts.unloadFirst !== false) {
|
|
509
|
+
const u = await unloadTtsWorker();
|
|
510
|
+
if (u.ok) {
|
|
511
|
+
const wasRunning = u.json?.running !== false;
|
|
512
|
+
policy.push(wasRunning ? '先 /tts/unload?kill=1(旧 worker 在跑,先杀再加载)' : '/tts/unload?kill=1(worker 本来没跑)');
|
|
513
|
+
} else {
|
|
514
|
+
policy.push(`/tts/unload 失败(${u.code || 'error'}),继续尝试直接合成`);
|
|
515
|
+
}
|
|
516
|
+
await sleep(600);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// 2) 显存不够就停 strata(TTS 需要 ~5.2G,35B 至少占 20G)
|
|
520
|
+
const vram = await ensureVram(CFG.ttsNeedVramMb, { stop: ['strata'] });
|
|
521
|
+
if (!vram.ok) {
|
|
522
|
+
return err('vram_insufficient', `${vram.error};先关掉占显存的后端(或 POST http://127.0.0.1:8199/api/backend/strata/stop)再试`, {
|
|
523
|
+
backend: 'localai',
|
|
524
|
+
policy,
|
|
525
|
+
vram,
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
if (vram.stopped?.length) policy.push(`空闲显存 ${vram.before}MB → 停 ${vram.stopped.join(',')} 后 ${vram.freeMb}MB`);
|
|
529
|
+
if (vram.freeMb !== null) notes.push(`TTS 前空闲显存 ${vram.freeMb}MB`);
|
|
530
|
+
|
|
531
|
+
const payload = {
|
|
532
|
+
text: t,
|
|
533
|
+
voice: opts.voice || '',
|
|
534
|
+
speed: Number(opts.speed ?? 1) || 1,
|
|
535
|
+
format: opts.format || 'wav',
|
|
536
|
+
};
|
|
537
|
+
const r = await request(url, {
|
|
538
|
+
method: 'POST',
|
|
539
|
+
...jsonBody(payload),
|
|
540
|
+
timeoutMs: opts.timeoutMs || CFG.heavyTimeoutMs,
|
|
541
|
+
as: 'buffer',
|
|
542
|
+
});
|
|
543
|
+
if (!r.ok) {
|
|
544
|
+
if (r.code === 'http_error' && (r.status === 404 || r.status === 405)) {
|
|
545
|
+
return {
|
|
546
|
+
...r,
|
|
547
|
+
code: 'tts_unavailable',
|
|
548
|
+
error: `localai ${url} 还没上线(HTTP ${r.status});等 /tts 接好后重试,或先用系统 SAPI 占位`,
|
|
549
|
+
backend: 'localai',
|
|
550
|
+
policy,
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
return { ...r, backend: 'localai', policy };
|
|
554
|
+
}
|
|
555
|
+
const ct = String(r.contentType || '').toLowerCase();
|
|
556
|
+
const h = r.res?.headers;
|
|
557
|
+
const hdr = {
|
|
558
|
+
elapsedMs: Number(h?.get('x-tts-elapsed-ms') || 0) || undefined,
|
|
559
|
+
durationMs: Number(h?.get('x-tts-duration-ms') || 0) || undefined,
|
|
560
|
+
vramAllocMb: Number(h?.get('x-tts-vram-alloc-mb') || 0) || undefined,
|
|
561
|
+
vramPeakMb: Number(h?.get('x-tts-vram-peak-mb') || 0) || undefined,
|
|
562
|
+
};
|
|
563
|
+
if (hdr.vramPeakMb) policy.push(`TTS worker 显存峰值 ${hdr.vramPeakMb}MB(alloc ${hdr.vramAllocMb ?? '?'}MB)`);
|
|
564
|
+
const outDir = ensureOutDir(opts.outDir, 'audio');
|
|
565
|
+
const outPath = absPath(opts.outPath) || join(outDir, `tts-${stamp()}.wav`);
|
|
566
|
+
try {
|
|
567
|
+
mkdirSync(dirname(outPath), { recursive: true });
|
|
568
|
+
} catch { /* ignore */ }
|
|
569
|
+
|
|
570
|
+
let result;
|
|
571
|
+
if (ct.includes('json')) {
|
|
572
|
+
// 兼容:服务端可能返回 {path}/{url}/{base64}
|
|
573
|
+
let j;
|
|
574
|
+
try {
|
|
575
|
+
j = JSON.parse(r.buffer.toString('utf8'));
|
|
576
|
+
} catch {
|
|
577
|
+
return err('bad_response', 'TTS 返回 JSON 解析失败', { backend: 'localai', policy });
|
|
578
|
+
}
|
|
579
|
+
if (j && typeof j.path === 'string' && existsSync(j.path)) {
|
|
580
|
+
result = { ok: true, backend: 'localai', path: j.path, bytes: statSync(j.path).size, format: payload.format, ms: r.ms };
|
|
581
|
+
} else {
|
|
582
|
+
const b64 = j && (j.audio_base64 || j.base64 || j.audio);
|
|
583
|
+
if (typeof b64 === 'string' && b64.length > 0) {
|
|
584
|
+
try {
|
|
585
|
+
const buf = Buffer.from(b64, 'base64');
|
|
586
|
+
writeFileSync(outPath, buf);
|
|
587
|
+
result = { ok: true, backend: 'localai', path: outPath, bytes: buf.length, format: payload.format, ms: r.ms };
|
|
588
|
+
} catch (e) {
|
|
589
|
+
return err('write_failed', `写 WAV 失败:${e instanceof Error ? e.message : String(e)}`, { backend: 'localai', policy });
|
|
590
|
+
}
|
|
591
|
+
} else {
|
|
592
|
+
return err('bad_response', 'TTS 返回 JSON 但既没有 path 也没有 base64 音频', { backend: 'localai', policy });
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
} else if (!r.buffer || r.buffer.length === 0) {
|
|
596
|
+
return err('bad_response', 'TTS 返回空音频', { backend: 'localai', contentType: ct, policy });
|
|
597
|
+
} else {
|
|
598
|
+
try {
|
|
599
|
+
writeFileSync(outPath, r.buffer);
|
|
600
|
+
} catch (e) {
|
|
601
|
+
return err('write_failed', `写 WAV 失败:${e instanceof Error ? e.message : String(e)}`, { backend: 'localai', policy });
|
|
602
|
+
}
|
|
603
|
+
result = {
|
|
604
|
+
ok: true,
|
|
605
|
+
backend: 'localai',
|
|
606
|
+
path: outPath,
|
|
607
|
+
bytes: r.buffer.length,
|
|
608
|
+
format: ct.includes('mpeg') || ct.includes('mp3') ? 'mp3' : (ct.includes('wav') || ct.includes('wave') ? 'wav' : payload.format),
|
|
609
|
+
contentType: ct,
|
|
610
|
+
ms: r.ms,
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// 3) 用完卸载(可选)
|
|
615
|
+
if (CFG.ttsIdleUnload === true) {
|
|
616
|
+
const u = await unloadTtsWorker();
|
|
617
|
+
policy.push(u.ok ? '合成后已 /tts/unload?kill=1 卸载(ttsIdleUnload=true)' : '合成后卸载失败,worker 仍占显存');
|
|
618
|
+
} else {
|
|
619
|
+
policy.push('合成后保留 worker(ttsIdleUnload=false);要还显存就 POST /tts/unload?kill=1');
|
|
620
|
+
}
|
|
621
|
+
const note = `显存策略:${policy.join(';')}`;
|
|
622
|
+
return {
|
|
623
|
+
...result,
|
|
624
|
+
ms: Date.now() - t0,
|
|
625
|
+
ttsMs: result.ms,
|
|
626
|
+
policy,
|
|
627
|
+
note,
|
|
628
|
+
...hdr,
|
|
629
|
+
freeVramMb: readFreeVramMb(),
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// ─────────────────────────────────────────────────────────────
|
|
634
|
+
// 2. LLM(localai → strata → gateway → ollama)
|
|
635
|
+
// ─────────────────────────────────────────────────────────────
|
|
636
|
+
|
|
637
|
+
/** LLM 默认超时:首调/冷启(Strata 35B 要加载)可能 60s+,默认放宽到 llmTimeoutMs */
|
|
638
|
+
function llmTimeout(opts) {
|
|
639
|
+
return Number(opts?.timeoutMs) || Number(CFG.llmTimeoutMs) || CFG.timeoutMs;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
async function llmLocalai(prompt, opts) {
|
|
643
|
+
const body = { prompt, max_tokens: Number(opts.maxTokens ?? 512) };
|
|
644
|
+
if (opts.model) body.model = opts.model;
|
|
645
|
+
const r = await request(`${CFG.localaiUrl}/llm`, {
|
|
646
|
+
method: 'POST', ...jsonBody(body), timeoutMs: llmTimeout(opts),
|
|
647
|
+
});
|
|
648
|
+
if (!r.ok) return { ...r, backend: 'localai' };
|
|
649
|
+
const j = r.json || {};
|
|
650
|
+
const text = String(j.text ?? '');
|
|
651
|
+
if (!text.trim()) return err('empty_content', 'localai /llm 返回空文本', { backend: 'localai', ms: r.ms });
|
|
652
|
+
return { ok: true, backend: 'localai', model: String(j.model ?? opts.model ?? ''), text, tok_per_s: j.tok_per_s, ms: r.ms };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
async function llmStrata(prompt, opts) {
|
|
656
|
+
const model = opts.model || CFG.strataModel;
|
|
657
|
+
const body = {
|
|
658
|
+
model,
|
|
659
|
+
messages: [{ role: 'user', content: prompt }],
|
|
660
|
+
max_tokens: Number(opts.maxTokens ?? 512),
|
|
661
|
+
temperature: Number(opts.temperature ?? 0.7),
|
|
662
|
+
stream: false,
|
|
663
|
+
// Strata/qwen3 必须关思考,否则 content 为空、思维链跑到 reasoning_content
|
|
664
|
+
enable_thinking: false,
|
|
665
|
+
chat_template_kwargs: { enable_thinking: false },
|
|
666
|
+
};
|
|
667
|
+
const r = await request(`${CFG.strataUrl}/chat/completions`, {
|
|
668
|
+
method: 'POST', ...jsonBody(body), timeoutMs: llmTimeout(opts),
|
|
669
|
+
});
|
|
670
|
+
if (!r.ok) return { ...r, backend: 'strata', model };
|
|
671
|
+
const j = r.json || {};
|
|
672
|
+
const msg = j?.choices?.[0]?.message || {};
|
|
673
|
+
const text = String(msg.content ?? '');
|
|
674
|
+
if (!text.trim()) {
|
|
675
|
+
return err('empty_content', `Strata 返回空 content(enable_thinking=false 没生效?reasoning_content=${String(msg.reasoning_content ?? '').slice(0, 80)})`, {
|
|
676
|
+
backend: 'strata', model, ms: r.ms, usage: j.usage,
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
return { ok: true, backend: 'strata', model, text, usage: j.usage, ms: r.ms };
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** 网关 8090:OpenAI 兼容聚合(local-first + 配额),模型名默认 local-auto */
|
|
683
|
+
async function llmGateway(prompt, opts) {
|
|
684
|
+
const model = opts.model || CFG.gatewayModel || 'local-auto';
|
|
685
|
+
const body = {
|
|
686
|
+
model,
|
|
687
|
+
messages: [{ role: 'user', content: prompt }],
|
|
688
|
+
max_tokens: Number(opts.maxTokens ?? 512),
|
|
689
|
+
temperature: Number(opts.temperature ?? 0.7),
|
|
690
|
+
stream: false,
|
|
691
|
+
};
|
|
692
|
+
const jb = jsonBody(body);
|
|
693
|
+
const gwKey = resolveGatewayKey(CFG);
|
|
694
|
+
if (gwKey) jb.headers.authorization = `Bearer ${gwKey}`;
|
|
695
|
+
const r = await request(`${CFG.gatewayUrl}/chat/completions`, {
|
|
696
|
+
method: 'POST', ...jb, timeoutMs: llmTimeout(opts),
|
|
697
|
+
});
|
|
698
|
+
if (!r.ok) return { ...r, backend: 'gateway', model };
|
|
699
|
+
const j = r.json || {};
|
|
700
|
+
const text = String(j?.choices?.[0]?.message?.content ?? '');
|
|
701
|
+
if (!text.trim()) return err('empty_content', '网关返回空 content', { backend: 'gateway', model, ms: r.ms, usage: j.usage });
|
|
702
|
+
return { ok: true, backend: 'gateway', model, text, usage: j.usage, ms: r.ms, upstream: j?.model };
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
async function llmOllama(prompt, opts) {
|
|
706
|
+
const model = opts.model || CFG.llmModel;
|
|
707
|
+
if (!model) return err('bad_arg', 'ollama 需要指定模型(localModels.llmModel 或调用参数 model)', { backend: 'ollama' });
|
|
708
|
+
const body = { model, prompt, stream: false, options: { num_predict: Number(opts.maxTokens ?? 512) } };
|
|
709
|
+
const r = await request(`${CFG.ollamaUrl}/api/generate`, {
|
|
710
|
+
method: 'POST', ...jsonBody(body), timeoutMs: llmTimeout(opts),
|
|
711
|
+
});
|
|
712
|
+
if (!r.ok) return { ...r, backend: 'ollama' };
|
|
713
|
+
const j = r.json || {};
|
|
714
|
+
const text = String(j.response ?? '');
|
|
715
|
+
if (!text.trim()) return err('empty_content', 'ollama 返回空文本', { backend: 'ollama', model, ms: r.ms });
|
|
716
|
+
return { ok: true, backend: 'ollama', model, text, ms: r.ms };
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* 本地大模型:backend = auto | localai | strata | gateway | ollama
|
|
721
|
+
* auto 链:localai → strata(35B,自动关思考)→ gateway(8090 + key)→ ollama。
|
|
722
|
+
* 全部失败时返回最后一次错误 + attempts。
|
|
723
|
+
*/
|
|
724
|
+
export async function localLlm(prompt, opts = {}) {
|
|
725
|
+
const gate = localCapabilityState('llm');
|
|
726
|
+
if (!gate.ok) return gate;
|
|
727
|
+
const p = String(prompt || '').trim();
|
|
728
|
+
if (!p) return err('bad_arg', 'prompt 不能为空');
|
|
729
|
+
const backend = String(opts.backend || CFG.llmBackend || 'auto').toLowerCase();
|
|
730
|
+
const chain = backend === 'auto' ? ['localai', 'strata', 'gateway', 'ollama'] : [backend];
|
|
731
|
+
const attempts = [];
|
|
732
|
+
for (const b of chain) {
|
|
733
|
+
let r;
|
|
734
|
+
if (b === 'localai') r = await llmLocalai(p, opts);
|
|
735
|
+
else if (b === 'strata') r = await llmStrata(p, opts);
|
|
736
|
+
else if (b === 'gateway') r = await llmGateway(p, opts);
|
|
737
|
+
else if (b === 'ollama') r = await llmOllama(p, opts);
|
|
738
|
+
else return err('bad_arg', `未知 backend:${b}(可选 auto/localai/strata/gateway/ollama)`);
|
|
739
|
+
if (r.ok) return { ...r, attempts };
|
|
740
|
+
attempts.push({ backend: b, code: r.code, error: r.error });
|
|
741
|
+
}
|
|
742
|
+
const last = attempts[attempts.length - 1] || {};
|
|
743
|
+
// 统一回 all_backends_failed(把最后一条的 code 放 lastCode,方便上层判因但不必穷举)
|
|
744
|
+
return err(
|
|
745
|
+
'all_backends_failed',
|
|
746
|
+
`本地 LLM 全部失败:${attempts.map((a) => `${a.backend}=${a.code}`).join(' / ')}`,
|
|
747
|
+
{ attempts, lastCode: last.code, lastError: last.error },
|
|
748
|
+
);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// ─────────────────────────────────────────────────────────────
|
|
752
|
+
// 3. 文生图(ComfyUI 8188/8189/7860,或 SD WebUI /sdapi/v1/txt2img)
|
|
753
|
+
// ─────────────────────────────────────────────────────────────
|
|
754
|
+
|
|
755
|
+
function comfyWorkflow(prompt, o) {
|
|
756
|
+
const ckpt = o.checkpoint || CFG.comfyCheckpoint;
|
|
757
|
+
return {
|
|
758
|
+
'3': {
|
|
759
|
+
class_type: 'KSampler',
|
|
760
|
+
inputs: {
|
|
761
|
+
seed: Number(o.seed ?? Math.floor(Math.random() * 1e9)),
|
|
762
|
+
steps: Number(o.steps ?? 20),
|
|
763
|
+
cfg: Number(o.cfg ?? 7),
|
|
764
|
+
sampler_name: 'euler',
|
|
765
|
+
scheduler: 'normal',
|
|
766
|
+
denoise: 1,
|
|
767
|
+
model: ['4', 0],
|
|
768
|
+
positive: ['6', 0],
|
|
769
|
+
negative: ['7', 0],
|
|
770
|
+
latent_image: ['5', 0],
|
|
771
|
+
},
|
|
772
|
+
},
|
|
773
|
+
'4': { class_type: 'CheckpointLoaderSimple', inputs: { ckpt_name: ckpt } },
|
|
774
|
+
'5': { class_type: 'EmptyLatentImage', inputs: { width: Number(o.width ?? 512), height: Number(o.height ?? 512), batch_size: 1 } },
|
|
775
|
+
'6': { class_type: 'CLIPTextEncode', inputs: { text: prompt, clip: ['4', 1] } },
|
|
776
|
+
'7': { class_type: 'CLIPTextEncode', inputs: { text: String(o.negative ?? 'lowres, blurry, watermark'), clip: ['4', 1] } },
|
|
777
|
+
'8': { class_type: 'VAEDecode', inputs: { samples: ['3', 0], vae: ['4', 2] } },
|
|
778
|
+
'9': { class_type: 'SaveImage', inputs: { filename_prefix: 'qqbot_local', images: ['8', 0] } },
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
async function probeComfy(base) {
|
|
783
|
+
const r = await request(`${base}/system_stats`, { timeoutMs: 2500 });
|
|
784
|
+
return r.ok && r.json && (r.json.system || r.json.devices);
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
async function probeSdWebui(base) {
|
|
788
|
+
const r = await request(`${base}/sdapi/v1/sd-models`, { timeoutMs: 2500 });
|
|
789
|
+
return r.ok && Array.isArray(r.json);
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
async function imageViaSdWebui(base, prompt, o, heavy) {
|
|
793
|
+
const body = {
|
|
794
|
+
prompt,
|
|
795
|
+
negative_prompt: String(o.negative ?? ''),
|
|
796
|
+
steps: Number(o.steps ?? 20),
|
|
797
|
+
width: Number(o.width ?? 512),
|
|
798
|
+
height: Number(o.height ?? 512),
|
|
799
|
+
cfg_scale: Number(o.cfg ?? 7),
|
|
800
|
+
sampler_name: 'Euler a',
|
|
801
|
+
};
|
|
802
|
+
const r = await request(`${base}/sdapi/v1/txt2img`, { method: 'POST', ...jsonBody(body), timeoutMs: heavy, as: 'json' });
|
|
803
|
+
if (!r.ok) return { ...r, backend: 'sdwebui', base };
|
|
804
|
+
const b64 = r.json?.images?.[0];
|
|
805
|
+
if (!b64) return err('bad_response', 'SD WebUI 没返回图片', { backend: 'sdwebui', base });
|
|
806
|
+
const outDir = ensureOutDir(o.outDir, 'image');
|
|
807
|
+
const outPath = absPath(o.outPath) || join(outDir, `img-${stamp()}.png`);
|
|
808
|
+
try {
|
|
809
|
+
const buf = Buffer.from(String(b64).replace(/^data:image\/\w+;base64,/, ''), 'base64');
|
|
810
|
+
writeFileSync(outPath, buf);
|
|
811
|
+
return { ok: true, backend: 'sdwebui', base, path: outPath, bytes: buf.length, ms: r.ms };
|
|
812
|
+
} catch (e) {
|
|
813
|
+
return err('write_failed', `写 PNG 失败:${e instanceof Error ? e.message : String(e)}`, { backend: 'sdwebui', base });
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
async function imageViaComfy(base, prompt, o, heavy) {
|
|
818
|
+
const body = { prompt: comfyWorkflow(prompt, o), client_id: `qqbot-${Date.now()}` };
|
|
819
|
+
const created = await request(`${base}/prompt`, { method: 'POST', ...jsonBody(body), timeoutMs: 15000 });
|
|
820
|
+
if (!created.ok) return { ...created, backend: 'comfy', base };
|
|
821
|
+
const pid = created.json?.prompt_id;
|
|
822
|
+
if (!pid) return err('bad_response', 'ComfyUI 没返回 prompt_id', { backend: 'comfy', base });
|
|
823
|
+
const deadline = Date.now() + heavy;
|
|
824
|
+
let img;
|
|
825
|
+
while (Date.now() < deadline) {
|
|
826
|
+
const h = await request(`${base}/history/${pid}`, { timeoutMs: 5000 });
|
|
827
|
+
if (h.ok && h.json && h.json[pid]) {
|
|
828
|
+
const outs = h.json[pid].outputs || {};
|
|
829
|
+
for (const node of Object.keys(outs)) {
|
|
830
|
+
const arr = outs[node]?.images;
|
|
831
|
+
if (Array.isArray(arr) && arr[0]?.filename) {
|
|
832
|
+
img = arr[0];
|
|
833
|
+
break;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
if (img) break;
|
|
837
|
+
}
|
|
838
|
+
await new Promise((r) => setTimeout(r, 800));
|
|
839
|
+
}
|
|
840
|
+
if (!img) return err('timeout', `ComfyUI 出图超时(>${heavy}ms)`, { backend: 'comfy', base, promptId: pid });
|
|
841
|
+
const q = new URLSearchParams({ filename: img.filename, subfolder: img.subfolder || '', type: img.type || 'output' });
|
|
842
|
+
const got = await request(`${base}/view?${q.toString()}`, { timeoutMs: heavy, as: 'buffer' });
|
|
843
|
+
if (!got.ok) return { ...got, backend: 'comfy', base };
|
|
844
|
+
const outDir = ensureOutDir(o.outDir, 'image');
|
|
845
|
+
const outPath = absPath(o.outPath) || join(outDir, `img-${stamp()}.png`);
|
|
846
|
+
try {
|
|
847
|
+
writeFileSync(outPath, got.buffer);
|
|
848
|
+
return { ok: true, backend: 'comfy', base, path: outPath, bytes: got.buffer.length, promptId: pid, ms: got.ms };
|
|
849
|
+
} catch (e) {
|
|
850
|
+
return err('write_failed', `写 PNG 失败:${e instanceof Error ? e.message : String(e)}`, { backend: 'comfy', base });
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* 跑一次「只打一行 JSON」的 CLI,返回 { ok, json, ms }。
|
|
856
|
+
* 工具箱(ai-toolkit.py)的契约就是最后一行 JSON + 退出码,这里只负责超时和取行。
|
|
857
|
+
*/
|
|
858
|
+
function runJsonCli(file, args, timeoutMs) {
|
|
859
|
+
return new Promise((done) => {
|
|
860
|
+
const t0 = Date.now();
|
|
861
|
+
let out = '';
|
|
862
|
+
let errOut = '';
|
|
863
|
+
let child;
|
|
864
|
+
try {
|
|
865
|
+
child = spawn(file, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
866
|
+
} catch (e) {
|
|
867
|
+
done(err('spawn_failed', `起不来 ${file}:${e instanceof Error ? e.message : String(e)}`, { ms: 0 }));
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
const timer = setTimeout(() => {
|
|
871
|
+
try { child.kill(); } catch { /* 已退出 */ }
|
|
872
|
+
done(err('timeout', `工具箱超过 ${timeoutMs}ms 没回话`, { ms: Date.now() - t0 }));
|
|
873
|
+
}, timeoutMs);
|
|
874
|
+
child.stdout.on('data', (b) => { out += b.toString('utf8'); });
|
|
875
|
+
child.stderr.on('data', (b) => { errOut += b.toString('utf8'); });
|
|
876
|
+
child.on('error', (e) => {
|
|
877
|
+
clearTimeout(timer);
|
|
878
|
+
done(err('spawn_failed', `工具箱进程异常:${e instanceof Error ? e.message : String(e)}`, { ms: Date.now() - t0 }));
|
|
879
|
+
});
|
|
880
|
+
child.on('close', (code) => {
|
|
881
|
+
clearTimeout(timer);
|
|
882
|
+
const line = out.split(/\r?\n/).reverse().find((s) => s.trim().startsWith('{'));
|
|
883
|
+
let json = null;
|
|
884
|
+
if (line) {
|
|
885
|
+
try { json = JSON.parse(line); } catch { json = null; }
|
|
886
|
+
}
|
|
887
|
+
const ms = Date.now() - t0;
|
|
888
|
+
if (!json) {
|
|
889
|
+
done(err('bad_response', `工具箱没返回 JSON(rc=${code}):${(errOut || out).trim().slice(-300) || '无输出'}`, { ms, rc: code }));
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
done({ ok: true, json, ms });
|
|
893
|
+
});
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* 走统一工具箱 scripts/ai-toolkit.py(FLUX.1 dev/krea 的 Q8 档,画质优先)。
|
|
899
|
+
* 契约写在 ai-toolkit.py 顶部:CLI 只打一行 JSON,退出码 0/2/3/4。
|
|
900
|
+
* 这条路径和 dsh / workbuddy 用的是同一套,qqbot 不自己拼 ComfyUI workflow,避免两边漂移。
|
|
901
|
+
*/
|
|
902
|
+
async function imageViaToolkit(prompt, o, heavy) {
|
|
903
|
+
const py = absPath(CFG.toolkitPython);
|
|
904
|
+
const script = absPath(CFG.toolkitScript);
|
|
905
|
+
if (!py || !existsSync(py)) {
|
|
906
|
+
return err('toolkit_missing', `ai-toolkit 的 Python 不存在:${py || '(toolkitPython 没配)'}`, { toolkitPython: py });
|
|
907
|
+
}
|
|
908
|
+
if (!script || !existsSync(script)) {
|
|
909
|
+
return err('toolkit_missing', `ai-toolkit 脚本不存在:${script || '(toolkitScript 没配)'}`, { toolkitScript: script });
|
|
910
|
+
}
|
|
911
|
+
const want = String(o.model || CFG.toolkitImageModel || 'krea');
|
|
912
|
+
const model = ['schnell', 'dev', 'dev8', 'krea', 'qwen'].includes(want) ? want : 'krea';
|
|
913
|
+
const outPath = absPath(o.outPath) || join(ensureOutDir(o.outDir, 'image'), `img-${stamp()}.png`);
|
|
914
|
+
const args = [script, 'image', '-p', prompt, '--model', model, '--out', outPath, '--start', '--json'];
|
|
915
|
+
if (Number(o.width) > 0) args.push('--w', String(Math.round(Number(o.width))));
|
|
916
|
+
if (Number(o.height) > 0) args.push('--h', String(Math.round(Number(o.height))));
|
|
917
|
+
if (Number(o.steps) > 0) args.push('--steps', String(Math.round(Number(o.steps))));
|
|
918
|
+
if (Number(o.seed) > 0) args.push('--seed', String(Math.round(Number(o.seed))));
|
|
919
|
+
const r = await runJsonCli(py, args, Math.max(heavy, Number(CFG.toolkitTimeoutMs) || 0));
|
|
920
|
+
if (!r.ok) return { ...r, backend: 'toolkit', model };
|
|
921
|
+
const j = r.json;
|
|
922
|
+
if (j.ok !== true) {
|
|
923
|
+
return err('toolkit_failed', String(j.error || 'ai-toolkit 返回 ok=false'), {
|
|
924
|
+
backend: 'toolkit', model, toolkitCode: j.code, hint: j.hint,
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
const path = (j.files || [])[0];
|
|
928
|
+
if (!path || !existsSync(path)) {
|
|
929
|
+
return err('bad_response', 'ai-toolkit 说成功但没落盘 PNG', { backend: 'toolkit', model, raw: j });
|
|
930
|
+
}
|
|
931
|
+
let bytes = 0;
|
|
932
|
+
try { bytes = statSync(path).size; } catch { /* 读不到大小不影响出图 */ }
|
|
933
|
+
return {
|
|
934
|
+
ok: true,
|
|
935
|
+
backend: 'toolkit',
|
|
936
|
+
model,
|
|
937
|
+
path,
|
|
938
|
+
bytes,
|
|
939
|
+
width: j.width,
|
|
940
|
+
height: j.height,
|
|
941
|
+
steps: j.steps,
|
|
942
|
+
seed: j.seed,
|
|
943
|
+
ms: j.seconds ? Math.round(Number(j.seconds) * 1000) : r.ms,
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/** 复用仓库 draw 那套 sd_server(7861,diffusers + Counterfeit-V3):探活 → 按需起 → /draw → 校验 PNG */
|
|
948
|
+
async function imageViaSdServer(prompt, o, heavy) {
|
|
949
|
+
const t0 = Date.now();
|
|
950
|
+
const tried = [];
|
|
951
|
+
const clamp = (n, d) => Math.max(512, Math.min(1024, Math.round(Number(n) || d)));
|
|
952
|
+
const width = clamp(o.width, CFG.sdWidth);
|
|
953
|
+
const height = clamp(o.height, CFG.sdHeight);
|
|
954
|
+
|
|
955
|
+
let probe = await probeSdServer();
|
|
956
|
+
let spawned = null;
|
|
957
|
+
let loadMs = 0;
|
|
958
|
+
if (!probe.ok || !probe.loaded) {
|
|
959
|
+
// 没起(或正在起)→ 先算显存。已 loaded 的服务占着卡,跳过守卫。
|
|
960
|
+
if (!probe.ok) {
|
|
961
|
+
const vram = await ensureVram(CFG.imageNeedVramMb, { stop: ['strata'] });
|
|
962
|
+
tried.push({ step: 'vram', ok: vram.ok, freeMb: vram.freeMb, before: vram.before, stopped: vram.stopped, code: vram.code });
|
|
963
|
+
if (!vram.ok) {
|
|
964
|
+
return err('vram_insufficient', `${vram.error};先 POST http://127.0.0.1:8199/api/backend/strata/stop 或关掉占卡进程再试`, {
|
|
965
|
+
backend: 'sdserver', tried,
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
spawned = spawnSdServer();
|
|
969
|
+
if (!spawned.ok) return { ...spawned, backend: 'sdserver', tried };
|
|
970
|
+
tried.push({ step: 'spawn', ok: true, pid: spawned.pid, port: spawned.port });
|
|
971
|
+
}
|
|
972
|
+
const waited = await waitSdServer(Number(o.bootWaitMs) || CFG.sdBootWaitMs);
|
|
973
|
+
loadMs = waited.waitedMs || (Date.now() - t0);
|
|
974
|
+
tried.push({ step: 'boot', ok: waited.ok, waitedMs: loadMs, code: waited.code, error: waited.error });
|
|
975
|
+
if (!waited.ok) return { ...waited, backend: 'sdserver', tried };
|
|
976
|
+
probe = { ok: true, loaded: true, health: waited.health };
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
const outDir = ensureOutDir(o.outDir, 'image');
|
|
980
|
+
const outPath = absPath(o.outPath) || join(outDir, `sd-${stamp()}.png`);
|
|
981
|
+
try {
|
|
982
|
+
mkdirSync(dirname(outPath), { recursive: true });
|
|
983
|
+
} catch { /* ignore */ }
|
|
984
|
+
const body = {
|
|
985
|
+
prompt,
|
|
986
|
+
negative: String(o.negative ?? 'lowres, bad anatomy, bad hands, text, watermark, blurry'),
|
|
987
|
+
width,
|
|
988
|
+
height,
|
|
989
|
+
steps: Math.max(4, Math.min(40, Number(o.steps) || CFG.sdSteps)),
|
|
990
|
+
cfg: Number(o.cfg ?? 7),
|
|
991
|
+
seed: Number(o.seed || 0),
|
|
992
|
+
out: outPath,
|
|
993
|
+
};
|
|
994
|
+
const r = await request(`${CFG.sdServerUrl}/draw`, {
|
|
995
|
+
method: 'POST', ...jsonBody(body), timeoutMs: heavy,
|
|
996
|
+
});
|
|
997
|
+
if (!r.ok) return { ...r, backend: 'sdserver', tried };
|
|
998
|
+
const j = r.json || {};
|
|
999
|
+
const gotPath = absPath(j.path) || outPath;
|
|
1000
|
+
if (!existsSync(gotPath)) return err('bad_response', `sd_server 说画好了但文件不存在:${gotPath}`, { backend: 'sdserver', tried });
|
|
1001
|
+
const buf = readFileSync(gotPath);
|
|
1002
|
+
const dim = pngSize(buf);
|
|
1003
|
+
if (!dim) return err('bad_response', `产物不是合法 PNG:${gotPath}`, { backend: 'sdserver', tried });
|
|
1004
|
+
if (dim.width < 512 || dim.height < 512) {
|
|
1005
|
+
return err('bad_size', `产物尺寸 ${dim.width}x${dim.height} < 512x512,不符合要求`, { backend: 'sdserver', tried });
|
|
1006
|
+
}
|
|
1007
|
+
const totalMs = Date.now() - t0;
|
|
1008
|
+
const note = `sd_server 复用 draw 的 SD1.5 路径(${CFG.sdModel});显存守卫:起服务前空闲 ${CFG.imageNeedVramMb}MB 才出图,必要时停 strata 且不自动拉起`;
|
|
1009
|
+
return {
|
|
1010
|
+
ok: true,
|
|
1011
|
+
backend: 'sdserver',
|
|
1012
|
+
base: CFG.sdServerUrl,
|
|
1013
|
+
path: gotPath,
|
|
1014
|
+
bytes: buf.length,
|
|
1015
|
+
width: dim.width,
|
|
1016
|
+
height: dim.height,
|
|
1017
|
+
seed: j.seed,
|
|
1018
|
+
steps: j.steps,
|
|
1019
|
+
ms: totalMs,
|
|
1020
|
+
drawMs: Number(j.ms) || r.ms,
|
|
1021
|
+
loadMs,
|
|
1022
|
+
health: probe.health,
|
|
1023
|
+
vramFreeMb: readFreeVramMb(),
|
|
1024
|
+
note,
|
|
1025
|
+
tried,
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* 文生图:imageBackend = toolkit(默认首选,走 scripts/ai-toolkit.py 的 FLUX Q8 画质档)
|
|
1031
|
+
* | auto(toolkit → sdserver → 旧端口,逐级退化)
|
|
1032
|
+
* | sdserver(7861 Counterfeit SD1.5)| sdwebui | comfyui(扫 imagePorts)。
|
|
1033
|
+
* 全都不在/显存不够 → 结构化错误,绝不返回假图。
|
|
1034
|
+
*/
|
|
1035
|
+
export async function localImage(prompt, opts = {}) {
|
|
1036
|
+
const gate = localCapabilityState('image');
|
|
1037
|
+
if (!gate.ok) return gate;
|
|
1038
|
+
const p = String(prompt || '').trim();
|
|
1039
|
+
if (!p) return err('bad_arg', 'prompt 不能为空');
|
|
1040
|
+
const heavy = Number(opts.timeoutMs || CFG.heavyTimeoutMs);
|
|
1041
|
+
const mode = String(opts.backend || CFG.imageBackend || 'auto').toLowerCase();
|
|
1042
|
+
|
|
1043
|
+
let toolkitErr = null;
|
|
1044
|
+
if (mode === 'toolkit' || mode === 'auto') {
|
|
1045
|
+
const r = await imageViaToolkit(p, opts, heavy);
|
|
1046
|
+
if (r.ok || mode === 'toolkit') return r;
|
|
1047
|
+
toolkitErr = r;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
if (mode === 'sdserver' || mode === 'auto') {
|
|
1051
|
+
const r = await imageViaSdServer(p, opts, heavy);
|
|
1052
|
+
if (r.ok || mode === 'sdserver') return r;
|
|
1053
|
+
// auto:sdserver 不成再扫旧端口
|
|
1054
|
+
const legacy = await imageViaPorts(p, opts, heavy);
|
|
1055
|
+
return { ...legacy, triedSdServer: r, ...(toolkitErr ? { triedToolkit: toolkitErr } : {}) };
|
|
1056
|
+
}
|
|
1057
|
+
const legacy = await imageViaPorts(p, opts, heavy);
|
|
1058
|
+
return toolkitErr ? { ...legacy, triedToolkit: toolkitErr } : legacy;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
async function imageViaPorts(prompt, opts, heavy) {
|
|
1062
|
+
const tried = [];
|
|
1063
|
+
for (const port of listImagePorts()) {
|
|
1064
|
+
const base = `http://127.0.0.1:${port}`;
|
|
1065
|
+
if (await probeSdWebui(base)) {
|
|
1066
|
+
tried.push({ base, kind: 'sdwebui', up: true });
|
|
1067
|
+
const r = await imageViaSdWebui(base, prompt, opts, heavy);
|
|
1068
|
+
if (r.ok) return { ...r, tried };
|
|
1069
|
+
tried[tried.length - 1].error = r.error;
|
|
1070
|
+
continue;
|
|
1071
|
+
}
|
|
1072
|
+
if (await probeComfy(base)) {
|
|
1073
|
+
tried.push({ base, kind: 'comfy', up: true });
|
|
1074
|
+
const r = await imageViaComfy(base, prompt, opts, heavy);
|
|
1075
|
+
if (r.ok) return { ...r, tried };
|
|
1076
|
+
tried[tried.length - 1].error = r.error;
|
|
1077
|
+
continue;
|
|
1078
|
+
}
|
|
1079
|
+
tried.push({ base, kind: 'none', up: false });
|
|
1080
|
+
}
|
|
1081
|
+
return err(
|
|
1082
|
+
'image_backend_unavailable',
|
|
1083
|
+
`没有可用的文生图后端(试过 ${tried.map((t) => t.base).join(' / ')}):8188 被 localai 占着,ComfyUI/SD WebUI 都没起`,
|
|
1084
|
+
{ tried },
|
|
1085
|
+
);
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// ─────────────────────────────────────────────────────────────
|
|
1089
|
+
// 4. 统一模型注册表(.models 全量:语言/图/视频/音频一个入口)
|
|
1090
|
+
// ─────────────────────────────────────────────────────────────
|
|
1091
|
+
|
|
1092
|
+
/** 注册表缓存(scripts/model-registry.py / ai-toolkit 写,按 mtime 判新旧) */
|
|
1093
|
+
const REGISTRY_CACHE = join(PKG_ROOT, 'config', 'models.registry.json');
|
|
1094
|
+
const REGISTRY_MAX_AGE_MS = 10 * 60 * 1000;
|
|
1095
|
+
|
|
1096
|
+
function readRegistryCache() {
|
|
1097
|
+
try {
|
|
1098
|
+
const st = statSync(REGISTRY_CACHE);
|
|
1099
|
+
const j = JSON.parse(readFileSync(REGISTRY_CACHE, 'utf8'));
|
|
1100
|
+
if (!j || !Array.isArray(j.models)) return null;
|
|
1101
|
+
return { ...j, ageMs: Date.now() - st.mtimeMs, source: 'cache' };
|
|
1102
|
+
} catch {
|
|
1103
|
+
return null;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/**
|
|
1108
|
+
* 列出本机全部模型(统一注册表)。
|
|
1109
|
+
* 顺序:内存/文件缓存 → ai-toolkit 8195 /models(现场扫,会顺手刷新缓存)→ 旧缓存兜底。
|
|
1110
|
+
* 断网、ai-toolkit 没起都**不抛异常**,最多回一份带 stale 标记的旧数据。
|
|
1111
|
+
* @param {{kind?:string, repair?:boolean, maxAgeMs?:number}} [opts]
|
|
1112
|
+
*/
|
|
1113
|
+
export async function listModels(opts = {}) {
|
|
1114
|
+
const kind = String(opts.kind || '').toLowerCase();
|
|
1115
|
+
const maxAge = Number(opts.maxAgeMs ?? REGISTRY_MAX_AGE_MS);
|
|
1116
|
+
const pick = (data) => {
|
|
1117
|
+
if (!kind) return data;
|
|
1118
|
+
const models = (data.models || []).filter((m) => String(m.kind || '').toLowerCase() === kind);
|
|
1119
|
+
const counts = {};
|
|
1120
|
+
for (const m of models) counts[m.kind] = (counts[m.kind] || 0) + 1;
|
|
1121
|
+
return { ...data, models, counts, total_gb: Math.round(models.reduce((s, m) => s + (Number(m.size_gb) || 0), 0) * 100) / 100 };
|
|
1122
|
+
};
|
|
1123
|
+
const cached = readRegistryCache();
|
|
1124
|
+
if (cached && !opts.repair && cached.ageMs < maxAge) return { ok: true, ...pick(cached) };
|
|
1125
|
+
const r = await request(`${CFG.toolkitUrl}/models${kind ? `?kind=${encodeURIComponent(kind)}` : ''}`, { timeoutMs: 30000 });
|
|
1126
|
+
if (r.ok && r.json && Array.isArray(r.json.models)) {
|
|
1127
|
+
return { ok: true, ...pick(r.json), source: 'toolkit', ms: r.ms };
|
|
1128
|
+
}
|
|
1129
|
+
if (cached) {
|
|
1130
|
+
return {
|
|
1131
|
+
ok: true,
|
|
1132
|
+
...pick(cached),
|
|
1133
|
+
stale: true,
|
|
1134
|
+
note: `这份是 ${Math.round(cached.ageMs / 60000)} 分钟前的缓存;ai-toolkit ${CFG.toolkitUrl} 没起(${r.code}),`
|
|
1135
|
+
+ '要看最新的就 `python scripts/ai-toolkit.py serve --port 8195` 或 `python scripts/model-registry.py --write`',
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
return err(
|
|
1139
|
+
'registry_unavailable',
|
|
1140
|
+
`拿不到模型注册表:${r.code || 'unknown'}(缓存 ${REGISTRY_CACHE} 也不存在)`,
|
|
1141
|
+
{ hint: 'python scripts/model-registry.py --write 生成缓存,或起 ai-toolkit serve --port 8195', url: `${CFG.toolkitUrl}/models` },
|
|
1142
|
+
);
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
/** 从注册表里挑出某一类可选模型名(设置页/工具用;纯本地,不发网络)
|
|
1146
|
+
* 2026-11-28:默认**跳过被停用的模型**(config/models.enabled.json 里记着的那批),
|
|
1147
|
+
* 这样「模型库」里点停用 = 本工具的下拉和 local_models 的推荐也不会再挑它。 */
|
|
1148
|
+
export function registryIds(kind, data, opts = {}) {
|
|
1149
|
+
const ms = (data && data.models) || [];
|
|
1150
|
+
return ms
|
|
1151
|
+
.filter((m) => (!kind || m.kind === kind) && (opts.includeDisabled === true || m.enabled !== false))
|
|
1152
|
+
.map((m) => m.id).filter(Boolean);
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// ─────────────────────────────────────────────────────────────
|
|
1156
|
+
// 5. 健康汇总
|
|
1157
|
+
// ─────────────────────────────────────────────────────────────
|
|
1158
|
+
|
|
1159
|
+
/** 三个后端 + 图像端口的健康汇总(开关状态一并回,方便她给主人报) */
|
|
1160
|
+
export async function localStatus() {
|
|
1161
|
+
const out = {
|
|
1162
|
+
ok: true,
|
|
1163
|
+
switches: {
|
|
1164
|
+
enabled: CFG.enabled === true,
|
|
1165
|
+
asr: CFG.asr === true,
|
|
1166
|
+
ocr: CFG.ocr === true,
|
|
1167
|
+
tts: CFG.tts === true,
|
|
1168
|
+
llm: CFG.llm === true,
|
|
1169
|
+
image: CFG.image === true,
|
|
1170
|
+
},
|
|
1171
|
+
endpoints: {
|
|
1172
|
+
localai: CFG.localaiUrl,
|
|
1173
|
+
ollama: CFG.ollamaUrl,
|
|
1174
|
+
strata: CFG.strataUrl,
|
|
1175
|
+
gateway: CFG.gatewayUrl,
|
|
1176
|
+
sdserver: CFG.sdServerUrl,
|
|
1177
|
+
imagePorts: listImagePorts(),
|
|
1178
|
+
},
|
|
1179
|
+
vramFreeMb: readFreeVramMb(),
|
|
1180
|
+
backends: {},
|
|
1181
|
+
notes: [],
|
|
1182
|
+
};
|
|
1183
|
+
// localai
|
|
1184
|
+
const la = await request(`${CFG.localaiUrl}/health`, { timeoutMs: 3000 });
|
|
1185
|
+
out.backends.localai = la.ok
|
|
1186
|
+
? { up: true, health: la.json, ms: la.ms }
|
|
1187
|
+
: { up: false, code: la.code, error: la.error };
|
|
1188
|
+
// ollama
|
|
1189
|
+
const ol = await request(`${CFG.ollamaUrl}/api/tags`, { timeoutMs: 3000 });
|
|
1190
|
+
out.backends.ollama = ol.ok
|
|
1191
|
+
? { up: true, models: (ol.json?.models || []).map((m) => m.name).slice(0, 10), count: (ol.json?.models || []).length, ms: ol.ms }
|
|
1192
|
+
: { up: false, code: ol.code, error: ol.error };
|
|
1193
|
+
// strata
|
|
1194
|
+
const st = await request(`${CFG.strataUrl}/models`, { timeoutMs: 3000 });
|
|
1195
|
+
out.backends.strata = st.ok
|
|
1196
|
+
? { up: true, models: (st.json?.data || []).map((m) => m.id).slice(0, 10), ms: st.ms }
|
|
1197
|
+
: { up: false, code: st.code, error: st.error };
|
|
1198
|
+
// gateway 8090
|
|
1199
|
+
const gwKey = resolveGatewayKey(CFG);
|
|
1200
|
+
const gw = await request(`${CFG.gatewayUrl}/models`, {
|
|
1201
|
+
timeoutMs: 3000,
|
|
1202
|
+
headers: gwKey ? { authorization: `Bearer ${gwKey}` } : undefined,
|
|
1203
|
+
});
|
|
1204
|
+
out.backends.gateway = gw.ok
|
|
1205
|
+
? { up: true, models: (gw.json?.data || []).map((m) => m.id).slice(0, 10), ms: gw.ms }
|
|
1206
|
+
: { up: false, code: gw.code, error: gw.error };
|
|
1207
|
+
// sd_server 7861(draw 复用的那套)
|
|
1208
|
+
const sd = await probeSdServer();
|
|
1209
|
+
out.backends.sdserver = sd.ok
|
|
1210
|
+
? { up: true, loaded: sd.loaded === true, model: sd.health?.model, device: sd.health?.device, ms: sd.ms }
|
|
1211
|
+
: { up: false, code: sd.code, error: sd.error };
|
|
1212
|
+
// image ports
|
|
1213
|
+
const img = [];
|
|
1214
|
+
for (const port of listImagePorts()) {
|
|
1215
|
+
const base = `http://127.0.0.1:${port}`;
|
|
1216
|
+
const sd = await probeSdWebui(base);
|
|
1217
|
+
if (sd) {
|
|
1218
|
+
img.push({ base, kind: 'sdwebui', up: true });
|
|
1219
|
+
continue;
|
|
1220
|
+
}
|
|
1221
|
+
const cf = await probeComfy(base);
|
|
1222
|
+
img.push({ base, kind: cf ? 'comfy' : 'none', up: !!cf });
|
|
1223
|
+
}
|
|
1224
|
+
out.backends.image = img;
|
|
1225
|
+
if (!out.switches.enabled) out.notes.push('总开关关着:所有 local_* 工具都会直接返回 disabled。' + SETTINGS_HINT);
|
|
1226
|
+
if (out.switches.enabled) {
|
|
1227
|
+
for (const cap of Object.keys(CAP_LABEL)) {
|
|
1228
|
+
if (!out.switches[cap]) out.notes.push(`「${CAP_LABEL[cap]}」分开关关着(localModels.${cap})`);
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
if (out.backends.localai.up && out.backends.localai.health?.tts === false) {
|
|
1232
|
+
out.notes.push('localai /tts 未就绪(/health 里 tts=false)');
|
|
1233
|
+
}
|
|
1234
|
+
if (!out.backends.gateway.up) out.notes.push('网关 8090 没起:cd /f/qqbot/services/gateway && start //b "" "E:\\Anaconda\\envs\\ai25\\pythonw.exe" app.py');
|
|
1235
|
+
if (!out.backends.sdserver.up) out.notes.push('sd_server 7861 没起:local_image 会自动起(首次加载约 30-90s)');
|
|
1236
|
+
if (out.vramFreeMb !== null && out.vramFreeMb < 6000) out.notes.push(`当前空闲显存只有 ${out.vramFreeMb}MB,出图/TTS 前可能要先腾卡`);
|
|
1237
|
+
// 统一注册表:让"本机到底有哪些模型"有唯一答案(语言/图/视频/音频)
|
|
1238
|
+
const reg = await listModels({});
|
|
1239
|
+
out.models = reg.ok
|
|
1240
|
+
? {
|
|
1241
|
+
counts: reg.counts,
|
|
1242
|
+
total_gb: reg.total_gb,
|
|
1243
|
+
source: reg.source,
|
|
1244
|
+
stale: !!reg.stale,
|
|
1245
|
+
llm: registryIds('llm', reg).slice(0, 20),
|
|
1246
|
+
image: registryIds('image', reg).slice(0, 20),
|
|
1247
|
+
video: registryIds('video', reg).slice(0, 20),
|
|
1248
|
+
audio: registryIds('audio', reg).slice(0, 20),
|
|
1249
|
+
}
|
|
1250
|
+
: { error: reg.error, code: reg.code };
|
|
1251
|
+
if (reg.ok && reg.stale) out.notes.push(`模型注册表是旧缓存(${reg.note || ''})`);
|
|
1252
|
+
|
|
1253
|
+
out.notes.push(CFG.vramGuardNote);
|
|
1254
|
+
return out;
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
// ─────────────────────────────────────────────────────────────
|
|
1258
|
+
// 5. QQ 工具装配(由 channel-tools.js 传入宿主 defineTool)
|
|
1259
|
+
// ─────────────────────────────────────────────────────────────
|
|
1260
|
+
|
|
1261
|
+
/**
|
|
1262
|
+
* 把能力层装成 QQ 工具。**本文件不 import defineTool**,只接收宿主注入的工厂,
|
|
1263
|
+
* 这样 `node --check` 与纯 node 自测都不需要宿主依赖。
|
|
1264
|
+
* @param {(def:any)=>any} defineTool 宿主 @deepseek-ai/dsh-tools 的 defineTool
|
|
1265
|
+
* @param {{managersOf?:()=>any[]}} [opts]
|
|
1266
|
+
* @returns {any[]} tools(形如 { tool, label },与 channel-tools 的 toolDefs 兼容)
|
|
1267
|
+
*/
|
|
1268
|
+
export function buildLocalModelTools(defineTool, opts = {}) {
|
|
1269
|
+
const simple = (name, description, parameters, run) => defineTool({
|
|
1270
|
+
name,
|
|
1271
|
+
description,
|
|
1272
|
+
parameters,
|
|
1273
|
+
output: {
|
|
1274
|
+
schema: {
|
|
1275
|
+
type: 'object', additionalProperties: false,
|
|
1276
|
+
properties: { ok: { type: 'boolean', required: true }, msg: { type: 'string', required: true } },
|
|
1277
|
+
},
|
|
1278
|
+
render: (_a, v) => [{ type: 'text', text: v.ok ? v.msg : `失败: ${v.msg}` }],
|
|
1279
|
+
},
|
|
1280
|
+
async execute(args) {
|
|
1281
|
+
try {
|
|
1282
|
+
const r = await run(args || {});
|
|
1283
|
+
if (r && r.ok === true) return { ok: true, msg: r.msg ?? '完成' };
|
|
1284
|
+
const code = r?.code ? `[${r.code}] ` : '';
|
|
1285
|
+
return { ok: false, msg: `${code}${r?.error || r?.msg || '未知错误'}` };
|
|
1286
|
+
}
|
|
1287
|
+
catch (e) {
|
|
1288
|
+
return { ok: false, msg: e instanceof Error ? e.message : String(e) };
|
|
1289
|
+
}
|
|
1290
|
+
},
|
|
1291
|
+
});
|
|
1292
|
+
|
|
1293
|
+
const DISABLED_NOTE = '(总开关或该能力开关关着时直接返回 disabled,不会去连后端)';
|
|
1294
|
+
|
|
1295
|
+
const asrTool = simple(
|
|
1296
|
+
'local_asr',
|
|
1297
|
+
'本地语音转文字(faster-whisper,走 localai 8188 /asr)。需要本机存在音频文件,返回识别文本。' + DISABLED_NOTE +
|
|
1298
|
+
'\n开关: localModels.enabled + localModels.asr',
|
|
1299
|
+
{
|
|
1300
|
+
file: { type: 'string', required: true, description: '音频文件绝对路径(wav/mp3/m4a 等,本机)' },
|
|
1301
|
+
lang: { type: 'string', description: '语言,默认 zh' },
|
|
1302
|
+
timeoutMs: { type: 'number', description: '超时毫秒(默认 60000)' },
|
|
1303
|
+
},
|
|
1304
|
+
async (a) => {
|
|
1305
|
+
const r = await localAsr(a.file, { lang: a.lang, timeoutMs: a.timeoutMs });
|
|
1306
|
+
if (!r.ok) return r;
|
|
1307
|
+
return { ok: true, msg: r.text ? r.text : '(识别成功但没听出文字)', backend: r.backend, path: r.path };
|
|
1308
|
+
},
|
|
1309
|
+
);
|
|
1310
|
+
|
|
1311
|
+
const ocrTool = simple(
|
|
1312
|
+
'local_ocr',
|
|
1313
|
+
'本地图片 OCR(PaddleOCR,走 localai 8188 /ocr)。需要本机图片文件,返回逐行文字。' + DISABLED_NOTE +
|
|
1314
|
+
'\n开关: localModels.enabled + localModels.ocr',
|
|
1315
|
+
{
|
|
1316
|
+
file: { type: 'string', required: true, description: '图片文件绝对路径(png/jpg 等)' },
|
|
1317
|
+
timeoutMs: { type: 'number', description: '超时毫秒(默认 60000)' },
|
|
1318
|
+
},
|
|
1319
|
+
async (a) => {
|
|
1320
|
+
const r = await localOcr(a.file, { timeoutMs: a.timeoutMs });
|
|
1321
|
+
if (!r.ok) return r;
|
|
1322
|
+
return { ok: true, msg: r.text ? r.text : '(没识别到文字)', count: r.count };
|
|
1323
|
+
},
|
|
1324
|
+
);
|
|
1325
|
+
|
|
1326
|
+
const ttsTool = simple(
|
|
1327
|
+
'local_tts',
|
|
1328
|
+
'本地语音合成(走 localai 8188 /tts,返回 wav 文件路径)。显存策略:默认先 /tts/unload?kill=1 杀旧 worker,空闲显存不够会先停 strata,再合成;note 里写清做了什么。' + DISABLED_NOTE +
|
|
1329
|
+
'\n开关: localModels.enabled + localModels.tts',
|
|
1330
|
+
{
|
|
1331
|
+
text: { type: 'string', required: true, description: '要读的文字(≤1000 字)' },
|
|
1332
|
+
voice: { type: 'string', description: '音色 id(可选,留空用后端默认)' },
|
|
1333
|
+
speed: { type: 'number', description: '语速倍率,默认 1' },
|
|
1334
|
+
unloadFirst: { type: 'boolean', description: '合成前先 kill 旧 worker(默认 true;false=热缓存直出)' },
|
|
1335
|
+
timeoutMs: { type: 'number', description: '超时毫秒(默认 300000,冷启动要加载模型)' },
|
|
1336
|
+
},
|
|
1337
|
+
async (a) => {
|
|
1338
|
+
const text = String(a.text || '').slice(0, 1000);
|
|
1339
|
+
const r = await localTts(text, { voice: a.voice, speed: a.speed, timeoutMs: a.timeoutMs, unloadFirst: a.unloadFirst });
|
|
1340
|
+
if (!r.ok) return r;
|
|
1341
|
+
return { ok: true, msg: `已合成 ${r.bytes} 字节 ${r.format} → ${r.path}\n${r.note || ''}`, path: r.path, note: r.note };
|
|
1342
|
+
},
|
|
1343
|
+
);
|
|
1344
|
+
|
|
1345
|
+
const llmTool = simple(
|
|
1346
|
+
'local_llm',
|
|
1347
|
+
'本地大模型补一句/扩写/翻译。backend:auto(localai → strata 35B → 网关 8090 → ollama)/ localai / strata / gateway / ollama。' +
|
|
1348
|
+
'Strata 会自动带 enable_thinking=false;网关走 8090 + key。' +
|
|
1349
|
+
'**注意**:Strata 35B 常驻约 20.5G 显存,冷启可能 60s+。' + DISABLED_NOTE +
|
|
1350
|
+
'\n开关: localModels.enabled + localModels.llm',
|
|
1351
|
+
{
|
|
1352
|
+
prompt: { type: 'string', required: true, description: '提示词' },
|
|
1353
|
+
backend: { type: 'string', enum: ['auto', 'localai', 'strata', 'gateway', 'ollama'], description: '指定后端(默认 auto 依次试)' },
|
|
1354
|
+
model: { type: 'string', description: '指定模型名(ollama 必填;gateway 默认 local-auto;留空用配置)' },
|
|
1355
|
+
maxTokens: { type: 'number', description: '最多生成 token,默认 512' },
|
|
1356
|
+
timeoutMs: { type: 'number', description: '超时毫秒(默认 120000,35B 冷启要等)' },
|
|
1357
|
+
},
|
|
1358
|
+
async (a) => {
|
|
1359
|
+
const r = await localLlm(a.prompt, { backend: a.backend, model: a.model, maxTokens: a.maxTokens, timeoutMs: a.timeoutMs });
|
|
1360
|
+
if (!r.ok) return r;
|
|
1361
|
+
const txt = String(r.text || '').trim();
|
|
1362
|
+
return { ok: true, msg: `[${r.backend}${r.model ? `/${r.model}` : ''} ${r.ms}ms] ${txt || '(空回复)'}` };
|
|
1363
|
+
},
|
|
1364
|
+
);
|
|
1365
|
+
|
|
1366
|
+
const imageTool = simple(
|
|
1367
|
+
'local_image',
|
|
1368
|
+
'本地文生图(默认走统一工具箱 scripts/ai-toolkit.py 的 FLUX.1 画质档:dev8=Q8/24步、krea=Q8/28步;' +
|
|
1369
|
+
'退化链 toolbox → sd_server 7861 → 8188/8189/7860)。' +
|
|
1370
|
+
'真出 PNG 到 out/image/<yyyy-MM>/,返回路径+尺寸+耗时;显存不够会先停 strata 且不自动重启,**绝不返回假图**。' + DISABLED_NOTE +
|
|
1371
|
+
'\n开关: localModels.enabled + localModels.image',
|
|
1372
|
+
{
|
|
1373
|
+
prompt: { type: 'string', required: true, description: '画面描述(qwen 档中文提示词原生支持,效果最好;FLUX 档英文更好)' },
|
|
1374
|
+
width: { type: 'number', description: '宽(默认按档位:schnell 1024 / dev8·krea 1216 / qwen 1024)' },
|
|
1375
|
+
height: { type: 'number', description: '高(默认按档位:schnell 1024 / dev8·krea 832 / qwen 1024)' },
|
|
1376
|
+
steps: { type: 'number', description: '步数(不填用档位默认:schnell 4 / dev8 24 / krea 28 / qwen 20)' },
|
|
1377
|
+
negative: { type: 'string', description: '负向提示词(qwen 档一般留空)' },
|
|
1378
|
+
model: { type: 'string', enum: ['schnell', 'dev', 'dev8', 'krea', 'qwen'], description: '画质档:schnell 最快 / dev8·krea FLUX 最高画质 / qwen=Qwen-Image-2512(中文、画内文字、审美最强,约 12G 权重)' },
|
|
1379
|
+
backend: { type: 'string', enum: ['toolkit', 'auto', 'sdserver', 'sdwebui', 'comfyui'], description: '出图后端,默认 auto(toolkit 优先)' },
|
|
1380
|
+
seed: { type: 'number', description: '随机种子(0=随机)' },
|
|
1381
|
+
timeoutMs: { type: 'number', description: '超时毫秒(默认 300000;画质档冷启要等 ComfyUI)' },
|
|
1382
|
+
},
|
|
1383
|
+
async (a) => {
|
|
1384
|
+
const r = await localImage(a.prompt, {
|
|
1385
|
+
width: a.width, height: a.height, steps: a.steps, negative: a.negative,
|
|
1386
|
+
model: a.model, backend: a.backend, seed: a.seed, timeoutMs: a.timeoutMs,
|
|
1387
|
+
});
|
|
1388
|
+
if (!r.ok) return r;
|
|
1389
|
+
return {
|
|
1390
|
+
ok: true,
|
|
1391
|
+
msg: `已出图(${r.backend}${r.model ? `/${r.model}` : ''})${r.width}x${r.height} ${r.bytes} 字节 ${r.ms}ms → ${r.path}`,
|
|
1392
|
+
path: r.path,
|
|
1393
|
+
width: r.width,
|
|
1394
|
+
height: r.height,
|
|
1395
|
+
bytes: r.bytes,
|
|
1396
|
+
ms: r.ms,
|
|
1397
|
+
};
|
|
1398
|
+
},
|
|
1399
|
+
);
|
|
1400
|
+
|
|
1401
|
+
const enhanceTool = simple(
|
|
1402
|
+
'local_enhance',
|
|
1403
|
+
'对已经生成/已有的图片、视频、音频做「修复增强」:图片=去噪+局部对比+锐化(可选 2x 放大);' +
|
|
1404
|
+
'视频=时域去噪+锐化+响度归一;音频=高通+响度归一。参数写死在 scripts/media-enhance.py(可复现),' +
|
|
1405
|
+
'产物落 out/<kind>/<yyyy-MM>/enhanced/,同目录有 -report.json 记录前后指标。' + DISABLED_NOTE +
|
|
1406
|
+
'\n开关: localModels.enabled + localModels.image',
|
|
1407
|
+
{
|
|
1408
|
+
input: { type: 'string', required: true, description: '本机文件绝对路径(png/jpg/mp4/wav…)' },
|
|
1409
|
+
kind: { type: 'string', enum: ['image', 'video', 'audio'], description: '输入类型(留空按扩展名猜)' },
|
|
1410
|
+
preset: { type: 'string', enum: ['light', 'photo', 'anime'], description: '图片预设:light=不改尺寸只压噪点(默认);photo/anime=2x 放大' },
|
|
1411
|
+
scale: { type: 'number', description: '放大倍数(0=用预设默认,1=不放大)' },
|
|
1412
|
+
timeoutMs: { type: 'number', description: '超时毫秒(默认 600000)' },
|
|
1413
|
+
},
|
|
1414
|
+
async (a) => {
|
|
1415
|
+
const py = absPath(CFG.toolkitPython);
|
|
1416
|
+
const script = absPath(CFG.toolkitScript);
|
|
1417
|
+
if (!py || !existsSync(py)) return err('toolkit_missing', `ai-toolkit 的 Python 不存在:${py || '(toolkitPython 没配)'}`);
|
|
1418
|
+
if (!script || !existsSync(script)) return err('toolkit_missing', `ai-toolkit 脚本不存在:${script || '(toolkitScript 没配)'}`);
|
|
1419
|
+
const input = String(a.input || '').trim();
|
|
1420
|
+
if (!input || !existsSync(input)) return err('bad_input', `输入不存在:${input}`);
|
|
1421
|
+
const kind = a.kind || (/\.(mp4|mov|mkv|webm|avi)$/i.test(input) ? 'video'
|
|
1422
|
+
: /\.(wav|mp3|flac|ogg|opus)$/i.test(input) ? 'audio' : 'image');
|
|
1423
|
+
const args = [script, 'enhance', '--kind', kind, '-i', input, '--json'];
|
|
1424
|
+
if (kind === 'image' && a.preset) args.push('--preset', String(a.preset));
|
|
1425
|
+
if (a.scale) args.push('--scale', String(Math.round(Number(a.scale))));
|
|
1426
|
+
const r = await runJsonCli(py, args, Math.max(30000, Number(a.timeoutMs) || 600000));
|
|
1427
|
+
if (!r.ok) return r;
|
|
1428
|
+
const j = r.json;
|
|
1429
|
+
if (j.ok !== true) return err('enhance_failed', String(j.error || 'media-enhance 返回 ok=false'));
|
|
1430
|
+
const g = j.gain || {};
|
|
1431
|
+
const line = kind === 'image'
|
|
1432
|
+
? `锐度 x${g.sharpness_x ?? '?'} · 噪点 x${g.noise_x ?? '?'}(>1 表示更干净)`
|
|
1433
|
+
: `响度 ${j.loudness_before ?? '?'} → ${j.loudness_after ?? '?'} LUFS`;
|
|
1434
|
+
return {
|
|
1435
|
+
ok: true,
|
|
1436
|
+
msg: `已修复(${kind}/${j.preset || '默认'})${line}\n产物: ${j.output}\n对比/报告: ${j.compare || j.report || '-'}`,
|
|
1437
|
+
};
|
|
1438
|
+
},
|
|
1439
|
+
);
|
|
1440
|
+
|
|
1441
|
+
const statusTool = simple(
|
|
1442
|
+
'local_status',
|
|
1443
|
+
'本地模型总检:返回总开关+五个分开关、localai/ollama/Strata/网关 8090/sd_server 健康、图像端口占用、空闲显存、以及显存守卫提示。' +
|
|
1444
|
+
'主人问「本地模型能不能用」「显示卡能不能出图」时先调这个。**不受开关限制**(只读探测)。',
|
|
1445
|
+
{},
|
|
1446
|
+
async () => {
|
|
1447
|
+
const s = await localStatus();
|
|
1448
|
+
const on = (b) => (b?.up ? 'up' : 'down');
|
|
1449
|
+
const sw = s.switches;
|
|
1450
|
+
const lines = [
|
|
1451
|
+
`开关: 总${sw.enabled ? '开' : '关'} · asr${sw.asr ? '开' : '关'} · ocr${sw.ocr ? '开' : '关'} · tts${sw.tts ? '开' : '关'} · llm${sw.llm ? '开' : '关'} · image${sw.image ? '开' : '关'}`,
|
|
1452
|
+
`localai 8188: ${on(s.backends.localai)}${s.backends.localai.up ? `(asr=${s.backends.localai.health?.asr ?? '?'}, ocr=${s.backends.localai.health?.ocr ?? '?'}, tts=${s.backends.localai.health?.tts ?? '未上线'})` : ''}`,
|
|
1453
|
+
`ollama 11434: ${on(s.backends.ollama)}${s.backends.ollama.up ? `(${s.backends.ollama.count} 个模型)` : ''}`,
|
|
1454
|
+
`Strata 8080: ${on(s.backends.strata)}${s.backends.strata.up ? `(${(s.backends.strata.models || []).slice(0, 3).join(', ')})` : ''}`,
|
|
1455
|
+
`网关 8090: ${on(s.backends.gateway)}${s.backends.gateway.up ? `(${(s.backends.gateway.models || []).slice(0, 3).join(', ')})` : ''}`,
|
|
1456
|
+
`sd_server 7861: ${on(s.backends.sdserver)}${s.backends.sdserver.up ? `(loaded=${s.backends.sdserver.loaded})` : ''}`,
|
|
1457
|
+
`空闲显存: ${s.vramFreeMb === null ? '未知' : `${s.vramFreeMb}MB`}`,
|
|
1458
|
+
`图像端口: ${(s.backends.image || []).map((i) => `${i.base.replace('http://127.0.0.1:', '')}:${i.kind}`).join(' · ')}`,
|
|
1459
|
+
...(s.notes || []).map((n) => `· ${n}`),
|
|
1460
|
+
];
|
|
1461
|
+
return { ok: true, msg: lines.join('\n') };
|
|
1462
|
+
},
|
|
1463
|
+
);
|
|
1464
|
+
|
|
1465
|
+
const modelsTool = simple(
|
|
1466
|
+
'local_models',
|
|
1467
|
+
'列出本机**全部**可用模型(统一注册表):语言/出图/生视频/音频,带 id、后端、大小、量化、真实路径,以及"新模型该放哪"。' +
|
|
1468
|
+
'主人问「本地有哪些模型」「能不能用某个模型」「我下的模型放哪」时调它。**不受开关限制**(只读扫描)。' +
|
|
1469
|
+
'想指定某个模型跑活时,把返回的 id 传给 local_llm / local_image 的 model 参数(或写进设置页对应栏位)。',
|
|
1470
|
+
{
|
|
1471
|
+
kind: { type: 'string', enum: ['llm', 'image', 'video', 'audio', 'ocr'], description: '只看某一类;不填=全部' },
|
|
1472
|
+
refresh: { type: 'boolean', description: '忽略 10 分钟缓存,现场重扫(默认 false)' },
|
|
1473
|
+
},
|
|
1474
|
+
async (a) => {
|
|
1475
|
+
const r = await listModels({ kind: a.kind, repair: a.refresh === true });
|
|
1476
|
+
if (!r.ok) return r;
|
|
1477
|
+
const ms = r.models || [];
|
|
1478
|
+
const offN = ms.filter((m) => m.enabled === false).length;
|
|
1479
|
+
const lines = [
|
|
1480
|
+
`共 ${ms.length} 个(${Object.entries(r.counts || {}).map(([k, v]) => `${k} ${v}`).join(' · ')}),合计 ${r.total_gb}GB`
|
|
1481
|
+
+ (offN ? `;其中 ${offN} 个已停用(设置页最上面「🗂 模型库」可重新启用)` : ''),
|
|
1482
|
+
...ms.slice(0, 60).map((m) => `· [${m.kind}${m.subkind ? '/' + m.subkind : ''}] ${m.display || m.id}${m.display && m.display !== m.id ? '(' + m.id + ')' : ''} — ${m.backend || '?'} ${m.size_gb}GB${m.quant ? ' ' + m.quant : ''}${m.enabled === false ? ' 【已停用】' : ''}`),
|
|
1483
|
+
ms.length > 60 ? `…(只列前 60 个,要全部就 kind 过滤)` : '',
|
|
1484
|
+
r.stale ? `⚠️ ${r.note || '数据是旧缓存'}` : '',
|
|
1485
|
+
'放新模型:.models/image|video|audio/{unet,checkpoints,clip,text_encoders,vae,loras} / llm/{ollama,gguf,strata}',
|
|
1486
|
+
`产物一律落 ${OUT_ROOT}\\{image,video,audio,text}\\<yyyy-MM>\\`,
|
|
1487
|
+
].filter(Boolean);
|
|
1488
|
+
return { ok: true, msg: lines.join('\n'), counts: r.counts, total_gb: r.total_gb, source: r.source, models: ms.slice(0, 60) };
|
|
1489
|
+
},
|
|
1490
|
+
);
|
|
1491
|
+
|
|
1492
|
+
return [asrTool, ocrTool, ttsTool, llmTool, imageTool, enhanceTool, statusTool, modelsTool].map((tool) => ({ tool }));
|
|
1493
|
+
}
|
|
1494
|
+
|