@linjz/opencode-qqbot 0.3.16 → 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 -266
- package/README.zh-CN.md +313 -0
- package/dist/notify-cli.js +64 -12
- package/dist/opencode-qqbot-plugin.js +356 -92
- package/dist/openqq-bot.js +878 -226
- package/dist/openqq-cli.js +253 -64
- package/dist/openqq-watchdog.js +373 -110
- package/package.json +2 -2
- package/src/bridge.ts +292 -3
- package/src/cli/notify.ts +4 -1
- package/src/cli/watchdog-main.ts +22 -7
- package/src/commands.ts +36 -10
- package/src/config.ts +39 -5
- package/src/core/bot-config.ts +66 -0
- package/src/core/bot-control.ts +21 -3
- package/src/core/bot-launcher.ts +4 -2
- package/src/core/cron-reminders.ts +84 -0
- package/src/core/discovery.ts +207 -169
- package/src/core/error-rescue.ts +1 -1
- package/src/core/file-log.ts +16 -7
- package/src/core/inflight-journal.ts +1 -0
- package/src/core/instance-lock.ts +32 -1
- package/src/core/log-rotate.ts +91 -0
- package/src/core/mirror.ts +7 -1
- package/src/core/notices.ts +62 -0
- package/src/core/outbound-sanitize.ts +29 -0
- package/src/core/permission.ts +7 -0
- package/src/core/queue-view.ts +1 -0
- package/src/core/send-media.ts +29 -2
- package/src/core/start-error.ts +26 -0
- package/src/core/stt.ts +55 -0
- package/src/core/supervisor-election.ts +53 -0
- package/src/core/watchdog.ts +171 -14
- package/src/index.ts +262 -250
- package/src/opencode/client.ts +32 -1
- package/src/opencode/mirror.ts +10 -3
- package/src/plugin-entry.ts +21 -2
- package/src/qq/gateway.ts +35 -0
- package/src/qq/media.ts +21 -0
- package/src/qq/sender.ts +50 -1
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: {
|
|
@@ -40,14 +41,41 @@ export interface RoleConfig {
|
|
|
40
41
|
* 行为与 2026-11-17 之前完全一致——存量部署零迁移。
|
|
41
42
|
* 多角色模式下 ALLOWED_USERS/QQ_SANDBOX/QQ_APP_* 只作兜底缺项,不再单独生效。
|
|
42
43
|
*/
|
|
43
|
-
|
|
44
|
-
|
|
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()
|
|
45
69
|
if (raw) {
|
|
46
70
|
const roles = parseRolesJson(raw)
|
|
47
71
|
if (roles.length > 0) return roles
|
|
48
72
|
console.warn("[config] QQ_BOTS 配置存在但解析结果为空,回退 legacy 单角色模式")
|
|
49
73
|
}
|
|
50
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
|
+
)
|
|
51
79
|
return [{
|
|
52
80
|
name: single.qq.appId,
|
|
53
81
|
appId: single.qq.appId,
|
|
@@ -123,17 +151,21 @@ function askTwo(q1: string, q2: string): Promise<[string, string]> {
|
|
|
123
151
|
}
|
|
124
152
|
|
|
125
153
|
export async function ensureConfig(): Promise<void> {
|
|
126
|
-
|
|
154
|
+
// P2 配置分层(2026-11-23 owner 裁定):config.json 最低用户层,先叠加——
|
|
155
|
+
// 「已设不覆盖」使其落在继承环境与 .env 之下(.env 在其后加载自然覆盖它)。
|
|
156
|
+
applyConfigOverlay()
|
|
157
|
+
|
|
158
|
+
if (hasUsableCredentials()) return
|
|
127
159
|
|
|
128
160
|
if (existsSync(ENV_FILE)) {
|
|
129
161
|
loadEnvFile(ENV_FILE)
|
|
130
|
-
if (
|
|
162
|
+
if (hasUsableCredentials()) return
|
|
131
163
|
}
|
|
132
164
|
|
|
133
165
|
const localEnv = join(process.cwd(), ".env")
|
|
134
166
|
if (existsSync(localEnv)) {
|
|
135
167
|
loadEnvFile(localEnv)
|
|
136
|
-
if (
|
|
168
|
+
if (hasUsableCredentials()) return
|
|
137
169
|
}
|
|
138
170
|
|
|
139
171
|
console.log("首次运行,需要配置 QQ 机器人凭证")
|
|
@@ -147,6 +179,8 @@ export async function ensureConfig(): Promise<void> {
|
|
|
147
179
|
|
|
148
180
|
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }) // POSIX 凭据目录仅本人可入
|
|
149
181
|
const envContent = [
|
|
182
|
+
`# 多角色(唯一角色源,推荐):QQ_BOTS=[{"appId":"…","secret":"…","sandbox":false,"name":"开发角色","allowedUsers":[]}]`,
|
|
183
|
+
`# 以下 legacy 单角色字段已弃用,将于 2026-12-31 移除`,
|
|
150
184
|
`QQ_APP_ID=${appId}`,
|
|
151
185
|
`QQ_APP_SECRET=${appSecret}`,
|
|
152
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
|
+
}
|
package/src/core/bot-control.ts
CHANGED
|
@@ -34,16 +34,34 @@ export function resolveInstalledBotEntry(fromUrl: string, exists: (p: string) =>
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
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
|
|
37
40
|
try {
|
|
38
41
|
for (const line of readFileSync(envPath, "utf-8").split("\n")) {
|
|
39
42
|
const t = line.trim()
|
|
40
43
|
if (!t || t.startsWith("#")) continue
|
|
41
44
|
const eq = t.indexOf("=")
|
|
42
|
-
if (eq
|
|
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()
|
|
43
52
|
}
|
|
44
53
|
} catch {
|
|
45
54
|
/* 无 .env */
|
|
46
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
|
+
}
|
|
47
65
|
return null
|
|
48
66
|
}
|
|
49
67
|
|
|
@@ -111,12 +129,12 @@ export interface RestartResult {
|
|
|
111
129
|
* design §3.9.1 归一:杀/拉唯一权威 = superviseOnce(request=manual-restart)。
|
|
112
130
|
* 复用同一 grace-kill(TERM→宽限→KILL→确认死亡才拉)+ spawn 原语,
|
|
113
131
|
* 受 supervisor.json 强度账(15min/3 次 give-up、2min 冷却)与认领互斥约束,
|
|
114
|
-
*
|
|
132
|
+
* 审计分家(主动杀/验尸拉新)落统一日志 openqq.log——restart 不再有独立杀逻辑。
|
|
115
133
|
*/
|
|
116
134
|
export async function restartBot(opts: RestartOptions): Promise<RestartResult> {
|
|
117
135
|
const log = opts.log ?? (() => {})
|
|
118
136
|
const appId = readAppId()
|
|
119
|
-
if (!appId) throw new Error("缺少 ~/.openqq/.env
|
|
137
|
+
if (!appId) throw new Error("缺少 ~/.openqq/.env 的角色凭据(QQ_APP_ID 或 QQ_BOTS 首角色),无法定位实例锁")
|
|
120
138
|
if (!opts.force) {
|
|
121
139
|
const idle = await waitUntilIdle({
|
|
122
140
|
timeoutMs: opts.timeoutMs,
|
package/src/core/bot-launcher.ts
CHANGED
|
@@ -195,9 +195,11 @@ export function buildLaunchPlan(runtime: Runtime, entry: string, logPath?: strin
|
|
|
195
195
|
return { command: resolveRuntimeCommand("node"), args: [entry], env }
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
-
/** 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 停止写入保留备查)。 */
|
|
199
201
|
export function botLogPath(): string {
|
|
200
|
-
return join(homedir(), ".openqq", "
|
|
202
|
+
return join(homedir(), ".openqq", "openqq.log")
|
|
201
203
|
}
|
|
202
204
|
|
|
203
205
|
/**
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// @input: 纯文本(无依赖)+ setTimeout(调度器)
|
|
2
|
+
// @output: parseCronReminder / ReminderScheduler
|
|
3
|
+
// @pos: core - 定时提醒(2026-11-23 学习吸收 Y-1,源=openclaw outbound/cron-scheduler.ts P0)
|
|
4
|
+
//
|
|
5
|
+
// 触发形态(AI 在正文内嵌标记,与 openclaw 同款):
|
|
6
|
+
// QQBOT_PAYLOAD: {"type":"cron_reminder","at":"in 30m","text":"去开评审会"}
|
|
7
|
+
// at 支持:ISO 8601 / Unix ms(>1e12)/ "in Nm/Nh/Nd";过去时刻拒收。
|
|
8
|
+
// 标记从用户可见正文剥离(不留脚手架痕迹);剥完为空则以确认句回执。
|
|
9
|
+
// 单次提醒(setTimeout,进程内存态)——重启即失,与 openclaw 同口径;
|
|
10
|
+
// 每用户同时在册上限防标记轰炸。
|
|
11
|
+
|
|
12
|
+
/** 解析 cron 标记(纯函数供测试)。命中并合法 → 绝对时刻/提醒文本/剥净正文;否则 null。 */
|
|
13
|
+
export function parseCronReminder(
|
|
14
|
+
text: string,
|
|
15
|
+
now: number,
|
|
16
|
+
): { atMs: number; reminderText: string; cleanedText: string } | null {
|
|
17
|
+
const m = /QQBOT_PAYLOAD:\s*(\{[\s\S]*?\})/.exec(text)
|
|
18
|
+
if (!m) return null
|
|
19
|
+
let payload: { type?: unknown; at?: unknown; text?: unknown }
|
|
20
|
+
try {
|
|
21
|
+
payload = JSON.parse(m[1]) as typeof payload
|
|
22
|
+
} catch {
|
|
23
|
+
return null
|
|
24
|
+
}
|
|
25
|
+
if (payload?.type !== "cron_reminder") return null
|
|
26
|
+
const reminderText = typeof payload.text === "string" ? payload.text.trim().slice(0, 200) : ""
|
|
27
|
+
if (!reminderText) return null
|
|
28
|
+
const atMs = resolveAt(payload.at, now)
|
|
29
|
+
if (atMs === null || atMs <= now + 5_000) return null
|
|
30
|
+
// 剥净:含标记的整行移除,残余空行收敛
|
|
31
|
+
const cleanedText = text
|
|
32
|
+
.split("\n")
|
|
33
|
+
.filter((line) => !line.includes("QQBOT_PAYLOAD:"))
|
|
34
|
+
.join("\n")
|
|
35
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
36
|
+
.trim()
|
|
37
|
+
return { atMs, reminderText, cleanedText }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** at 字段解析(纯函数):ISO / Unix ms / "in Nm|Nh|Nd"。 */
|
|
41
|
+
export function resolveAt(at: unknown, now: number): number | null {
|
|
42
|
+
if (typeof at === "number" && Number.isFinite(at)) {
|
|
43
|
+
return at > 1e12 ? at : null // 小于 1e12 按秒记的可能性不存在于本域,拒收防误用
|
|
44
|
+
}
|
|
45
|
+
if (typeof at !== "string") return null
|
|
46
|
+
const rel = /^in\s+(\d+)\s*([mhd])$/i.exec(at.trim())
|
|
47
|
+
if (rel) {
|
|
48
|
+
const n = Number(rel[1])
|
|
49
|
+
const unit = { m: 60_000, h: 3_600_000, d: 86_400_000 }[rel[2].toLowerCase()] ?? 0
|
|
50
|
+
return now + n * unit
|
|
51
|
+
}
|
|
52
|
+
const t = Date.parse(at)
|
|
53
|
+
return Number.isNaN(t) ? null : t
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 进程内单次提醒调度:每用户同时在册上限(防标记轰炸),到点投递并出册。 */
|
|
57
|
+
export class ReminderScheduler {
|
|
58
|
+
private readonly pending = new Map<string, Set<ReturnType<typeof setTimeout>>>()
|
|
59
|
+
constructor(private readonly maxPerUser = 10) {}
|
|
60
|
+
|
|
61
|
+
/** 注册。返回 false=被拒(超上限/参数非法),调用方如实回执。 */
|
|
62
|
+
schedule(userId: string, atMs: number, text: string, deliver: (userId: string, text: string) => void): boolean {
|
|
63
|
+
if (!userId || !text.trim() || atMs <= Date.now()) return false
|
|
64
|
+
const set = this.pending.get(userId) ?? new Set()
|
|
65
|
+
if (set.size >= this.maxPerUser) return false
|
|
66
|
+
const timer = setTimeout(() => {
|
|
67
|
+
set.delete(timer)
|
|
68
|
+
console.log(`[cron] 提醒到点 user=${userId.slice(0, 8)}… text=${text.slice(0, 30)}`)
|
|
69
|
+
try {
|
|
70
|
+
deliver(userId, `⏰ 提醒:${text}`)
|
|
71
|
+
} catch (error) {
|
|
72
|
+
console.error("[cron] 提醒投递失败:", error)
|
|
73
|
+
}
|
|
74
|
+
}, atMs - Date.now())
|
|
75
|
+
set.add(timer)
|
|
76
|
+
this.pending.set(userId, set)
|
|
77
|
+
return true
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 在册数(测试断言用)。 */
|
|
81
|
+
size(userId: string): number {
|
|
82
|
+
return this.pending.get(userId)?.size ?? 0
|
|
83
|
+
}
|
|
84
|
+
}
|