@linjz/opencode-qqbot 0.0.0-stage → 0.3.1

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.
@@ -0,0 +1,304 @@
1
+ // @input: ../opencode/client (FormInfo/FormField/FormOption), ../qq/types (MessageContext)
2
+ // @output: renderFormPrompt, parseFormAnswer, createFormBridge, FORM_PROMPT_TTL_MS
3
+ // @pos: core - 表单桥接(L 项 2026-10-30):V2 Form(选择弹窗 A/B/C/D)的 QQ 同步与作答回传。
4
+ //
5
+ // 背景:昨晚"卡到今天"事故的真凶即此类弹窗(V2 Form:MCP input form/选择表单)。
6
+ // 2.1.3 即有完整 REST(GET /api/form 全局列表 / POST .../form/{id}/reply)+ SSE 事件
7
+ // (form.created/form.replied,探针实采)——纯外部 bot 可桥,无需插件无需升级。
8
+ // MVP 边界:单交互字段完整支持(选择/多选/布尔/自由文本);多字段表单提示回桌面。
9
+ import type { FormInfo, OpencodeClient } from "../opencode/client.js"
10
+ import type { MessageContext } from "../qq/types.js"
11
+ import type { InlineKeyboard, KeyboardButton } from "../qq/api.js"
12
+ import { redactSecrets } from "../opencode/history.js"
13
+
14
+ export const FORM_PROMPT_TTL_MS = 30 * 60 * 1000
15
+ const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
16
+ const BUTTON_LABEL_MAX = 10
17
+ const BUTTONS_PER_ROW = 2
18
+
19
+ // 宽松字段视图:V2 字段类型可能扩展(external 等),运行时用宽类型读取可选属性,
20
+ // 未知类型走自由文本兜底而不是报错。
21
+ interface FieldLike {
22
+ key: string
23
+ type: string
24
+ title?: string
25
+ description?: string
26
+ required?: boolean
27
+ hidden?: boolean
28
+ options?: Array<{ value: string; label: string; description?: string }>
29
+ minimum?: number
30
+ maximum?: number
31
+ minItems?: number
32
+ maxItems?: number
33
+ }
34
+
35
+ // 找第一个可交互字段(MVP:单字段表单完整支持)
36
+ export function primaryField(form: FormInfo): FieldLike | undefined {
37
+ return form.fields.find((f) => !(f as FieldLike).hidden)
38
+ }
39
+
40
+ /** 渲染表单为 QQ 文本(选项字母化 A/B/C/D;多选提示逗号分隔)。 */
41
+ export function renderFormPrompt(form: FormInfo): string {
42
+ const field = primaryField(form)
43
+ const lines = [`📝 需要你的选择:${redactSecrets(form.title)}`]
44
+ if (!field) {
45
+ lines.push("(空表单,请回桌面处理)")
46
+ return lines.join("\n")
47
+ }
48
+ const visible = form.fields.filter((f) => !(f as FieldLike).hidden)
49
+ if (visible.length > 1) {
50
+ lines.push("(该表单含多个输入项,请在桌面端完成)")
51
+ return lines.join("\n")
52
+ }
53
+ if (field.title) lines.push(redactSecrets(field.title))
54
+ if (field.description) lines.push(redactSecrets(field.description))
55
+ if ((field.type === "multiselect" || field.type === "string") && field.options?.length) {
56
+ field.options.slice(0, LETTERS.length).forEach((opt, i) => {
57
+ lines.push(`${LETTERS[i]}) ${redactSecrets(opt.label)}`)
58
+ })
59
+ lines.push(field.type === "multiselect" ? '回复字母(多选用逗号,如 "A,C")' : "回复字母/序号或选项文字")
60
+ } else if (field.type === "boolean") {
61
+ lines.push("回复 是 / 否")
62
+ } else {
63
+ lines.push("请直接回复内容")
64
+ }
65
+ lines.push("(30 分钟未答自动取消)")
66
+ return lines.join("\n")
67
+ }
68
+
69
+ function tokenToOption(token: string, field: FieldLike): string | undefined {
70
+ const t = token.trim()
71
+ if (!t) return undefined
72
+ const opts = field.options ?? []
73
+ // 字母 A/B/C...
74
+ const letterIdx = LETTERS.indexOf(t.toUpperCase())
75
+ if (letterIdx >= 0 && letterIdx < opts.length) return opts[letterIdx].value
76
+ // 1-based 序号
77
+ const num = Number(t)
78
+ if (Number.isInteger(num) && num >= 1 && num <= opts.length) return opts[num - 1].value
79
+ // 精确匹配 value 或 label
80
+ const hit = opts.find((o) => o.value === t || o.label === t)
81
+ return hit?.value
82
+ }
83
+
84
+ /** 解析用户回复为 Form.Answer;无法解析返回 null(调用方发提示)。 */
85
+ export function parseFormAnswer(form: FormInfo, text: string): Record<string, unknown> | null {
86
+ const field = primaryField(form)
87
+ if (!field) return null
88
+ const t = text.trim()
89
+ if (!t) return null
90
+
91
+ if (field.type === "boolean") {
92
+ if (/^(是|yes|y|true|1|对)$/i.test(t)) return { [field.key]: true }
93
+ if (/^(否|no|n|false|0|不对)$/i.test(t)) return { [field.key]: false }
94
+ return null
95
+ }
96
+ if (field.type === "number" || field.type === "integer") {
97
+ const n = Number(t)
98
+ if (!Number.isFinite(n)) return null
99
+ if (field.type === "integer" && !Number.isInteger(n)) return null
100
+ if (typeof field.minimum === "number" && n < field.minimum) return null
101
+ if (typeof field.maximum === "number" && n > field.maximum) return null
102
+ return { [field.key]: field.type === "integer" ? Math.floor(n) : n }
103
+ }
104
+ if (field.type === "multiselect") {
105
+ const tokens = t.split(/[,,、\s]+/).filter(Boolean)
106
+ if (tokens.length === 0) return null
107
+ const values: string[] = []
108
+ for (const token of tokens) {
109
+ const v = tokenToOption(token, field)
110
+ if (v === undefined) return null
111
+ if (!values.includes(v)) values.push(v)
112
+ }
113
+ if (typeof field.minItems === "number" && values.length < field.minItems) return null
114
+ if (typeof field.maxItems === "number" && values.length > field.maxItems) return null
115
+ return { [field.key]: values }
116
+ }
117
+ if (field.type === "string" && field.options?.length) {
118
+ const v = tokenToOption(t, field)
119
+ return v === undefined ? null : { [field.key]: v }
120
+ }
121
+ // string 无选项 / 未知类型 = 自由文本兜底
122
+ return { [field.key]: t }
123
+ }
124
+
125
+ export interface PendingForm {
126
+ form: FormInfo
127
+ ctx: MessageContext
128
+ timer: ReturnType<typeof setTimeout> | null
129
+ }
130
+
131
+ // ── 表单按钮(2026-10-30 弹窗验证前置:点选式作答)──
132
+
133
+ /** button_data:t 判别 + formID + 字段 key + 选项 value(明文 JSON,与审批同款 P0 格式) */
134
+ export interface FormButtonData {
135
+ t: "form"
136
+ f: string
137
+ k: string
138
+ v: string
139
+ }
140
+
141
+ export function encodeFormButton(data: FormButtonData): string {
142
+ return JSON.stringify(data)
143
+ }
144
+
145
+ export function decodeFormButton(raw: string | undefined): FormButtonData | undefined {
146
+ if (!raw) return undefined
147
+ try {
148
+ const parsed = JSON.parse(raw) as Partial<FormButtonData>
149
+ if (parsed && typeof parsed === "object" && parsed.t === "form" && typeof parsed.f === "string" && typeof parsed.k === "string" && typeof parsed.v === "string") {
150
+ return parsed as FormButtonData
151
+ }
152
+ } catch {
153
+ // fall through
154
+ }
155
+ return undefined
156
+ }
157
+
158
+ function clipButtonLabel(text: string): string {
159
+ const s = text.trim()
160
+ return s.length > BUTTON_LABEL_MAX ? s.slice(0, BUTTON_LABEL_MAX - 1) + "…" : s
161
+ }
162
+
163
+ /**
164
+ * 构建表单选项键盘:单可见字段 + 有 options 时可用(string=单选直点直交;
165
+ * multiselect=点一个先交单值数组,多值仍走文字)。多字段/无选项 → null(文字作答)。
166
+ */
167
+ export function buildFormKeyboard(form: FormInfo, ownerOpenid: string): InlineKeyboard | null {
168
+ const visible = form.fields.filter((f) => !(f as FieldLike).hidden)
169
+ if (visible.length !== 1) return null
170
+ const field = visible[0] as FieldLike
171
+ const opts = field.options
172
+ if (!opts?.length) return null
173
+ if (field.type !== "string" && field.type !== "multiselect") return null
174
+ const buttons: KeyboardButton[] = opts.slice(0, 20).map((opt) => ({
175
+ id: `form-${form.id}-${opt.value}`.slice(0, 64),
176
+ // visited_label:点击后原生回显(按钮变已访问态、其余置灰),不再发明文确认消息
177
+ render_data: { label: clipButtonLabel(opt.label), visited_label: clipButtonLabel(`✓ ${opt.label}`), style: 1 },
178
+ action: {
179
+ type: 1,
180
+ permission: { type: 2, specify_user_ids: [ownerOpenid] },
181
+ data: encodeFormButton({ t: "form", f: form.id, k: field.key, v: opt.value }),
182
+ },
183
+ }))
184
+ const rows: Array<{ buttons: KeyboardButton[] }> = []
185
+ for (let i = 0; i < buttons.length; i += BUTTONS_PER_ROW) {
186
+ rows.push({ buttons: buttons.slice(i, i + BUTTONS_PER_ROW) })
187
+ }
188
+ return { content: { rows } }
189
+ }
190
+
191
+ export interface FormBridgeDeps {
192
+ client: OpencodeClient
193
+ sendReply: (ctx: MessageContext, text: string) => Promise<void>
194
+ safeDeliver: (ctx: MessageContext, text: string) => Promise<void>
195
+ /** 按钮卡片发送(有键盘时优先;返回 false 自动降级文字) */
196
+ sendFormCard?: (ctx: MessageContext, form: FormInfo, keyboard: InlineKeyboard) => Promise<boolean>
197
+ }
198
+
199
+ export interface FormBridge {
200
+ pushForm: (userId: string, ctx: MessageContext, form: FormInfo) => void
201
+ tryResolveText: (userId: string, text: string) => boolean
202
+ /** 按钮互动回调:匹配挂起表单则提交并返回 true;非本域返回 false */
203
+ handleButton: (event: { user_openid?: string; group_member_openid?: string; data?: { resolved?: { button_data?: string } } }) => boolean
204
+ hasPending: (userId: string) => boolean
205
+ getPending: (userId: string) => PendingForm | undefined
206
+ }
207
+
208
+ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
209
+ const pending = new Map<string, PendingForm>()
210
+
211
+ function clear(userId: string): PendingForm | undefined {
212
+ const entry = pending.get(userId)
213
+ if (!entry) return undefined
214
+ if (entry.timer) clearTimeout(entry.timer)
215
+ pending.delete(userId)
216
+ return entry
217
+ }
218
+
219
+ function submit(userId: string, form: FormInfo, ctx: MessageContext, answer: Record<string, unknown>, display: string, silent = false): void {
220
+ clear(userId)
221
+ void (async () => {
222
+ try {
223
+ await deps.client.form.reply({ path: { sessionID: form.sessionID, formID: form.id }, body: { answer } })
224
+ // 按钮路径静默(visited_label 原生回显已表达结果);文字路径保留明文回执
225
+ if (!silent) {
226
+ void deps.safeDeliver(ctx, `✅ 已提交选择:${display}`).catch(() => {})
227
+ }
228
+ console.log(`[form-bridge] 表单已作答 user=${userId.slice(0, 8)}… form=${form.id} answer=${display}`)
229
+ } catch (error) {
230
+ const msg = error instanceof Error ? error.message : String(error)
231
+ if (msg.includes("AlreadySettled") || msg.includes("already")) {
232
+ void deps.safeDeliver(ctx, "该选择已在桌面端处理过,任务应已继续").catch(() => {})
233
+ } else {
234
+ void deps.safeDeliver(ctx, `⚠️ 提交失败:${msg.slice(0, 120)}`).catch(() => {})
235
+ }
236
+ }
237
+ })()
238
+ }
239
+
240
+ function pushForm(userId: string, ctx: MessageContext, form: FormInfo): void {
241
+ // 去重:同表单已在挂起中
242
+ if (pending.get(userId)?.form.id === form.id) return
243
+ // 单一交互槽:新表单取代旧槽(提示旧表单失效)
244
+ const prev = clear(userId)
245
+ if (prev) {
246
+ void deps.safeDeliver(ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)").catch(() => {})
247
+ }
248
+ const entry: PendingForm = { form, ctx, timer: null }
249
+ entry.timer = setTimeout(() => {
250
+ if (pending.get(userId)?.form.id !== form.id) return
251
+ clear(userId)
252
+ void deps.safeDeliver(ctx, "⏰ 选择请求超时(30 分钟未作答),任务可能已被取消;可回桌面重试").catch(() => {})
253
+ }, FORM_PROMPT_TTL_MS)
254
+ pending.set(userId, entry)
255
+ console.log(`[form-bridge] 表单已推送 user=${userId.slice(0, 8)}… form=${form.id} title=${form.title.slice(0, 40)}`)
256
+ void (async () => {
257
+ const keyboard = buildFormKeyboard(form, ctx.userId)
258
+ if (keyboard && deps.sendFormCard) {
259
+ const sent = await deps.sendFormCard(ctx, form, keyboard).catch(() => false)
260
+ if (sent) return
261
+ }
262
+ await deps.sendReply(ctx, renderFormPrompt(form)).catch((error) => {
263
+ console.error("[form-bridge] 表单推送失败:", error instanceof Error ? error.message : error)
264
+ })
265
+ })()
266
+ }
267
+
268
+ /** 有挂起表单则消费本条文本(解析成功→提交;失败→提示),返回 true;无挂起返回 false。 */
269
+ function tryResolveText(userId: string, text: string): boolean {
270
+ const entry = pending.get(userId)
271
+ if (!entry) return false
272
+ const answer = parseFormAnswer(entry.form, text)
273
+ if (!answer) {
274
+ const field = primaryField(entry.form)
275
+ const hint =
276
+ field?.type === "multiselect"
277
+ ? '没看懂,请按选项字母回复(多选用逗号,如 "A,C")'
278
+ : field?.type === "boolean"
279
+ ? "请回复 是 或 否"
280
+ : "没看懂,请按提示回复"
281
+ void deps.sendReply(entry.ctx, hint).catch(() => {})
282
+ return true
283
+ }
284
+ submit(userId, entry.form, entry.ctx, answer, text.trim())
285
+ return true
286
+ }
287
+
288
+ function handleButton(event: { user_openid?: string; group_member_openid?: string; data?: { resolved?: { button_data?: string } } }): boolean {
289
+ const userId = event.user_openid ?? event.group_member_openid
290
+ if (!userId) return false
291
+ const button = decodeFormButton(event.data?.resolved?.button_data)
292
+ if (!button) return false
293
+ const entry = pending.get(userId)
294
+ if (!entry || entry.form.id !== button.f) {
295
+ console.log(`[form-bridge] 拒识过期表单按钮 user=${userId.slice(0, 8)}… form=${button.f}`)
296
+ return true // 已消费(拒识),不再下放
297
+ }
298
+ const answer: Record<string, unknown> = { [button.k]: button.v }
299
+ submit(userId, entry.form, entry.ctx, answer, button.v, true) // 按钮路径静默(visited_label 原生回显)
300
+ return true
301
+ }
302
+
303
+ return { pushForm, tryResolveText, handleButton, hasPending: (u) => pending.has(u), getPending: (u) => pending.get(u) }
304
+ }
@@ -0,0 +1,195 @@
1
+ // HC2(2026-10-26):运行中链路自愈巡检。
2
+ // 复盘3 教训:bot 与 opencode 平时零流量 + 看门狗只验进程心跳 → 下游死亡
3
+ // 不可观测(2026-10-26 实证:端口漂移后黑暗 3 天,直到用户消息撞上)。
4
+ // 本模块给链路装独立心跳:
5
+ // 每 OPENCODE_LINKWATCH_MINUTES(默认 30)分钟静默 healthCheck;
6
+ // 失败 → 立即端口发现 → 命中即原地热换基(client.rebase + onRebase 联动
7
+ // eventstream)→ 立即复验;
8
+ // 事故状态机落盘 ~/.openqq/incident.json(open/closed/attempts/rebasedTo,
9
+ // 跨重启延续计数、重启不洗白);
10
+ // 告警走 QQ 主动消息(每事故 open + fixed 各 ≤1 条,去重不骚扰)。
11
+ // @input: client(healthCheck/rebase)、discoverOpencode、alarm 回调、fs
12
+ // @output: startLinkWatch, LinkWatchDeps, IncidentRecord, incidentPath
13
+ // @pos: core - 链路巡检(HC2)
14
+ import { existsSync, readFileSync, writeFileSync } from "fs"
15
+ import { join } from "path"
16
+ import { homedir } from "os"
17
+ import { discoverOpencode, persistDiscovery, type OpencodeDiscovery } from "./discovery.js"
18
+ import { healthCheck, type OpencodeClient } from "../opencode/client.js"
19
+
20
+ export interface LinkWatchDeps {
21
+ client: OpencodeClient
22
+ // 热换基联动:eventstream 等持有同源 base 的组件在此同步换址
23
+ onRebase?: (baseUrl: string, discovery: OpencodeDiscovery) => void
24
+ // 告警通道(QQ 主动消息);未提供则仅落盘+日志
25
+ alarm?: (text: string) => Promise<void>
26
+ intervalMin?: number
27
+ // 测试注入:跳过 netstat 全扫描
28
+ discover?: (password?: string) => Promise<OpencodeDiscovery | null>
29
+ // 测试注入:事故文件路径(默认 ~/.openqq/incident.json)
30
+ incidentFile?: string
31
+ }
32
+
33
+ export interface IncidentRecord {
34
+ state: "open" | "closed"
35
+ since: string // ISO:首次失败时刻
36
+ lastCheck: string // ISO
37
+ lastError: string
38
+ attempts: number
39
+ rebasedTo?: string
40
+ }
41
+
42
+ export function incidentPath(): string {
43
+ return join(homedir(), ".openqq", "incident.json")
44
+ }
45
+
46
+ function saveIncident(path: string, rec: IncidentRecord): void {
47
+ try {
48
+ writeFileSync(path, JSON.stringify(rec, null, 2))
49
+ } catch (error) {
50
+ console.error("[linkwatch] incident 落盘失败:", error instanceof Error ? error.message : error)
51
+ }
52
+ }
53
+
54
+ function nowIso(): string {
55
+ return new Date().toISOString()
56
+ }
57
+
58
+ export interface LinkWatch {
59
+ stop(): void
60
+ // 测试/手动触发一轮巡检(与定时循环共用同一状态机,busy 互斥)
61
+ runOnce(): Promise<void>
62
+ }
63
+
64
+ export function startLinkWatch(deps: LinkWatchDeps): LinkWatch {
65
+ const envMin = Number(process.env.OPENCODE_LINKWATCH_MINUTES)
66
+ const intervalMs = Math.max(1, deps.intervalMin ?? (Number.isFinite(envMin) && envMin > 0 ? envMin : 30)) * 60_000
67
+ const file = deps.incidentFile ?? incidentPath()
68
+ const discover = deps.discover ?? ((p?: string) => discoverOpencode({ password: p }))
69
+ const password = process.env.OPENCODE_PASSWORD
70
+
71
+ let rec: IncidentRecord | null = null
72
+ let alarmOpenSent = false // 去重:每事故 open 告警只发一次(含跨重启)
73
+ let stopped = false
74
+ let busy = false
75
+ let loopTimer: ReturnType<typeof setTimeout> | null = null
76
+
77
+ // 恢复落盘的未结事故(跨重启延续;重启后不重发 open 告警,避免看门狗
78
+ // 周期重启导致告警风暴)
79
+ try {
80
+ if (existsSync(file)) {
81
+ const raw = JSON.parse(readFileSync(file, "utf-8")) as IncidentRecord
82
+ if (raw?.state === "open" && typeof raw.since === "string") {
83
+ rec = raw
84
+ alarmOpenSent = true
85
+ console.log(`[linkwatch] 恢复未结事故:自 ${raw.since}(attempts=${raw.attempts}),继续自愈`)
86
+ }
87
+ }
88
+ } catch {
89
+ // 损坏即视为无事故
90
+ }
91
+
92
+ async function fire(text: string): Promise<void> {
93
+ try {
94
+ await deps.alarm?.(text)
95
+ } catch (error) {
96
+ console.error("[linkwatch] 告警发送失败:", error instanceof Error ? error.message : error)
97
+ }
98
+ }
99
+
100
+ async function tick(): Promise<void> {
101
+ if (stopped || busy) return
102
+ busy = true
103
+ try {
104
+ try {
105
+ await healthCheck(deps.client, true)
106
+ // 健康:若有未结事故 → 结案(含恢复告警)
107
+ if (rec?.state === "open") {
108
+ const open = rec
109
+ const durMin = Math.max(1, Math.round((Date.now() - new Date(open.since).getTime()) / 60_000))
110
+ console.log(`[linkwatch] 链路恢复(中断约 ${durMin} 分钟,共 ${open.attempts} 次巡检失败)`)
111
+ if (!open.rebasedTo) {
112
+ // rebase 恢复路径在切换时已发过 fixed 告警;只有自然恢复才发恢复通知
113
+ await fire(`✅ OpenCode 链路恢复(中断约 ${durMin} 分钟,共 ${open.attempts} 次巡检失败)`)
114
+ }
115
+ saveIncident(file, { ...open, state: "closed", lastCheck: nowIso() })
116
+ rec = null
117
+ alarmOpenSent = false
118
+ }
119
+ return
120
+ } catch (error) {
121
+ const msg = error instanceof Error ? error.message : String(error)
122
+ if (!rec) {
123
+ rec = { state: "open", since: nowIso(), lastCheck: nowIso(), lastError: msg, attempts: 0 }
124
+ console.error(`[linkwatch] ⚠️ 链路失联开始(${msg}),转入自愈巡检`)
125
+ }
126
+ const inc = rec
127
+ inc.attempts++
128
+ inc.lastError = msg
129
+ inc.lastCheck = nowIso()
130
+
131
+ // 首次失败才发 open 告警(去重)
132
+ if (!alarmOpenSent) {
133
+ alarmOpenSent = true
134
+ await fire(
135
+ `⚠️ OpenCode 链路失联(自 ${inc.since.slice(11, 16)} 起,错误:${msg.slice(0, 80)})。已转入自动自愈:发现新端口会自动切换并通知。`,
136
+ )
137
+ }
138
+
139
+ // 自愈:端口发现 → 热换基 → 复验
140
+ const found = await discover(password)
141
+ if (found && found.baseUrl !== deps.client.baseUrl) {
142
+ deps.client.rebase(found.baseUrl)
143
+ deps.onRebase?.(found.baseUrl, found)
144
+ persistDiscovery(found)
145
+ inc.rebasedTo = found.baseUrl
146
+ saveIncident(file, inc)
147
+ console.log(`[linkwatch] 热换基完成 → ${found.baseUrl}(v${found.version}),复验中…`)
148
+ try {
149
+ await healthCheck(deps.client, true)
150
+ console.log("[linkwatch] ✅ 换基复验通过,链路恢复")
151
+ await fire(`✅ OpenCode 端口已漂移,已自动切换旧地址 → ${found.baseUrl}(v${found.version}),链路恢复。`)
152
+ saveIncident(file, { ...inc, state: "closed", lastCheck: nowIso() })
153
+ rec = null
154
+ alarmOpenSent = false
155
+ } catch (e2) {
156
+ inc.lastError = e2 instanceof Error ? e2.message : String(e2)
157
+ inc.lastCheck = nowIso()
158
+ saveIncident(file, inc)
159
+ console.error("[linkwatch] 换基后仍失联,下轮继续:", inc.lastError)
160
+ }
161
+ } else {
162
+ // 未发现新端口(服务真宕/同口抖动):保持 open,下一轮再试
163
+ saveIncident(file, inc)
164
+ console.error(`[linkwatch] 第 ${inc.attempts} 次巡检失败,未发现新端口(${msg.slice(0, 80)})`)
165
+ }
166
+ }
167
+ } finally {
168
+ busy = false
169
+ }
170
+ }
171
+
172
+ // 可取消 sleep:stop() 清掉 pending 定时器,独立脚本(runOnce 后退出)不再悬挂
173
+ function waitInterval(): Promise<void> {
174
+ return new Promise((resolve) => {
175
+ loopTimer = setTimeout(resolve, intervalMs)
176
+ })
177
+ }
178
+
179
+ const loop = async (): Promise<void> => {
180
+ while (!stopped) {
181
+ await waitInterval()
182
+ if (stopped) break
183
+ await tick()
184
+ }
185
+ }
186
+ void loop()
187
+
188
+ return {
189
+ stop: () => {
190
+ stopped = true
191
+ if (loopTimer) clearTimeout(loopTimer)
192
+ },
193
+ runOnce: tick,
194
+ }
195
+ }
@@ -0,0 +1,173 @@
1
+ // @input: ../opencode/{client, eventstream, mirror, sessions}, ../qq/types, ../commands, fs/path/os
2
+ // @output: createMirror
3
+ // @pos: 根层/core - 摘要镜像域(O7d 2026-10-15 自 bridge.ts 拆出:会话订阅、
4
+ // QQ 回合标记与延迟解锁、回合完成摘要投递、开关持久化)
5
+ import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs"
6
+ import { join } from "path"
7
+ import { homedir } from "os"
8
+ import type { MessageContext } from "../qq/types.js"
9
+ import type { OpencodeClient } from "../opencode/client.js"
10
+ import { createEventStream } from "../opencode/eventstream.js"
11
+ import { buildDigest } from "../opencode/mirror.js"
12
+ import type { SessionManager } from "../opencode/sessions.js"
13
+ import type { MirrorApi } from "../commands.js"
14
+
15
+ type EventStream = ReturnType<typeof createEventStream>
16
+
17
+ // 摘要镜像开关(~/.openqq/settings.json 持久;BOM 防御与 greeted 一致)
18
+ const MIRROR_SETTINGS_FILE = join(homedir(), ".openqq", "settings.json")
19
+
20
+ function loadMirrorEnabled(): boolean {
21
+ try {
22
+ if (existsSync(MIRROR_SETTINGS_FILE)) {
23
+ const raw = readFileSync(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "")
24
+ const parsed = JSON.parse(raw)
25
+ if (typeof parsed?.mirror === "boolean") return parsed.mirror
26
+ }
27
+ } catch {
28
+ // fall through to default
29
+ }
30
+ return true // 默认开(用户点单 A 摘要镜像)
31
+ }
32
+
33
+ function saveMirrorEnabled(enabled: boolean): void {
34
+ try {
35
+ mkdirSync(join(homedir(), ".openqq"), { recursive: true })
36
+ let existing: Record<string, unknown> = {}
37
+ if (existsSync(MIRROR_SETTINGS_FILE)) {
38
+ try {
39
+ const raw = readFileSync(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "")
40
+ const parsed = JSON.parse(raw)
41
+ if (parsed && typeof parsed === "object") existing = parsed
42
+ } catch {
43
+ // 损坏则重建
44
+ }
45
+ }
46
+ existing.mirror = enabled
47
+ writeFileSync(MIRROR_SETTINGS_FILE, JSON.stringify(existing, null, 2), "utf-8")
48
+ } catch (error) {
49
+ console.error("[mirror] 保存设置失败:", error)
50
+ }
51
+ }
52
+
53
+ export interface MirrorDeps {
54
+ sessions: SessionManager
55
+ eventStream: EventStream
56
+ client: OpencodeClient
57
+ lastCtx: ReadonlyMap<string, MessageContext> // bridge 拥有写权,本域只读
58
+ safeDeliver: (ctx: MessageContext, text: string) => Promise<void>
59
+ bgWaits: ReadonlyMap<string, { cancel: () => void }> // 后台等待在途则不解锁
60
+ busyUsers: ReadonlySet<string> // 会话主人在忙则不解锁(5 秒宽限内再判定)
61
+ }
62
+
63
+ export interface Mirror {
64
+ api: MirrorApi
65
+ ensureSubs: () => void
66
+ beginTurn: (sessionId: string) => void // 新 QQ 回合:补挂订阅 + 在途标记
67
+ scheduleUnlock: (sessionId: string) => void
68
+ }
69
+
70
+ export function createMirror(deps: MirrorDeps): Mirror {
71
+ const { sessions, eventStream, client, lastCtx, safeDeliver, bgWaits, busyUsers } = deps
72
+ const mirrorUnsubs = new Map<string, () => void>() // 摘要镜像订阅(独立于 /watch)
73
+ const qqTurnActive = new Set<string>() // QQ 发起的轮次在途(镜像跳过防重复)
74
+ const mirrorState = { enabled: loadMirrorEnabled() }
75
+
76
+ // ===== 摘要镜像(E 阶段 A 方案):桌面会话轮次完成 → QQ 摘要卡 =====
77
+ // 与 /watch 观察推送互补:观察给过程里程碑,镜像给问答正文摘要。
78
+ // QQ 自己发起的轮次由 promptAndWait 正常回复,不重复镜像(qqTurnActive 守卫)。
79
+ function ensureMirrorSubs(): void {
80
+ if (!mirrorState.enabled) return
81
+ for (const { sessionId } of sessions.all()) {
82
+ if (mirrorUnsubs.has(sessionId)) continue
83
+ mirrorUnsubs.set(
84
+ sessionId,
85
+ eventStream.subscribe(sessionId, (ev) => {
86
+ if (!mirrorState.enabled) return
87
+ if (ev.type !== "session.execution.succeeded") return
88
+ if (qqTurnActive.has(sessionId)) {
89
+ console.log(`[mirror] 跳过:QQ 回合在途(由 promptAndWait 直答)session=${sessionId}`)
90
+ return
91
+ }
92
+ void mirrorTurn(sessionId)
93
+ }),
94
+ )
95
+ }
96
+ }
97
+
98
+ function disableMirrorSubs(): void {
99
+ for (const unsub of mirrorUnsubs.values()) unsub()
100
+ mirrorUnsubs.clear()
101
+ }
102
+
103
+ // QQ 轮次结束后延迟解锁镜像:SSE 完成事件可能晚于 promptAndWait 返回,
104
+ // 5 秒宽限内若又有新 QQ 回合/后台等待在途则不解锁(防竞态开窗)。
105
+ function scheduleMirrorUnlock(sessionId: string): void {
106
+ setTimeout(() => {
107
+ if (bgWaits.has(sessionId)) return
108
+ const ownerBusy = sessions
109
+ .all()
110
+ .some((x) => x.sessionId === sessionId && busyUsers.has(x.userId))
111
+ if (ownerBusy) return
112
+ qqTurnActive.delete(sessionId)
113
+ }, 5000)
114
+ }
115
+
116
+ async function mirrorTurn(sessionID: string): Promise<void> {
117
+ try {
118
+ const owners = sessions.all().filter((x) => x.sessionId === sessionID).map((x) => x.userId)
119
+ if (owners.length === 0) {
120
+ console.log(`[mirror] 跳过:会话无映射主人 session=${sessionID}`)
121
+ return
122
+ }
123
+ const listJson = await client.session.messages({ path: { id: sessionID } })
124
+ const digest = buildDigest(listJson?.data ?? [])
125
+ if (!digest) {
126
+ console.log(`[mirror] 跳过:无可摘要内容(空轮/纯工具轮)session=${sessionID}`)
127
+ return
128
+ }
129
+ for (const userId of owners) {
130
+ // 无最近 ctx(重启后尚未收到新消息)→ 构造主动通道 ctx,
131
+ // deliver 的被动尝试失败会自然降级为主动消息(D4 配额内)。
132
+ const recent = lastCtx.get(userId)
133
+ const ctx: MessageContext = recent ?? { type: "c2c", userId, msgId: "", content: "" }
134
+ await safeDeliver(ctx, digest)
135
+ }
136
+ console.log(`[mirror] 会话 ${sessionID} 摘要已镜像给 ${owners.length} 个用户`)
137
+ } catch (error) {
138
+ console.error("[mirror] 摘要镜像失败:", error)
139
+ }
140
+ }
141
+
142
+ const api: MirrorApi = {
143
+ set(enabled) {
144
+ const prev = mirrorState.enabled
145
+ mirrorState.enabled = enabled
146
+ saveMirrorEnabled(enabled)
147
+ if (enabled) {
148
+ if (!prev) ensureMirrorSubs()
149
+ } else {
150
+ disableMirrorSubs()
151
+ }
152
+ return enabled
153
+ ? "✅ 摘要镜像已开启:桌面会话轮次完成后推送问答摘要"
154
+ : "🔇 摘要镜像已关闭(/mirror on 重新开启)"
155
+ },
156
+ status() {
157
+ const subs = mirrorUnsubs.size
158
+ return mirrorState.enabled
159
+ ? `📋 摘要镜像:开(已挂 ${subs} 个会话订阅)`
160
+ : "📋 摘要镜像:关(/mirror on 开启)"
161
+ },
162
+ }
163
+
164
+ return {
165
+ api,
166
+ ensureSubs: ensureMirrorSubs,
167
+ beginTurn(sessionId: string): void {
168
+ ensureMirrorSubs()
169
+ qqTurnActive.add(sessionId)
170
+ },
171
+ scheduleUnlock: scheduleMirrorUnlock,
172
+ }
173
+ }