@mcviseron/dsh-qq-bridge 0.3.11 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/bot/main.py +26 -0
  2. package/lib/index.js +73 -24
  3. package/package.json +1 -1
package/bot/main.py CHANGED
@@ -31,6 +31,24 @@ from viseron_qqbotpy import configure_logging, load_env, get_logger, load_panels
31
31
 
32
32
  from bridge import BridgeClient, BridgeError, download_image
33
33
 
34
+
35
+ def _ensure_std_streams() -> None:
36
+ """pythonw 启动时没有控制台,sys.stdout/stderr 是 None,print 会直接抛错。"""
37
+ if sys.stdout is not None and sys.stderr is not None:
38
+ return
39
+ try:
40
+ log_dir = Path(__file__).resolve().parent / "state"
41
+ log_dir.mkdir(parents=True, exist_ok=True)
42
+ stream = open(log_dir / "stdout.log", "a", encoding="utf-8", buffering=1)
43
+ except OSError:
44
+ stream = open(os.devnull, "w", encoding="utf-8")
45
+ if sys.stdout is None:
46
+ sys.stdout = stream
47
+ if sys.stderr is None:
48
+ sys.stderr = stream
49
+
50
+
51
+ _ensure_std_streams()
34
52
  ROOT = Path(__file__).resolve().parent
35
53
  # 机器人本身是无窗运行的;它再拉 tasklist / taskkill 时如果没带这个标志,Windows 会
36
54
  # 给它分配一个新控制台(Win11 上就是弹出的 Windows Terminal 窗口),所以统一带上。
@@ -4145,6 +4163,14 @@ def _heartbeat() -> None:
4145
4163
 
4146
4164
  def run_bot() -> int:
4147
4165
  """One bot process, no supervision."""
4166
+ # 单实例:两个 bot 同时连同一个 AppID,QQ 的每条消息会被它们各自回一遍
4167
+ # (实测一条消息回 6 条就是这么来的)。pid 文件里那个还活着就直接退出。
4168
+ existing = _read_pid(CHILD_PID)
4169
+ if existing and existing != os.getpid() and _alive(existing):
4170
+ print(f"[bot] already running as pid={existing}; exiting", flush=True)
4171
+ return 0
4172
+ _write_pid(CHILD_PID, os.getpid())
4173
+
4148
4174
  from dataclasses import replace as dataclass_replace
4149
4175
 
4150
4176
  from runtime_config import RuntimeConfig
package/lib/index.js CHANGED
@@ -114,6 +114,73 @@ export function apply(ctx, rawConfig) {
114
114
  const approvals = new Map()
115
115
  /** Sessions this process already applied the model selection to. */
116
116
  const selected = new Set()
117
+ // 每个 Session 只塞一次人设:新会话、以及 /新会话|/分组 这类由 rebind 建出来的会话
118
+ // 都算「没收到过」,否则 rebind 建完再发消息时 freshSession 已是 false,人设永远不生效。
119
+ const personaSent = new Set()
120
+
121
+ // 拉起机器人 supervisor。Windows 上必须完全没有控制台窗口:
122
+ // python.exe 是控制台程序,detached 时 CREATE_NO_WINDOW 会被忽略,用户就会看到黑窗、
123
+ // 关掉窗等于把机器人杀了。所以优先用 pythonw.exe(GUI 子系统,没有控制台可弹);
124
+ // pythonw 下 sys.stdout 是 None 会让 print 抛错,因此用 pipe 接管输出写进这里。
125
+ // 机器人自己会写 <botDir>/state/{supervisor,child}.pid;这两个还活着就不要再拉一个,
126
+ // 否则两个进程同时连同一个 AppID,一条消息会被回多遍(实测回过 6 条)。
127
+ const botAlreadyRunning = async (botDir) => {
128
+ const fs = await import('node:fs')
129
+ const { join } = await import('node:path')
130
+ for (const name of ['supervisor.pid', 'child.pid']) {
131
+ let pid = 0
132
+ try {
133
+ pid = Number.parseInt(fs.readFileSync(join(botDir, 'state', name), 'utf8').trim(), 10)
134
+ } catch (error) {
135
+ continue
136
+ }
137
+ if (!Number.isInteger(pid) || pid <= 0) continue
138
+ try {
139
+ process.kill(pid, 0)
140
+ return pid
141
+ } catch (error) {
142
+ continue
143
+ }
144
+ }
145
+ return 0
146
+ }
147
+
148
+ const spawnSupervisor = async (pythonPath, botDir) => {
149
+ const { spawn } = await import('node:child_process')
150
+ const fs = await import('node:fs')
151
+ const { join } = await import('node:path')
152
+ const running = await botAlreadyRunning(botDir)
153
+ if (running !== 0) {
154
+ log(`bot already running (pid ${running}); skip spawn`)
155
+ return { pid: running, reused: true }
156
+ }
157
+ let exe = pythonPath
158
+ if (/python\.exe$/i.test(pythonPath)) {
159
+ const pyw = pythonPath.replace(/python\.exe$/i, 'pythonw.exe')
160
+ if (fs.existsSync(pyw)) exe = pyw
161
+ }
162
+ // 子进程的 stdout/stderr 指到一个日志文件句柄:句柄有效(pythonw 下 print 不会因
163
+ // sys.stdout 为 None 崩),父进程退出不会留下断掉的管道,而且 pythonw 没有控制台可弹。
164
+ let fd = -1
165
+ try {
166
+ fs.mkdirSync(config.dataDir, { recursive: true })
167
+ fd = fs.openSync(join(config.dataDir, 'supervisor.log'), 'a')
168
+ } catch (error) {
169
+ fd = -1
170
+ }
171
+ const child = spawn(exe, ['-u', 'main.py', '--supervise'], {
172
+ cwd: botDir,
173
+ detached: true,
174
+ windowsHide: true,
175
+ stdio: fd >= 0 ? ['ignore', fd, fd] : 'ignore',
176
+ })
177
+ if (fd >= 0) {
178
+ try { fs.closeSync(fd) } catch (error) { /* child 已继承句柄 */ }
179
+ }
180
+ child.on('error', (error) => log(`bot supervisor spawn failed: ${error.message}`))
181
+ child.unref()
182
+ return child
183
+ }
117
184
  /** Last time the bot long-polled us; approvals go to QQ only while this is fresh. */
118
185
  let lastPullAt = 0
119
186
 
@@ -128,16 +195,7 @@ export function apply(ctx, rawConfig) {
128
195
  sourceDir: join(pluginRoot, 'bot'),
129
196
  log,
130
197
  launch: async (pythonPath, botDir) => {
131
- const { spawn } = await import('node:child_process')
132
- const child = spawn(pythonPath, ['-u', 'main.py', '--supervise'], {
133
- cwd: botDir,
134
- detached: true,
135
- stdio: 'ignore',
136
- windowsHide: true,
137
- creationflags: process.platform === 'win32' ? 0x08000000 : 0,
138
- })
139
- child.on('error', (error) => log(`bot supervisor spawn failed: ${error.message}`))
140
- child.unref()
198
+ const child = await spawnSupervisor(pythonPath, botDir)
141
199
  log(`bot supervisor spawned after install (pid ${child.pid})`)
142
200
  return child.pid
143
201
  },
@@ -527,8 +585,10 @@ export function apply(ctx, rawConfig) {
527
585
  selected.add(sessionId)
528
586
  }
529
587
 
530
- // 人设随请求带过来;只有刚建的新会话才塞进提示词,之后不再重复
531
- const persona = freshSession && typeof body?.persona === 'string' ? body.persona : ''
588
+ // 人设随请求带过来;这个 Session 还没收到过就塞进提示词,之后不再重复
589
+ const wantsPersona = typeof body?.persona === 'string' && body.persona.trim() !== '' && !personaSent.has(sessionId)
590
+ if (wantsPersona) personaSent.add(sessionId)
591
+ const persona = wantsPersona ? body.persona : ''
532
592
  const content = [{ type: 'text', text: composePrompt({ text, convKey, senderName, isOwner: body?.isOwner === true, chime: body?.chime === true, quote, persona }) }]
533
593
  for (const image of images.slice(0, 4)) {
534
594
  const mediaType = typeof image?.mediaType === 'string' ? image.mediaType : ''
@@ -829,18 +889,7 @@ export function apply(ctx, rawConfig) {
829
889
  log(`bot autostart skipped: 解释器不存在 ${pythonPath}`)
830
890
  return
831
891
  }
832
- const { spawn } = await import('node:child_process')
833
- const child = spawn(pythonPath, ['-u', 'main.py', '--supervise'], {
834
- cwd: botDir,
835
- detached: true,
836
- stdio: 'ignore',
837
- windowsHide: true,
838
- // detached 会在 Windows 上给子进程一个新控制台,windowsHide 压不住它:
839
- // 用户会看到一个黑窗口,关掉它就等于把机器人杀了。CREATE_NO_WINDOW 才真正无窗。
840
- creationflags: process.platform === 'win32' ? 0x08000000 : 0,
841
- })
842
- child.on('error', (error) => log(`bot autostart failed: ${error.message}`))
843
- child.unref()
892
+ const child = await spawnSupervisor(pythonPath, botDir)
844
893
  log(`bot supervisor spawned (pid ${child.pid})`)
845
894
  } catch (error) {
846
895
  log(`bot autostart failed: ${error instanceof Error ? error.message : String(error)}`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcviseron/dsh-qq-bridge",
3
- "version": "0.3.11",
3
+ "version": "0.3.13",
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",