@linjz/opencode-qqbot 0.3.14 → 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 (52) hide show
  1. package/README.md +73 -5
  2. package/bin/openqq.js +34 -0
  3. package/dist/notify-cli.js +593 -0
  4. package/dist/opencode-qqbot-plugin.js +938 -65
  5. package/dist/openqq-bot.js +3585 -717
  6. package/dist/openqq-cli.js +791 -0
  7. package/dist/openqq-watchdog.js +1063 -0
  8. package/package.json +9 -5
  9. package/src/bridge.ts +1338 -157
  10. package/src/cli/notify-main.ts +6 -0
  11. package/src/cli/notify.ts +167 -0
  12. package/src/cli/openqq-main.ts +95 -0
  13. package/src/cli/service-main.ts +302 -0
  14. package/src/cli/watchdog-main.ts +77 -0
  15. package/src/commands.ts +644 -554
  16. package/src/config.ts +87 -2
  17. package/src/core/bot-control.ts +148 -0
  18. package/src/core/bot-launcher.ts +106 -13
  19. package/src/core/card-approval.ts +20 -9
  20. package/src/core/delivery.ts +145 -54
  21. package/src/core/discovery.ts +22 -4
  22. package/src/core/file-log.ts +35 -3
  23. package/src/core/form-bridge.ts +16 -7
  24. package/src/core/form-journal.ts +4 -4
  25. package/src/core/gateway-state.ts +3 -3
  26. package/src/core/inflight-journal.ts +214 -36
  27. package/src/core/instance-lock.ts +21 -6
  28. package/src/core/linkwatch.ts +3 -4
  29. package/src/core/markdown.ts +117 -0
  30. package/src/core/message-queue.ts +242 -91
  31. package/src/core/mirror.ts +222 -182
  32. package/src/core/notify-sink.ts +93 -0
  33. package/src/core/outbox.ts +10 -9
  34. package/src/core/permission.ts +627 -301
  35. package/src/core/question-form.ts +230 -0
  36. package/src/core/queue-view.ts +661 -0
  37. package/src/core/send-media.ts +32 -0
  38. package/src/core/storage.ts +34 -0
  39. package/src/core/watchdog.ts +513 -0
  40. package/src/core/zombie-reaper.ts +127 -0
  41. package/src/index.ts +140 -52
  42. package/src/opencode/client.ts +206 -27
  43. package/src/opencode/eventstream.ts +94 -12
  44. package/src/opencode/history.ts +4 -2
  45. package/src/opencode/mirror.ts +15 -2
  46. package/src/opencode/sessions.ts +135 -37
  47. package/src/plugin-entry.ts +120 -112
  48. package/src/qq/api.ts +165 -61
  49. package/src/qq/gateway.ts +80 -17
  50. package/src/qq/media.ts +5 -1
  51. package/src/qq/sender.ts +30 -18
  52. package/src/qq/types.ts +7 -0
@@ -0,0 +1,6 @@
1
+ // @input: ./notify.ts(runNotifyCli)
2
+ // @output:(无导出)——notify CLI 的自执行入口(构建目标:dist/notify-cli.js)
3
+ // @pos: cli - bin/openqq.js notify 子命令的落点;测试请 import ./notify.ts(不要引入本文件)。
4
+ import { main } from "./notify.js"
5
+
6
+ process.exitCode = await main(process.argv.slice(2))
@@ -0,0 +1,167 @@
1
+ // @input: node:fs/homedir/join、../config(ENV_FILE/loadEnvFile)、../qq/api(getAccessToken 校准用不入队)、./outbox.ts、../core/notify-sink.ts(resolveNotifyRecipients/defaultOutboxPath)
2
+ // @output: runNotifyCli(argv)(供 bin/openqq.js 与测试调用),只入队不发送。
3
+ // @pos: cli - openqq notify 外部入队通道(feature:headless 定时任务结果推送)。
4
+ // BOT(notify-sink)进程消费投递;CLI 不取 token、不连 OpenCode、不抢实例锁。
5
+ // @note: 设计文档:Desktop `opencode-qqbot-feature-request.md` Part 1;
6
+ // 收件人 fail-closed:缺省取 ALLOWED_USERS 唯一项;显式 --user 必须命中名单。
7
+ import { existsSync, readFileSync } from "node:fs"
8
+ import { createOutbox } from "../core/outbox.js"
9
+ import { ENV_FILE, loadEnvFile } from "../config.js"
10
+ import { defaultOutboxPath, resolveNotifyRecipients } from "../core/notify-sink.js"
11
+
12
+ export interface NotifyCliOptions {
13
+ filePath?: string
14
+ now?: number
15
+ env?: { allowedUsers: readonly string[] }
16
+ }
17
+
18
+ /** CLI 结果(--json 输出同 shape;dry-run 时 queued=false 并附 wouldEnqueue)。 */
19
+ export interface NotifyCliResult {
20
+ ok: boolean
21
+ queued: boolean
22
+ id: string
23
+ user: string
24
+ chars: number
25
+ truncated: boolean
26
+ dryRun: boolean
27
+ json: boolean
28
+ reason?: string
29
+ }
30
+
31
+ /** 保守截断:默认 1500 字(主动消息日配额 100/天——长输出拆几十条会吃光);0=不截断。 */
32
+ export const NOTIFY_DEFAULT_MAX_CHARS = 1500
33
+
34
+ interface ParsedArgs {
35
+ text?: string
36
+ filePath?: string
37
+ stdin?: boolean
38
+ user?: string
39
+ id?: string
40
+ maxChars: number
41
+ ttlHours?: number
42
+ dryRun: boolean
43
+ json: boolean
44
+ help: boolean
45
+ }
46
+
47
+ function parseArgs(argv: readonly string[]): ParsedArgs {
48
+ const parsed: ParsedArgs = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false }
49
+ for (let i = 0; i < argv.length; i++) {
50
+ const a = argv[i]
51
+ const next = argv[i + 1]
52
+ switch (a) {
53
+ case "--text": parsed.text = next; i++; break
54
+ case "--file": parsed.filePath = next; i++; break
55
+ case "--stdin": parsed.stdin = true; break
56
+ case "--user": parsed.user = next; i++; break
57
+ case "--id": parsed.id = next; i++; break
58
+ case "--max-chars": parsed.maxChars = Number(next); i++; break
59
+ case "--ttl-hours": parsed.ttlHours = Number(next); i++; break
60
+ case "--dry-run": parsed.dryRun = true; break
61
+ case "--json": parsed.json = true; break
62
+ case "--help": case "-h": parsed.help = true; i++; break
63
+ default:
64
+ throw new Error(`未知参数:${a}(用法:openqq notify --text "…" | --file <p> | --stdin)`)
65
+ }
66
+ }
67
+ if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
68
+ throw new Error("必须提供正文来源:--text / --file / --stdin 三选一")
69
+ }
70
+ if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
71
+ throw new Error("--max-chars 必须是 >= 0 的有限数(0=不截断)")
72
+ }
73
+ return parsed
74
+ }
75
+
76
+ /** 收件人 fail-closed:显式 --user 必须命中名单;缺省仅取 ALLOWED_USERS 唯一项。 */
77
+ export function resolveUser(envAllowed: readonly string[], explicit?: string): string {
78
+ return resolveNotifyRecipients(envAllowed, explicit)
79
+ }
80
+
81
+ /** 正文来源:--text / --file / --stdin;--file - 读 stdin(同步可读)。 */
82
+ function readBody(parsed: ParsedArgs): string {
83
+ if (parsed.text !== undefined) return parsed.text
84
+ if (parsed.filePath !== undefined) {
85
+ if (parsed.filePath === "-") return readFileSync(0 as unknown as number, "utf8")
86
+ if (!existsSync(parsed.filePath)) throw new Error(`--file 不存在:${parsed.filePath}`)
87
+ return readFileSync(parsed.filePath, "utf8")
88
+ }
89
+ if (parsed.stdin) return readFileSync(0 as unknown as number, "utf8")
90
+ return ""
91
+ }
92
+
93
+ export async function runNotifyCli(
94
+ argv: readonly string[],
95
+ options: NotifyCliOptions = {},
96
+ ): Promise<NotifyCliResult> {
97
+ const now = options.now ?? Date.now()
98
+ const parsed = parseArgs(argv)
99
+ if (parsed.help) {
100
+ const help = [
101
+ "用法:openqq notify --text \"…\" | --file <路径> | --stdin",
102
+ " --user <openid> 收件人;缺省取 ALLOWED_USERS 唯一项(多用户必须显式指定)",
103
+ " --id <key> 幂等键(同 key 不重复投递)",
104
+ " --max-chars <n> 截断上限,默认 1500,0 不截断",
105
+ " --ttl-hours <n> 队列等待上限,默认 24(env QQ_NOTIFY_TTL_HOURS 兜底)",
106
+ " --dry-run / --json 不入队 / 机器可读输出",
107
+ ].join("\n")
108
+ console.log(help)
109
+ return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" }
110
+ }
111
+ // .env 注入:bot 进程入口已做;CLI 独立进程需自行加载(ALLOWED_USERS/凭据同源单点)
112
+ if (!options.env && existsSync(ENV_FILE)) loadEnvFile(ENV_FILE)
113
+ const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "")
114
+ .split(/[,\s]+/).filter(Boolean)
115
+ const user = resolveUser(allowedUsers, parsed.user)
116
+ if (!user) {
117
+ throw new Error(
118
+ allowedUsers.length === 0
119
+ ? "ALLOWED_USERS 为空——fail-closed 不允许无名单入队(先在 ~/.openqq/.env 配置)"
120
+ : parsed.user
121
+ ? `收件人不在名单:${parsed.user}(ALLOWED_USERS 共 ${allowedUsers.length} 项,--user 必须精确命中;请核对 openid)`
122
+ : "多用户名单必须用 --user <openid> 显式指定收件人",
123
+ )
124
+ }
125
+ const raw = readBody(parsed)
126
+ const max = parsed.maxChars
127
+ const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}…` : raw
128
+ const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`
129
+ const filePath = options.filePath ?? defaultOutboxPath()
130
+ if (parsed.dryRun) {
131
+ return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true, json: parsed.json }
132
+ }
133
+ const ttlHours =
134
+ parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24)
135
+ const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0
136
+ ? now + ttlHours * 60 * 60 * 1000
137
+ : now
138
+ const outbox = createOutbox({ filePath, pollIntervalMs: 0 })
139
+ const entry = await outbox.enqueue({
140
+ ...(parsed.id ? { id: parsed.id } : {}),
141
+ kind: "notify",
142
+ payload: { text: content },
143
+ ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
144
+ sessionId: "",
145
+ nextAttemptAt,
146
+ })
147
+ return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false, json: parsed.json }
148
+ }
149
+
150
+ /** bin/openqq.js 入口:返回进程退出码(0=已入队;1=参数/配置错误)。 */
151
+ export async function main(argv: readonly string[]): Promise<number> {
152
+ try {
153
+ const result = await runNotifyCli(argv)
154
+ if (result.reason === "help") return 0
155
+ if (result.json) {
156
+ console.log(JSON.stringify(result))
157
+ } else if (result.queued && !result.dryRun) {
158
+ console.log(`[notify] 已入队 id=${result.id} user=${result.user} chars=${result.chars}${result.truncated ? "(已截断)" : ""}`)
159
+ } else if (result.dryRun) {
160
+ console.log(`[notify] dry-run:将入队 user=${result.user} chars=${result.chars}${result.truncated ? "(已截断)" : ""}`)
161
+ }
162
+ return result.ok ? 0 : 1
163
+ } catch (error) {
164
+ console.error(`[notify] 入队失败:${error instanceof Error ? error.message : String(error)}`)
165
+ return 1
166
+ }
167
+ }
@@ -0,0 +1,95 @@
1
+ // @input: argv(restart | service ...)、core/bot-control、cli/service-main
2
+ // @output: (side-effect) 重启/自启注册/状态查询
3
+ // @pos: cli - 运维命令入口(dist/openqq-cli.js)
4
+ //
5
+ // 用法:
6
+ // node dist/openqq-cli.js restart [--force] [--timeout-min 60]
7
+ // node dist/openqq-cli.js service install|uninstall|status
8
+ // 2026-11-09 架构红线:取代 safe-restart.ps1 / start-openqq.ps1 / watchdog.ps1,全 TS 跨平台。
9
+ import { existsSync } from "fs"
10
+ import { dirname, join } from "path"
11
+ import { fileURLToPath } from "url"
12
+ import { restartBot } from "../core/bot-control.js"
13
+ import {
14
+ serviceInstall,
15
+ serviceStatus,
16
+ serviceUninstall,
17
+ type CommandResult,
18
+ type ServiceSpec,
19
+ } from "./service-main.js"
20
+ import { resolveBunCommand, locateOnPath, resolveRuntime } from "../core/bot-launcher.js"
21
+
22
+ const DEFAULT_INTERVAL_MIN = 10
23
+
24
+ function sibling(name: string): string {
25
+ const here = dirname(fileURLToPath(import.meta.url))
26
+ const candidates = [join(here, name), join(here, "..", "dist", name)]
27
+ return candidates.find((p) => existsSync(p)) ?? candidates[0]
28
+ }
29
+
30
+ function runtimeCommand(): string {
31
+ const runtime = resolveRuntime()
32
+ if (runtime === "bun") return resolveBunCommand() ?? throwNoRuntime("bun")
33
+ if (runtime === "node") return locateOnPath("node") ?? throwNoRuntime("node")
34
+ throw new Error("未找到 bun/node 运行时")
35
+ }
36
+
37
+ function throwNoRuntime(kind: string): never {
38
+ throw new Error(`未找到 ${kind} 全路径可执行体——注册动作需要全路径命令(静默红线)`)
39
+ }
40
+
41
+ function printResult(label: string, r: CommandResult): void {
42
+ console.log(`[${label}] ${r.ok ? "OK" : "FAIL"}\n${r.detail}`)
43
+ process.exitCode = r.ok ? 0 : 1
44
+ }
45
+
46
+ function parseFlag(argv: string[], name: string): string | null {
47
+ const i = argv.indexOf(name)
48
+ return i >= 0 ? (argv[i + 1] ?? "") : null
49
+ }
50
+
51
+ async function main(): Promise<void> {
52
+ const [cmd, sub] = process.argv.slice(2)
53
+
54
+ if (cmd === "restart") {
55
+ const force = process.argv.includes("--force")
56
+ const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"))
57
+ const res = await restartBot({
58
+ force,
59
+ timeoutMs: Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60_000 : undefined,
60
+ spawnFromUrl: import.meta.url,
61
+ log: (line) => console.log(line),
62
+ })
63
+ console.log(`[restart] ${res.action}(${res.reason})killed=${res.killedPid ?? "-"} spawned=${res.spawnedPid ?? "-"}`)
64
+ process.exitCode = res.action === "restarted" ? 0 : 2
65
+ return
66
+ }
67
+
68
+ if (cmd === "service") {
69
+ const spec: ServiceSpec = {
70
+ runtimeCmd: runtimeCommand(),
71
+ scriptPath: sibling("openqq-watchdog.js"),
72
+ intervalMin: DEFAULT_INTERVAL_MIN,
73
+ }
74
+ if (sub === "install") return printResult("service install", serviceInstall(spec))
75
+ if (sub === "uninstall") return printResult("service uninstall", serviceUninstall())
76
+ if (sub === "status") {
77
+ const r = serviceStatus()
78
+ return printResult("service status", {
79
+ ok: r.ok,
80
+ detail: `runtime=${spec.runtimeCmd}\nscript=${spec.scriptPath}\n${r.detail}`,
81
+ })
82
+ }
83
+ console.error("用法:openqq service install|uninstall|status")
84
+ process.exitCode = 2
85
+ return
86
+ }
87
+
88
+ console.error("用法:openqq-cli restart [--force] [--timeout-min N] | service install|uninstall|status")
89
+ process.exitCode = 2
90
+ }
91
+
92
+ void main().catch((error) => {
93
+ console.error("[openqq-cli] 执行失败:", error instanceof Error ? error.message : error)
94
+ process.exit(1)
95
+ })
@@ -0,0 +1,302 @@
1
+ // @input: 平台(process.platform)、运行时命令、看门狗产物路径
2
+ // @output: build* 纯函数 + serviceInstall/serviceUninstall/serviceStatus
3
+ // @pos: cli - 自启注册器(全平台唯一的 OS 差异点,代码仍是 TS)
4
+ //
5
+ // 2026-11-09 架构红线:平台差异只允许出现在「注册自启项」这一处。
6
+ // 本文件生成三平台的注册配置;不引入 .ps1/.vbs/.bat 作为运行时代码。
7
+ import { spawnSync } from "child_process"
8
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "fs"
9
+ import { homedir, tmpdir } from "os"
10
+ import { join } from "path"
11
+
12
+ export const WIN_TASK_NAME = "OpenQQBotWatchdog"
13
+ export const SYSTEMD_UNIT = "openqq-watchdog"
14
+ export const LAUNCHD_LABEL = "com.linjp.opencode-qqbot.watchdog"
15
+
16
+ export interface ServiceSpec {
17
+ /** 运行时可执行文件(bun 或 node 的绝对路径) */
18
+ runtimeCmd: string
19
+ /** dist/openqq-watchdog.js 绝对路径 */
20
+ scriptPath: string
21
+ intervalMin: number
22
+ }
23
+
24
+ export interface CommandResult {
25
+ ok: boolean
26
+ detail: string
27
+ }
28
+
29
+ function run(cmd: string, args: string[]): CommandResult {
30
+ try {
31
+ // windowsHide:CLI 巡检/注册时不弹控制台窗口(2026-11-09 用户反馈“时不时闪一下”)
32
+ const r = spawnSync(cmd, args, { encoding: "utf-8", windowsHide: true })
33
+ const detail = `${cmd} ${args.join(" ")}\n${(r.stdout ?? "").trim()}${(r.stderr ?? "").trim() ? `\n${r.stderr.trim()}` : ""}`
34
+ return { ok: r.status === 0, detail }
35
+ } catch (error) {
36
+ return { ok: false, detail: `执行失败:${error instanceof Error ? error.message : String(error)}` }
37
+ }
38
+ }
39
+
40
+ // ---------- 纯函数(导出供测试) ----------
41
+
42
+ const escXml = (s: string): string =>
43
+ s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
44
+
45
+ /**
46
+ * Windows 任务 XML(S4U 注册,2026-11-09 静默拉起缺陷③):
47
+ * schtasks 直调 console 程序在 Interactive 登录型下每次 tick 闪现控制台窗口
48
+ * (Win11 默认终端宿主=Windows Terminal)。S4U=非交互会话,进程零窗口、免存密码。
49
+ * 纯函数生成,注册动作不经任何 shell 中转。
50
+ */
51
+ export function buildSchtasksTaskXml(spec: ServiceSpec, now = new Date()):
52
+ string {
53
+ const user = escXml(process.env.USERNAME ?? "SYSTEM")
54
+ const trigger =
55
+ `<TimeTrigger><StartBoundary>${now.toISOString()}</StartBoundary>` +
56
+ `<Repetition><Interval>PT${spec.intervalMin}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition>` +
57
+ `<Enabled>true</Enabled></TimeTrigger>`
58
+ return [
59
+ '<?xml version="1.0" encoding="UTF-16"?>',
60
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
61
+ `<RegistrationInfo><Author>${user}</Author><Description>OpenCode QQBot watchdog (plugin-managed, silent)</Description></RegistrationInfo>`,
62
+ `<Triggers>${trigger}</Triggers>`,
63
+ '<Principals><Principal id="Author">' +
64
+ `<UserId>${user}</UserId><LogonType>S4U</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>`,
65
+ "<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>" +
66
+ "<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>" +
67
+ "<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>" +
68
+ "<ExecutionTimeLimit>PT5M</ExecutionTimeLimit><StartWhenAvailable>true</StartWhenAvailable>" +
69
+ "<Enabled>true</Enabled></Settings>",
70
+ '<Actions Context="Author"><Exec>' +
71
+ `<Command>${escXml(spec.runtimeCmd)}</Command>` +
72
+ `<Arguments>${escXml(`"${spec.scriptPath}" --once`)}</Arguments>` +
73
+ '</Exec></Actions>',
74
+ "</Task>",
75
+ "",
76
+ ].join("\n")
77
+ }
78
+
79
+ export function buildSchtasksXmlArgs(xmlPath: string): string[] {
80
+ return ["/Create", "/TN", WIN_TASK_NAME, "/XML", xmlPath, "/F"]
81
+ }
82
+
83
+ /** conhost.exe 全路径(Windows 自带;不存在作 fallback 判定) */
84
+ export function conhostPath(platform = process.platform): string | null {
85
+ if (platform !== "win32") return null
86
+ const p = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "conhost.exe")
87
+ try {
88
+ return statSync(p).isFile() ? p : null
89
+ } catch {
90
+ return null
91
+ }
92
+ }
93
+
94
+ /**
95
+ * 第二梯队:conhost --headless 包装(实测零闪窗、非 shell、无需提权)。
96
+ * 适用未提权进程注册 S4U 被 Access denied 的场景;需用户已登录(Interactive 会话)。
97
+ * 仅在「自启注册」这一处使用(平台差异收口红线)。
98
+ */
99
+ export function buildSchtasksConhostArgs(spec: ServiceSpec): string[] {
100
+ const conhost = conhostPath() ?? "C:\\Windows\\System32\\conhost.exe"
101
+ const tr = `"${conhost}" --headless "${spec.runtimeCmd}" "${spec.scriptPath}" --once`
102
+ return ["/Create", "/TN", WIN_TASK_NAME, "/SC", "MINUTE", "/MO", String(spec.intervalMin), "/TR", tr, "/F"]
103
+ }
104
+
105
+ export function buildSchtasksCreateArgs(spec: ServiceSpec): string[] {
106
+ const tr = `"${spec.runtimeCmd}" "${spec.scriptPath}" --once`
107
+ return ["/Create", "/TN", WIN_TASK_NAME, "/SC", "MINUTE", "/MO", String(spec.intervalMin), "/TR", tr, "/F"]
108
+ }
109
+
110
+ export function buildSchtasksDeleteArgs(): string[] {
111
+ return ["/Delete", "/TN", WIN_TASK_NAME, "/F"]
112
+ }
113
+
114
+ export function buildSystemdService(spec: ServiceSpec): string {
115
+ return [
116
+ "[Unit]",
117
+ "Description=OpenCode QQBot watchdog (plugin-managed)",
118
+ "After=default.target",
119
+ "",
120
+ "[Service]",
121
+ "Type=oneshot",
122
+ `ExecStart="${spec.runtimeCmd}" "${spec.scriptPath}" --once`,
123
+ "",
124
+ ].join("\n")
125
+ }
126
+
127
+ export function buildSystemdTimer(intervalMin: number): string {
128
+ return [
129
+ "[Unit]",
130
+ "Description=OpenCode QQBot watchdog timer",
131
+ "",
132
+ "[Timer]",
133
+ "OnBootSec=2min",
134
+ `OnUnitActiveSec=${intervalMin}min`,
135
+ `Unit=${SYSTEMD_UNIT}.service`,
136
+ "",
137
+ "[Install]",
138
+ "WantedBy=timers.target",
139
+ "",
140
+ ].join("\n")
141
+ }
142
+
143
+ export function buildLaunchdPlist(spec: ServiceSpec): string {
144
+ const esc = (s: string): string => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
145
+ return [
146
+ '<?xml version="1.0" encoding="UTF-8"?>',
147
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
148
+ '<plist version="1.0">',
149
+ "<dict>",
150
+ " <key>Label</key>",
151
+ ` <string>${LAUNCHD_LABEL}</string>`,
152
+ " <key>ProgramArguments</key>",
153
+ " <array>",
154
+ ` <string>${esc(spec.runtimeCmd)}</string>`,
155
+ ` <string>${esc(spec.scriptPath)}</string>`,
156
+ " <string>--once</string>",
157
+ " </array>",
158
+ " <key>StartInterval</key>",
159
+ ` <integer>${spec.intervalMin * 60}</integer>`,
160
+ " <key>RunAtLoad</key>",
161
+ " <true/>",
162
+ "</dict>",
163
+ "</plist>",
164
+ "",
165
+ ].join("\n")
166
+ }
167
+
168
+ export function systemdDir(): string {
169
+ return join(homedir(), ".config", "systemd", "user")
170
+ }
171
+
172
+ export function launchdPath(): string {
173
+ return join(homedir(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`)
174
+ }
175
+
176
+ // ---------- 平台执行 ----------
177
+
178
+ /** 查询已注册任务的形态(注册层唯一平台差异点):S4U > conhost --headless > Interactive */
179
+ export function registeredForm(platform = process.platform): "s4u" | "conhost" | "interactive" | "unknown" {
180
+ if (platform !== "win32") return "unknown"
181
+ const q = run("schtasks", ["/Query", "/TN", WIN_TASK_NAME, "/XML"])
182
+ if (!q.ok) return "unknown"
183
+ if (/<LogonType>S4U<\/LogonType>/.test(q.detail)) return "s4u"
184
+ if (q.detail.includes("--headless") && /<Command>[^<]*conhost\.exe/i.test(q.detail)) return "conhost"
185
+ return "interactive"
186
+ }
187
+
188
+ export function isS4uRegistered(platform = process.platform): boolean {
189
+ return registeredForm(platform) === "s4u"
190
+ }
191
+
192
+ const FORM_LABEL: Record<string, string> = {
193
+ s4u: "S4U(非交互会话,tick 零窗口)",
194
+ conhost: "conhost --headless(隐藏控制台,需已登录会话)",
195
+ interactive: "Interactive(可能闪窗)",
196
+ unknown: "未知形态",
197
+ }
198
+
199
+ export function serviceInstall(spec: ServiceSpec, platform = process.platform): CommandResult {
200
+ if (platform === "win32") {
201
+ // 三级梯队(2026-11-09 静默拉起缺陷③):
202
+ // ① XML+S4U(最优,需提权/管理员令牌——未提权实证 Access denied)
203
+ // ② conhost --headless 包装(不需提权、零闪窗、非 shell;需已登录)
204
+ // ③ 旧 Interactive 直调(有看门狗保底,可能闪窗)
205
+ // 每级失败都落到下一级,保证「有看门狗」优先于「看门狗静默」——最终形态在 serviceStatus 可辨。
206
+ const xmlPath = join(tmpdir(), `openqq-watchdog-task-${process.pid}.xml`)
207
+ try {
208
+ // schtasks 的 XML 解析器只接受 UTF-16+UTF-16LE BOM(实证:UTF-8 声名/无 BOM 均「无法切换编码」)
209
+ writeFileSync(xmlPath, Buffer.concat([
210
+ new Uint8Array([0xff, 0xfe]),
211
+ Buffer.from(buildSchtasksTaskXml(spec), "utf-16le"),
212
+ ]))
213
+ const res = run("schtasks", buildSchtasksXmlArgs(xmlPath))
214
+ if (res.ok) {
215
+ return { ok: true, detail: `${res.detail}\n注册形态: ${FORM_LABEL.s4u}` }
216
+ }
217
+ const xmlErr = res.detail
218
+ rmSync(xmlPath, { force: true })
219
+ const conhostRes = run("schtasks", buildSchtasksConhostArgs(spec))
220
+ if (conhostRes.ok) {
221
+ return { ok: true, detail: `${conhostRes.detail}\n注册形态: ${FORM_LABEL.conhost}\n(S4U 注册失败,已回退 conhost --headless 梯队,schtasks 原始输出:${xmlErr})` }
222
+ }
223
+ const legacy = run("schtasks", buildSchtasksCreateArgs(spec))
224
+ return {
225
+ ...legacy,
226
+ detail: `${legacy.detail}\n(S4U 与 conhost --headless 梯队均失败,已回退 Interactive 形态;S4U 输出:${xmlErr} | conhost 输出:${conhostRes.detail})`,
227
+ }
228
+ } finally {
229
+ try {
230
+ rmSync(xmlPath, { force: true })
231
+ } catch {
232
+ /* 临时文件清理失败不阻断 */
233
+ }
234
+ }
235
+ }
236
+ if (platform === "linux") {
237
+ const dir = systemdDir()
238
+ mkdirSync(dir, { recursive: true })
239
+ writeFileSync(join(dir, `${SYSTEMD_UNIT}.service`), buildSystemdService(spec))
240
+ writeFileSync(join(dir, `${SYSTEMD_UNIT}.timer`), buildSystemdTimer(spec.intervalMin))
241
+ const reload = run("systemctl", ["--user", "daemon-reload"])
242
+ if (!reload.ok) return reload
243
+ const enable = run("systemctl", ["--user", "enable", "--now", `${SYSTEMD_UNIT}.timer`])
244
+ return {
245
+ ok: enable.ok,
246
+ detail: `${enable.detail}\n提示:无图形会话时需 loginctl enable-linger $USER 才能常驻`,
247
+ }
248
+ }
249
+ if (platform === "darwin") {
250
+ const path = launchdPath()
251
+ mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true })
252
+ writeFileSync(path, buildLaunchdPlist(spec))
253
+ return run("launchctl", ["load", "-w", path])
254
+ }
255
+ return { ok: false, detail: `不支持的平台:${platform}` }
256
+ }
257
+
258
+ export function serviceUninstall(platform = process.platform): CommandResult {
259
+ if (platform === "win32") return run("schtasks", buildSchtasksDeleteArgs())
260
+ if (platform === "linux") {
261
+ run("systemctl", ["--user", "disable", "--now", `${SYSTEMD_UNIT}.timer`])
262
+ rmSync(join(systemdDir(), `${SYSTEMD_UNIT}.timer`), { force: true })
263
+ rmSync(join(systemdDir(), `${SYSTEMD_UNIT}.service`), { force: true })
264
+ return run("systemctl", ["--user", "daemon-reload"])
265
+ }
266
+ if (platform === "darwin") {
267
+ const path = launchdPath()
268
+ const res = run("launchctl", ["unload", "-w", path])
269
+ rmSync(path, { force: true })
270
+ return res
271
+ }
272
+ return { ok: false, detail: `不支持的平台:${platform}` }
273
+ }
274
+
275
+ export function serviceStatus(platform = process.platform): CommandResult {
276
+ if (platform === "win32") {
277
+ const q = run("schtasks", ["/Query", "/TN", WIN_TASK_NAME])
278
+ const form = q.ok ? `注册形态: ${FORM_LABEL[registeredForm(platform)]}` : "任务未注册"
279
+ return { ...q, detail: `${q.detail}\n${form}` }
280
+ }
281
+ if (platform === "linux") {
282
+ const exists = existsSync(join(systemdDir(), `${SYSTEMD_UNIT}.timer`))
283
+ const active = run("systemctl", ["--user", "is-active", `${SYSTEMD_UNIT}.timer`])
284
+ return { ok: exists && active.ok, detail: `unit 文件存在=${exists}\n${active.detail}` }
285
+ }
286
+ if (platform === "darwin") {
287
+ const path = launchdPath()
288
+ return { ok: existsSync(path), detail: `${path} 存在=${existsSync(path)}\n${run("launchctl", ["list", LAUNCHD_LABEL]).detail}` }
289
+ }
290
+ return { ok: false, detail: `不支持的平台:${platform}` }
291
+ }
292
+
293
+ /** 读取已安装的 unit/plist 内容(诊断用) */
294
+ export function readInstalledConfig(platform = process.platform): string | null {
295
+ try {
296
+ if (platform === "linux") return readFileSync(join(systemdDir(), `${SYSTEMD_UNIT}.timer`), "utf-8")
297
+ if (platform === "darwin") return readFileSync(launchdPath(), "utf-8")
298
+ return null
299
+ } catch {
300
+ return null
301
+ }
302
+ }
@@ -0,0 +1,77 @@
1
+ // @input: argv(--once | --loop | --interval-min N)、~/.openqq 锁/心跳、core/watchdog(superviseOnce)、core/bot-control
2
+ // @output: (side-effect) 巡检并在必要时重启 bot;give-up 时 QQ 告警
3
+ // @pos: cli - 跨平台监督者入口(dist/openqq-watchdog.js)
4
+ //
5
+ // 用法:
6
+ // node dist/openqq-watchdog.js --once # 单次巡检(自启项/timer 调这个)
7
+ // node dist/openqq-watchdog.js --loop # 常驻循环(默认 10 分钟)
8
+ // node dist/openqq-watchdog.js --interval-min 5 # 自定义周期
9
+ // 退出码:0=正常(含"健康/冷却/让行");1=运行时/配置错误。
10
+ //
11
+ // 2026-11-09 重构:裸 healOnce 升级为 superviseOnce——优雅杀(TERM→宽限→KILL)、
12
+ // 冷却(防互踢)、重启强度(超限 give-up 并告警,不当永动机)、监督者认领互斥。
13
+ import { botWatchdogPaths, readEnvField, appendWatchdogLog, superviseOnce } from "../core/watchdog.js"
14
+ import { readAppId, startBot } from "../core/bot-control.js"
15
+ import { runNotifyCli } from "./notify.js"
16
+ import { join } from "path"
17
+ import { homedir } from "os"
18
+
19
+ const DEFAULT_INTERVAL_MIN = 10
20
+
21
+ function parseArgs(argv: string[]): { loop: boolean; intervalMin: number } {
22
+ const loop = argv.includes("--loop")
23
+ const idx = argv.indexOf("--interval-min")
24
+ const raw = idx >= 0 ? Number(argv[idx + 1]) : Number.NaN
25
+ const intervalMin = Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_INTERVAL_MIN
26
+ return { loop, intervalMin }
27
+ }
28
+
29
+ function currentAppId(): string | null {
30
+ return readAppId() ?? readEnvField(join(homedir(), ".openqq", ".env"), "QQ_APP_ID")
31
+ }
32
+
33
+ /** give-up 上报:入队 QQ 通知(bot 恢复后送达)+本进程日志;失败静默(fail-open)。 */
34
+ function alert(message: string): void {
35
+ void runNotifyCli(["--text", message, "--id", `supervisor-giveup-${Date.now()}`]).then(
36
+ (r) => console.log(`[supervisor] 告警已入队 user=${r.user}`),
37
+ (error) => console.error("[supervisor] 告警入队失败:", error instanceof Error ? error.message : error),
38
+ )
39
+ }
40
+
41
+ async function tick(appId: string): Promise<void> {
42
+ const result = await superviseOnce({
43
+ paths: botWatchdogPaths(appId),
44
+ spawn: () => startBot(import.meta.url, (line) => console.log(line)),
45
+ log: (line) => console.log(line),
46
+ alert,
47
+ })
48
+ console.log(`[supervisor] ${result.action}:${result.detail}`)
49
+ // 健康时静默落盘(避免每 10 分钟一行膨胀日志),异常必记
50
+ if (result.action !== "ok") appendWatchdogLog(`[supervisor] ${result.action}:${result.detail}`)
51
+ }
52
+
53
+ async function main(): Promise<void> {
54
+ const args = parseArgs(process.argv.slice(2))
55
+ const appId = currentAppId()
56
+ if (!appId) {
57
+ console.error("[watchdog] 未找到 QQ_APP_ID(~/.openqq/.env),无法定位实例锁")
58
+ process.exit(1)
59
+ }
60
+ console.log(`[watchdog] 模式=${args.loop ? `loop/${args.intervalMin}min` : "once"}(监督矩阵:冷却2m/强度3次15m/优雅杀8s)`)
61
+ await tick(appId)
62
+ if (!args.loop) return
63
+ const timer = setInterval(() => {
64
+ void tick(appId).catch((error) => console.error("[watchdog] 巡检失败:", error instanceof Error ? error.message : error))
65
+ }, args.intervalMin * 60_000)
66
+ const stop = (): void => {
67
+ clearInterval(timer)
68
+ process.exit(0)
69
+ }
70
+ process.once("SIGINT", stop)
71
+ process.once("SIGTERM", stop)
72
+ }
73
+
74
+ void main().catch((error) => {
75
+ console.error("[watchdog] 致命错误:", error instanceof Error ? error.message : error)
76
+ process.exit(1)
77
+ })