@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/core/discovery.ts
CHANGED
|
@@ -1,151 +1,207 @@
|
|
|
1
|
-
// HC1(2026-10-26):opencode 服务端口漂移自动发现。
|
|
2
|
-
// 背景:桌面端 2.1.3 后台服务 = opencode-cli.exe serve --service,端口动态分配
|
|
3
|
-
//(实证 49374→28894;服务重建/系统重启后可能再变,且无持久化发现文件)。
|
|
4
|
-
// bot 配置的 OPENCODE_BASE_URL 失联(ECONNREFUSED)时,扫描本机 TCP 监听口
|
|
5
|
-
// 并逐口探测 /api/info 签名:
|
|
6
|
-
// {"version":"2.1.3","pid":44152,"urls":["http://127.0.0.1:28894"],"paths":{...}}
|
|
7
|
-
// 签名要求 version 字符串 + urls 数组 + paths 对象三层同构,随机端口误报概率≈0。
|
|
8
|
-
// 仅匹配 `${port}/api/info`:bot 的 V2 端点契约即 base=.../api(见 client.ts),
|
|
9
|
-
// 无 /api 前缀的形态与本契约不符,不采用。
|
|
10
|
-
// @input: 127.0.0.1 监听口(netstat -ano -p tcp)、/api/info 端点
|
|
11
|
-
// @output: discoverOpencode, probeOpencodeEndpoint, parseListenPorts, isOpencodeInfo, persistDiscovery
|
|
12
|
-
// @pos: core - 端口发现(HC1,Windows only)
|
|
13
|
-
import { exec } from "node:child_process"
|
|
14
|
-
import { promisify } from "node:util"
|
|
15
|
-
import { mkdirSync, writeFileSync } from "fs"
|
|
16
|
-
import { join } from "path"
|
|
17
|
-
import { homedir } from "os"
|
|
18
|
-
|
|
19
|
-
const execAsync = promisify(exec)
|
|
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
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
return null
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
}
|
|
151
|
-
|
|
1
|
+
// HC1(2026-10-26):opencode 服务端口漂移自动发现。
|
|
2
|
+
// 背景:桌面端 2.1.3 后台服务 = opencode-cli.exe serve --service,端口动态分配
|
|
3
|
+
//(实证 49374→28894;服务重建/系统重启后可能再变,且无持久化发现文件)。
|
|
4
|
+
// bot 配置的 OPENCODE_BASE_URL 失联(ECONNREFUSED)时,扫描本机 TCP 监听口
|
|
5
|
+
// 并逐口探测 /api/info 签名:
|
|
6
|
+
// {"version":"2.1.3","pid":44152,"urls":["http://127.0.0.1:28894"],"paths":{...}}
|
|
7
|
+
// 签名要求 version 字符串 + urls 数组 + paths 对象三层同构,随机端口误报概率≈0。
|
|
8
|
+
// 仅匹配 `${port}/api/info`:bot 的 V2 端点契约即 base=.../api(见 client.ts),
|
|
9
|
+
// 无 /api 前缀的形态与本契约不符,不采用。
|
|
10
|
+
// @input: 127.0.0.1 监听口(netstat -ano -p tcp)、/api/info 端点
|
|
11
|
+
// @output: discoverOpencode, probeOpencodeEndpoint, parseListenPorts, isOpencodeInfo, persistDiscovery, getLastScanUnauthorized, readLastDiscovered, resolveInitialBaseUrl
|
|
12
|
+
// @pos: core - 端口发现(HC1,Windows only)
|
|
13
|
+
import { exec } from "node:child_process"
|
|
14
|
+
import { promisify } from "node:util"
|
|
15
|
+
import { mkdirSync, readFileSync, writeFileSync } from "fs"
|
|
16
|
+
import { join } from "path"
|
|
17
|
+
import { homedir } from "os"
|
|
18
|
+
|
|
19
|
+
const execAsync = promisify(exec)
|
|
20
|
+
|
|
21
|
+
// 最近一次扫描里返回 401 的端口数(凭据不匹配诊断)。
|
|
22
|
+
// 2026-11-09 掉线事故:密码失配时每个端口都 401 → 签名全不命中,日志只剩
|
|
23
|
+
// 「无签名命中」,看起来像"服务不存在",排障要多绕很久。计数器让调用方能把
|
|
24
|
+
// 「服务不在」和「服务在但密码错」区分开。
|
|
25
|
+
let lastScanUnauthorized = 0
|
|
26
|
+
|
|
27
|
+
export function getLastScanUnauthorized(): number {
|
|
28
|
+
return lastScanUnauthorized
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface OpencodeDiscovery {
|
|
32
|
+
baseUrl: string
|
|
33
|
+
port: number
|
|
34
|
+
version: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type InfoPayload = { version?: unknown; urls?: unknown; paths?: unknown }
|
|
38
|
+
|
|
39
|
+
// /api/info 签名校验:version(string) + urls(非空数组) + paths(对象) 三层同构。
|
|
40
|
+
export function isOpencodeInfo(body: unknown): boolean {
|
|
41
|
+
if (body === null || typeof body !== "object") return false
|
|
42
|
+
const b = body as InfoPayload
|
|
43
|
+
return (
|
|
44
|
+
typeof b.version === "string" &&
|
|
45
|
+
b.version.length > 0 &&
|
|
46
|
+
Array.isArray(b.urls) &&
|
|
47
|
+
b.urls.length > 0 &&
|
|
48
|
+
b.paths !== null &&
|
|
49
|
+
typeof b.paths === "object"
|
|
50
|
+
)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// netstat/ss 输出 → 本机监听口列表(去重,保持首次出现序)。
|
|
54
|
+
// 跨平台兼容三形态(QQ 官方插件纯 TS 零 OS 分支为参照——我们也要不挑系统):
|
|
55
|
+
// Windows: TCP 127.0.0.1:28894 0.0.0.0:0 LISTENING 44152
|
|
56
|
+
// Linux ss: LISTEN 0 128 127.0.0.1:28894 0.0.0.0:*
|
|
57
|
+
// macOS: tcp4 0 0 127.0.0.1.28894 *.* LISTEN(注意 macOS 是点分隔)
|
|
58
|
+
// 规则:LISTEN(ING) 行内,取含 : 或 . 分隔的地址列,末段数字即端口;
|
|
59
|
+
// 裸 IP 末段可能误当端口(如 127.0.0.1 → 1),无害——探测时签名不符即跳过。
|
|
60
|
+
export function parseListenPorts(output: string): number[] {
|
|
61
|
+
const ports = new Set<number>()
|
|
62
|
+
for (const raw of output.split(/\r?\n/)) {
|
|
63
|
+
const line = raw.trim()
|
|
64
|
+
if (!/\bLISTEN(?:ING)?\b/i.test(line)) continue
|
|
65
|
+
for (const col of line.split(/\s+/)) {
|
|
66
|
+
const m = /^[\w.[\]:%*]*[:.](\d+)$/.exec(col)
|
|
67
|
+
if (!m) continue
|
|
68
|
+
const port = Number(m[1])
|
|
69
|
+
if (Number.isInteger(port) && port > 0 && port < 65536) ports.add(port)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return [...ports]
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 跨平台监听口枚举:Windows=netstat -ano -p tcp;Linux=ss -tln(兜底 netstat -tln);
|
|
76
|
+
// macOS=netstat -an -p tcp(兜底 ss)。命令失败→换备选→全灭则记日志返回空。
|
|
77
|
+
async function listListenPorts(): Promise<number[]> {
|
|
78
|
+
const platform = process.platform
|
|
79
|
+
const candidates: string[] =
|
|
80
|
+
platform === "win32"
|
|
81
|
+
? ["netstat -ano -p tcp"]
|
|
82
|
+
: platform === "darwin"
|
|
83
|
+
? ["netstat -an -p tcp", "ss -tln"]
|
|
84
|
+
: ["ss -tln", "netstat -tln"]
|
|
85
|
+
for (const cmd of candidates) {
|
|
86
|
+
try {
|
|
87
|
+
// windowsHide(2026-11-10 静默审计补齐):exec 经 cmd 中转,缺此参数时每次端口探测
|
|
88
|
+
// 弹可见控制台——owner 实证「修订后仍见 DOS 弹窗一闪」的闪现源之一。
|
|
89
|
+
const { stdout } = await execAsync(cmd, { maxBuffer: 10 * 1024 * 1024, timeout: 10_000, windowsHide: true })
|
|
90
|
+
const ports = parseListenPorts(stdout)
|
|
91
|
+
if (ports.length > 0) return ports
|
|
92
|
+
} catch (error) {
|
|
93
|
+
console.log(`[discovery] ${cmd.split(" ")[0]} 不可用: ${error instanceof Error ? error.message : error}`)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
console.log("[discovery] 监听口枚举工具全部不可用,跳过端口扫描")
|
|
97
|
+
return []
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// 探测单个 /api/info URL;命中签名返回版本号,否则 null
|
|
101
|
+
//(连接拒/超时/404/非 JSON/签名不符同归 null,永不抛出)。
|
|
102
|
+
export async function probeOpencodeEndpoint(
|
|
103
|
+
url: string,
|
|
104
|
+
opts?: { password?: string; timeoutMs?: number },
|
|
105
|
+
): Promise<string | null> {
|
|
106
|
+
const ac = new AbortController()
|
|
107
|
+
const timer = setTimeout(() => ac.abort(), opts?.timeoutMs ?? 900)
|
|
108
|
+
try {
|
|
109
|
+
const headers: Record<string, string> = {}
|
|
110
|
+
if (opts?.password) {
|
|
111
|
+
headers.Authorization = `Basic ${Buffer.from(`opencode:${opts.password}`).toString("base64")}`
|
|
112
|
+
}
|
|
113
|
+
const res = await fetch(url, { headers, signal: ac.signal, redirect: "manual" })
|
|
114
|
+
if (!res.ok) {
|
|
115
|
+
if (res.status === 401) lastScanUnauthorized++
|
|
116
|
+
return null
|
|
117
|
+
}
|
|
118
|
+
const body: unknown = JSON.parse(await res.text())
|
|
119
|
+
if (!isOpencodeInfo(body)) return null
|
|
120
|
+
return (body as InfoPayload).version as string
|
|
121
|
+
} catch {
|
|
122
|
+
return null
|
|
123
|
+
} finally {
|
|
124
|
+
clearTimeout(timer)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// 端口发现主流程:默认 netstat 自动列口;测试可注入 ports 跳过扫描。
|
|
129
|
+
// 建议调用方在外层包 try/catch——本函数不向上抛(内部兜底日志)。
|
|
130
|
+
export async function discoverOpencode(opts?: {
|
|
131
|
+
password?: string
|
|
132
|
+
timeoutMs?: number
|
|
133
|
+
ports?: number[]
|
|
134
|
+
}): Promise<OpencodeDiscovery | null> {
|
|
135
|
+
const ports = opts?.ports ?? (await listListenPorts())
|
|
136
|
+
if (ports.length === 0) return null
|
|
137
|
+
const started = Date.now()
|
|
138
|
+
let probed = 0
|
|
139
|
+
lastScanUnauthorized = 0
|
|
140
|
+
for (const port of ports) {
|
|
141
|
+
probed++
|
|
142
|
+
const version = await probeOpencodeEndpoint(`http://127.0.0.1:${port}/api/info`, opts)
|
|
143
|
+
if (version !== null) {
|
|
144
|
+
const hit: OpencodeDiscovery = { baseUrl: `http://127.0.0.1:${port}/api`, port, version }
|
|
145
|
+
console.log(
|
|
146
|
+
`[discovery] 命中 opencode 服务:${hit.baseUrl}(v${hit.version},第 ${probed}/${ports.length} 口,${Date.now() - started}ms)`,
|
|
147
|
+
)
|
|
148
|
+
return hit
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const unauth = lastScanUnauthorized
|
|
152
|
+
const hint = unauth > 0 ? `(其中 ${unauth} 个返回 401:凭据不匹配,检查 OPENCODE_PASSWORD / OPENCODE_BASE_URL)` : ""
|
|
153
|
+
console.log(`[discovery] 扫描 ${ports.length} 个监听口(${Date.now() - started}ms),无签名命中${hint}`)
|
|
154
|
+
return null
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// 发现结果落盘 ~/.openqq/last-discovered.json,供看门狗/排障查看。不写 .env。
|
|
158
|
+
const LAST_DISCOVERED_PATH = join(homedir(), ".openqq", "last-discovered.json")
|
|
159
|
+
|
|
160
|
+
export interface LastDiscovered {
|
|
161
|
+
baseUrl: string
|
|
162
|
+
port: number
|
|
163
|
+
version: string
|
|
164
|
+
at: string
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** 读上次自动发现档案(无档案/损坏 → null,绝不抛)。 */
|
|
168
|
+
export function readLastDiscovered(path: string = LAST_DISCOVERED_PATH): LastDiscovered | null {
|
|
169
|
+
try {
|
|
170
|
+
const raw = JSON.parse(readFileSync(path, "utf-8")) as Partial<LastDiscovered>
|
|
171
|
+
if (typeof raw.baseUrl === "string" && /^https?:\/\//.test(raw.baseUrl) && Number.isInteger(raw.port)) {
|
|
172
|
+
return raw as LastDiscovered
|
|
173
|
+
}
|
|
174
|
+
} catch {
|
|
175
|
+
/* 无档案或损坏 → 视为无 */
|
|
176
|
+
}
|
|
177
|
+
return null
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 启动初始 URL 决议(DEF-20261120-01c:owner「能自动发现的不必配置」举一反三):
|
|
182
|
+
* 显式 OPENCODE_BASE_URL > 上次自动发现档案(引擎换端口时第 1 次重试即纠正)
|
|
183
|
+
* > 占位地址(连接秒拒,快进重试-发现环)。三层都兜在既有 waitForOpencode
|
|
184
|
+
* 退避机制内,无新状态。
|
|
185
|
+
*/
|
|
186
|
+
export function resolveInitialBaseUrl(
|
|
187
|
+
explicit: string,
|
|
188
|
+
last: LastDiscovered | null,
|
|
189
|
+
): { url: string; source: "explicit" | "last-discovered" | "placeholder" } {
|
|
190
|
+
const trimmed = explicit.trim()
|
|
191
|
+
if (trimmed) return { url: trimmed, source: "explicit" }
|
|
192
|
+
if (last) return { url: last.baseUrl.replace(/\/+$/, ""), source: "last-discovered" }
|
|
193
|
+
return { url: "http://127.0.0.1:1/api", source: "placeholder" }
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function persistDiscovery(d: OpencodeDiscovery): void {
|
|
197
|
+
try {
|
|
198
|
+
const dir = join(homedir(), ".openqq")
|
|
199
|
+
mkdirSync(dir, { recursive: true })
|
|
200
|
+
writeFileSync(
|
|
201
|
+
join(dir, "last-discovered.json"),
|
|
202
|
+
JSON.stringify({ ...d, at: new Date().toISOString() }, null, 2),
|
|
203
|
+
)
|
|
204
|
+
} catch (error) {
|
|
205
|
+
console.log(`[discovery] 发现结果落盘失败: ${error instanceof Error ? error.message : error}`)
|
|
206
|
+
}
|
|
207
|
+
}
|
package/src/core/error-rescue.ts
CHANGED
|
@@ -27,7 +27,7 @@ export function rescueText(kind: ProviderErrorKind, rawMessage: string): string
|
|
|
27
27
|
`服务端原文:${raw}`,
|
|
28
28
|
"",
|
|
29
29
|
"恢复方式(都不用等模型在线)——",
|
|
30
|
-
"1. 换现成模型:发 /
|
|
30
|
+
"1. 换现成模型:发 /models 看列表,或 /models provider/id 直接切换",
|
|
31
31
|
"2. 更新 key:在桌面端 opencode 里更新该服务的 key 后,直接重发你的问题",
|
|
32
32
|
].join("\n")
|
|
33
33
|
}
|
package/src/core/file-log.ts
CHANGED
|
@@ -1,15 +1,45 @@
|
|
|
1
1
|
// @input: fs(追加写)
|
|
2
|
-
// @output: installFileLog
|
|
3
|
-
// @pos: core - 可选文件日志双写(QQ_LOG_FILE
|
|
2
|
+
// @output: installFileLog, fileLogStatus, formatLocalTimestamp
|
|
3
|
+
// @pos: core - 可选文件日志双写(QQ_LOG_FILE 环境变量开启;2026-11-05 起默认开启)
|
|
4
4
|
//
|
|
5
5
|
// 背景(2026-10-30 清债 P2):插件拉起的 detached bot 无控制台,bun 子进程 fd
|
|
6
6
|
// 重定向实测不落盘(bot.out.log 0 字节)——改为 bot 进程内 console 双写,
|
|
7
7
|
// 不依赖 spawn 侧 fd 语义,跨运行时(bun/node)确定生效。
|
|
8
|
-
//
|
|
9
|
-
|
|
8
|
+
// 轮转:2026-11-20 起归 core/log-rotate.ts 统一管辖(20MB/保留 4 代/总预算 100MB,
|
|
9
|
+
// env QQ_LOG_MAX_MB / QQ_LOG_KEEP / QQ_LOG_TOTAL_MB 可调)——与 watchdog 审计写同一
|
|
10
|
+
// 文件 ~/.openqq/openqq.log,一个阈值管全部。
|
|
11
|
+
// 2026-11-05:install 返回卸载函数不变;新增 fileLogStatus() 供 /status 展示
|
|
12
|
+
// 「日志最后写入时间」,堵住"日志 17:17 后无写入却无人发现"的观测缺口。
|
|
13
|
+
import { appendFileSync, existsSync, mkdirSync, statSync } from "fs"
|
|
10
14
|
import { join } from "path"
|
|
15
|
+
import { inspect } from "util"
|
|
16
|
+
import { enforceLogBudget, logLimitsFromEnv, rotateLogIfNeeded } from "./log-rotate.js"
|
|
11
17
|
|
|
12
|
-
|
|
18
|
+
interface ActiveLog {
|
|
19
|
+
path: string
|
|
20
|
+
lastWriteAt: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let active: ActiveLog | null = null
|
|
24
|
+
|
|
25
|
+
/** 本地时区时间戳(含偏移,如 2026-11-05T21:09:09.292+08:00)——2026-11-05 用户反馈:
|
|
26
|
+
* 日志全是 UTC(Z 结尾),与本地时钟差 8 小时,排障要对表。统一改本地。 */
|
|
27
|
+
export function formatLocalTimestamp(d = new Date()): string {
|
|
28
|
+
const pad = (n: number, w = 2): string => String(n).padStart(w, "0")
|
|
29
|
+
const offMin = -d.getTimezoneOffset() // 本地超前 UTC 的分钟数(中国 = +480)
|
|
30
|
+
const sign = offMin >= 0 ? "+" : "-"
|
|
31
|
+
const abs = Math.abs(offMin)
|
|
32
|
+
return (
|
|
33
|
+
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
|
|
34
|
+
`T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}` +
|
|
35
|
+
`${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 当前生效的文件日志(未安装返回 null)。 */
|
|
40
|
+
export function fileLogStatus(): { path: string; lastWriteAt: number } | null {
|
|
41
|
+
return active ? { ...active } : null
|
|
42
|
+
}
|
|
13
43
|
|
|
14
44
|
/** console.log/warn/error 双写到文件;返回卸载函数(测试用) */
|
|
15
45
|
export function installFileLog(logPath: string): () => void {
|
|
@@ -18,13 +48,23 @@ export function installFileLog(logPath: string): () => void {
|
|
|
18
48
|
} catch {
|
|
19
49
|
/* 目录已存在或不可建——写时再兜底 */
|
|
20
50
|
}
|
|
51
|
+
const state: ActiveLog = { path: logPath, lastWriteAt: 0 }
|
|
52
|
+
active = state
|
|
53
|
+
const limits = logLimitsFromEnv()
|
|
21
54
|
const write = (level: string, args: unknown[]): void => {
|
|
22
55
|
try {
|
|
23
|
-
|
|
24
|
-
|
|
56
|
+
// 轮转+预算闸由 log-rotate 统一管辖;statSync 每行一次沿用既有代价口径
|
|
57
|
+
if (existsSync(logPath) && statSync(logPath).size > limits.maxBytes) {
|
|
58
|
+
if (rotateLogIfNeeded(logPath, limits)) enforceLogBudget(logPath, limits)
|
|
25
59
|
}
|
|
26
|
-
|
|
27
|
-
|
|
60
|
+
// 2026-11-20 修:非字符串参数用 util.inspect(JSON.stringify(Error)=="{}" 会把
|
|
61
|
+
// 错误消息与堆栈整个吞掉——11-20 启动失败 {} 事故的根因级教训);breakLength
|
|
62
|
+
// 拉满保持单行,不破坏行级日志结构。
|
|
63
|
+
const line = args
|
|
64
|
+
.map((a) => (typeof a === "string" ? a : inspect(a, { depth: 4, maxStringLength: 500, breakLength: Infinity, colors: false })))
|
|
65
|
+
.join(" ")
|
|
66
|
+
appendFileSync(logPath, `${formatLocalTimestamp()} [${level}] ${line}\n`, { mode: 0o600 })
|
|
67
|
+
state.lastWriteAt = Date.now()
|
|
28
68
|
} catch {
|
|
29
69
|
// 日志绝不阻断主流程
|
|
30
70
|
}
|
|
@@ -41,5 +81,6 @@ export function installFileLog(logPath: string): () => void {
|
|
|
41
81
|
console.log = orig.log
|
|
42
82
|
console.warn = orig.warn
|
|
43
83
|
console.error = orig.error
|
|
84
|
+
if (active === state) active = null
|
|
44
85
|
}
|
|
45
86
|
}
|
package/src/core/form-bridge.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @input: ../opencode/client (FormInfo/FormField/FormOption), ../qq/types (MessageContext), ./form-journal
|
|
1
|
+
// @input: ../opencode/client (FormInfo/FormField/FormOption), ../qq/types (MessageContext), ./form-journal
|
|
2
2
|
// @output: renderFormPrompt, parseFormAnswer, createFormBridge, FORM_PROMPT_TTL_MS
|
|
3
3
|
// @pos: core - 表单桥接:QQ 同步、作答回传、跨重启恢复与服务端对账。
|
|
4
4
|
//
|
|
@@ -173,7 +173,7 @@ function clipButtonLabel(text: string): string {
|
|
|
173
173
|
}
|
|
174
174
|
|
|
175
175
|
/** 单选直接提交字符串;多选按钮与文字路径一致,提交单值数组。 */
|
|
176
|
-
export function buildFormKeyboard(form: FormInfo,
|
|
176
|
+
export function buildFormKeyboard(form: FormInfo, _ownerOpenid: string): InlineKeyboard | null {
|
|
177
177
|
const visible = form.fields.filter((f) => !(f as FieldLike).hidden)
|
|
178
178
|
if (visible.length !== 1) return null
|
|
179
179
|
const field = visible[0] as FieldLike
|
|
@@ -183,9 +183,11 @@ export function buildFormKeyboard(form: FormInfo, ownerOpenid: string): InlineKe
|
|
|
183
183
|
const buttons: KeyboardButton[] = opts.slice(0, 20).map((opt) => ({
|
|
184
184
|
id: `form-${form.id}-${opt.value}`.slice(0, 64),
|
|
185
185
|
render_data: { label: clipButtonLabel(opt.label), visited_label: clipButtonLabel(`✓ ${opt.label}`), style: 1 },
|
|
186
|
+
// permission 形状对齐腾讯 P0({type:2} 不带 specify_user_ids,同审批卡;
|
|
187
|
+
// 平台校验收敛后冲突形状会导致客户端不渲染键盘)。
|
|
186
188
|
action: {
|
|
187
189
|
type: 1,
|
|
188
|
-
permission: { type: 2
|
|
190
|
+
permission: { type: 2 },
|
|
189
191
|
data: encodeFormButton({ t: "form", f: form.id, k: field.key, v: opt.value }),
|
|
190
192
|
},
|
|
191
193
|
}))
|
|
@@ -207,7 +209,7 @@ export interface FormInteractionEvent {
|
|
|
207
209
|
export interface FormBridgeDeps {
|
|
208
210
|
client: OpencodeClient
|
|
209
211
|
sendReply: (ctx: MessageContext, text: string) => Promise<void>
|
|
210
|
-
safeDeliver: (ctx: MessageContext, text: string) => Promise<
|
|
212
|
+
safeDeliver: (ctx: MessageContext, text: string) => Promise<boolean>
|
|
211
213
|
sendFormCard?: (ctx: MessageContext, form: FormInfo, keyboard: InlineKeyboard) => Promise<boolean>
|
|
212
214
|
/** 测试/嵌入方可显式指定台账;生产默认 ~/.openqq/forms.json 或 QQ_FORM_JOURNAL_FILE。 */
|
|
213
215
|
journalPath?: string
|
|
@@ -247,9 +249,10 @@ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
|
|
|
247
249
|
return tracked
|
|
248
250
|
}
|
|
249
251
|
|
|
250
|
-
function deliver(ctx: MessageContext, text: string): Promise<
|
|
252
|
+
function deliver(ctx: MessageContext, text: string): Promise<boolean> {
|
|
251
253
|
return track(deps.safeDeliver(ctx, text).catch((error) => {
|
|
252
254
|
console.error("[form-bridge] 回执投递失败:", error instanceof Error ? error.message : error)
|
|
255
|
+
return false
|
|
253
256
|
}))
|
|
254
257
|
}
|
|
255
258
|
|
|
@@ -483,6 +486,12 @@ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
|
|
|
483
486
|
pending.set(userId, entry)
|
|
484
487
|
scheduleExpiry(userId, entry)
|
|
485
488
|
if (previous) {
|
|
489
|
+
// 举一反三(2026-11-05):被取代的旧表单台账必须同步清理——否则非终态记录
|
|
490
|
+
// 永久残留,每次重启都被 restore 重载(updatedAt 比较能防顶替新槽,但僵尸账
|
|
491
|
+
// 无限累积),与 bgWait superseded 同罪。
|
|
492
|
+
try {
|
|
493
|
+
journal.remove(userId, previous.form.id)
|
|
494
|
+
} catch { /* 下次替换/reconcile 再清理 */ }
|
|
486
495
|
void deliver(previous.ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)")
|
|
487
496
|
}
|
|
488
497
|
console.log(`[form-bridge] 表单已推送 user=${userId.slice(0, 8)}… form=${form.id} title=${form.title.slice(0, 40)}`)
|
package/src/core/form-journal.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
// @input: fs/path/os, ../opencode/client (FormInfo), ../qq/types (MessageContext)
|
|
1
|
+
// @input: fs/path/os, ../opencode/client (FormInfo), ../qq/types (MessageContext)
|
|
2
2
|
// @output: FormJournalEntry, FormJournal, createFormJournal, defaultFormJournalPath
|
|
3
3
|
// @pos: core - 表单交互恢复台账(同步落盘、原子替换、跨进程短临界区锁)
|
|
4
4
|
//
|
|
5
5
|
// 只保存恢复所需数据:表单定义、最小路由 ctx、答案与回显文本。QQ 原事件、附件、
|
|
6
6
|
// 引用内容和被动回复 msgId 一律不落盘;恢复后的通知必须使用主动消息语义。
|
|
7
|
+
import { storageFile } from "./storage.js"
|
|
7
8
|
import {
|
|
8
9
|
closeSync,
|
|
9
10
|
existsSync,
|
|
@@ -15,8 +16,7 @@ import {
|
|
|
15
16
|
unlinkSync,
|
|
16
17
|
writeFileSync,
|
|
17
18
|
} from "fs"
|
|
18
|
-
import { dirname
|
|
19
|
-
import { homedir } from "os"
|
|
19
|
+
import { dirname } from "path"
|
|
20
20
|
import type { FormInfo } from "../opencode/client.js"
|
|
21
21
|
import type { MessageContext } from "../qq/types.js"
|
|
22
22
|
|
|
@@ -53,7 +53,7 @@ const sleepArray = new Int32Array(new SharedArrayBuffer(4))
|
|
|
53
53
|
const STATES = new Set<FormLifecycleState>(["pending", "clickReceived", "submitting", "replied", "cancelled", "expired"])
|
|
54
54
|
|
|
55
55
|
export function defaultFormJournalPath(): string {
|
|
56
|
-
return process.env.QQ_FORM_JOURNAL_FILE ||
|
|
56
|
+
return process.env.QQ_FORM_JOURNAL_FILE || storageFile("forms.json")
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
/** 只保留恢复路由;空 msgId 明确表达重启后使用主动消息,而非复用过期被动窗口。 */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @input: fs/path/os(落盘)、env(窗口可调)
|
|
1
|
+
// @input: fs/path/os(落盘)、env(窗口可调)
|
|
2
2
|
// @output: loadGatewayState, saveGatewayState, clearGatewayState, GATEWAY_STATE_FILE
|
|
3
3
|
// @pos: core - QQ 网关 session/seq 持久化(修复②:重启不再 IDENTIFY 失忆重刷 backlog)
|
|
4
4
|
//
|
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
// op9 InvalidSession 回退 IDENTIFY(gateway 已有该处理路径,无死循环)。
|
|
9
9
|
// 风控:文件只存 session_id/seq/时间戳,无凭据;损坏/超龄一律作废不阻塞启动;
|
|
10
10
|
// 保存走临时文件原子 rename,与台账同风格。
|
|
11
|
+
import { storageFile } from "./storage.js"
|
|
11
12
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, unlinkSync } from "fs"
|
|
12
13
|
import { join } from "path"
|
|
13
|
-
import { homedir } from "os"
|
|
14
14
|
|
|
15
15
|
export interface GatewayPersistState {
|
|
16
16
|
session_id: string
|
|
@@ -18,7 +18,7 @@ export interface GatewayPersistState {
|
|
|
18
18
|
savedAt: number
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
export const GATEWAY_STATE_FILE =
|
|
21
|
+
export const GATEWAY_STATE_FILE = storageFile("gateway-state.json")
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
24
|
* RESUME 尝试窗口:QQ 网关断线会话 TTL 观测约 1h(427 每小时 RESUMED 实证)。
|