@linjz/opencode-qqbot 0.3.15 → 0.3.16

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 (50) hide show
  1. package/README.md +42 -5
  2. package/bin/openqq.js +13 -0
  3. package/dist/notify-cli.js +28 -14
  4. package/dist/opencode-qqbot-plugin.js +934 -64
  5. package/dist/openqq-bot.js +3095 -677
  6. package/dist/openqq-cli.js +791 -0
  7. package/dist/openqq-watchdog.js +1063 -0
  8. package/package.json +8 -5
  9. package/src/bridge.ts +1310 -150
  10. package/src/cli/notify.ts +167 -158
  11. package/src/cli/openqq-main.ts +95 -0
  12. package/src/cli/service-main.ts +302 -0
  13. package/src/cli/watchdog-main.ts +77 -0
  14. package/src/commands.ts +644 -554
  15. package/src/config.ts +85 -0
  16. package/src/core/bot-control.ts +148 -0
  17. package/src/core/bot-launcher.ts +106 -13
  18. package/src/core/card-approval.ts +20 -9
  19. package/src/core/delivery.ts +145 -54
  20. package/src/core/discovery.ts +22 -4
  21. package/src/core/file-log.ts +35 -3
  22. package/src/core/form-bridge.ts +14 -5
  23. package/src/core/form-journal.ts +4 -4
  24. package/src/core/gateway-state.ts +3 -3
  25. package/src/core/inflight-journal.ts +214 -36
  26. package/src/core/instance-lock.ts +10 -2
  27. package/src/core/linkwatch.ts +3 -4
  28. package/src/core/markdown.ts +117 -0
  29. package/src/core/message-queue.ts +242 -91
  30. package/src/core/mirror.ts +222 -182
  31. package/src/core/notify-sink.ts +93 -96
  32. package/src/core/outbox.ts +10 -9
  33. package/src/core/permission.ts +627 -303
  34. package/src/core/question-form.ts +230 -0
  35. package/src/core/queue-view.ts +661 -0
  36. package/src/core/send-media.ts +32 -0
  37. package/src/core/storage.ts +34 -0
  38. package/src/core/watchdog.ts +513 -0
  39. package/src/core/zombie-reaper.ts +127 -0
  40. package/src/index.ts +140 -52
  41. package/src/opencode/client.ts +206 -27
  42. package/src/opencode/eventstream.ts +94 -12
  43. package/src/opencode/history.ts +4 -2
  44. package/src/opencode/mirror.ts +15 -2
  45. package/src/opencode/sessions.ts +135 -37
  46. package/src/plugin-entry.ts +120 -115
  47. package/src/qq/api.ts +165 -61
  48. package/src/qq/gateway.ts +79 -16
  49. package/src/qq/sender.ts +30 -18
  50. package/src/qq/types.ts +7 -0
package/src/config.ts CHANGED
@@ -19,6 +19,91 @@ export interface Config {
19
19
  allowedUsers: string[]
20
20
  }
21
21
 
22
+ /**
23
+ * 多角色(2026-11-17 owner 裁定:单进程挂多个 QQ bot 身份,参考 openclaw-qqbot
24
+ * 具名账号表)。一个 Role = 一个 appId 身份:自己的凭证/沙箱开关/白名单/
25
+ * 网关连接/数据分桶(~/.openqq/roles/<appId>/)。openid 按 app 隔离,
26
+ * 因此各角色的用户体系天然不相交。
27
+ */
28
+ export interface RoleConfig {
29
+ /** 角色名(日志前缀用,可选) */
30
+ name: string
31
+ appId: string
32
+ clientSecret: string
33
+ sandbox: boolean
34
+ allowedUsers: string[]
35
+ }
36
+
37
+ /**
38
+ * 解析多角色配置。来源:env QQ_BOTS(JSON 数组,见 parseRolesJson)。
39
+ * 未配置时回退 legacy 单角色(QQ_APP_ID/QQ_APP_SECRET/QQ_SANDBOX/ALLOWED_USERS),
40
+ * 行为与 2026-11-17 之前完全一致——存量部署零迁移。
41
+ * 多角色模式下 ALLOWED_USERS/QQ_SANDBOX/QQ_APP_* 只作兜底缺项,不再单独生效。
42
+ */
43
+ export function loadRoles(): RoleConfig[] {
44
+ const raw = (process.env.QQ_BOTS ?? "").trim()
45
+ if (raw) {
46
+ const roles = parseRolesJson(raw)
47
+ if (roles.length > 0) return roles
48
+ console.warn("[config] QQ_BOTS 配置存在但解析结果为空,回退 legacy 单角色模式")
49
+ }
50
+ const single = loadConfig()
51
+ return [{
52
+ name: single.qq.appId,
53
+ appId: single.qq.appId,
54
+ clientSecret: single.qq.clientSecret,
55
+ sandbox: single.qq.sandbox,
56
+ allowedUsers: single.allowedUsers,
57
+ }]
58
+ }
59
+
60
+ /**
61
+ * QQ_BOTS JSON 解析与校验(纯函数)。形态:
62
+ * [{"appId":"...","secret":"...","sandbox":false,"name":"开发角色","allowedUsers":["..."]}]
63
+ * 校验规则:必须是数组、每项必含非空 appId/secret;sandbox 默认 false;
64
+ * allowedUsers 默认 []; name 默认 appId。非法项跳过并 warn,全非法返回 []。
65
+ */
66
+ export function parseRolesJson(raw: string): RoleConfig[] {
67
+ let parsed: unknown
68
+ try {
69
+ parsed = JSON.parse(raw)
70
+ } catch {
71
+ console.warn("[config] QQ_BOTS 不是合法 JSON,已忽略")
72
+ return []
73
+ }
74
+ if (!Array.isArray(parsed)) {
75
+ console.warn("[config] QQ_BOTS 必须是数组,已忽略")
76
+ return []
77
+ }
78
+ const roles: RoleConfig[] = []
79
+ for (const [i, item] of parsed.entries()) {
80
+ const r = item as Partial<Record<"appId" | "secret" | "sandbox" | "name" | "allowedUsers", unknown>>
81
+ const appId = typeof r?.appId === "string" ? r.appId.trim() : ""
82
+ const secret = typeof r?.secret === "string" ? r.secret.trim() : ""
83
+ if (!appId || !secret) {
84
+ console.warn(`[config] QQ_BOTS[${i}] 缺少 appId/secret,已跳过`)
85
+ continue
86
+ }
87
+ const allowedUsers = Array.isArray(r?.allowedUsers)
88
+ ? r.allowedUsers.filter((u): u is string => typeof u === "string" && !!u.trim()).map((u) => u.trim())
89
+ : []
90
+ roles.push({
91
+ name: typeof r?.name === "string" && r.name.trim() ? r.name.trim() : appId,
92
+ appId,
93
+ clientSecret: secret,
94
+ sandbox: r?.sandbox === true,
95
+ allowedUsers,
96
+ })
97
+ }
98
+ // 同 appId 重复=配置错误,后者覆盖前者(日志可见),防双连接互踢
99
+ const seen = new Map<string, RoleConfig>()
100
+ for (const role of roles) {
101
+ if (seen.has(role.appId)) console.warn(`[config] QQ_BOTS 中 appId=${role.appId} 重复,后者覆盖前者`)
102
+ seen.set(role.appId, role)
103
+ }
104
+ return [...seen.values()]
105
+ }
106
+
22
107
  const CONFIG_DIR = join(homedir(), ".openqq")
23
108
  export const ENV_FILE = join(CONFIG_DIR, ".env")
24
109
 
@@ -0,0 +1,148 @@
1
+ // @input: ~/.openqq/.env、实例锁、在途台账、core/bot-launcher(运行时解析与 detached 拉起)、
2
+ // core/watchdog(superviseOnce 杀/拉唯一权威)
3
+ // @output: resolveInstalledBotEntry, readAppId, countInflight, waitUntilIdle, startBot, restartBot
4
+ // @pos: core - bot 生命周期控制(跨平台;替代 safe-restart.ps1 / start-openqq.ps1)
5
+ //
6
+ // 2026-11-09 架构红线:重启是运维代码,必须随插件包分发且跨平台。
7
+ // 单实例真相=锁文件 pid(不再按命令行正则枚举进程,避免 OS 命令与误杀)。
8
+ // 2026-11-10 design §3.9.1 归一:杀/拉唯一权威 = superviseOnce。restartBot 只是它的
9
+ // 调用方(等空闲 → 同一 grace-kill+spawn 原语 + supervisor.json 强度账 + 审计分家 +
10
+ // 认领互斥),本文件不再实现任何独立杀逻辑(原 stopLockedBot 已删除)。
11
+ import { existsSync, readFileSync } from "fs"
12
+ import { dirname, join } from "path"
13
+ import { homedir } from "os"
14
+ import { fileURLToPath } from "url"
15
+ import {
16
+ buildLaunchPlan,
17
+ botLogPath,
18
+ resolveRuntime,
19
+ spawnBotDetached,
20
+ } from "./bot-launcher.js"
21
+ import { botWatchdogPaths, superviseOnce } from "./watchdog.js"
22
+
23
+ /** 从任意入口文件定位同包内的 bot 产物:dist 同目录 → 包根 dist → dev 源码 */
24
+ export function resolveInstalledBotEntry(fromUrl: string, exists: (p: string) => boolean = existsSync): string | null {
25
+ const here = dirname(fileURLToPath(fromUrl))
26
+ const candidates = [
27
+ join(here, "openqq-bot.js"), // 打包后:dist/ 同级
28
+ join(here, "..", "dist", "openqq-bot.js"), // src/cli/ → 包根 dist/
29
+ join(here, "..", "src", "index.ts"), // dist/ → 包根 src/(dev)
30
+ join(here, "..", "..", "src", "index.ts"), // src/cli/ → src/index.ts(dev)
31
+ ]
32
+ for (const c of candidates) if (exists(c)) return c
33
+ return null
34
+ }
35
+
36
+ export function readAppId(envPath = join(homedir(), ".openqq", ".env")): string | null {
37
+ try {
38
+ for (const line of readFileSync(envPath, "utf-8").split("\n")) {
39
+ const t = line.trim()
40
+ if (!t || t.startsWith("#")) continue
41
+ const eq = t.indexOf("=")
42
+ if (eq > 0 && t.slice(0, eq).trim() === "QQ_APP_ID") return t.slice(eq + 1).trim() || null
43
+ }
44
+ } catch {
45
+ /* 无 .env */
46
+ }
47
+ return null
48
+ }
49
+
50
+ export function inflightPath(): string {
51
+ return join(homedir(), ".openqq", "inflight.json")
52
+ }
53
+
54
+ /** 在途回合数(safe-restart 的空闲判据:state=inflight 即算活跃) */
55
+ export function countInflight(path = inflightPath()): number {
56
+ try {
57
+ const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown
58
+ if (!Array.isArray(raw)) return 0
59
+ return raw.filter((e) => (e as { state?: string }).state === "inflight").length
60
+ } catch {
61
+ return 0
62
+ }
63
+ }
64
+
65
+ export async function waitUntilIdle(opts?: {
66
+ timeoutMs?: number
67
+ pollMs?: number
68
+ onWait?: (inflight: number, elapsedMs: number) => void
69
+ }): Promise<boolean> {
70
+ const timeoutMs = opts?.timeoutMs ?? 60 * 60_000
71
+ const pollMs = opts?.pollMs ?? 10_000
72
+ const started = Date.now()
73
+ for (;;) {
74
+ const n = countInflight()
75
+ if (n === 0) return true
76
+ const elapsed = Date.now() - started
77
+ if (elapsed >= timeoutMs) return false
78
+ opts?.onWait?.(n, elapsed)
79
+ await new Promise((r) => setTimeout(r, pollMs))
80
+ }
81
+ }
82
+
83
+ /** 按安装形态拉起 bot(detached,日志走 QQ_LOG_FILE) */
84
+ export function startBot(fromUrl: string, log: (line: string) => void = () => {}): number {
85
+ const entry = resolveInstalledBotEntry(fromUrl)
86
+ if (!entry) throw new Error("未找到 bot 入口(dist/openqq-bot.js 或 src/index.ts)——安装不完整")
87
+ const runtime = resolveRuntime()
88
+ if (!runtime) throw new Error("未找到 bun/node 运行时")
89
+ const plan = buildLaunchPlan(runtime, entry, botLogPath())
90
+ const pid = spawnBotDetached(plan)
91
+ log(`[bot-control] 已拉起 pid=${pid}(runtime=${runtime},entry=${entry})`)
92
+ return pid
93
+ }
94
+
95
+ export interface RestartOptions {
96
+ force?: boolean
97
+ timeoutMs?: number
98
+ spawnFromUrl: string
99
+ log?: (line: string) => void
100
+ }
101
+
102
+ export interface RestartResult {
103
+ action: "restarted" | "skipped"
104
+ killedPid: number | null
105
+ spawnedPid: number | null
106
+ reason: string
107
+ }
108
+
109
+ /**
110
+ * 安全重启:默认等空闲;-Force 跳过等待。跨平台,等价于旧 safe-restart.ps1。
111
+ * design §3.9.1 归一:杀/拉唯一权威 = superviseOnce(request=manual-restart)。
112
+ * 复用同一 grace-kill(TERM→宽限→KILL→确认死亡才拉)+ spawn 原语,
113
+ * 受 supervisor.json 强度账(15min/3 次 give-up、2min 冷却)与认领互斥约束,
114
+ * 审计分家(主动杀/验尸拉新)落 watchdog.log——restart 不再有独立杀逻辑。
115
+ */
116
+ export async function restartBot(opts: RestartOptions): Promise<RestartResult> {
117
+ const log = opts.log ?? (() => {})
118
+ const appId = readAppId()
119
+ if (!appId) throw new Error("缺少 ~/.openqq/.env 的 QQ_APP_ID,无法定位实例锁")
120
+ if (!opts.force) {
121
+ const idle = await waitUntilIdle({
122
+ timeoutMs: opts.timeoutMs,
123
+ onWait: (n, elapsed) => log(`[bot-control] 仍在途 ${n} 条(已等 ${Math.round(elapsed / 1000)}s),继续等待空闲`),
124
+ })
125
+ if (!idle) {
126
+ log("[bot-control] 等待空闲超时:本次不重启(需要时用 --force)")
127
+ return { action: "skipped", killedPid: null, spawnedPid: null, reason: "等待空闲超时" }
128
+ }
129
+ }
130
+ const r = await superviseOnce({
131
+ paths: botWatchdogPaths(appId),
132
+ request: "manual-restart",
133
+ spawn: () => startBot(opts.spawnFromUrl, log),
134
+ log,
135
+ })
136
+ switch (r.action) {
137
+ case "restart":
138
+ return { action: "restarted", killedPid: r.killedPid, spawnedPid: r.spawnedPid, reason: opts.force ? "force(经监督矩阵)" : "idle(经监督矩阵)" }
139
+ case "cooldown":
140
+ return { action: "skipped", killedPid: null, spawnedPid: null, reason: `监督矩阵冷却跳过:${r.detail}` }
141
+ case "give-up":
142
+ return { action: "skipped", killedPid: null, spawnedPid: null, reason: `监督矩阵 give-up:${r.detail}` }
143
+ case "yield":
144
+ return { action: "skipped", killedPid: null, spawnedPid: null, reason: `认领互斥:${r.detail}` }
145
+ default:
146
+ return { action: "skipped", killedPid: null, spawnedPid: null, reason: `无需动作:${r.detail}` }
147
+ }
148
+ }
@@ -6,8 +6,8 @@
6
6
  // 子进程脱离 serve 生命周期(serve 重载/重启不碰 bot)。运行时解析 bun→node:
7
7
  // bun 直接跑源码(.js→.ts 映射);node 跑发布时预打的 dist/openqq-bot.js bundle。
8
8
  import { spawn, spawnSync } from "child_process"
9
- import { existsSync, readFileSync } from "fs"
10
- import { join, dirname } from "path"
9
+ import { existsSync, readFileSync, statSync } from "fs"
10
+ import { join, dirname, isAbsolute } from "path"
11
11
  import { homedir } from "os"
12
12
 
13
13
  export type Runtime = "bun" | "node"
@@ -19,28 +19,107 @@ export function resolveRuntime(probe: (cmd: string) => boolean = defaultProbe):
19
19
  return null
20
20
  }
21
21
 
22
+ /**
23
+ * 文件系统可执行判定(2026-11-09 静默拉起缺陷修复):
24
+ * 存在于 PATH 的裸名(如 bun.cmd shim)经 CreateProcess 会退化为 cmd.exe /c 中转 →
25
+ * 弹出可见控制台窗口(Windows Terminal 宿主实证)。拉起命令一律归一为全路径。
26
+ * 纯 fs 判定,不 spawn 子进程——探测本身也不许有 cmd 中转副作用。
27
+ */
28
+ function isExecutable(p: string): boolean {
29
+ try {
30
+ const st = statSync(p)
31
+ return st.isFile() && (process.platform === "win32" || (st.mode & 0o111) !== 0)
32
+ } catch {
33
+ return false
34
+ }
35
+ }
36
+
37
+ /** 在 PATH 上定位可执行体并返回全路径;Windows 只认 .exe(.cmd/.bat 必经 cmd 中转,排除) */
38
+ export function locateOnPath(cmd: string, pathEnv = process.env.PATH ?? process.env.Path ?? ""): string | null {
39
+ if (isAbsolute(cmd)) return isExecutable(cmd) ? cmd : null
40
+ const isWin = process.platform === "win32"
41
+ for (const dir of pathEnv.split(isWin ? ";" : ":")) {
42
+ if (!dir) continue
43
+ const base = isWin && !/\.[a-z]+$/i.test(cmd) ? `${cmd}.exe` : cmd
44
+ const full = join(dir, base)
45
+ if (isExecutable(full)) return full
46
+ }
47
+ if (isWin) return resolveThroughShim(cmd, pathEnv)
48
+ return null
49
+ }
50
+
51
+ // 两种 npm shim exec 行形态:`%dp0%\x\y.exe`(npm 老式)与 `%~dp0\x\y.exe`(新式)。
52
+ // 注意:`~` 必须显式可选(%~?),写成 %~-?dp0 会让 ~ 变字面必选而漏掉 %dp0% 形态。
53
+ const SHIM_PATTERN_LINE = /%~?dp0%?\\?([^"\n]+?\.exe)/
54
+ const SHIM_PATTERN_ABS = /([A-Za-z]:\\[^\n"]+?\.exe)/
55
+
56
+ /**
57
+ * .cmd/.bat shim 反查真实 exe(2026-11-09 静默拉起缺陷):
58
+ * Windows 上 PATH 可能只有 bun.cmd(npm 全局 bin),裸名命中也必须取回真实
59
+ * bun.exe——从 shim 内容提取 %~dp0 相对或全路径,零进程、零 cmd 中转。
60
+ */
61
+ export function resolveThroughShim(bare: string, pathEnv = process.env.PATH ?? process.env.Path ?? ""): string | null {
62
+ for (const dir of pathEnv.split(";")) {
63
+ if (!dir) continue
64
+ for (const ext of [".cmd", ".bat"]) {
65
+ const shimPath = join(dir, bare + ext)
66
+ let text: string
67
+ try {
68
+ text = readFileSync(shimPath, "utf-8")
69
+ } catch {
70
+ continue
71
+ }
72
+ const rel = SHIM_PATTERN_LINE.exec(text)
73
+ if (rel) {
74
+ const full = join(dir, rel[1]!)
75
+ if (isExecutable(full)) return full
76
+ }
77
+ const abs = SHIM_PATTERN_ABS.exec(text)
78
+ if (abs) {
79
+ const full = abs[1]!
80
+ if (isExecutable(full)) return full
81
+ }
82
+ }
83
+ }
84
+ return null
85
+ }
86
+
22
87
  function bunCandidates(): string[] {
23
- const candidates = ["bun", "bun.exe", "bun.cmd", "bun.bat"]
24
88
  if (process.platform === "win32") {
25
89
  const appdata = process.env.APPDATA || join(homedir(), "AppData", "Roaming")
26
- candidates.push(join(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"))
27
- } else {
28
- candidates.push("/usr/local/bin/bun", "/opt/homebrew/bin/bun", join(homedir(), ".bun", "bin", "bun"))
90
+ // 全路径探测先行(bun.exe 直调),裸名 shim(bun.cmd/bun.bat)永不作为拉起命令
91
+ return [
92
+ join(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"),
93
+ join(homedir(), ".bun", "bin", "bun.exe"),
94
+ "bun",
95
+ "bun.exe",
96
+ ]
29
97
  }
30
- return candidates
98
+ return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun", join(homedir(), ".bun", "bin", "bun"), "bun"]
31
99
  }
32
100
 
33
- /** 解析可用 bun 命令(覆盖 npm 安装形态:PATH 上只有 bun.ps1,可执行体在包内) */
101
+ /** 解析可用 bun 命令。返回值恒为全路径可执行体(裸名经 locateOnPath 归一)。 */
34
102
  export function resolveBunCommand(probe: (cmd: string) => boolean = defaultProbe): string | null {
103
+ if (probe !== defaultProbe) {
104
+ // 注入契约(测试用):probe 决定可用性;裸名命中必须折算全路径(locate 失败时 shim 反查)
105
+ for (const c of bunCandidates()) {
106
+ if (!probe(c)) continue
107
+ if (isAbsolute(c)) return c
108
+ return locateOnPath(c) ?? resolveThroughShim(c) ?? null
109
+ }
110
+ return null
111
+ }
112
+ // 生产:纯 fs 判定——不 spawn 子进程(探测自身不许有 cmd 中转副作用),恒返回全路径
35
113
  for (const c of bunCandidates()) {
36
- if (probe(c)) return c
114
+ const full = locateOnPath(c) ?? (isAbsolute(c) ? null : resolveThroughShim(c))
115
+ if (full) return full
37
116
  }
38
117
  return null
39
118
  }
40
119
 
41
120
  function defaultProbe(cmd: string): boolean {
42
121
  try {
43
- const r = spawnSync(cmd, ["--version"], { stdio: "ignore" })
122
+ const r = spawnSync(cmd, ["--version"], { stdio: "ignore", windowsHide: true })
44
123
  return r.status === 0
45
124
  } catch {
46
125
  return false
@@ -54,6 +133,18 @@ export interface LaunchPlan {
54
133
  env: NodeJS.ProcessEnv
55
134
  }
56
135
 
136
+ /**
137
+ * 拉起命令全路径不变量(2026-11-09 静默拉起缺陷):
138
+ * Plan.command 必须是全路径可执行体——裸名(bun/node)在 Windows 上会命中 .cmd shim
139
+ * 或触发 cmd.exe 中转,弹出可见控制台窗口(Windows Terminal 宿主实证)。
140
+ * 解析失败即抛错,绝不回落裸名。
141
+ */
142
+ export function resolveRuntimeCommand(runtime: Runtime): string {
143
+ const cmd = runtime === "bun" ? resolveBunCommand() : locateOnPath("node")
144
+ if (!cmd) throw new Error(`未找到 ${runtime} 可执行体(全路径解析失败),拒绝生成裸名拉起计划`)
145
+ return cmd
146
+ }
147
+
57
148
  /**
58
149
  * 解析 bot 入口文件(按安装形态探测,纯函数供测试):
59
150
  * 1. 插件同目录 bot.js(plugins 目录自包含安装形态——官方规范的一键安装)
@@ -99,10 +190,9 @@ export function buildLaunchPlan(runtime: Runtime, entry: string, logPath?: strin
99
190
  ...(logPath ? { QQ_LOG_FILE: logPath } : {}),
100
191
  }
101
192
  if (runtime === "bun") {
102
- const bunCmd = resolveBunCommand() ?? "bun"
103
- return { command: bunCmd, args: ["run", entry], env }
193
+ return { command: resolveRuntimeCommand("bun"), args: ["run", entry], env }
104
194
  }
105
- return { command: "node", args: [entry], env }
195
+ return { command: resolveRuntimeCommand("node"), args: [entry], env }
106
196
  }
107
197
 
108
198
  /** bot 输出日志(detached 后 stdout/stderr 的唯一去向) */
@@ -112,6 +202,8 @@ export function botLogPath(): string {
112
202
 
113
203
  /**
114
204
  * detached 拉起 bot(跨平台同 API;Windows 隐藏控制台窗口)。
205
+ * 静默红线(2026-11-09):Plan.command 恒为全路径可执行体;显式 shell:false——
206
+ * 裸名或 shell 中转会在 Windows 上经 cmd.exe 弹出可见控制台(Windows Terminal 宿主实证)。
115
207
  * 日志由 bot 进程内文件双写承担(QQ_LOG_FILE,见 buildLaunchPlan)——
116
208
  * spawn 侧 fd 重定向在 bun 下实测不落盘(2026-10-30 清债 P2),不再依赖。
117
209
  * 返回 pid;拉起失败抛错(调用方记日志)。
@@ -122,6 +214,7 @@ export function spawnBotDetached(plan: LaunchPlan): number {
122
214
  stdio: "ignore",
123
215
  env: plan.env,
124
216
  windowsHide: true,
217
+ shell: false, // 静默红线:禁 shell 中转(cmd.exe 会另开控制台)
125
218
  })
126
219
  child.unref() // 父进程(serve)退出不带走 bot
127
220
  if (typeof child.pid !== "number") throw new Error("spawn 未返回 pid")
@@ -11,10 +11,17 @@
11
11
  // 与文字菜单并行不互拆:卡片优先,发送失败自动降级文字;文字通道原样保留。
12
12
  // 安全基线(fail-closed):忽略按钮=不决策(权限保持挂起至 TTL);
13
13
  // button_data 内嵌 request.id,槽位已被新请求替换时旧按钮点击直接拒识。
14
+ //
15
+ // ★ 卡片层契约(2026-11-17 固化):本层只负责「渲染+收发」,决策语义全在
16
+ // permission.ts(挂起/裁决/持久化)——两层不得互渗:卡片发送失败降级文字菜单时
17
+ // 决策通道不变(文字回复走 parsePermissionDecision 同一入口);
18
+ // 互动 ACK 必须 3 秒内先 ack 再业务(平台同 id 只受理一次,失败 ACK 可安全重试一次)。
19
+ // 多角色:卡片发送用本角色 token/底座(getAccessToken 按 appId 分槽自动路由),
20
+ // 不得跨角色代发。实测锚点:2026-11-17 20:17 测试角色审批卡全生命周期 ✅。
14
21
  import { getAccessToken, sendC2CMessage, sendGroupMessage, type InlineKeyboard, type KeyboardButton } from "../qq/api.js"
15
22
  import type { InteractionEvent, MessageContext } from "../qq/types.js"
16
23
  import type { PermissionDecision, PermissionRequest } from "../opencode/client.js"
17
- import { formatPermissionPrompt, type PendingPermission } from "./permission.js"
24
+ import { formatPermissionPrompt, type PendingPermission, type PermOrigin } from "./permission.js"
18
25
 
19
26
  /** QQ 按钮 label 长度限制(dsh P0 实证) */
20
27
  export const BUTTON_LABEL_MAX = 10
@@ -55,16 +62,19 @@ function clipLabel(text: string): string {
55
62
  return s.length > BUTTON_LABEL_MAX ? s.slice(0, BUTTON_LABEL_MAX - 1) + "…" : s
56
63
  }
57
64
 
58
- function makeButton(label: string, style: number, data: ApprovalButtonData, ownerOpenid: string): KeyboardButton {
59
- // visited_label = 点击后的原生回显(QQ 客户端把已点按钮渲染为已访问态、其余置灰——
60
- // 这就是"dsh 点一个其余变灰"的平台原生机制,2026-10-30 用户要求抄的效果)
65
+ function makeButton(label: string, style: number, data: ApprovalButtonData, _ownerOpenid: string): KeyboardButton {
66
+ // visited_label = 点击后的原生回显(QQ 客户端把已点按钮渲染为已访问态)。
67
+ // 注意:group_id 单选互斥在 C2C 多行布局下被平台校验拒绝(实测
68
+ // "rows.buttons.id 无效",2026-11-05),已与腾讯对齐撤下;互斥体感由 visited_label 承担。
69
+ // _ownerOpenid 保留在签名里维持 buildApprovalKeyboard 的既有接口(身份索引在交互回调侧完成)。
61
70
  const visited = data.d === "once" || data.d === "always" ? `✓ ${label}` : data.d === "reject" ? `✗ ${label}` : label
62
71
  return {
63
72
  id: `approval-${data.d}-${data.r}`.slice(0, 64),
64
73
  render_data: { label: clipLabel(label), visited_label: clipLabel(visited), style },
65
- // permission.type=2 + specify_user_ids:仅审批发起人可点(官方 P0 字段,
66
- // 防止群里其他人代点裁决)
67
- action: { type: 1, permission: { type: 2, specify_user_ids: [ownerOpenid] }, data: encodeButtonData(data) },
74
+ // permission 形状对齐腾讯 P0 当前实现(approval-renderer.ts):{type:2} 不带 specify_user_ids。
75
+ // 官方语义 type=2=所有人可操作;叠加 specify_user_ids 是冲突形状——平台校验收敛后
76
+ // 客户端直接不渲染键盘(dsh-notifier#26 实证:API 2xx、正文到、按钮没)。
77
+ action: { type: 1, permission: { type: 2 }, data: encodeButtonData(data) },
68
78
  }
69
79
  }
70
80
 
@@ -93,12 +103,13 @@ export async function sendApprovalCard(
93
103
  ctx: MessageContext,
94
104
  request: PermissionRequest,
95
105
  mainSessionId: string,
106
+ origin?: PermOrigin,
96
107
  ): Promise<boolean> {
97
108
  try {
98
109
  const token = await getAccessToken(deps.appId, deps.clientSecret)
99
110
  const keyboard = buildApprovalKeyboard(request, ctx.userId)
100
- // 正文复用现有格式化(用户看到的字段与文字菜单完全一致)
101
- const text = formatPermissionPrompt(request, mainSessionId)
111
+ // 正文复用现有格式化(用户看到的字段与文字菜单完全一致);origin 标注发起来源
112
+ const text = formatPermissionPrompt(request, mainSessionId, origin)
102
113
  if (ctx.type === "group" && ctx.groupId) {
103
114
  await sendGroupMessage(token, ctx.groupId, text, ctx.msgId, undefined, true, keyboard)
104
115
  } else {