@mcviseron/dsh-qq-bridge 0.2.1 → 0.3.0

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/lib/install.js ADDED
@@ -0,0 +1,324 @@
1
+ /**
2
+ * 一键把机器人运行环境装好:找系统 Python → 建 venv → 装依赖 → 复制随包代码 →
3
+ * 写配置 → 拉起守护进程。只用 Node 标准库,Windows / macOS / Linux 通用。
4
+ * 安装器不认识设置面板,只认参数与回调,方便离线测试。
5
+ */
6
+ import { spawn } from 'node:child_process'
7
+ import { cp, mkdir, readFile, stat, writeFile } from 'node:fs/promises'
8
+ import { join, relative, resolve, sep } from 'node:path'
9
+
10
+ export const STEPS = ['查找 Python', '创建 venv', '安装依赖', '复制机器人代码', '写入配置', '启动守护进程']
11
+
12
+ /** 复制代码时跳过的目录 / 文件:机器人的状态与凭据不进安装目录。 */
13
+ const SKIP_DIRS = new Set(['state', 'logs', '__pycache__', '.pytest_cache', '.git', '.idea', '.vscode'])
14
+ // .env 里是 AppID / AppSecret,绝不能随包或进安装目录
15
+ const SKIP_FILES = new Set(['config.json', '.env', 'state.json', 'groups.json', 'members.json', 'store.json'])
16
+
17
+ const REQUIREMENTS = ['aiohttp>=3.7,<4', 'Pillow>=10', 'viseron-qqbotpy>=0.4.4']
18
+ const MIRROR = 'https://pypi.tuna.tsinghua.edu.cn/simple'
19
+ const ALIYUN = 'https://mirrors.aliyun.com/pypi/simple'
20
+
21
+ /** 跑一条外部命令,把 stdout/stderr 合并返回;失败时把尾部输出带进错误。 */
22
+ export function runCommand(command, args, options = {}) {
23
+ return new Promise((done, fail) => {
24
+ let output = ''
25
+ let settled = false
26
+ const settle = (error, value) => {
27
+ if (settled) return
28
+ settled = true
29
+ clearTimeout(timer)
30
+ if (error) fail(error)
31
+ else done(value)
32
+ }
33
+ const child = spawn(command, args, { cwd: options.cwd, windowsHide: true, shell: false })
34
+ const timer = setTimeout(() => {
35
+ child.kill()
36
+ settle(new Error(`${command} 超时(${options.timeoutMs ?? 120000}ms)`))
37
+ }, options.timeoutMs ?? 120000)
38
+ const collect = (chunk) => {
39
+ const text = chunk.toString()
40
+ output += text
41
+ if (output.length > 12000) output = output.slice(-12000)
42
+ options.onText?.(text)
43
+ }
44
+ child.stdout?.on('data', collect)
45
+ child.stderr?.on('data', collect)
46
+ child.once('error', (error) => settle(new Error(`${command} 启动失败:${error.message}`)))
47
+ child.once('close', (code) => {
48
+ if (code === 0) settle(undefined, output)
49
+ else settle(new Error(`${command} ${args.join(' ')} 退出码 ${code}:${output.trim().slice(-600)}`))
50
+ })
51
+ })
52
+ }
53
+
54
+ /** venv 里的解释器路径。 */
55
+ export function venvPython(venvDir) {
56
+ return process.platform === 'win32' ? join(venvDir, 'Scripts', 'python.exe') : join(venvDir, 'bin', 'python')
57
+ }
58
+
59
+ /** 已安装记录(install.json),没有就是 undefined。 */
60
+ export async function readInstall(dataDir) {
61
+ try {
62
+ const parsed = JSON.parse(await readFile(join(dataDir, 'install.json'), 'utf8'))
63
+ if (parsed !== null && typeof parsed === 'object') return parsed
64
+ } catch {
65
+ // 没装过 / 文件坏了都按未安装处理
66
+ }
67
+ return undefined
68
+ }
69
+
70
+ async function exists(path) {
71
+ try {
72
+ await stat(path)
73
+ return true
74
+ } catch {
75
+ return false
76
+ }
77
+ }
78
+
79
+ export class Installer {
80
+ #dataDir
81
+ /** 随包机器人源码目录(可先留空,安装前再解析)。 */
82
+ sourceDir
83
+ #log
84
+ #run
85
+ #launch
86
+ #busy = false
87
+ #installed
88
+ #state
89
+
90
+ /**
91
+ * @param {{dataDir: string, sourceDir: string, log?: (line: string) => void,
92
+ * run?: typeof runCommand, launch?: (pythonPath: string, botDir: string) => Promise<number|undefined>}} options
93
+ */
94
+ constructor({ dataDir, sourceDir, log = () => {}, run = runCommand, launch }) {
95
+ this.#dataDir = dataDir
96
+ this.sourceDir = sourceDir
97
+ this.#log = log
98
+ this.#run = run
99
+ this.#launch = launch
100
+ this.botDir = join(dataDir, 'bot')
101
+ this.venvDir = join(dataDir, 'venv')
102
+ this.pythonPath = venvPython(this.venvDir)
103
+ // 注意:这里不能叫 ok —— HTTP 回执里的 ok 是"请求成功",会被这个字段覆盖成 400
104
+ this.#state = { running: false, done: false, succeeded: false, step: -1, steps: STEPS, lines: [], error: '', botDir: this.botDir, pythonPath: this.pythonPath }
105
+ }
106
+
107
+ /** 当前安装状态(含历史日志行,供面板轮询)。 */
108
+ state() {
109
+ return { ...this.#state, lines: [...this.#state.lines], installed: this.#installed }
110
+ }
111
+
112
+ /** 已完成安装时返回记录,供自动启动复用。 */
113
+ async load() {
114
+ this.#installed = await readInstall(this.#dataDir)
115
+ return this.#installed
116
+ }
117
+
118
+ #say(line) {
119
+ const text = String(line).trim()
120
+ if (text === '') return
121
+ this.#state.lines.push(text)
122
+ if (this.#state.lines.length > 400) this.#state.lines.splice(0, this.#state.lines.length - 400)
123
+ this.#log(text)
124
+ }
125
+
126
+ /** 后台开始安装;重复点击不会并行跑第二份。 */
127
+ start(options = {}) {
128
+ if (this.#busy) return { ok: true, alreadyRunning: true, state: this.state() }
129
+ this.#busy = true
130
+ this.#state = { ...this.#state, running: true, done: false, succeeded: false, step: 0, lines: [], error: '' }
131
+ void this.#runAll(options)
132
+ return { ok: true, started: true, state: this.state() }
133
+ }
134
+
135
+ async #runAll({ appid = '', appsecret = '', autoGroupRoot = '', bridgeUrl = '', bridgeToken = '' } = {}) {
136
+ try {
137
+ const python = await this.#step(0, () => this.#findPython())
138
+ const venv = await this.#step(1, () => this.#ensureVenv(python))
139
+ await this.#step(2, () => this.#installDeps(venv))
140
+ await this.#step(3, () => this.#copySources())
141
+ await this.#step(4, () => this.#writeConfig({ appid, appsecret, autoGroupRoot, bridgeUrl, bridgeToken }))
142
+ const record = await this.#step(5, () => this.#record(python))
143
+ this.#installed = record
144
+ this.#state = { ...this.#state, running: false, done: true, succeeded: true, step: STEPS.length }
145
+ this.#say('安装完成:机器人目录 ' + this.botDir)
146
+ } catch (error) {
147
+ const message = error instanceof Error ? error.message : String(error)
148
+ this.#state = { ...this.#state, running: false, done: true, succeeded: false, error: message }
149
+ this.#say('安装失败:' + message)
150
+ } finally {
151
+ this.#busy = false
152
+ }
153
+ }
154
+
155
+ async #step(index, work) {
156
+ this.#state = { ...this.#state, step: index }
157
+ this.#say('▶ ' + STEPS[index])
158
+ return await work()
159
+ }
160
+
161
+ /** 找一个 3.10+ 的解释器(py 启动器优先,其次 PATH 里的 python)。 */
162
+ async #findPython() {
163
+ const candidates = process.platform === 'win32'
164
+ ? [['py', '-3.12'], ['py', '-3.11'], ['py', '-3'], ['python'], ['python3']]
165
+ : [['python3'], ['python']]
166
+ const probe = 'import sys;print("%d.%d" % sys.version_info[:2])'
167
+ for (const candidate of candidates) {
168
+ const [command, ...args] = candidate
169
+ const label = [command, ...args].join(' ')
170
+ try {
171
+ const output = await this.#run(command, [...args, '-c', probe], { timeoutMs: 20000 })
172
+ const match = /^(\d+)\.(\d+)/m.exec(output.trim())
173
+ if (match === null) continue
174
+ const version = Number(match[1]) + Number(match[2]) / 100
175
+ if (Number(match[1]) === 3 && Number(match[2]) >= 10) {
176
+ this.#say(`用 ${label}(Python ${match[1]}.${match[2]})`)
177
+ return { command, args, label, max: String(match[1]) + '.' + String(match[2]) }
178
+ }
179
+ this.#say(`${label} 是 Python ${match[1]}.${match[2]},需要 3.10+`)
180
+ } catch (error) {
181
+ this.#say(`${label} 不可用`)
182
+ }
183
+ }
184
+ throw new Error('没找到 Python 3.10+。装个 Python 3.12(https://www.python.org/downloads/,勾选 Add to PATH)后再点一次。')
185
+ }
186
+
187
+ /** 建(或复用)venv;返回 venv 解释器路径。 */
188
+ async #ensureVenv(python) {
189
+ if (await exists(this.pythonPath)) {
190
+ this.#say('venv 已存在,直接复用:' + this.venvDir)
191
+ return this.pythonPath
192
+ }
193
+ await mkdir(this.#dataDir, { recursive: true })
194
+ await this.#run(python.command, [...python.args, '-m', 'venv', this.venvDir], { timeoutMs: 180000, onText: (text) => this.#say(text) })
195
+ if (!(await exists(this.pythonPath))) throw new Error('venv 建好了但找不到 ' + this.pythonPath)
196
+ this.#say('venv 就绪:' + this.pythonPath)
197
+ return this.pythonPath
198
+ }
199
+
200
+ /** pip 装 aiohttp / Pillow / viseron-qqbotpy:配置源 → 清华 → 阿里云,每个源都有硬超时。 */
201
+ async #installDeps(pythonPath) {
202
+ // 顺序有讲究:配置源最常见就是清华/阿里,所以第二、三个用彼此不同的镜像再兜一遍
203
+ const sources = [
204
+ { label: 'pip 配置的源', extra: [] },
205
+ { label: '阿里云镜像', extra: ['-i', ALIYUN] },
206
+ { label: '清华镜像', extra: ['-i', MIRROR] },
207
+ ]
208
+ for (const source of sources) {
209
+ this.#say('尝试安装源:' + source.label)
210
+ try {
211
+ // -u 让 pip 的输出实时流到面板;每个源 4 分钟封顶,卡住就换下一个,不会无限等
212
+ await this.#run(
213
+ pythonPath,
214
+ ['-u', '-m', 'pip', 'install', '--disable-pip-version-check', '--no-input', '--progress-bar', 'off',
215
+ '--timeout', '20', '--retries', '1', ...source.extra, ...REQUIREMENTS],
216
+ { timeoutMs: 240000, onText: (text) => this.#say(text) },
217
+ )
218
+ this.#say('依赖安装完成(' + source.label + ')')
219
+ break
220
+ } catch (error) {
221
+ this.#say('这个源没装上:' + (error instanceof Error ? error.message.split('\n')[0] : String(error)))
222
+ if (source === sources[sources.length - 1]) throw new Error('三个安装源都没成功,检查网络后重试(或手动在 venv 里 pip install)')
223
+ }
224
+ }
225
+ // 机器人自己 import 的是 viseron_qqbotpy(PyPI 包名 viseron-qqbotpy),不是 botpy
226
+ await this.#run(pythonPath, ['-c', 'import aiohttp, PIL, viseron_qqbotpy; print("deps ok")'], { timeoutMs: 30000 })
227
+ .then(() => this.#say('依赖自检通过(aiohttp / Pillow / viseron_qqbotpy)'))
228
+ .catch(() => this.#say('依赖自检没通过,机器人启动时可能报错'))
229
+ }
230
+
231
+ /** 把随包的 bot/ 复制到安装目录(跳过状态与凭据)。 */
232
+ async #copySources() {
233
+ if (!(await exists(this.sourceDir))) throw new Error('找不到随包的机器人代码:' + this.sourceDir)
234
+ await mkdir(this.botDir, { recursive: true })
235
+ let copied = 0
236
+ await cp(this.sourceDir, this.botDir, {
237
+ recursive: true,
238
+ force: true,
239
+ filter: (source) => {
240
+ const parts = relative(this.sourceDir, source).split(sep)
241
+ if (parts[0] === '') return true
242
+ if (parts.some((part) => SKIP_DIRS.has(part))) return false
243
+ if (SKIP_FILES.has(parts[parts.length - 1])) return false
244
+ copied += 1
245
+ return true
246
+ },
247
+ })
248
+ this.#say(`已复制 ${copied} 项到 ${this.botDir}`)
249
+ }
250
+
251
+ /** 写 bot/config.json 与 bot/.env:面板可改的进 json,启动时读的进 .env。 */
252
+ async #writeConfig({ appid, appsecret, autoGroupRoot, bridgeUrl, bridgeToken }) {
253
+ // 面板回传的密钥是打码值(pHjC****N6),写进去等于没有,必须跳过
254
+ const clean = (value) => {
255
+ const text = typeof value === 'string' ? value.trim() : ''
256
+ return text.includes('****') ? '' : text
257
+ }
258
+ const realAppid = clean(appid)
259
+ const realSecret = clean(appsecret)
260
+ if ((typeof appid === 'string' && appid.trim() !== '') && realAppid === '') this.#say('AppID 是打码值,跳过写入')
261
+ if ((typeof appsecret === 'string' && appsecret.trim() !== '') && realSecret === '') this.#say('AppSecret 是打码值,跳过写入(请在设置里填真实值)')
262
+
263
+ const configPath = join(this.botDir, 'config.json')
264
+ let current = {}
265
+ try {
266
+ const parsed = JSON.parse(await readFile(configPath, 'utf8'))
267
+ if (parsed !== null && typeof parsed === 'object') current = parsed
268
+ } catch {
269
+ current = {}
270
+ }
271
+ if (realAppid !== '') current.appid = realAppid
272
+ if (realSecret !== '') current.appsecret = realSecret
273
+ if (typeof autoGroupRoot === 'string' && autoGroupRoot.trim() !== '') current.auto_group_root = autoGroupRoot.trim()
274
+ await writeFile(configPath, JSON.stringify(current, null, 2), 'utf8')
275
+ this.#say('配置已写入 ' + configPath)
276
+
277
+ // load_config() 只看 .env,config.json 是后来的覆盖;缺 .env 会直接 "APPID / APPSECRET missing"
278
+ const envPath = join(this.botDir, '.env')
279
+ const existing = {}
280
+ try {
281
+ for (const line of (await readFile(envPath, 'utf8')).split('\n')) {
282
+ const match = /^([A-Z_]+)=(.*)$/.exec(line.trim())
283
+ if (match !== null) existing[match[1]] = match[2]
284
+ }
285
+ } catch {
286
+ // 第一次安装没有 .env,按空处理
287
+ }
288
+ const env = { ...existing }
289
+ if (realAppid !== '') env.APPID = realAppid
290
+ if (realSecret !== '') env.APPSECRET = realSecret
291
+ if (typeof bridgeUrl === 'string' && bridgeUrl.trim() !== '') env.BRIDGE_URL = bridgeUrl.trim()
292
+ if (typeof bridgeToken === 'string' && bridgeToken.trim() !== '') env.BRIDGE_TOKEN = bridgeToken.trim()
293
+ env.QQ_SANDBOX = env.QQ_SANDBOX ?? '0'
294
+ const body = Object.entries(env).map(([key, value]) => key + '=' + value).join('\n') + '\n'
295
+ await writeFile(envPath, body, 'utf8')
296
+ this.#say('凭据已写入 ' + envPath + (realSecret === '' ? '(AppSecret 待填)' : ''))
297
+ }
298
+
299
+ /** 拉起守护进程并落 install.json。 */
300
+ async #record(python) {
301
+ const record = {
302
+ botDir: this.botDir,
303
+ pythonPath: this.pythonPath,
304
+ basePython: python.label,
305
+ pythonVersion: python.max,
306
+ installedAt: new Date().toISOString(),
307
+ }
308
+ await writeFile(join(this.#dataDir, 'install.json'), JSON.stringify(record, null, 2), 'utf8')
309
+ if (typeof this.#launch === 'function') {
310
+ const pid = await this.#launch(this.pythonPath, this.botDir)
311
+ this.#say(pid === undefined ? '守护进程已申请启动' : `守护进程已启动(pid ${pid})`)
312
+ }
313
+ return record
314
+ }
315
+ }
316
+
317
+ /** 随包源码在哪:发布包里是 <plugin>/bot,开发仓库里是 <repo>/bot。 */
318
+ export async function resolveSourceDir(pluginRoot) {
319
+ const packaged = resolve(pluginRoot, 'bot')
320
+ if (await exists(join(packaged, 'main.py'))) return packaged
321
+ const dev = resolve(pluginRoot, '..', 'bot')
322
+ if (await exists(join(dev, 'main.py'))) return dev
323
+ return packaged
324
+ }
package/lib/server.js CHANGED
@@ -7,7 +7,7 @@ import { createServer } from 'node:http'
7
7
 
8
8
  const MAX_BODY_BYTES = 1 << 20
9
9
  const LOOPBACK = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])
10
- const ROUTES = new Set(['health', 'status', 'pull', 'inbound', 'approval', 'reset', 'switch', 'sessions', 'judge', 'permission', 'rebind', 'commands', 'command', 'answer'])
10
+ const ROUTES = new Set(['health', 'status', 'pull', 'inbound', 'approval', 'reset', 'switch', 'sessions', 'judge', 'permission', 'rebind', 'commands', 'command', 'answer', 'install'])
11
11
 
12
12
  /** Write one JSON response. */
13
13
  function respond(res, status, value) {
@@ -16,6 +16,10 @@ function respond(res, status, value) {
16
16
  'content-type': 'application/json; charset=utf-8',
17
17
  'content-length': body.length,
18
18
  'cache-control': 'no-store',
19
+ // 设置面板跑在 DSH GUI 的源上,跨源读回执需要这几个头
20
+ 'access-control-allow-origin': '*',
21
+ 'access-control-allow-headers': 'content-type,x-bridge-token,x-qqbridge-install',
22
+ 'access-control-allow-methods': 'GET,POST,OPTIONS',
19
23
  })
20
24
  res.end(body)
21
25
  }
@@ -133,13 +137,21 @@ export class HttpBridge {
133
137
  respond(res, 403, { ok: false, error: 'loopback only' })
134
138
  return
135
139
  }
136
- if (this.token !== '' && req.headers['x-bridge-token'] !== this.token) {
140
+ const url = new URL(req.url ?? '/', `http://${this.host}:${this.port}`)
141
+ const path = url.pathname.replace(/^\/+|\/+$/g, '')
142
+
143
+ // 预检不带 token,必须在鉴权之前回
144
+ if (req.method === 'OPTIONS') {
145
+ respond(res, 204, { ok: true })
146
+ return
147
+ }
148
+ // install 由设置面板直接调用:需要自定义请求头(浏览器会先发预检),
149
+ // 但不带 bridge token —— 端口本身只监听回环,且它只做"本地建环境"这一件事
150
+ const installCall = path === 'install' && req.headers['x-qqbridge-install'] === '1'
151
+ if (!installCall && this.token !== '' && req.headers['x-bridge-token'] !== this.token) {
137
152
  respond(res, 401, { ok: false, error: 'bad token' })
138
153
  return
139
154
  }
140
-
141
- const url = new URL(req.url ?? '/', `http://${this.host}:${this.port}`)
142
- const path = url.pathname.replace(/^\/+|\/+$/g, '')
143
155
  if (!ROUTES.has(path)) {
144
156
  respond(res, 404, { ok: false, error: 'unknown route' })
145
157
  return
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcviseron/dsh-qq-bridge",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "DeepSeek Harness plugin: bridge QQ conversations (driven by an external viseron-botpy bot) to DSH sessions — injects user messages, captures assistant replies, streams C2C answers, and relays tool approvals to the bot owner.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -13,9 +13,13 @@
13
13
  },
14
14
  "files": [
15
15
  "lib",
16
+ "bot",
16
17
  "cordis.patch.yml",
17
18
  "README.md"
18
19
  ],
20
+ "scripts": {
21
+ "prepack": "node scripts/pack-bot.mjs"
22
+ },
19
23
  "repository": {
20
24
  "type": "git",
21
25
  "url": "git+https://github.com/MCviseron/dsh-qqbot-bridge.git"