@linjz/opencode-qqbot 0.3.15 → 0.3.17
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/README.md +303 -229
- package/README.zh-CN.md +313 -0
- package/bin/openqq.js +13 -0
- package/dist/notify-cli.js +92 -26
- package/dist/opencode-qqbot-plugin.js +1201 -67
- package/dist/openqq-bot.js +3963 -893
- package/dist/openqq-cli.js +980 -0
- package/dist/openqq-watchdog.js +1326 -0
- package/package.json +8 -5
- package/src/bridge.ts +1599 -150
- package/src/cli/notify.ts +170 -158
- package/src/cli/openqq-main.ts +95 -0
- package/src/cli/service-main.ts +302 -0
- package/src/cli/watchdog-main.ts +92 -0
- package/src/commands.ts +670 -554
- package/src/config.ts +122 -3
- package/src/core/bot-config.ts +66 -0
- package/src/core/bot-control.ts +166 -0
- package/src/core/bot-launcher.ts +110 -15
- package/src/core/card-approval.ts +20 -9
- package/src/core/cron-reminders.ts +84 -0
- package/src/core/delivery.ts +145 -54
- package/src/core/discovery.ts +207 -151
- package/src/core/error-rescue.ts +1 -1
- package/src/core/file-log.ts +50 -9
- package/src/core/form-bridge.ts +14 -5
- package/src/core/form-journal.ts +4 -4
- package/src/core/gateway-state.ts +3 -3
- package/src/core/inflight-journal.ts +215 -36
- package/src/core/instance-lock.ts +42 -3
- package/src/core/linkwatch.ts +3 -4
- package/src/core/log-rotate.ts +91 -0
- package/src/core/markdown.ts +117 -0
- package/src/core/message-queue.ts +242 -91
- package/src/core/mirror.ts +228 -182
- package/src/core/notices.ts +62 -0
- package/src/core/notify-sink.ts +93 -96
- package/src/core/outbound-sanitize.ts +29 -0
- package/src/core/outbox.ts +10 -9
- package/src/core/permission.ts +634 -303
- package/src/core/question-form.ts +230 -0
- package/src/core/queue-view.ts +662 -0
- package/src/core/send-media.ts +61 -2
- package/src/core/start-error.ts +26 -0
- package/src/core/storage.ts +34 -0
- package/src/core/stt.ts +55 -0
- package/src/core/supervisor-election.ts +53 -0
- package/src/core/watchdog.ts +670 -0
- package/src/core/zombie-reaper.ts +127 -0
- package/src/index.ts +262 -162
- package/src/opencode/client.ts +237 -27
- package/src/opencode/eventstream.ts +94 -12
- package/src/opencode/history.ts +4 -2
- package/src/opencode/mirror.ts +25 -5
- package/src/opencode/sessions.ts +135 -37
- package/src/plugin-entry.ts +139 -115
- package/src/qq/api.ts +165 -61
- package/src/qq/gateway.ts +114 -16
- package/src/qq/media.ts +21 -0
- package/src/qq/sender.ts +79 -18
- package/src/qq/types.ts +7 -0
package/src/config.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
|
|
|
5
5
|
import { join } from "path"
|
|
6
6
|
import { homedir } from "os"
|
|
7
7
|
import { createInterface } from "readline"
|
|
8
|
+
import { applyConfigOverlay } from "./core/bot-config.js"
|
|
8
9
|
|
|
9
10
|
export interface Config {
|
|
10
11
|
qq: {
|
|
@@ -19,6 +20,118 @@ export interface Config {
|
|
|
19
20
|
allowedUsers: string[]
|
|
20
21
|
}
|
|
21
22
|
|
|
23
|
+
/**
|
|
24
|
+
* 多角色(2026-11-17 owner 裁定:单进程挂多个 QQ bot 身份,参考 openclaw-qqbot
|
|
25
|
+
* 具名账号表)。一个 Role = 一个 appId 身份:自己的凭证/沙箱开关/白名单/
|
|
26
|
+
* 网关连接/数据分桶(~/.openqq/roles/<appId>/)。openid 按 app 隔离,
|
|
27
|
+
* 因此各角色的用户体系天然不相交。
|
|
28
|
+
*/
|
|
29
|
+
export interface RoleConfig {
|
|
30
|
+
/** 角色名(日志前缀用,可选) */
|
|
31
|
+
name: string
|
|
32
|
+
appId: string
|
|
33
|
+
clientSecret: string
|
|
34
|
+
sandbox: boolean
|
|
35
|
+
allowedUsers: string[]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 解析多角色配置。来源:env QQ_BOTS(JSON 数组,见 parseRolesJson)。
|
|
40
|
+
* 未配置时回退 legacy 单角色(QQ_APP_ID/QQ_APP_SECRET/QQ_SANDBOX/ALLOWED_USERS),
|
|
41
|
+
* 行为与 2026-11-17 之前完全一致——存量部署零迁移。
|
|
42
|
+
* 多角色模式下 ALLOWED_USERS/QQ_SANDBOX/QQ_APP_* 只作兜底缺项,不再单独生效。
|
|
43
|
+
*/
|
|
44
|
+
/**
|
|
45
|
+
* 可用凭据判定(纯函数,2026-11-20 应修尽修批):legacy 字段齐全 或 QQ_BOTS
|
|
46
|
+
* 解析出 ≥1 合法角色。ensureConfig 用它做早退——纯 QQ_BOTS 部署(无 legacy 字段)
|
|
47
|
+
* 不再掉进交互提问分支(detached 进程 stdin 无TTY会挂起)。
|
|
48
|
+
*/
|
|
49
|
+
export function hasUsableCredentials(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
50
|
+
if ((env.QQ_APP_ID ?? "").trim() && (env.QQ_APP_SECRET ?? "").trim()) return true
|
|
51
|
+
const raw = (env.QQ_BOTS ?? "").trim()
|
|
52
|
+
if (!raw) return false
|
|
53
|
+
return parseRolesJson(raw).length > 0
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 主角色 appId(纯函数):legacy QQ_APP_ID 优先,缺省回退 QQ_BOTS 首角色——
|
|
58
|
+
* restart/看门狗/插件引导器等单点探活调用方的锁路径锚点,在纯多角色部署下不再瞎。
|
|
59
|
+
*/
|
|
60
|
+
export function primaryAppId(env: NodeJS.ProcessEnv = process.env): string | null {
|
|
61
|
+
const legacy = (env.QQ_APP_ID ?? "").trim()
|
|
62
|
+
if (legacy) return legacy
|
|
63
|
+
const raw = (env.QQ_BOTS ?? "").trim()
|
|
64
|
+
if (!raw) return null
|
|
65
|
+
return parseRolesJson(raw)[0]?.appId ?? null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function loadRoles(): RoleConfig[] { const raw = (process.env.QQ_BOTS ?? "").trim()
|
|
69
|
+
if (raw) {
|
|
70
|
+
const roles = parseRolesJson(raw)
|
|
71
|
+
if (roles.length > 0) return roles
|
|
72
|
+
console.warn("[config] QQ_BOTS 配置存在但解析结果为空,回退 legacy 单角色模式")
|
|
73
|
+
}
|
|
74
|
+
const single = loadConfig()
|
|
75
|
+
console.warn(
|
|
76
|
+
"[config] legacy 单角色配置(QQ_APP_ID/QQ_APP_SECRET)已弃用——QQ_BOTS 多角色表是唯一角色源;" +
|
|
77
|
+
"legacy 兜底将于 2026-12-31 移除,请迁移 .env:QQ_BOTS=[{\"appId\":\"…\",\"secret\":\"…\",\"sandbox\":false,\"name\":\"角色名\"}]",
|
|
78
|
+
)
|
|
79
|
+
return [{
|
|
80
|
+
name: single.qq.appId,
|
|
81
|
+
appId: single.qq.appId,
|
|
82
|
+
clientSecret: single.qq.clientSecret,
|
|
83
|
+
sandbox: single.qq.sandbox,
|
|
84
|
+
allowedUsers: single.allowedUsers,
|
|
85
|
+
}]
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* QQ_BOTS JSON 解析与校验(纯函数)。形态:
|
|
90
|
+
* [{"appId":"...","secret":"...","sandbox":false,"name":"开发角色","allowedUsers":["..."]}]
|
|
91
|
+
* 校验规则:必须是数组、每项必含非空 appId/secret;sandbox 默认 false;
|
|
92
|
+
* allowedUsers 默认 []; name 默认 appId。非法项跳过并 warn,全非法返回 []。
|
|
93
|
+
*/
|
|
94
|
+
export function parseRolesJson(raw: string): RoleConfig[] {
|
|
95
|
+
let parsed: unknown
|
|
96
|
+
try {
|
|
97
|
+
parsed = JSON.parse(raw)
|
|
98
|
+
} catch {
|
|
99
|
+
console.warn("[config] QQ_BOTS 不是合法 JSON,已忽略")
|
|
100
|
+
return []
|
|
101
|
+
}
|
|
102
|
+
if (!Array.isArray(parsed)) {
|
|
103
|
+
console.warn("[config] QQ_BOTS 必须是数组,已忽略")
|
|
104
|
+
return []
|
|
105
|
+
}
|
|
106
|
+
const roles: RoleConfig[] = []
|
|
107
|
+
for (const [i, item] of parsed.entries()) {
|
|
108
|
+
const r = item as Partial<Record<"appId" | "secret" | "sandbox" | "name" | "allowedUsers", unknown>>
|
|
109
|
+
const appId = typeof r?.appId === "string" ? r.appId.trim() : ""
|
|
110
|
+
const secret = typeof r?.secret === "string" ? r.secret.trim() : ""
|
|
111
|
+
if (!appId || !secret) {
|
|
112
|
+
console.warn(`[config] QQ_BOTS[${i}] 缺少 appId/secret,已跳过`)
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
const allowedUsers = Array.isArray(r?.allowedUsers)
|
|
116
|
+
? r.allowedUsers.filter((u): u is string => typeof u === "string" && !!u.trim()).map((u) => u.trim())
|
|
117
|
+
: []
|
|
118
|
+
roles.push({
|
|
119
|
+
name: typeof r?.name === "string" && r.name.trim() ? r.name.trim() : appId,
|
|
120
|
+
appId,
|
|
121
|
+
clientSecret: secret,
|
|
122
|
+
sandbox: r?.sandbox === true,
|
|
123
|
+
allowedUsers,
|
|
124
|
+
})
|
|
125
|
+
}
|
|
126
|
+
// 同 appId 重复=配置错误,后者覆盖前者(日志可见),防双连接互踢
|
|
127
|
+
const seen = new Map<string, RoleConfig>()
|
|
128
|
+
for (const role of roles) {
|
|
129
|
+
if (seen.has(role.appId)) console.warn(`[config] QQ_BOTS 中 appId=${role.appId} 重复,后者覆盖前者`)
|
|
130
|
+
seen.set(role.appId, role)
|
|
131
|
+
}
|
|
132
|
+
return [...seen.values()]
|
|
133
|
+
}
|
|
134
|
+
|
|
22
135
|
const CONFIG_DIR = join(homedir(), ".openqq")
|
|
23
136
|
export const ENV_FILE = join(CONFIG_DIR, ".env")
|
|
24
137
|
|
|
@@ -38,17 +151,21 @@ function askTwo(q1: string, q2: string): Promise<[string, string]> {
|
|
|
38
151
|
}
|
|
39
152
|
|
|
40
153
|
export async function ensureConfig(): Promise<void> {
|
|
41
|
-
|
|
154
|
+
// P2 配置分层(2026-11-23 owner 裁定):config.json 最低用户层,先叠加——
|
|
155
|
+
// 「已设不覆盖」使其落在继承环境与 .env 之下(.env 在其后加载自然覆盖它)。
|
|
156
|
+
applyConfigOverlay()
|
|
157
|
+
|
|
158
|
+
if (hasUsableCredentials()) return
|
|
42
159
|
|
|
43
160
|
if (existsSync(ENV_FILE)) {
|
|
44
161
|
loadEnvFile(ENV_FILE)
|
|
45
|
-
if (
|
|
162
|
+
if (hasUsableCredentials()) return
|
|
46
163
|
}
|
|
47
164
|
|
|
48
165
|
const localEnv = join(process.cwd(), ".env")
|
|
49
166
|
if (existsSync(localEnv)) {
|
|
50
167
|
loadEnvFile(localEnv)
|
|
51
|
-
if (
|
|
168
|
+
if (hasUsableCredentials()) return
|
|
52
169
|
}
|
|
53
170
|
|
|
54
171
|
console.log("首次运行,需要配置 QQ 机器人凭证")
|
|
@@ -62,6 +179,8 @@ export async function ensureConfig(): Promise<void> {
|
|
|
62
179
|
|
|
63
180
|
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }) // POSIX 凭据目录仅本人可入
|
|
64
181
|
const envContent = [
|
|
182
|
+
`# 多角色(唯一角色源,推荐):QQ_BOTS=[{"appId":"…","secret":"…","sandbox":false,"name":"开发角色","allowedUsers":[]}]`,
|
|
183
|
+
`# 以下 legacy 单角色字段已弃用,将于 2026-12-31 移除`,
|
|
65
184
|
`QQ_APP_ID=${appId}`,
|
|
66
185
|
`QQ_APP_SECRET=${appSecret}`,
|
|
67
186
|
`QQ_SANDBOX=false`,
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// @input: node:fs/path/os、process.env(QQ_CONFIG_FILE 测试覆盖)
|
|
2
|
+
// @output: parseConfigJson/computeOverlay/applyConfigOverlay/configJsonPath
|
|
3
|
+
// @pos: core - 行为配置分层(2026-11-23 owner 裁定 P2:对齐官方「json=行为、env=密钥」)
|
|
4
|
+
//
|
|
5
|
+
// 层级(高→低):继承环境 > ~/.openqq/.env > ~/.openqq/config.json > 内置默认。
|
|
6
|
+
// config.json 为平铺 JSON,键名与 env 相同(零映射表,文档一句讲清);
|
|
7
|
+
// 只收行为键,密钥(QQ_APP_SECRET/OPENCODE_PASSWORD 等)仍必须走 .env——
|
|
8
|
+
// 叠加规则「已设不覆盖」:在 .env 加载前应用,天然落位最低用户层。
|
|
9
|
+
// 叠加方式是写入 process.env——业务代码 51 处读取点零改动(最小侵入)。
|
|
10
|
+
|
|
11
|
+
import { existsSync, readFileSync } from "node:fs"
|
|
12
|
+
import { homedir } from "node:os"
|
|
13
|
+
import { join } from "node:path"
|
|
14
|
+
|
|
15
|
+
/** config.json 路径:QQ_CONFIG_FILE 覆盖(测试/多实例隔离用),默认 ~/.openqq/config.json */
|
|
16
|
+
export function configJsonPath(env: NodeJS.ProcessEnv = process.env): string {
|
|
17
|
+
return env.QQ_CONFIG_FILE?.trim() || join(homedir(), ".openqq", "config.json")
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 解析平铺配置(纯函数供测试):只收 string/number/boolean 叶值并转字符串;嵌套对象忽略。 */
|
|
21
|
+
export function parseConfigJson(raw: string): Record<string, string> {
|
|
22
|
+
let parsed: unknown
|
|
23
|
+
try {
|
|
24
|
+
parsed = JSON.parse(raw)
|
|
25
|
+
} catch {
|
|
26
|
+
console.warn("[config] config.json 不是合法 JSON,已忽略")
|
|
27
|
+
return {}
|
|
28
|
+
}
|
|
29
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
30
|
+
console.warn("[config] config.json 必须是平铺 JSON 对象,已忽略")
|
|
31
|
+
return {}
|
|
32
|
+
}
|
|
33
|
+
const out: Record<string, string> = {}
|
|
34
|
+
for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
|
|
35
|
+
if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
|
|
36
|
+
out[k] = String(v)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return out
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 计算应叠加的键(纯函数供测试):config 中 env 已存在的键跳过(继承环境最高优先)。 */
|
|
43
|
+
export function computeOverlay(
|
|
44
|
+
env: NodeJS.ProcessEnv,
|
|
45
|
+
config: Record<string, string>,
|
|
46
|
+
): Array<[string, string]> {
|
|
47
|
+
return Object.entries(config).filter(([k]) => env[k] === undefined)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 读 config.json 并叠加进 env(缺省 process.env);返回叠加条数;文件缺失/读失败静默 0。 */
|
|
51
|
+
export function applyConfigOverlay(env: NodeJS.ProcessEnv = process.env): number {
|
|
52
|
+
const path = configJsonPath(env)
|
|
53
|
+
if (!existsSync(path)) return 0
|
|
54
|
+
let raw: string
|
|
55
|
+
try {
|
|
56
|
+
raw = readFileSync(path, "utf-8")
|
|
57
|
+
} catch {
|
|
58
|
+
return 0
|
|
59
|
+
}
|
|
60
|
+
const overlay = computeOverlay(env, parseConfigJson(raw))
|
|
61
|
+
for (const [k, v] of overlay) env[k] = v
|
|
62
|
+
if (overlay.length > 0) {
|
|
63
|
+
console.log(`[config] config.json 已叠加 ${overlay.length} 项(env/.env 优先): ${path}`)
|
|
64
|
+
}
|
|
65
|
+
return overlay.length
|
|
66
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
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
|
+
// 2026-11-20 应修尽修批:legacy 字段优先,缺省回退 QQ_BOTS 首角色(纯多角色部署的
|
|
38
|
+
// restart/探活锚点——此前只认 legacy 字段,纯 QQ_BOTS 部署下 restart/看门狗全瞎)。
|
|
39
|
+
let botsRaw: string | null = null
|
|
40
|
+
try {
|
|
41
|
+
for (const line of readFileSync(envPath, "utf-8").split("\n")) {
|
|
42
|
+
const t = line.trim()
|
|
43
|
+
if (!t || t.startsWith("#")) continue
|
|
44
|
+
const eq = t.indexOf("=")
|
|
45
|
+
if (eq < 0) continue
|
|
46
|
+
const key = t.slice(0, eq).trim()
|
|
47
|
+
if (key === "QQ_APP_ID") {
|
|
48
|
+
const v = t.slice(eq + 1).trim()
|
|
49
|
+
if (v) return v
|
|
50
|
+
}
|
|
51
|
+
if (key === "QQ_BOTS") botsRaw = t.slice(eq + 1).trim()
|
|
52
|
+
}
|
|
53
|
+
} catch {
|
|
54
|
+
/* 无 .env */
|
|
55
|
+
}
|
|
56
|
+
if (botsRaw) {
|
|
57
|
+
try {
|
|
58
|
+
const arr = JSON.parse(botsRaw) as Array<{ appId?: unknown }>
|
|
59
|
+
const first = Array.isArray(arr) ? arr[0]?.appId : undefined
|
|
60
|
+
if (typeof first === "string" && first) return first
|
|
61
|
+
} catch {
|
|
62
|
+
/* 坏 JSON 视为无 */
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function inflightPath(): string {
|
|
69
|
+
return join(homedir(), ".openqq", "inflight.json")
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 在途回合数(safe-restart 的空闲判据:state=inflight 即算活跃) */
|
|
73
|
+
export function countInflight(path = inflightPath()): number {
|
|
74
|
+
try {
|
|
75
|
+
const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown
|
|
76
|
+
if (!Array.isArray(raw)) return 0
|
|
77
|
+
return raw.filter((e) => (e as { state?: string }).state === "inflight").length
|
|
78
|
+
} catch {
|
|
79
|
+
return 0
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function waitUntilIdle(opts?: {
|
|
84
|
+
timeoutMs?: number
|
|
85
|
+
pollMs?: number
|
|
86
|
+
onWait?: (inflight: number, elapsedMs: number) => void
|
|
87
|
+
}): Promise<boolean> {
|
|
88
|
+
const timeoutMs = opts?.timeoutMs ?? 60 * 60_000
|
|
89
|
+
const pollMs = opts?.pollMs ?? 10_000
|
|
90
|
+
const started = Date.now()
|
|
91
|
+
for (;;) {
|
|
92
|
+
const n = countInflight()
|
|
93
|
+
if (n === 0) return true
|
|
94
|
+
const elapsed = Date.now() - started
|
|
95
|
+
if (elapsed >= timeoutMs) return false
|
|
96
|
+
opts?.onWait?.(n, elapsed)
|
|
97
|
+
await new Promise((r) => setTimeout(r, pollMs))
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 按安装形态拉起 bot(detached,日志走 QQ_LOG_FILE) */
|
|
102
|
+
export function startBot(fromUrl: string, log: (line: string) => void = () => {}): number {
|
|
103
|
+
const entry = resolveInstalledBotEntry(fromUrl)
|
|
104
|
+
if (!entry) throw new Error("未找到 bot 入口(dist/openqq-bot.js 或 src/index.ts)——安装不完整")
|
|
105
|
+
const runtime = resolveRuntime()
|
|
106
|
+
if (!runtime) throw new Error("未找到 bun/node 运行时")
|
|
107
|
+
const plan = buildLaunchPlan(runtime, entry, botLogPath())
|
|
108
|
+
const pid = spawnBotDetached(plan)
|
|
109
|
+
log(`[bot-control] 已拉起 pid=${pid}(runtime=${runtime},entry=${entry})`)
|
|
110
|
+
return pid
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface RestartOptions {
|
|
114
|
+
force?: boolean
|
|
115
|
+
timeoutMs?: number
|
|
116
|
+
spawnFromUrl: string
|
|
117
|
+
log?: (line: string) => void
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface RestartResult {
|
|
121
|
+
action: "restarted" | "skipped"
|
|
122
|
+
killedPid: number | null
|
|
123
|
+
spawnedPid: number | null
|
|
124
|
+
reason: string
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 安全重启:默认等空闲;-Force 跳过等待。跨平台,等价于旧 safe-restart.ps1。
|
|
129
|
+
* design §3.9.1 归一:杀/拉唯一权威 = superviseOnce(request=manual-restart)。
|
|
130
|
+
* 复用同一 grace-kill(TERM→宽限→KILL→确认死亡才拉)+ spawn 原语,
|
|
131
|
+
* 受 supervisor.json 强度账(15min/3 次 give-up、2min 冷却)与认领互斥约束,
|
|
132
|
+
* 审计分家(主动杀/验尸拉新)落统一日志 openqq.log——restart 不再有独立杀逻辑。
|
|
133
|
+
*/
|
|
134
|
+
export async function restartBot(opts: RestartOptions): Promise<RestartResult> {
|
|
135
|
+
const log = opts.log ?? (() => {})
|
|
136
|
+
const appId = readAppId()
|
|
137
|
+
if (!appId) throw new Error("缺少 ~/.openqq/.env 的角色凭据(QQ_APP_ID 或 QQ_BOTS 首角色),无法定位实例锁")
|
|
138
|
+
if (!opts.force) {
|
|
139
|
+
const idle = await waitUntilIdle({
|
|
140
|
+
timeoutMs: opts.timeoutMs,
|
|
141
|
+
onWait: (n, elapsed) => log(`[bot-control] 仍在途 ${n} 条(已等 ${Math.round(elapsed / 1000)}s),继续等待空闲`),
|
|
142
|
+
})
|
|
143
|
+
if (!idle) {
|
|
144
|
+
log("[bot-control] 等待空闲超时:本次不重启(需要时用 --force)")
|
|
145
|
+
return { action: "skipped", killedPid: null, spawnedPid: null, reason: "等待空闲超时" }
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const r = await superviseOnce({
|
|
149
|
+
paths: botWatchdogPaths(appId),
|
|
150
|
+
request: "manual-restart",
|
|
151
|
+
spawn: () => startBot(opts.spawnFromUrl, log),
|
|
152
|
+
log,
|
|
153
|
+
})
|
|
154
|
+
switch (r.action) {
|
|
155
|
+
case "restart":
|
|
156
|
+
return { action: "restarted", killedPid: r.killedPid, spawnedPid: r.spawnedPid, reason: opts.force ? "force(经监督矩阵)" : "idle(经监督矩阵)" }
|
|
157
|
+
case "cooldown":
|
|
158
|
+
return { action: "skipped", killedPid: null, spawnedPid: null, reason: `监督矩阵冷却跳过:${r.detail}` }
|
|
159
|
+
case "give-up":
|
|
160
|
+
return { action: "skipped", killedPid: null, spawnedPid: null, reason: `监督矩阵 give-up:${r.detail}` }
|
|
161
|
+
case "yield":
|
|
162
|
+
return { action: "skipped", killedPid: null, spawnedPid: null, reason: `认领互斥:${r.detail}` }
|
|
163
|
+
default:
|
|
164
|
+
return { action: "skipped", killedPid: null, spawnedPid: null, reason: `无需动作:${r.detail}` }
|
|
165
|
+
}
|
|
166
|
+
}
|
package/src/core/bot-launcher.ts
CHANGED
|
@@ -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
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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
|
|
98
|
+
return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun", join(homedir(), ".bun", "bin", "bun"), "bun"]
|
|
31
99
|
}
|
|
32
100
|
|
|
33
|
-
/** 解析可用 bun
|
|
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
|
-
|
|
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,19 +190,22 @@ export function buildLaunchPlan(runtime: Runtime, entry: string, logPath?: strin
|
|
|
99
190
|
...(logPath ? { QQ_LOG_FILE: logPath } : {}),
|
|
100
191
|
}
|
|
101
192
|
if (runtime === "bun") {
|
|
102
|
-
|
|
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
|
-
/** bot 输出日志(detached 后 stdout/stderr
|
|
198
|
+
/** bot 输出日志(detached 后 stdout/stderr 的唯一去向)。
|
|
199
|
+
* 2026-11-20 合并批:统一为 ~/.openqq/openqq.log(bot 与看门狗同文件,
|
|
200
|
+
* 滚动/预算归 core/log-rotate.ts;旧名 bot.out.log 停止写入保留备查)。 */
|
|
109
201
|
export function botLogPath(): string {
|
|
110
|
-
return join(homedir(), ".openqq", "
|
|
202
|
+
return join(homedir(), ".openqq", "openqq.log")
|
|
111
203
|
}
|
|
112
204
|
|
|
113
205
|
/**
|
|
114
206
|
* detached 拉起 bot(跨平台同 API;Windows 隐藏控制台窗口)。
|
|
207
|
+
* 静默红线(2026-11-09):Plan.command 恒为全路径可执行体;显式 shell:false——
|
|
208
|
+
* 裸名或 shell 中转会在 Windows 上经 cmd.exe 弹出可见控制台(Windows Terminal 宿主实证)。
|
|
115
209
|
* 日志由 bot 进程内文件双写承担(QQ_LOG_FILE,见 buildLaunchPlan)——
|
|
116
210
|
* spawn 侧 fd 重定向在 bun 下实测不落盘(2026-10-30 清债 P2),不再依赖。
|
|
117
211
|
* 返回 pid;拉起失败抛错(调用方记日志)。
|
|
@@ -122,6 +216,7 @@ export function spawnBotDetached(plan: LaunchPlan): number {
|
|
|
122
216
|
stdio: "ignore",
|
|
123
217
|
env: plan.env,
|
|
124
218
|
windowsHide: true,
|
|
219
|
+
shell: false, // 静默红线:禁 shell 中转(cmd.exe 会另开控制台)
|
|
125
220
|
})
|
|
126
221
|
child.unref() // 父进程(serve)退出不带走 bot
|
|
127
222
|
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,
|
|
59
|
-
// visited_label = 点击后的原生回显(QQ
|
|
60
|
-
//
|
|
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
|
|
66
|
-
//
|
|
67
|
-
|
|
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 {
|