@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/opencode/mirror.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import type { SessionMessage } from "./client.js"
|
|
9
9
|
import { redactSecrets } from "./history.js"
|
|
10
|
+
import { labelBlock } from "../core/markdown.js"
|
|
10
11
|
|
|
11
12
|
const USER_CLIP = 160
|
|
12
13
|
|
|
@@ -21,6 +22,16 @@ function answerClipLimit(): number {
|
|
|
21
22
|
|
|
22
23
|
// 逻辑回合并发幂等键:同一用户消息 + 最终 assistant。不同 location 的
|
|
23
24
|
// execution.succeeded 事件 ID 可以不同,但同一逻辑回合仍只应镜像一次。
|
|
25
|
+
// 摘要锚定用户消息 id(DEF-20261118-P6 来源身份守卫用):与 digestTurnKey 同一
|
|
26
|
+
// 锚点口径——时间序最后的 user 消息。无 user 消息返回 undefined(守卫放行给既有逻辑)。
|
|
27
|
+
export function digestAnchorUserId(messages: SessionMessage[]): string | undefined {
|
|
28
|
+
const ordered = [...messages].reverse()
|
|
29
|
+
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
30
|
+
if (ordered[i].type === "user") return ordered[i].id ?? undefined
|
|
31
|
+
}
|
|
32
|
+
return undefined
|
|
33
|
+
}
|
|
34
|
+
|
|
24
35
|
export function digestTurnKey(messages: SessionMessage[]): string | null {
|
|
25
36
|
const ordered = [...messages].reverse()
|
|
26
37
|
let lastUserIdx = -1
|
|
@@ -43,16 +54,23 @@ export function digestTurnKey(messages: SessionMessage[]): string | null {
|
|
|
43
54
|
export function buildDigest(messages: SessionMessage[]): string | null {
|
|
44
55
|
const ordered = [...messages].reverse()
|
|
45
56
|
|
|
57
|
+
// A 方案第三桶(owner 2026-11-23):回合边界消息 type=synthetic = 引擎自主注入
|
|
58
|
+
// (goal 续跑/自动化)——既非 QQ 派发也非桌面输入,实证 shape(11-23 goal 会话
|
|
59
|
+
// 消息流):continuation 为 synthetic 型 user 消息。此类回合标「🎯 目标续跑摘要」,
|
|
60
|
+
// 不再冒名「桌面」。
|
|
46
61
|
let lastUserIdx = -1
|
|
62
|
+
let goalDriven = false
|
|
47
63
|
for (let i = ordered.length - 1; i >= 0; i--) {
|
|
48
|
-
|
|
64
|
+
const t = (ordered[i] as { type?: string }).type
|
|
65
|
+
if (t === "user" || t === "synthetic") {
|
|
49
66
|
lastUserIdx = i
|
|
67
|
+
goalDriven = t === "synthetic"
|
|
50
68
|
break
|
|
51
69
|
}
|
|
52
70
|
}
|
|
53
71
|
if (lastUserIdx < 0) return null
|
|
54
72
|
|
|
55
|
-
const userText = ((ordered[lastUserIdx] as { text?: string }).text ?? "").trim()
|
|
73
|
+
const userText = goalDriven ? "" : ((ordered[lastUserIdx] as { text?: string }).text ?? "").trim()
|
|
56
74
|
|
|
57
75
|
let answer = ""
|
|
58
76
|
for (let i = ordered.length - 1; i > lastUserIdx; i--) {
|
|
@@ -66,15 +84,17 @@ export function buildDigest(messages: SessionMessage[]): string | null {
|
|
|
66
84
|
}
|
|
67
85
|
if (!answer) return null
|
|
68
86
|
|
|
69
|
-
const lines = ["📋 桌面问答摘要"]
|
|
87
|
+
const lines = [goalDriven ? "🎯 目标续跑摘要" : "📋 桌面问答摘要"]
|
|
70
88
|
if (userText) lines.push(`🧑 ${clip(userText, USER_CLIP)}`)
|
|
71
89
|
const clipLimit = answerClipLimit()
|
|
72
90
|
if (clipLimit > 0) {
|
|
73
91
|
lines.push(`🤖 ${clip(answer, clipLimit)}`)
|
|
74
92
|
if (answer.length > clipLimit) lines.push(`(答案共 ${answer.length} 字,回 /history 看更多)`)
|
|
75
93
|
} else {
|
|
76
|
-
// 全文模式:保留原文换行/排版(clip
|
|
77
|
-
|
|
94
|
+
// 全文模式:保留原文换行/排版(clip 的空白折叠只用于截断模式)。
|
|
95
|
+
// 标签必须走 labelBlock:正文以 ```/标题/列表等块级语法开头时独占一行,
|
|
96
|
+
// 否则 "🤖 ```" 让开围栏不顶格 → QQ 渲染空代码卡 + 正文外泄(2026-11-10 截图实证)。
|
|
97
|
+
lines.push(labelBlock("🤖", answer))
|
|
78
98
|
}
|
|
79
99
|
return redactSecrets(lines.join("\n"))
|
|
80
100
|
}
|
package/src/opencode/sessions.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
// @input: ./client (OpencodeClient)
|
|
1
|
+
// @input: ./client (OpencodeClient)
|
|
2
2
|
// @output: SessionManager, UserSession
|
|
3
3
|
// @pos: opencode层 - QQ用户<->OpenCode Session 映射管理(持久化到 ~/.openqq/sessions.json)
|
|
4
|
+
import { storageFile } from "../core/storage.js"
|
|
4
5
|
import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs"
|
|
5
|
-
import {
|
|
6
|
-
import { homedir } from "os"
|
|
6
|
+
import { dirname } from "path"
|
|
7
7
|
import type { OpencodeClient } from "./client.js"
|
|
8
8
|
|
|
9
9
|
interface UserSession {
|
|
@@ -12,17 +12,23 @@ interface UserSession {
|
|
|
12
12
|
modelId?: string
|
|
13
13
|
providerId?: string
|
|
14
14
|
agentId?: string
|
|
15
|
+
/** 项目归属(location.directory)缓存——新建会话继承链的同步来源;由 enforceLocation 回写 */
|
|
16
|
+
directory?: string
|
|
15
17
|
}
|
|
16
18
|
|
|
17
|
-
const
|
|
18
|
-
const STORE_FILE = join(STORE_DIR, "sessions.json")
|
|
19
|
+
const STORE_FILE = storageFile("sessions.json")
|
|
19
20
|
|
|
20
21
|
export class SessionManager {
|
|
21
22
|
private sessions = new Map<string, UserSession>()
|
|
22
23
|
private client: OpencodeClient
|
|
24
|
+
/** DEF-qqbot-20261112-7:持久化路径可注入——单测必须写临时文件,禁写生产映射
|
|
25
|
+
* (2026-11-12 实证:session-model/status-title 套件直写 ~/.openqq/sessions.json,
|
|
26
|
+
* 夹具 u1-u4/sid2-4 垃圾入库;多管理器陈旧整图回写还把 owner 绑定顶回去) */
|
|
27
|
+
private readonly storeFile: string
|
|
23
28
|
|
|
24
|
-
constructor(client: OpencodeClient) {
|
|
29
|
+
constructor(client: OpencodeClient, storeFile: string = STORE_FILE) {
|
|
25
30
|
this.client = client
|
|
31
|
+
this.storeFile = storeFile
|
|
26
32
|
this.loadSessions()
|
|
27
33
|
}
|
|
28
34
|
|
|
@@ -30,9 +36,9 @@ export class SessionManager {
|
|
|
30
36
|
//(2026-10-13 实测教训:重启清空内存映射 → 用户 QQ 消息落到全新会话,AI 失忆从零探索)。
|
|
31
37
|
private loadSessions(): void {
|
|
32
38
|
try {
|
|
33
|
-
if (!existsSync(
|
|
39
|
+
if (!existsSync(this.storeFile)) return
|
|
34
40
|
// 手工编辑或 PowerShell Out-File 常带 BOM,JSON.parse 会炸——先剥掉
|
|
35
|
-
const raw = readFileSync(
|
|
41
|
+
const raw = readFileSync(this.storeFile, "utf8").replace(/^\uFEFF/, "")
|
|
36
42
|
const parsed = JSON.parse(raw) as Record<string, UserSession>
|
|
37
43
|
for (const [userId, session] of Object.entries(parsed)) {
|
|
38
44
|
if (session?.sessionId) this.sessions.set(userId, session)
|
|
@@ -47,8 +53,9 @@ export class SessionManager {
|
|
|
47
53
|
|
|
48
54
|
private saveSessions(): void {
|
|
49
55
|
try {
|
|
50
|
-
|
|
51
|
-
|
|
56
|
+
const dir = dirname(this.storeFile)
|
|
57
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
58
|
+
writeFileSync(this.storeFile, JSON.stringify(Object.fromEntries(this.sessions), null, 2), "utf8")
|
|
52
59
|
} catch (error) {
|
|
53
60
|
console.error("[sessions] 会话映射持久化失败:", error)
|
|
54
61
|
}
|
|
@@ -58,40 +65,94 @@ export class SessionManager {
|
|
|
58
65
|
const existing = this.sessions.get(userId)
|
|
59
66
|
if (existing) return existing
|
|
60
67
|
|
|
61
|
-
const
|
|
68
|
+
const directory = this.peekInheritDirectory(userId)
|
|
69
|
+
const result = await this.client.session.create({ location: { directory } })
|
|
62
70
|
const session: UserSession = {
|
|
63
71
|
sessionId: result.data!.id,
|
|
64
72
|
title: result.data!.title,
|
|
65
73
|
}
|
|
66
74
|
this.sessions.set(userId, session)
|
|
67
75
|
this.saveSessions()
|
|
76
|
+
await this.enforceLocation(userId, session.sessionId, directory)
|
|
68
77
|
return session
|
|
69
78
|
}
|
|
70
79
|
|
|
71
80
|
async createNew(userId: string): Promise<UserSession> {
|
|
72
|
-
const
|
|
81
|
+
const directory = this.peekInheritDirectory(userId)
|
|
82
|
+
// owner 裁定 2026-11-09:/new 继承「当前会话」的模型/Agent(仅新建这一次性代入;
|
|
83
|
+
// 切换已有会话永不继承——见 switchSession)。
|
|
84
|
+
const prev = this.sessions.get(userId)
|
|
85
|
+
const inheritedModel = prev?.providerId && prev.modelId ? { providerID: prev.providerId, id: prev.modelId } : undefined
|
|
86
|
+
const inheritedAgent = prev?.agentId
|
|
87
|
+
const result = await this.client.session.create({ location: { directory } })
|
|
73
88
|
const session: UserSession = {
|
|
74
89
|
sessionId: result.data!.id,
|
|
75
90
|
title: result.data!.title,
|
|
91
|
+
...(inheritedModel ? { providerId: inheritedModel.providerID, modelId: inheritedModel.id } : {}),
|
|
92
|
+
...(inheritedAgent ? { agentId: inheritedAgent } : {}),
|
|
76
93
|
}
|
|
77
94
|
this.sessions.set(userId, session)
|
|
78
95
|
this.saveSessions()
|
|
96
|
+
if (inheritedModel) {
|
|
97
|
+
void this.client.session
|
|
98
|
+
.setModel({ path: { id: session.sessionId }, body: { model: inheritedModel } })
|
|
99
|
+
.catch((error) => console.error("[sessions] 新会话继承模型失败(映射已存):", error))
|
|
100
|
+
}
|
|
101
|
+
if (inheritedAgent) {
|
|
102
|
+
void this.client.session
|
|
103
|
+
.setAgent({ path: { id: session.sessionId }, body: { agent: inheritedAgent } })
|
|
104
|
+
.catch((error) => console.error("[sessions] 新会话继承 Agent 失败(映射已存):", error))
|
|
105
|
+
}
|
|
106
|
+
await this.enforceLocation(userId, session.sessionId, directory)
|
|
79
107
|
return session
|
|
80
108
|
}
|
|
81
109
|
|
|
82
|
-
|
|
110
|
+
// 2026-11-09 对齐官方会话归属校验(引擎 session/load 语义):
|
|
111
|
+
// 会话与 location.directory 强绑定,load 必须携带会话自己的目录,否则 -32602。
|
|
112
|
+
// 因此切换会话时必须显式携带目标会话的 directory(来自 /sessions 列表的 location)。
|
|
113
|
+
switchSession(userId: string, sessionId: string, title?: string, directory?: string): void {
|
|
83
114
|
const prev = this.sessions.get(userId)
|
|
84
115
|
const changed = prev?.sessionId !== sessionId
|
|
85
116
|
this.sessions.set(userId, {
|
|
86
117
|
...prev,
|
|
87
118
|
sessionId,
|
|
88
119
|
title,
|
|
120
|
+
// 显式传入的 directory(切换场景,可能跨项目);undefined=未知,
|
|
121
|
+
// 加载时经 resolveDirectory 从服务端回填,绝不沿用旧会话目录
|
|
122
|
+
directory,
|
|
89
123
|
})
|
|
90
124
|
this.saveSessions()
|
|
91
|
-
//
|
|
92
|
-
|
|
125
|
+
// 2026-11-09 owner 裁定(反转 2026-10-29 设计):切换**不继承**——模型/Agent
|
|
126
|
+
// 是会话级状态(桌面端同语义),不得用本用户在此前会话的偏好覆盖目标会话;
|
|
127
|
+
// 反向从目标会话回读真实设置写回映射(/status 与后续 /model 以目标为准)。
|
|
93
128
|
if (changed) {
|
|
94
|
-
void this.
|
|
129
|
+
void this.refreshSettingsFromServer(userId)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 切换后回读目标会话的会话级设置(model/agent)写回映射;服务端未设则清空(显示「默认」)。 */
|
|
134
|
+
private async refreshSettingsFromServer(userId: string): Promise<void> {
|
|
135
|
+
const s = this.sessions.get(userId)
|
|
136
|
+
if (!s) return
|
|
137
|
+
try {
|
|
138
|
+
const detail = await this.client.session.get({ path: { id: s.sessionId } })
|
|
139
|
+
const model = detail?.data?.model
|
|
140
|
+
const agent = detail?.data?.agent
|
|
141
|
+
const cur = detail?.data
|
|
142
|
+
if (!cur) return
|
|
143
|
+
if (model?.providerID && model?.id) {
|
|
144
|
+
s.providerId = model.providerID
|
|
145
|
+
s.modelId = model.id
|
|
146
|
+
} else {
|
|
147
|
+
delete s.providerId
|
|
148
|
+
delete s.modelId
|
|
149
|
+
}
|
|
150
|
+
if (typeof agent === "string" && agent) s.agentId = agent
|
|
151
|
+
else delete s.agentId
|
|
152
|
+
this.saveSessions()
|
|
153
|
+
} catch (error) {
|
|
154
|
+
// 回读失败保留旧显示(不阻断切换主操作)
|
|
155
|
+
console.error("[sessions] 回读目标会话设置失败(保留旧映射):", error)
|
|
95
156
|
}
|
|
96
157
|
}
|
|
97
158
|
|
|
@@ -99,9 +160,61 @@ export class SessionManager {
|
|
|
99
160
|
return this.sessions.get(userId)
|
|
100
161
|
}
|
|
101
162
|
|
|
102
|
-
//
|
|
103
|
-
|
|
104
|
-
|
|
163
|
+
// ===== 项目归属继承链(2026-11-09 缺陷修复:孤儿会话 desktop 不可见)=====
|
|
164
|
+
// 根因:此前 session.create({}) 空体创建 → location.directory 为空 → desktop 端
|
|
165
|
+
// 会话不归任何项目(location 是 desktop 会话列表与配置链、服务加载的单位)。
|
|
166
|
+
// 取值:① 继承当前绑定会话的 location.directory ② 无绑定/继承失败 → 部署默认
|
|
167
|
+
//(QQBOT_DEFAULT_CWD 约定 → bot 进程 cwd)。
|
|
168
|
+
|
|
169
|
+
/** 新建会话应继承的项目目录(同步取值:当前绑定详情内缓存优先,缺则默认)。 */
|
|
170
|
+
peekInheritDirectory(userId: string): string {
|
|
171
|
+
const current = this.sessions.get(userId)
|
|
172
|
+
const cached = current?.directory
|
|
173
|
+
if (cached) return cached
|
|
174
|
+
return process.env.QQBOT_DEFAULT_CWD ?? process.cwd()
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** 创建/接管后强制项目归属(REST 路径共用):
|
|
178
|
+
* 服务端已带 location 则不动;为空用 move 端点补写 desired(缺省=继承链)。
|
|
179
|
+
* 补写失败只记日志——不阻断会话,但桌面端可见性缺失要在日志可见。 */
|
|
180
|
+
async enforceLocation(userId: string, sessionId: string, desired?: string): Promise<void> {
|
|
181
|
+
const target = desired ?? this.peekInheritDirectory(userId)
|
|
182
|
+
try {
|
|
183
|
+
const detail = await this.client.session.get({ path: { id: sessionId } })
|
|
184
|
+
const dir = detail?.data?.location?.directory
|
|
185
|
+
if (dir) {
|
|
186
|
+
// 顺手把继承值缓存到映射(后续 /new 二次继承不再依赖远端现取)
|
|
187
|
+
const s = this.sessions.get(userId)
|
|
188
|
+
if (s && s.sessionId === sessionId && s.directory !== dir) {
|
|
189
|
+
s.directory = dir
|
|
190
|
+
this.saveSessions()
|
|
191
|
+
}
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
await this.client.session.move({ path: { id: sessionId }, body: { directory: target } })
|
|
195
|
+
const s = this.sessions.get(userId)
|
|
196
|
+
if (s && s.sessionId === sessionId) {
|
|
197
|
+
s.directory = target
|
|
198
|
+
this.saveSessions()
|
|
199
|
+
}
|
|
200
|
+
console.log(`[sessions] 会话 ${sessionId} 补写项目归属: ${target}`)
|
|
201
|
+
} catch (error) {
|
|
202
|
+
console.error("[sessions] 项目归属补写失败(会话可用,但桌面端可能不可见):", error)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** 从服务端详情回填目录缓存:目录解析/重试成功后落盘。 */
|
|
207
|
+
cacheDirectory(userId: string, sessionId: string, directory: string): void {
|
|
208
|
+
const s = this.sessions.get(userId)
|
|
209
|
+
if (s && s.sessionId === sessionId && s.directory !== directory) {
|
|
210
|
+
s.directory = directory
|
|
211
|
+
this.saveSessions()
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// 枚举全部映射(摘要镜像订阅、会话→用户反查、interactionTick 权限分仓轮询用)
|
|
216
|
+
all(): Array<{ userId: string; sessionId: string; directory?: string }> {
|
|
217
|
+
return [...this.sessions.entries()].map(([userId, s]) => ({ userId, sessionId: s.sessionId, directory: s.directory }))
|
|
105
218
|
}
|
|
106
219
|
|
|
107
220
|
// v2: 模型/agent 是 session 级(/prompt body 会被剥离),必须调 session 端点。
|
|
@@ -126,24 +239,9 @@ export class SessionManager {
|
|
|
126
239
|
this.saveSessions()
|
|
127
240
|
}
|
|
128
241
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
try {
|
|
133
|
-
if (s.providerId && s.modelId) {
|
|
134
|
-
await this.client.session.setModel({
|
|
135
|
-
path: { id: s.sessionId },
|
|
136
|
-
body: { model: { providerID: s.providerId, id: s.modelId } },
|
|
137
|
-
})
|
|
138
|
-
}
|
|
139
|
-
if (s.agentId) {
|
|
140
|
-
await this.client.session.setAgent({ path: { id: s.sessionId }, body: { agent: s.agentId } })
|
|
141
|
-
}
|
|
142
|
-
} catch (error) {
|
|
143
|
-
// 切会话是主操作,设置重放失败只记日志(目标会话用其自身/默认设置)
|
|
144
|
-
console.error("[sessions] 重放模型/Agent 设置失败:", error)
|
|
145
|
-
}
|
|
146
|
-
}
|
|
242
|
+
// (2026-11-09 移除 applySettings:切换即重放已被 owner 裁定废除——
|
|
243
|
+
// 模型/Agent 是会话级状态,覆盖目标会话=破坏其归属;显式 /model /agent 命令
|
|
244
|
+
// 仍直接写当前会话(setModel/setAgent),/new 的继承走 createNew 内置路径。)
|
|
147
245
|
|
|
148
246
|
getModel(userId: string): { providerId?: string; modelId?: string } {
|
|
149
247
|
const s = this.sessions.get(userId)
|
package/src/plugin-entry.ts
CHANGED
|
@@ -1,115 +1,139 @@
|
|
|
1
|
-
// @input: ./core/instance-lock(存活观测), ./core/bot-launcher(拉起)
|
|
2
|
-
// @output: default(Plugin.define server 入口)
|
|
3
|
-
// @pos: 根层 - D 路径插件入口:安装即常驻的引导器
|
|
4
|
-
//
|
|
5
|
-
// D 路径(2026-10-30 用户拍板):插件只做引导器+看门狗,bot 本体永远是
|
|
6
|
-
// detached 独立进程。spike 实证"插件约每小时被重载"在此形态下反转为免费巡检:
|
|
7
|
-
// 每次 setup 重跑=一次存活检查。插件 unload 绝不碰 bot。
|
|
8
|
-
// 多 location 并发加载(spike 实证 3 连实例):靠 bot 侧 try 模式文件锁仲裁——
|
|
9
|
-
// 只有第一个被拉起的 bot 持锁存活,其余自动退出。
|
|
10
|
-
import { Plugin } from "@opencode/plugin"
|
|
11
|
-
import { join } from "path"
|
|
12
|
-
import { homedir } from "os"
|
|
13
|
-
import { appendFileSync, existsSync, renameSync, statSync } from "fs"
|
|
14
|
-
import { fileURLToPath } from "url"
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
//
|
|
26
|
-
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
1
|
+
// @input: ./core/instance-lock(存活观测), ./core/bot-launcher(拉起)
|
|
2
|
+
// @output: default(Plugin.define server 入口)
|
|
3
|
+
// @pos: 根层 - D 路径插件入口:安装即常驻的引导器
|
|
4
|
+
//
|
|
5
|
+
// D 路径(2026-10-30 用户拍板):插件只做引导器+看门狗,bot 本体永远是
|
|
6
|
+
// detached 独立进程。spike 实证"插件约每小时被重载"在此形态下反转为免费巡检:
|
|
7
|
+
// 每次 setup 重跑=一次存活检查。插件 unload 绝不碰 bot。
|
|
8
|
+
// 多 location 并发加载(spike 实证 3 连实例):靠 bot 侧 try 模式文件锁仲裁——
|
|
9
|
+
// 只有第一个被拉起的 bot 持锁存活,其余自动退出。
|
|
10
|
+
import { Plugin } from "@opencode/plugin"
|
|
11
|
+
import { join } from "path"
|
|
12
|
+
import { homedir } from "os"
|
|
13
|
+
import { appendFileSync, existsSync, renameSync, statSync } from "fs"
|
|
14
|
+
import { fileURLToPath } from "url"
|
|
15
|
+
import { botWatchdogPaths, superviseOnce, appendWatchdogLog } from "./core/watchdog.js"
|
|
16
|
+
import { startBot } from "./core/bot-control.js"
|
|
17
|
+
import { runNotifyCli } from "./cli/notify.js"
|
|
18
|
+
import { readDotEnvField } from "./core/bot-launcher.js"
|
|
19
|
+
import { electSupervisor } from "./core/supervisor-election.js"
|
|
20
|
+
|
|
21
|
+
const ENV_FILE = join(homedir(), ".openqq", ".env")
|
|
22
|
+
const CHECK_INTERVAL_MS = (() => {
|
|
23
|
+
const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000")
|
|
24
|
+
return Number.isFinite(n) && n > 0 ? n : 300_000
|
|
25
|
+
})() // 看门狗巡检间隔(env QQ_WATCHDOG_INTERVAL_MS 可调;插件重载会重置,兜底是每小时 reload)
|
|
26
|
+
|
|
27
|
+
// —— 事件探针(2026-10-30 自 qqbot-event-probe.ts 并入,默认关)——
|
|
28
|
+
// 原独立探针已完成 spike 取证使命(form/permission 事件流实证);保留为可选诊断:
|
|
29
|
+
// ~/.openqq/.env 里 QQ_EVENT_PROBE=true 开启,全量事件 {ts,type,sessionID} 落
|
|
30
|
+
// ~/.openqq/opencode-events.jsonl(5MB 轮转,不记正文=零泄密面)。
|
|
31
|
+
const PROBE_FILE = join(homedir(), ".openqq", "opencode-events.jsonl")
|
|
32
|
+
const PROBE_ROTATE_BYTES = 5 * 1024 * 1024
|
|
33
|
+
|
|
34
|
+
function probeAppend(line: string): void {
|
|
35
|
+
try {
|
|
36
|
+
if (existsSync(PROBE_FILE) && statSync(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
|
|
37
|
+
renameSync(PROBE_FILE, PROBE_FILE + ".1")
|
|
38
|
+
}
|
|
39
|
+
appendFileSync(PROBE_FILE, line + "\n")
|
|
40
|
+
} catch {
|
|
41
|
+
// 探针永不阻断宿主
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export default Plugin.define({
|
|
46
|
+
id: "opencode-qqbot",
|
|
47
|
+
setup(_ctx) {
|
|
48
|
+
// P3(2026-10-30 清债):阻塞原因告警只在"状态变化"时打——插件每小时重载
|
|
49
|
+
// + 5min 巡检,缺凭据/无运行时不处理会重复喷日志。恢复畅通时复位。
|
|
50
|
+
let lastBlocker: string | null = null
|
|
51
|
+
const warnOnce = (key: string, message: string): void => {
|
|
52
|
+
if (lastBlocker === key) return
|
|
53
|
+
lastBlocker = key
|
|
54
|
+
console.warn(message)
|
|
55
|
+
}
|
|
56
|
+
const ensure = (): void => {
|
|
57
|
+
try {
|
|
58
|
+
// 2026-11-20 应修尽修批:legacy 字段缺省时回退 QQ_BOTS 首角色(纯多角色部署)
|
|
59
|
+
const botsRaw = readDotEnvField(ENV_FILE, "QQ_BOTS")
|
|
60
|
+
let botsFirst: string | null = null
|
|
61
|
+
if (botsRaw) {
|
|
62
|
+
try {
|
|
63
|
+
const arr = JSON.parse(botsRaw) as Array<{ appId?: unknown }>
|
|
64
|
+
const first = Array.isArray(arr) ? arr[0]?.appId : undefined
|
|
65
|
+
if (typeof first === "string" && first) botsFirst = first
|
|
66
|
+
} catch {
|
|
67
|
+
/* 坏 JSON 视为无 */
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const appId = readDotEnvField(ENV_FILE, "QQ_APP_ID") ?? botsFirst
|
|
71
|
+
if (!appId) {
|
|
72
|
+
warnOnce(
|
|
73
|
+
"cred",
|
|
74
|
+
"[opencode-qqbot] 未发现 ~/.openqq/.env 凭据——先运行 npx @linjz/opencode-qqbot setup 扫码绑定(或参考 README 手写 .env),完成后插件将在下次巡检自动拉起 bot",
|
|
75
|
+
)
|
|
76
|
+
return
|
|
77
|
+
}
|
|
78
|
+
// 双触发器归一(2026-11-20 owner 批):service(计划任务看门狗)与 plugin
|
|
79
|
+
// (本引导器巡检)租约选主——service 持租约时整轮让贤,连 superviseOnce
|
|
80
|
+
// 都不进(零干扰);service 停排/死亡后租约过期自动接管,双向自愈。
|
|
81
|
+
if (!electSupervisor("plugin")) return
|
|
82
|
+
// 2026-11-09 重构:巡检升级为 superviseOnce(与计划任务同一监督矩阵 + 认领互斥):
|
|
83
|
+
// 优雅杀/冷却/重启强度超限 give-up 并告警,杜绝裸「杀旧拉新」循环。
|
|
84
|
+
void superviseOnce({
|
|
85
|
+
paths: botWatchdogPaths(appId),
|
|
86
|
+
spawn: () => startBot(fileURLToPath(import.meta.url), (line) => console.log(line)),
|
|
87
|
+
log: (line) => console.log(line),
|
|
88
|
+
alert: (message) => {
|
|
89
|
+
console.warn(message)
|
|
90
|
+
void runNotifyCli(["--text", message, "--id", `supervisor-giveup-${Date.now()}`]).catch(() => {})
|
|
91
|
+
},
|
|
92
|
+
})
|
|
93
|
+
.then((result) => {
|
|
94
|
+
if (result.action === "restart") {
|
|
95
|
+
console.log(`[opencode-qqbot] bot 已拉起(${result.detail})`)
|
|
96
|
+
}
|
|
97
|
+
if (result.action === "ok" || result.action === "restart") lastBlocker = null
|
|
98
|
+
})
|
|
99
|
+
.catch((error) => {
|
|
100
|
+
// 2026-11-20 修:静默消除——巡检失败只进引擎 console 曾造成 6 分钟无人拉活空窗无人知
|
|
101
|
+
appendWatchdogLog(`[plugin] 巡检失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
102
|
+
console.error("[opencode-qqbot] 巡检失败:", error instanceof Error ? error.message : error)
|
|
103
|
+
})
|
|
104
|
+
} catch (error) {
|
|
105
|
+
// 引导器永不阻断宿主
|
|
106
|
+
console.error("[opencode-qqbot] 拉起失败:", error instanceof Error ? error.message : error)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
ensure()
|
|
110
|
+
const timer = setInterval(ensure, CHECK_INTERVAL_MS)
|
|
111
|
+
|
|
112
|
+
// 事件探针(可选,默认关):QQ_EVENT_PROBE=true 时订阅全量事件流落盘
|
|
113
|
+
let probeAbort: AbortController | null = null
|
|
114
|
+
if (readDotEnvField(ENV_FILE, "QQ_EVENT_PROBE") === "true") {
|
|
115
|
+
probeAbort = new AbortController()
|
|
116
|
+
const signal = probeAbort.signal
|
|
117
|
+
void (async () => {
|
|
118
|
+
probeAppend(JSON.stringify({ ts: new Date().toISOString(), type: "probe.started", sessionID: null }))
|
|
119
|
+
try {
|
|
120
|
+
for await (const event of _ctx.event.subscribe({ signal })) {
|
|
121
|
+
const ev = event as { type: string; data?: { sessionID?: string } }
|
|
122
|
+
probeAppend(
|
|
123
|
+
JSON.stringify({ ts: new Date().toISOString(), type: ev.type, sessionID: ev.data?.sessionID ?? null }),
|
|
124
|
+
)
|
|
125
|
+
}
|
|
126
|
+
} catch {
|
|
127
|
+
// abort 即退出(插件卸载路径)
|
|
128
|
+
}
|
|
129
|
+
})()
|
|
130
|
+
console.log("[opencode-qqbot] 事件探针已开启(QQ_EVENT_PROBE=true)")
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// 卸载只停巡检与探针——bot 是独立进程,继续存活(D 路径核心语义)
|
|
134
|
+
return () => {
|
|
135
|
+
clearInterval(timer)
|
|
136
|
+
probeAbort?.abort()
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
})
|