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
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
server.py — 本地保密会话窗口(本地模型聊天 / 本地生图),事后可一键焚毁
|
|
5
|
+
|
|
6
|
+
设计原则(2026-12-02 主人要求):
|
|
7
|
+
· 只绑 127.0.0.1,带随机 token;不开外网、不引用任何 CDN
|
|
8
|
+
· 服务端**不存对话历史**(历史只在浏览器内存),刷新即消失
|
|
9
|
+
· 生图只落临时文件,读完立刻删;图片字节只放内存,焚毁即清
|
|
10
|
+
· 不写 memory.db / 不写 DSH 日志 / 不经过任何云 API
|
|
11
|
+
|
|
12
|
+
2026-12-02 第二次修(主人实测「模型太少 / 服务起不来 / 回复就卡死 / 生图不行」):
|
|
13
|
+
· 模型清单:Ollama 默认库(11434) + 富模型库(.models/llm/ollama,按需起 11435) + Strata 全部档位
|
|
14
|
+
—— 以前只列 11434 的三个,主人要的 qwen3:8b / deepseek-r1:8b / qwen2.5:7b 等都在富库里
|
|
15
|
+
· 聊天:Ollama 走原生 /api/chat(NDJSON)→ 统一转成 SSE,前端只认一种格式;
|
|
16
|
+
每次只读一行就 flush,任何后端卡住都有硬超时,不再出现「整个页面僵住」
|
|
17
|
+
· Strata:不再同步等 240 秒才回话;没起来就立刻告诉前端「正在启动」,后台拉起
|
|
18
|
+
· 生图:先确保 ComfyUI(8191) + ai-toolkit(8195) 都起来,再转发 /image
|
|
19
|
+
|
|
20
|
+
启动:
|
|
21
|
+
python scripts/secure-room/server.py
|
|
22
|
+
→ 打开终端里打印的 http://127.0.0.1:8196/?t=<token>
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import subprocess
|
|
30
|
+
import secrets
|
|
31
|
+
import sys
|
|
32
|
+
import threading
|
|
33
|
+
import time
|
|
34
|
+
import urllib.error
|
|
35
|
+
import urllib.request
|
|
36
|
+
import uuid
|
|
37
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
38
|
+
from urllib.parse import urlparse, parse_qs
|
|
39
|
+
|
|
40
|
+
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
41
|
+
HTML = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'index.html')
|
|
42
|
+
TMP = os.path.join(ROOT, 'data', 'secure-room')
|
|
43
|
+
STRATA = 'http://127.0.0.1:8080/v1'
|
|
44
|
+
OLLAMA = 'http://127.0.0.1:11434'
|
|
45
|
+
OLLAMA_RICH = 'http://127.0.0.1:11435'
|
|
46
|
+
RICH_STORE = os.path.join(ROOT, '.models', 'llm', 'ollama')
|
|
47
|
+
TOOLKIT = 'http://127.0.0.1:8195'
|
|
48
|
+
COMFY = 'http://127.0.0.1:8191'
|
|
49
|
+
OLLAMA_EXE = os.path.expandvars(r'%LOCALAPPDATA%\Programs\Ollama\ollama.exe')
|
|
50
|
+
STRATA_PROFILES = ('strata-serve-32k.json', 'strata-serve-94k.json')
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ── 基础 HTTP ───────────────────────────────────────────────────────────────
|
|
54
|
+
def http_json(url: str, payload: dict | None = None, timeout=5, headers=None):
|
|
55
|
+
data = json.dumps(payload).encode() if payload is not None else None
|
|
56
|
+
h = {'content-type': 'application/json'} if data else {}
|
|
57
|
+
h.update(headers or {})
|
|
58
|
+
req = urllib.request.Request(url, data=data, headers=h, method='POST' if data else 'GET')
|
|
59
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
60
|
+
return json.loads(r.read().decode('utf-8', 'ignore'))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def up(url: str, timeout=1.5) -> bool:
|
|
64
|
+
try:
|
|
65
|
+
urllib.request.urlopen(url, timeout=timeout).close()
|
|
66
|
+
return True
|
|
67
|
+
except Exception:
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def spawn(args, cwd=None):
|
|
72
|
+
"""脱离父进程启动(服务端被杀也不带走子进程)"""
|
|
73
|
+
try:
|
|
74
|
+
subprocess.Popen(args, cwd=cwd or ROOT,
|
|
75
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
76
|
+
creationflags=0x00000008 | 0x00000200)
|
|
77
|
+
return True
|
|
78
|
+
except Exception as e:
|
|
79
|
+
print('[secure-room] spawn 失败:', e, flush=True)
|
|
80
|
+
return False
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def py_exe() -> str:
|
|
84
|
+
return os.environ.get('QQBOT_PYTHON') or sys.executable or r'E:\Anaconda\envs\ai25\python.exe'
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# ── Ollama:默认库 + 富模型库(第二个实例,11435)────────────────────────────
|
|
88
|
+
_rich_lock = threading.Lock()
|
|
89
|
+
_rich_started_at = 0.0
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def rich_ollama_up() -> bool:
|
|
93
|
+
return up(OLLAMA_RICH + '/api/tags')
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def ensure_rich_ollama(wait=25) -> bool:
|
|
97
|
+
"""富库(.models/llm/ollama)里放着 qwen3:8b / deepseek-r1:8b / qwen2.5:7b 等,
|
|
98
|
+
与默认库物理隔离,只能用第二个 ollama 实例(11435, OLLAMA_MODELS=富库)读到。"""
|
|
99
|
+
global _rich_started_at
|
|
100
|
+
if rich_ollama_up():
|
|
101
|
+
return True
|
|
102
|
+
if not os.path.isdir(RICH_STORE) or not os.path.isfile(OLLAMA_EXE):
|
|
103
|
+
return False
|
|
104
|
+
with _rich_lock:
|
|
105
|
+
if rich_ollama_up():
|
|
106
|
+
return True
|
|
107
|
+
if time.time() - _rich_started_at > 60: # 一分钟内不重复拉
|
|
108
|
+
_rich_started_at = time.time()
|
|
109
|
+
env = dict(os.environ)
|
|
110
|
+
env['OLLAMA_MODELS'] = RICH_STORE
|
|
111
|
+
env['OLLAMA_HOST'] = '127.0.0.1:11435'
|
|
112
|
+
env['OLLAMA_KEEP_ALIVE'] = '0'
|
|
113
|
+
try:
|
|
114
|
+
subprocess.Popen([OLLAMA_EXE, 'serve'], env=env, cwd=ROOT,
|
|
115
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
116
|
+
creationflags=0x00000008 | 0x00000200)
|
|
117
|
+
except Exception as e:
|
|
118
|
+
print('[secure-room] 富模型库启动失败:', e, flush=True)
|
|
119
|
+
return False
|
|
120
|
+
for _ in range(max(1, wait)):
|
|
121
|
+
if rich_ollama_up():
|
|
122
|
+
return True
|
|
123
|
+
time.sleep(1)
|
|
124
|
+
return False
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def ollama_tags(base: str):
|
|
128
|
+
try:
|
|
129
|
+
j = json.loads(urllib.request.urlopen(base + '/api/tags', timeout=3).read())
|
|
130
|
+
return [m.get('name') or m.get('model') for m in (j.get('models') or []) if m.get('name') or m.get('model')]
|
|
131
|
+
except Exception:
|
|
132
|
+
return []
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ── 模型清单 ────────────────────────────────────────────────────────────────
|
|
136
|
+
def strata_models():
|
|
137
|
+
"""Strata 的档位(离线也列出来,点了就自动拉)"""
|
|
138
|
+
out = []
|
|
139
|
+
for name in STRATA_PROFILES:
|
|
140
|
+
p = os.path.join(ROOT, 'services', 'compute', name)
|
|
141
|
+
try:
|
|
142
|
+
j = json.loads(open(p, encoding='utf-8').read())
|
|
143
|
+
except Exception:
|
|
144
|
+
continue
|
|
145
|
+
mid = j.get('model_name') or ''
|
|
146
|
+
if not mid:
|
|
147
|
+
continue
|
|
148
|
+
tag = '32k' if '32k' in name else ('94k' if '94k' in name else name)
|
|
149
|
+
out.append({'id': mid, 'backend': 'strata', 'label': mid + ' · ' + tag, 'profile': name})
|
|
150
|
+
if not out:
|
|
151
|
+
out.append({'id': 'qwen3.6-35b-a3b-ud-q4_k_xl', 'backend': 'strata',
|
|
152
|
+
'label': 'qwen3.6-35b-a3b-ud-q4_k_xl · 32k', 'profile': STRATA_PROFILES[0]})
|
|
153
|
+
return out
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def list_models():
|
|
157
|
+
"""本机可选题型:Ollama 默认库 + 富库 + Strata 档位"""
|
|
158
|
+
online_default = ollama_tags(OLLAMA)
|
|
159
|
+
models = []
|
|
160
|
+
for mid in online_default:
|
|
161
|
+
if 'embed' in mid:
|
|
162
|
+
continue
|
|
163
|
+
models.append({'id': mid, 'backend': 'ollama', 'store': 'default',
|
|
164
|
+
'label': mid + ' · ollama', 'online': True})
|
|
165
|
+
|
|
166
|
+
rich_up = rich_ollama_up()
|
|
167
|
+
rich = ollama_tags(OLLAMA_RICH) if rich_up else []
|
|
168
|
+
for mid in rich:
|
|
169
|
+
if 'embed' in mid or any(m['id'] == mid for m in models):
|
|
170
|
+
continue
|
|
171
|
+
models.append({'id': mid, 'backend': 'ollama', 'store': 'rich',
|
|
172
|
+
'label': mid + ' · ollama(富库)', 'online': True})
|
|
173
|
+
|
|
174
|
+
s_up = up(STRATA + '/models')
|
|
175
|
+
seen = set()
|
|
176
|
+
for m in strata_models():
|
|
177
|
+
if m['id'] in seen:
|
|
178
|
+
continue
|
|
179
|
+
seen.add(m['id'])
|
|
180
|
+
m['online'] = s_up
|
|
181
|
+
models.append(m)
|
|
182
|
+
return models
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def find_model(model: str):
|
|
186
|
+
for m in list_models():
|
|
187
|
+
if m['id'] == model:
|
|
188
|
+
return m
|
|
189
|
+
return None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# ── 后端拉起 ────────────────────────────────────────────────────────────────
|
|
193
|
+
def free_comfy():
|
|
194
|
+
"""生图模型先卸掉再拉 35B —— 22G 显存装不下两个"""
|
|
195
|
+
try:
|
|
196
|
+
http_json(COMFY + '/free', {'unload_models': True, 'free_memory': True}, timeout=15)
|
|
197
|
+
except Exception:
|
|
198
|
+
pass
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def stop_strata():
|
|
202
|
+
"""6222 显存只有一个:要生图就先让 Strata 让位(面板 409 时忽略)"""
|
|
203
|
+
try:
|
|
204
|
+
http_json('http://127.0.0.1:8199/api/backend/strata/stop', {}, timeout=20)
|
|
205
|
+
except Exception:
|
|
206
|
+
pass
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def strata_cmd():
|
|
210
|
+
"""Strata control 组件的版本号会变(0.1.68 → 之后),不能写死;这里扫最新一个。"""
|
|
211
|
+
base = os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Strata', 'components', 'control')
|
|
212
|
+
try:
|
|
213
|
+
vers = [d for d in os.listdir(base) if os.path.isdir(os.path.join(base, d))]
|
|
214
|
+
vers.sort(key=lambda s: [int(x) for x in s.split('.') if x.isdigit()], reverse=True)
|
|
215
|
+
for v in vers:
|
|
216
|
+
p = os.path.join(base, v, 'bin', 'strata.cmd')
|
|
217
|
+
if os.path.exists(p):
|
|
218
|
+
return p
|
|
219
|
+
except Exception:
|
|
220
|
+
pass
|
|
221
|
+
return ''
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def ensure_strata(wait=120) -> dict:
|
|
225
|
+
if up(STRATA + '/models'):
|
|
226
|
+
return {'ok': True, 'note': 'already'}
|
|
227
|
+
free_comfy()
|
|
228
|
+
try:
|
|
229
|
+
http_json('http://127.0.0.1:8199/api/backend/strata/start', {}, timeout=8)
|
|
230
|
+
except Exception:
|
|
231
|
+
cmd = strata_cmd()
|
|
232
|
+
if not cmd:
|
|
233
|
+
return {'ok': False, 'error': '找不到 strata.cmd(Strata 没装或目录变了)'}
|
|
234
|
+
profile = os.path.join(ROOT, 'services', 'compute', 'strata-serve-32k.json')
|
|
235
|
+
if not spawn(['cmd', '/c', cmd, 'serve', '--profile', profile, '--port', '8080', '--output', 'human']):
|
|
236
|
+
return {'ok': False, 'error': '拉不起 strata(找不到 strata.cmd)'}
|
|
237
|
+
for _ in range(max(1, wait)):
|
|
238
|
+
if up(STRATA + '/models'):
|
|
239
|
+
return {'ok': True, 'note': 'started'}
|
|
240
|
+
time.sleep(1)
|
|
241
|
+
return {'ok': False, 'error': 'Strata 启动超时'}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def start_strata_bg():
|
|
245
|
+
"""后台拉起,不阻塞这一次请求(35B 要 20~60 秒,页面不能陪着等)"""
|
|
246
|
+
if up(STRATA + '/models'):
|
|
247
|
+
return True
|
|
248
|
+
threading.Thread(target=ensure_strata, kwargs={'wait': 180}, daemon=True).start()
|
|
249
|
+
return False
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def ensure_comfy(wait=120) -> bool:
|
|
253
|
+
if up(COMFY + '/system_stats', timeout=2):
|
|
254
|
+
return True
|
|
255
|
+
bat = os.path.join(ROOT, 'services', 'comfyui', 'start_comfyui_8191.bat')
|
|
256
|
+
if os.path.isfile(bat):
|
|
257
|
+
spawn(['cmd', '/c', bat])
|
|
258
|
+
for _ in range(max(1, wait)):
|
|
259
|
+
if up(COMFY + '/system_stats', timeout=2):
|
|
260
|
+
return True
|
|
261
|
+
time.sleep(1)
|
|
262
|
+
return False
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def ensure_toolkit(wait=90) -> dict:
|
|
266
|
+
# /health 里要做 nvidia-smi 探测,1~2 秒才回,超时必须给够(1.5s 会误判离线)
|
|
267
|
+
if up(TOOLKIT + '/health', timeout=8):
|
|
268
|
+
return {'ok': True}
|
|
269
|
+
spawn([py_exe(), os.path.join(ROOT, 'scripts', 'ai-toolkit.py'), 'serve', '--port', '8195'])
|
|
270
|
+
for _ in range(max(1, wait)):
|
|
271
|
+
if up(TOOLKIT + '/health', timeout=8):
|
|
272
|
+
return {'ok': True}
|
|
273
|
+
time.sleep(1)
|
|
274
|
+
return {'ok': False, 'error': 'ai-toolkit 启动超时'}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# ── token ───────────────────────────────────────────────────────────────────
|
|
278
|
+
def _load_token() -> str:
|
|
279
|
+
p = os.path.join(TMP, '.token')
|
|
280
|
+
try:
|
|
281
|
+
t = open(p, encoding='utf-8').read().strip()
|
|
282
|
+
if len(t) >= 12:
|
|
283
|
+
return t
|
|
284
|
+
except Exception:
|
|
285
|
+
pass
|
|
286
|
+
t = secrets.token_urlsafe(12)
|
|
287
|
+
try:
|
|
288
|
+
os.makedirs(TMP, exist_ok=True)
|
|
289
|
+
open(p, 'w', encoding='utf-8').write(t)
|
|
290
|
+
except Exception:
|
|
291
|
+
pass
|
|
292
|
+
return t
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
TOKEN = _load_token()
|
|
296
|
+
IMAGES: dict[str, tuple[bytes, str]] = {}
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class Handler(BaseHTTPRequestHandler):
|
|
300
|
+
server_version = 'SecureRoom/1.1'
|
|
301
|
+
protocol_version = 'HTTP/1.1'
|
|
302
|
+
|
|
303
|
+
def log_message(self, fmt, *args):
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
def _send(self, code: int, body: bytes, ctype='application/json; charset=utf-8'):
|
|
307
|
+
self.send_response(code)
|
|
308
|
+
self.send_header('content-type', ctype)
|
|
309
|
+
self.send_header('cache-control', 'no-store')
|
|
310
|
+
self.send_header('x-content-type-options', 'nosniff')
|
|
311
|
+
self.send_header('content-length', str(len(body)))
|
|
312
|
+
self.end_headers()
|
|
313
|
+
try:
|
|
314
|
+
self.wfile.write(body)
|
|
315
|
+
except Exception:
|
|
316
|
+
pass
|
|
317
|
+
|
|
318
|
+
def _json(self, obj, code=200):
|
|
319
|
+
self._send(code, json.dumps(obj, ensure_ascii=False).encode('utf-8'))
|
|
320
|
+
|
|
321
|
+
def _authed(self) -> bool:
|
|
322
|
+
u = urlparse(self.path)
|
|
323
|
+
if parse_qs(u.query).get('t', [''])[0] == TOKEN:
|
|
324
|
+
return True
|
|
325
|
+
return self.headers.get('x-token', '') == TOKEN
|
|
326
|
+
|
|
327
|
+
def do_GET(self):
|
|
328
|
+
u = urlparse(self.path)
|
|
329
|
+
if u.path in ('/', '/index.html'):
|
|
330
|
+
try:
|
|
331
|
+
body = open(HTML, 'rb').read()
|
|
332
|
+
except Exception:
|
|
333
|
+
body = b'<h1>index.html missing</h1>'
|
|
334
|
+
return self._send(200, body, 'text/html; charset=utf-8')
|
|
335
|
+
if u.path.startswith('/img/'):
|
|
336
|
+
if not self._authed():
|
|
337
|
+
return self._json({'error': 'bad token'}, 403)
|
|
338
|
+
item = IMAGES.get(u.path[5:])
|
|
339
|
+
if not item:
|
|
340
|
+
return self._json({'error': 'gone'}, 404)
|
|
341
|
+
return self._send(200, item[0], item[1])
|
|
342
|
+
if u.path == '/api/status':
|
|
343
|
+
if not self._authed():
|
|
344
|
+
return self._json({'error': 'bad token'}, 403)
|
|
345
|
+
return self._json({
|
|
346
|
+
'strata': up(STRATA + '/models'),
|
|
347
|
+
'toolkit': up(TOOLKIT + '/health', timeout=8),
|
|
348
|
+
'comfy': up(COMFY + '/system_stats', timeout=2),
|
|
349
|
+
'ollama': up(OLLAMA + '/api/tags'),
|
|
350
|
+
'ollama_rich': rich_ollama_up(),
|
|
351
|
+
})
|
|
352
|
+
if u.path == '/api/models':
|
|
353
|
+
if not self._authed():
|
|
354
|
+
return self._json({'error': 'bad token'}, 403)
|
|
355
|
+
ensure_rich_ollama(wait=6)
|
|
356
|
+
return self._json({'models': list_models()})
|
|
357
|
+
return self._json({'error': 'not found'}, 404)
|
|
358
|
+
|
|
359
|
+
def do_POST(self):
|
|
360
|
+
u = urlparse(self.path)
|
|
361
|
+
if not self._authed():
|
|
362
|
+
return self._json({'error': 'bad token'}, 403)
|
|
363
|
+
n = int(self.headers.get('content-length') or 0)
|
|
364
|
+
try:
|
|
365
|
+
body = json.loads(self.rfile.read(n) or b'{}')
|
|
366
|
+
except Exception:
|
|
367
|
+
body = {}
|
|
368
|
+
if u.path == '/api/chat':
|
|
369
|
+
return self._chat(body)
|
|
370
|
+
if u.path == '/api/image':
|
|
371
|
+
return self._image(body)
|
|
372
|
+
if u.path == '/api/start':
|
|
373
|
+
return self._json({'strata': ensure_strata(wait=int(body.get('wait') or 90)),
|
|
374
|
+
'comfy': ensure_comfy(wait=int(body.get('comfy_wait') or 60)),
|
|
375
|
+
'toolkit': ensure_toolkit()})
|
|
376
|
+
if u.path == '/api/start-bg':
|
|
377
|
+
start_strata_bg()
|
|
378
|
+
return self._json({'ok': True, 'starting': True})
|
|
379
|
+
if u.path == '/api/purge':
|
|
380
|
+
IMAGES.clear()
|
|
381
|
+
try:
|
|
382
|
+
for f in os.listdir(TMP):
|
|
383
|
+
if f.startswith('.'):
|
|
384
|
+
continue
|
|
385
|
+
os.remove(os.path.join(TMP, f))
|
|
386
|
+
except Exception:
|
|
387
|
+
pass
|
|
388
|
+
return self._json({'ok': True})
|
|
389
|
+
return self._json({'error': 'not found'}, 404)
|
|
390
|
+
|
|
391
|
+
# ── 统一 SSE 输出 ───────────────────────────────────────────────────────
|
|
392
|
+
def _sse_start(self):
|
|
393
|
+
self.send_response(200)
|
|
394
|
+
self.send_header('content-type', 'text/event-stream; charset=utf-8')
|
|
395
|
+
self.send_header('cache-control', 'no-store')
|
|
396
|
+
self.send_header('connection', 'close')
|
|
397
|
+
self.end_headers()
|
|
398
|
+
self.close_connection = True
|
|
399
|
+
|
|
400
|
+
def _sse(self, obj):
|
|
401
|
+
try:
|
|
402
|
+
self.wfile.write(('data: ' + json.dumps(obj, ensure_ascii=False) + '\n\n').encode('utf-8'))
|
|
403
|
+
self.wfile.flush()
|
|
404
|
+
except Exception:
|
|
405
|
+
pass
|
|
406
|
+
|
|
407
|
+
# ── 聊天 ────────────────────────────────────────────────────────────────
|
|
408
|
+
def _chat(self, body):
|
|
409
|
+
model = str(body.get('model') or '').strip()
|
|
410
|
+
messages = body.get('messages') or []
|
|
411
|
+
temperature = float(body.get('temperature', 0.8))
|
|
412
|
+
# 2026-12-02 主人反馈「输出只有 800,上下文太短」:默认拉到 3072/8192,页面可调
|
|
413
|
+
max_tokens = min(max(int(body.get('max_tokens') or 3072), 64), 8192)
|
|
414
|
+
num_ctx = min(max(int(body.get('num_ctx') or 8192), 2048), 32768)
|
|
415
|
+
top_p = float(body.get('top_p') or 0.95)
|
|
416
|
+
system = str(body.get('system') or '').strip()
|
|
417
|
+
if system:
|
|
418
|
+
messages = [{'role': 'system', 'content': system}] + list(messages)
|
|
419
|
+
info = find_model(model) or {}
|
|
420
|
+
|
|
421
|
+
# Strata 没起来:后台拉,立刻回话(以前这里同步等 240 秒 = 页面僵死)
|
|
422
|
+
if info.get('backend') == 'strata' and not up(STRATA + '/models'):
|
|
423
|
+
start_strata_bg()
|
|
424
|
+
self._sse_start()
|
|
425
|
+
self._sse({'starting': '正在启动本地大模型(35B,首次约 30~60 秒)…启动好后再发一次即可'})
|
|
426
|
+
self._sse({'done': True})
|
|
427
|
+
return
|
|
428
|
+
|
|
429
|
+
if info.get('backend') == 'ollama':
|
|
430
|
+
base = OLLAMA_RICH if info.get('store') == 'rich' else OLLAMA
|
|
431
|
+
if base == OLLAMA_RICH and not rich_ollama_up():
|
|
432
|
+
if not ensure_rich_ollama(wait=20):
|
|
433
|
+
self._sse_start()
|
|
434
|
+
self._sse({'error': '富模型库没起来(11435)'})
|
|
435
|
+
self._sse({'done': True})
|
|
436
|
+
return
|
|
437
|
+
return self._chat_ollama(base, model, messages, temperature, max_tokens, num_ctx, top_p)
|
|
438
|
+
return self._chat_strata(model, messages, temperature, max_tokens)
|
|
439
|
+
|
|
440
|
+
def _chat_ollama(self, base, model, messages, temperature, max_tokens, num_ctx=8192, top_p=0.95):
|
|
441
|
+
payload = {
|
|
442
|
+
'model': model,
|
|
443
|
+
'messages': messages,
|
|
444
|
+
'stream': True,
|
|
445
|
+
'think': False,
|
|
446
|
+
'options': {'temperature': temperature, 'num_predict': max_tokens,
|
|
447
|
+
'num_ctx': num_ctx, 'top_p': top_p, 'repeat_penalty': 1.05,
|
|
448
|
+
'keep_alive': 0},
|
|
449
|
+
}
|
|
450
|
+
req = urllib.request.Request(base + '/api/chat', data=json.dumps(payload).encode(),
|
|
451
|
+
headers={'content-type': 'application/json'})
|
|
452
|
+
self._sse_start()
|
|
453
|
+
try:
|
|
454
|
+
with urllib.request.urlopen(req, timeout=300) as r:
|
|
455
|
+
for raw in r: # NDJSON:一行一个事件
|
|
456
|
+
line = raw.decode('utf-8', 'ignore').strip()
|
|
457
|
+
if not line:
|
|
458
|
+
continue
|
|
459
|
+
try:
|
|
460
|
+
j = json.loads(line)
|
|
461
|
+
except Exception:
|
|
462
|
+
continue
|
|
463
|
+
if j.get('error'):
|
|
464
|
+
self._sse({'error': str(j['error'])})
|
|
465
|
+
break
|
|
466
|
+
msg = j.get('message') or {}
|
|
467
|
+
piece = msg.get('content') or ''
|
|
468
|
+
if msg.get('thinking'):
|
|
469
|
+
self._sse({'thinking': msg['thinking']})
|
|
470
|
+
if piece:
|
|
471
|
+
self._sse({'delta': piece})
|
|
472
|
+
if j.get('done'):
|
|
473
|
+
break
|
|
474
|
+
except Exception as e:
|
|
475
|
+
self._sse({'error': 'Ollama 连接中断:' + str(e)})
|
|
476
|
+
self._sse({'done': True})
|
|
477
|
+
|
|
478
|
+
def _chat_strata(self, model, messages, temperature, max_tokens):
|
|
479
|
+
payload = {
|
|
480
|
+
'model': model or 'qwen3.6-35b-a3b-ud-q4_k_xl',
|
|
481
|
+
'messages': messages,
|
|
482
|
+
'temperature': temperature,
|
|
483
|
+
'max_tokens': max_tokens,
|
|
484
|
+
'stream': True,
|
|
485
|
+
'enable_thinking': False,
|
|
486
|
+
'chat_template_kwargs': {'enable_thinking': False},
|
|
487
|
+
}
|
|
488
|
+
req = urllib.request.Request(STRATA + '/chat/completions',
|
|
489
|
+
data=json.dumps(payload).encode(),
|
|
490
|
+
headers={'content-type': 'application/json'})
|
|
491
|
+
self._sse_start()
|
|
492
|
+
try:
|
|
493
|
+
with urllib.request.urlopen(req, timeout=900) as r:
|
|
494
|
+
for raw in r:
|
|
495
|
+
line = raw.decode('utf-8', 'ignore').strip()
|
|
496
|
+
if not line:
|
|
497
|
+
continue
|
|
498
|
+
if line.startswith('data:'):
|
|
499
|
+
data = line[5:].strip()
|
|
500
|
+
if data == '[DONE]':
|
|
501
|
+
break
|
|
502
|
+
try:
|
|
503
|
+
j = json.loads(data)
|
|
504
|
+
except Exception:
|
|
505
|
+
continue
|
|
506
|
+
d = ((j.get('choices') or [{}])[0].get('delta') or {})
|
|
507
|
+
if d.get('content'):
|
|
508
|
+
self._sse({'delta': d['content']})
|
|
509
|
+
continue
|
|
510
|
+
# 兜底:整包 JSON(非流式)
|
|
511
|
+
try:
|
|
512
|
+
j = json.loads(line)
|
|
513
|
+
except Exception:
|
|
514
|
+
continue
|
|
515
|
+
c = (((j.get('choices') or [{}])[0].get('message') or {}).get('content')) or ''
|
|
516
|
+
if c:
|
|
517
|
+
self._sse({'delta': c})
|
|
518
|
+
except Exception as e:
|
|
519
|
+
self._sse({'error': 'Strata 连接中断:' + str(e)})
|
|
520
|
+
self._sse({'done': True})
|
|
521
|
+
|
|
522
|
+
# ── 生图 ────────────────────────────────────────────────────────────────
|
|
523
|
+
def _image(self, body):
|
|
524
|
+
# 22G 显存只够一个:35B 在跑就先让它停,图的权重才装得下
|
|
525
|
+
if up(STRATA + '/models'):
|
|
526
|
+
stop_strata()
|
|
527
|
+
r = ensure_toolkit()
|
|
528
|
+
if not r.get('ok'):
|
|
529
|
+
return self._json({'ok': False, 'error': r.get('error')})
|
|
530
|
+
if not ensure_comfy(wait=int(body.get('comfy_wait') or 120)):
|
|
531
|
+
return self._json({'ok': False, 'error': 'ComfyUI(8191) 没起来,见 logs/comfyui8191.log'})
|
|
532
|
+
os.makedirs(TMP, exist_ok=True)
|
|
533
|
+
out = os.path.join(TMP, uuid.uuid4().hex + '.png')
|
|
534
|
+
req = {'prompt': body.get('prompt') or '', 'model': body.get('model') or 'krea', 'out': out}
|
|
535
|
+
for k in ('width', 'height', 'steps', 'seed', 'cfg', 'guidance'):
|
|
536
|
+
if body.get(k):
|
|
537
|
+
req[k] = body[k]
|
|
538
|
+
if body.get('negative'):
|
|
539
|
+
req['negative'] = body['negative']
|
|
540
|
+
try:
|
|
541
|
+
j = http_json(TOOLKIT + '/image', req, timeout=2400)
|
|
542
|
+
except Exception as e:
|
|
543
|
+
return self._json({'ok': False, 'error': '出图请求失败:' + str(e)})
|
|
544
|
+
if not j.get('ok'):
|
|
545
|
+
return self._json({'ok': False, 'error': j.get('error') or '出图失败', 'hint': j.get('hint')})
|
|
546
|
+
p = j.get('out') or j.get('path') or out
|
|
547
|
+
try:
|
|
548
|
+
raw = open(p, 'rb').read()
|
|
549
|
+
except Exception:
|
|
550
|
+
return self._json({'ok': False, 'error': '出图失败:' + json.dumps(j, ensure_ascii=False)[:200]})
|
|
551
|
+
key = uuid.uuid4().hex
|
|
552
|
+
IMAGES[key] = (raw, 'image/png')
|
|
553
|
+
try:
|
|
554
|
+
os.remove(p)
|
|
555
|
+
except Exception:
|
|
556
|
+
pass
|
|
557
|
+
return self._json({'ok': True, 'url': '/img/' + key, 'ms': j.get('ms')})
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def main():
|
|
561
|
+
ap = argparse.ArgumentParser()
|
|
562
|
+
ap.add_argument('--port', type=int, default=8196)
|
|
563
|
+
ap.add_argument('--open', action='store_true', help='启动后自动打开浏览器')
|
|
564
|
+
a = ap.parse_args()
|
|
565
|
+
os.makedirs(TMP, exist_ok=True)
|
|
566
|
+
url = 'http://127.0.0.1:%d/?t=%s' % (a.port, TOKEN)
|
|
567
|
+
srv = ThreadingHTTPServer(('127.0.0.1', a.port), Handler)
|
|
568
|
+
srv.daemon_threads = True
|
|
569
|
+
print('保密窗口:' + url, flush=True)
|
|
570
|
+
if a.open:
|
|
571
|
+
try:
|
|
572
|
+
os.startfile(url)
|
|
573
|
+
except Exception:
|
|
574
|
+
pass
|
|
575
|
+
try:
|
|
576
|
+
srv.serve_forever()
|
|
577
|
+
except KeyboardInterrupt:
|
|
578
|
+
pass
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
if __name__ == '__main__':
|
|
582
|
+
sys.exit(main())
|