@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
@@ -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 { join } from "path"
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 STORE_DIR = join(homedir(), ".openqq")
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(STORE_FILE)) return
39
+ if (!existsSync(this.storeFile)) return
34
40
  // 手工编辑或 PowerShell Out-File 常带 BOM,JSON.parse 会炸——先剥掉
35
- const raw = readFileSync(STORE_FILE, "utf8").replace(/^\uFEFF/, "")
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
- if (!existsSync(STORE_DIR)) mkdirSync(STORE_DIR, { recursive: true })
51
- writeFileSync(STORE_FILE, JSON.stringify(Object.fromEntries(this.sessions), null, 2), "utf8")
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 result = await this.client.session.create({})
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 result = await this.client.session.create({})
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
- switchSession(userId: string, sessionId: string, title?: string): void {
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
- // 切到别的会话时,把本用户记住的模型/Agent 重放到目标会话
92
- //(v2 模型是 session 级设置,不跟随 prompt)。
125
+ // 2026-11-09 owner 裁定(反转 2026-10-29 设计):切换**不继承**——模型/Agent
126
+ // 是会话级状态(桌面端同语义),不得用本用户在此前会话的偏好覆盖目标会话;
127
+ // 反向从目标会话回读真实设置写回映射(/status 与后续 /model 以目标为准)。
93
128
  if (changed) {
94
- void this.applySettings(userId)
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
- all(): Array<{ userId: string; sessionId: string }> {
104
- return [...this.sessions.entries()].map(([userId, s]) => ({ userId, sessionId: s.sessionId }))
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
- private async applySettings(userId: string): Promise<void> {
130
- const s = this.sessions.get(userId)
131
- if (!s) return
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)
@@ -1,115 +1,120 @@
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 { isInstanceAlive } from "./core/instance-lock.js"
16
- import { resolveRuntime, buildLaunchPlan, spawnBotDetached, resolveBotEntry, readDotEnvField, botLogPath } from "./core/bot-launcher.js"
17
-
18
- const ENV_FILE = join(homedir(), ".openqq", ".env")
19
- const CHECK_INTERVAL_MS = (() => {
20
- const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000")
21
- return Number.isFinite(n) && n > 0 ? n : 300_000
22
- })() // 看门狗巡检间隔(env QQ_WATCHDOG_INTERVAL_MS 可调;插件重载会重置,兜底是每小时 reload)
23
-
24
- // —— 事件探针(2026-10-30 自 qqbot-event-probe.ts 并入,默认关)——
25
- // 原独立探针已完成 spike 取证使命(form/permission 事件流实证);保留为可选诊断:
26
- // ~/.openqq/.env 里 QQ_EVENT_PROBE=true 开启,全量事件 {ts,type,sessionID} 落
27
- // ~/.openqq/opencode-events.jsonl(5MB 轮转,不记正文=零泄密面)。
28
- const PROBE_FILE = join(homedir(), ".openqq", "opencode-events.jsonl")
29
- const PROBE_ROTATE_BYTES = 5 * 1024 * 1024
30
-
31
- function probeAppend(line: string): void {
32
- try {
33
- if (existsSync(PROBE_FILE) && statSync(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
34
- renameSync(PROBE_FILE, PROBE_FILE + ".1")
35
- }
36
- appendFileSync(PROBE_FILE, line + "\n")
37
- } catch {
38
- // 探针永不阻断宿主
39
- }
40
- }
41
-
42
- export default Plugin.define({
43
- id: "opencode-qqbot",
44
- setup(_ctx) {
45
- // P3(2026-10-30 清债):阻塞原因告警只在"状态变化"时打——插件每小时重载
46
- // + 5min 巡检,缺凭据/无运行时不处理会重复喷日志。恢复畅通时复位。
47
- let lastBlocker: string | null = null
48
- const warnOnce = (key: string, message: string): void => {
49
- if (lastBlocker === key) return
50
- lastBlocker = key
51
- console.warn(message)
52
- }
53
- const ensure = (): void => {
54
- try {
55
- const appId = readDotEnvField(ENV_FILE, "QQ_APP_ID")
56
- if (!appId) {
57
- warnOnce(
58
- "cred",
59
- "[opencode-qqbot] 未发现 ~/.openqq/.env 凭据——先运行 npx @linjz/opencode-qqbot setup 扫码绑定(或参考 README 手写 .env),完成后插件将在下次巡检自动拉起 bot",
60
- )
61
- return
62
- }
63
- if (isInstanceAlive(appId)) {
64
- lastBlocker = null // 畅通复位
65
- return
66
- }
67
- const entry = resolveBotEntry(fileURLToPath(import.meta.url))
68
- if (!entry) {
69
- warnOnce("entry", "[opencode-qqbot] 未找到 bot 入口(bot.js / dist/openqq-bot.js / src/index.ts 全缺)——插件安装不完整")
70
- return
71
- }
72
- const runtime = resolveRuntime()
73
- if (!runtime) {
74
- warnOnce("runtime", "[opencode-qqbot] 未找到 bun/node 运行时,无法拉起 bot——请安装其中之一(https://bun.sh)")
75
- return
76
- }
77
- const pid = spawnBotDetached(buildLaunchPlan(runtime, entry, botLogPath()))
78
- console.log(`[opencode-qqbot] bot 已拉起(pid=${pid},runtime=${runtime},entry=${entry})`)
79
- lastBlocker = null
80
- } catch (error) {
81
- // 引导器永不阻断宿主
82
- console.error("[opencode-qqbot] 拉起失败:", error instanceof Error ? error.message : error)
83
- }
84
- }
85
- ensure()
86
- const timer = setInterval(ensure, CHECK_INTERVAL_MS)
87
-
88
- // 事件探针(可选,默认关):QQ_EVENT_PROBE=true 时订阅全量事件流落盘
89
- let probeAbort: AbortController | null = null
90
- if (readDotEnvField(ENV_FILE, "QQ_EVENT_PROBE") === "true") {
91
- probeAbort = new AbortController()
92
- const signal = probeAbort.signal
93
- void (async () => {
94
- probeAppend(JSON.stringify({ ts: new Date().toISOString(), type: "probe.started", sessionID: null }))
95
- try {
96
- for await (const event of _ctx.event.subscribe({ signal })) {
97
- const ev = event as { type: string; data?: { sessionID?: string } }
98
- probeAppend(
99
- JSON.stringify({ ts: new Date().toISOString(), type: ev.type, sessionID: ev.data?.sessionID ?? null }),
100
- )
101
- }
102
- } catch {
103
- // abort 即退出(插件卸载路径)
104
- }
105
- })()
106
- console.log("[opencode-qqbot] 事件探针已开启(QQ_EVENT_PROBE=true)")
107
- }
108
-
109
- // 卸载只停巡检与探针——bot 是独立进程,继续存活(D 路径核心语义)
110
- return () => {
111
- clearInterval(timer)
112
- probeAbort?.abort()
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 } 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
+
20
+ const ENV_FILE = join(homedir(), ".openqq", ".env")
21
+ const CHECK_INTERVAL_MS = (() => {
22
+ const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000")
23
+ return Number.isFinite(n) && n > 0 ? n : 300_000
24
+ })() // 看门狗巡检间隔(env QQ_WATCHDOG_INTERVAL_MS 可调;插件重载会重置,兜底是每小时 reload)
25
+
26
+ // —— 事件探针(2026-10-30 自 qqbot-event-probe.ts 并入,默认关)——
27
+ // 原独立探针已完成 spike 取证使命(form/permission 事件流实证);保留为可选诊断:
28
+ // ~/.openqq/.env 里 QQ_EVENT_PROBE=true 开启,全量事件 {ts,type,sessionID} 落
29
+ // ~/.openqq/opencode-events.jsonl(5MB 轮转,不记正文=零泄密面)。
30
+ const PROBE_FILE = join(homedir(), ".openqq", "opencode-events.jsonl")
31
+ const PROBE_ROTATE_BYTES = 5 * 1024 * 1024
32
+
33
+ function probeAppend(line: string): void {
34
+ try {
35
+ if (existsSync(PROBE_FILE) && statSync(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
36
+ renameSync(PROBE_FILE, PROBE_FILE + ".1")
37
+ }
38
+ appendFileSync(PROBE_FILE, line + "\n")
39
+ } catch {
40
+ // 探针永不阻断宿主
41
+ }
42
+ }
43
+
44
+ export default Plugin.define({
45
+ id: "opencode-qqbot",
46
+ setup(_ctx) {
47
+ // P3(2026-10-30 清债):阻塞原因告警只在"状态变化"时打——插件每小时重载
48
+ // + 5min 巡检,缺凭据/无运行时不处理会重复喷日志。恢复畅通时复位。
49
+ let lastBlocker: string | null = null
50
+ const warnOnce = (key: string, message: string): void => {
51
+ if (lastBlocker === key) return
52
+ lastBlocker = key
53
+ console.warn(message)
54
+ }
55
+ const ensure = (): void => {
56
+ try {
57
+ const appId = readDotEnvField(ENV_FILE, "QQ_APP_ID")
58
+ if (!appId) {
59
+ warnOnce(
60
+ "cred",
61
+ "[opencode-qqbot] 未发现 ~/.openqq/.env 凭据——先运行 npx @linjz/opencode-qqbot setup 扫码绑定(或参考 README 手写 .env),完成后插件将在下次巡检自动拉起 bot",
62
+ )
63
+ return
64
+ }
65
+ // 2026-11-09 重构:巡检升级为 superviseOnce(与计划任务同一监督矩阵 + 认领互斥):
66
+ // 优雅杀/冷却/重启强度超限 give-up 并告警,杜绝裸「杀旧拉新」循环。
67
+ void superviseOnce({
68
+ paths: botWatchdogPaths(appId),
69
+ spawn: () => startBot(fileURLToPath(import.meta.url), (line) => console.log(line)),
70
+ log: (line) => console.log(line),
71
+ alert: (message) => {
72
+ console.warn(message)
73
+ void runNotifyCli(["--text", message, "--id", `supervisor-giveup-${Date.now()}`]).catch(() => {})
74
+ },
75
+ })
76
+ .then((result) => {
77
+ if (result.action === "restart") {
78
+ console.log(`[opencode-qqbot] bot 已拉起(${result.detail})`)
79
+ }
80
+ if (result.action === "ok" || result.action === "restart") lastBlocker = null
81
+ })
82
+ .catch((error) => {
83
+ console.error("[opencode-qqbot] 巡检失败:", error instanceof Error ? error.message : error)
84
+ })
85
+ } catch (error) {
86
+ // 引导器永不阻断宿主
87
+ console.error("[opencode-qqbot] 拉起失败:", error instanceof Error ? error.message : error)
88
+ }
89
+ }
90
+ ensure()
91
+ const timer = setInterval(ensure, CHECK_INTERVAL_MS)
92
+
93
+ // 事件探针(可选,默认关):QQ_EVENT_PROBE=true 时订阅全量事件流落盘
94
+ let probeAbort: AbortController | null = null
95
+ if (readDotEnvField(ENV_FILE, "QQ_EVENT_PROBE") === "true") {
96
+ probeAbort = new AbortController()
97
+ const signal = probeAbort.signal
98
+ void (async () => {
99
+ probeAppend(JSON.stringify({ ts: new Date().toISOString(), type: "probe.started", sessionID: null }))
100
+ try {
101
+ for await (const event of _ctx.event.subscribe({ signal })) {
102
+ const ev = event as { type: string; data?: { sessionID?: string } }
103
+ probeAppend(
104
+ JSON.stringify({ ts: new Date().toISOString(), type: ev.type, sessionID: ev.data?.sessionID ?? null }),
105
+ )
106
+ }
107
+ } catch {
108
+ // abort 即退出(插件卸载路径)
109
+ }
110
+ })()
111
+ console.log("[opencode-qqbot] 事件探针已开启(QQ_EVENT_PROBE=true)")
112
+ }
113
+
114
+ // 卸载只停巡检与探针——bot 是独立进程,继续存活(D 路径核心语义)
115
+ return () => {
116
+ clearInterval(timer)
117
+ probeAbort?.abort()
118
+ }
119
+ },
120
+ })