@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.
Files changed (61) hide show
  1. package/README.md +303 -229
  2. package/README.zh-CN.md +313 -0
  3. package/bin/openqq.js +13 -0
  4. package/dist/notify-cli.js +92 -26
  5. package/dist/opencode-qqbot-plugin.js +1201 -67
  6. package/dist/openqq-bot.js +3963 -893
  7. package/dist/openqq-cli.js +980 -0
  8. package/dist/openqq-watchdog.js +1326 -0
  9. package/package.json +8 -5
  10. package/src/bridge.ts +1599 -150
  11. package/src/cli/notify.ts +170 -158
  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 +92 -0
  15. package/src/commands.ts +670 -554
  16. package/src/config.ts +122 -3
  17. package/src/core/bot-config.ts +66 -0
  18. package/src/core/bot-control.ts +166 -0
  19. package/src/core/bot-launcher.ts +110 -15
  20. package/src/core/card-approval.ts +20 -9
  21. package/src/core/cron-reminders.ts +84 -0
  22. package/src/core/delivery.ts +145 -54
  23. package/src/core/discovery.ts +207 -151
  24. package/src/core/error-rescue.ts +1 -1
  25. package/src/core/file-log.ts +50 -9
  26. package/src/core/form-bridge.ts +14 -5
  27. package/src/core/form-journal.ts +4 -4
  28. package/src/core/gateway-state.ts +3 -3
  29. package/src/core/inflight-journal.ts +215 -36
  30. package/src/core/instance-lock.ts +42 -3
  31. package/src/core/linkwatch.ts +3 -4
  32. package/src/core/log-rotate.ts +91 -0
  33. package/src/core/markdown.ts +117 -0
  34. package/src/core/message-queue.ts +242 -91
  35. package/src/core/mirror.ts +228 -182
  36. package/src/core/notices.ts +62 -0
  37. package/src/core/notify-sink.ts +93 -96
  38. package/src/core/outbound-sanitize.ts +29 -0
  39. package/src/core/outbox.ts +10 -9
  40. package/src/core/permission.ts +634 -303
  41. package/src/core/question-form.ts +230 -0
  42. package/src/core/queue-view.ts +662 -0
  43. package/src/core/send-media.ts +61 -2
  44. package/src/core/start-error.ts +26 -0
  45. package/src/core/storage.ts +34 -0
  46. package/src/core/stt.ts +55 -0
  47. package/src/core/supervisor-election.ts +53 -0
  48. package/src/core/watchdog.ts +670 -0
  49. package/src/core/zombie-reaper.ts +127 -0
  50. package/src/index.ts +262 -162
  51. package/src/opencode/client.ts +237 -27
  52. package/src/opencode/eventstream.ts +94 -12
  53. package/src/opencode/history.ts +4 -2
  54. package/src/opencode/mirror.ts +25 -5
  55. package/src/opencode/sessions.ts +135 -37
  56. package/src/plugin-entry.ts +139 -115
  57. package/src/qq/api.ts +165 -61
  58. package/src/qq/gateway.ts +114 -16
  59. package/src/qq/media.ts +21 -0
  60. package/src/qq/sender.ts +79 -18
  61. package/src/qq/types.ts +7 -0
package/src/cli/notify.ts CHANGED
@@ -1,158 +1,170 @@
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
- reason?: string
28
- }
29
-
30
- /** 保守截断:默认 1500 字(主动消息日配额 100/天——长输出拆几十条会吃光);0=不截断。 */
31
- export const NOTIFY_DEFAULT_MAX_CHARS = 1500
32
-
33
- interface ParsedArgs {
34
- text?: string
35
- filePath?: string
36
- stdin?: boolean
37
- user?: string
38
- id?: string
39
- maxChars: number
40
- ttlHours?: number
41
- dryRun: boolean
42
- json: boolean
43
- help: boolean
44
- }
45
-
46
- function parseArgs(argv: readonly string[]): ParsedArgs {
47
- const parsed: ParsedArgs = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false }
48
- for (let i = 0; i < argv.length; i++) {
49
- const a = argv[i]
50
- const next = argv[i + 1]
51
- switch (a) {
52
- case "--text": parsed.text = next; i++; break
53
- case "--file": parsed.filePath = next; i++; break
54
- case "--stdin": parsed.stdin = true; break
55
- case "--user": parsed.user = next; i++; break
56
- case "--id": parsed.id = next; i++; break
57
- case "--max-chars": parsed.maxChars = Number(next); i++; break
58
- case "--ttl-hours": parsed.ttlHours = Number(next); i++; break
59
- case "--dry-run": parsed.dryRun = true; break
60
- case "--json": parsed.json = true; break
61
- case "--help": case "-h": parsed.help = true; i++; break
62
- default:
63
- throw new Error(`未知参数:${a}(用法:openqq notify --text "…" | --file <p> | --stdin)`)
64
- }
65
- }
66
- if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
67
- throw new Error("必须提供正文来源:--text / --file / --stdin 三选一")
68
- }
69
- if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
70
- throw new Error("--max-chars 必须是 >= 0 的有限数(0=不截断)")
71
- }
72
- return parsed
73
- }
74
-
75
- /** 收件人 fail-closed:显式 --user 必须命中名单;缺省仅取 ALLOWED_USERS 唯一项。 */
76
- export function resolveUser(envAllowed: readonly string[], explicit?: string): string {
77
- return resolveNotifyRecipients(envAllowed, explicit)
78
- }
79
-
80
- /** 正文来源:--text / --file / --stdin;--file - 读 stdin(同步可读)。 */
81
- function readBody(parsed: ParsedArgs): string {
82
- if (parsed.text !== undefined) return parsed.text
83
- if (parsed.filePath !== undefined) {
84
- if (parsed.filePath === "-") return readFileSync(0 as unknown as number, "utf8")
85
- if (!existsSync(parsed.filePath)) throw new Error(`--file 不存在:${parsed.filePath}`)
86
- return readFileSync(parsed.filePath, "utf8")
87
- }
88
- if (parsed.stdin) return readFileSync(0 as unknown as number, "utf8")
89
- return ""
90
- }
91
-
92
- export async function runNotifyCli(
93
- argv: readonly string[],
94
- options: NotifyCliOptions = {},
95
- ): Promise<NotifyCliResult> {
96
- const now = options.now ?? Date.now()
97
- const parsed = parseArgs(argv)
98
- if (parsed.help) {
99
- const help = [
100
- "用法:openqq notify --text \"…\" | --file <路径> | --stdin",
101
- " --user <openid> 收件人;缺省取 ALLOWED_USERS 唯一项(多用户必须显式指定)",
102
- " --id <key> 幂等键(同 key 不重复投递)",
103
- " --max-chars <n> 截断上限,默认 1500,0 不截断",
104
- " --ttl-hours <n> 队列等待上限,默认 24(env QQ_NOTIFY_TTL_HOURS 兜底)",
105
- " --dry-run / --json 不入队 / 机器可读输出",
106
- ].join("\n")
107
- console.log(help)
108
- return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, reason: "help" }
109
- }
110
- // .env 注入:bot 进程入口已做;CLI 独立进程需自行加载(ALLOWED_USERS/凭据同源单点)
111
- if (!options.env && existsSync(ENV_FILE)) loadEnvFile(ENV_FILE)
112
- const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "")
113
- .split(/[,\s]+/).filter(Boolean)
114
- const user = resolveUser(allowedUsers, parsed.user)
115
- if (!user) {
116
- throw new Error(
117
- allowedUsers.length === 0
118
- ? "ALLOWED_USERS 为空——fail-closed 不允许无名单入队(先在 ~/.openqq/.env 配置)"
119
- : "多用户名单必须用 --user <openid> 显式指定收件人",
120
- )
121
- }
122
- const raw = readBody(parsed)
123
- const max = parsed.maxChars
124
- const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}…` : raw
125
- const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`
126
- const filePath = options.filePath ?? defaultOutboxPath()
127
- if (parsed.dryRun) {
128
- return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true }
129
- }
130
- const ttlHours =
131
- parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24)
132
- const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0
133
- ? now + ttlHours * 60 * 60 * 1000
134
- : now
135
- const outbox = createOutbox({ filePath, pollIntervalMs: 0 })
136
- const entry = await outbox.enqueue({
137
- ...(parsed.id ? { id: parsed.id } : {}),
138
- kind: "notify",
139
- payload: { text: content },
140
- ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
141
- sessionId: "",
142
- nextAttemptAt,
143
- })
144
- return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false }
145
- }
146
-
147
- /** bin/openqq.js 入口:返回进程退出码(0=已入队;1=参数/配置错误)。 */
148
- export async function main(argv: readonly string[]): Promise<number> {
149
- try {
150
- const result = await runNotifyCli(argv)
151
- if (result.reason === "help") return 0
152
- if (result.queued && !result.dryRun) console.log(`[notify] 已入队 id=${result.id} user=${result.user} chars=${result.chars}${result.truncated ? "(已截断)" : ""}`)
153
- return result.ok ? 0 : 1
154
- } catch (error) {
155
- console.error(`[notify] 入队失败:${error instanceof Error ? error.message : String(error)}`)
156
- return 1
157
- }
158
- }
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 { applyConfigOverlay } from "../core/bot-config.js"
11
+ import { defaultOutboxPath, resolveNotifyRecipients } from "../core/notify-sink.js"
12
+
13
+ export interface NotifyCliOptions {
14
+ filePath?: string
15
+ now?: number
16
+ env?: { allowedUsers: readonly string[] }
17
+ }
18
+
19
+ /** CLI 结果(--json 输出同 shape;dry-run 时 queued=false 并附 wouldEnqueue)。 */
20
+ export interface NotifyCliResult {
21
+ ok: boolean
22
+ queued: boolean
23
+ id: string
24
+ user: string
25
+ chars: number
26
+ truncated: boolean
27
+ dryRun: boolean
28
+ json: boolean
29
+ reason?: string
30
+ }
31
+
32
+ /** 保守截断:默认 1500 字(主动消息日配额 100/天——长输出拆几十条会吃光);0=不截断。 */
33
+ export const NOTIFY_DEFAULT_MAX_CHARS = 1500
34
+
35
+ interface ParsedArgs {
36
+ text?: string
37
+ filePath?: string
38
+ stdin?: boolean
39
+ user?: string
40
+ id?: string
41
+ maxChars: number
42
+ ttlHours?: number
43
+ dryRun: boolean
44
+ json: boolean
45
+ help: boolean
46
+ }
47
+
48
+ function parseArgs(argv: readonly string[]): ParsedArgs {
49
+ const parsed: ParsedArgs = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false }
50
+ for (let i = 0; i < argv.length; i++) {
51
+ const a = argv[i]
52
+ const next = argv[i + 1]
53
+ switch (a) {
54
+ case "--text": parsed.text = next; i++; break
55
+ case "--file": parsed.filePath = next; i++; break
56
+ case "--stdin": parsed.stdin = true; break
57
+ case "--user": parsed.user = next; i++; break
58
+ case "--id": parsed.id = next; i++; break
59
+ case "--max-chars": parsed.maxChars = Number(next); i++; break
60
+ case "--ttl-hours": parsed.ttlHours = Number(next); i++; break
61
+ case "--dry-run": parsed.dryRun = true; break
62
+ case "--json": parsed.json = true; break
63
+ case "--help": case "-h": parsed.help = true; i++; break
64
+ default:
65
+ throw new Error(`未知参数:${a}(用法:openqq notify --text "…" | --file <p> | --stdin)`)
66
+ }
67
+ }
68
+ if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
69
+ throw new Error("必须提供正文来源:--text / --file / --stdin 三选一")
70
+ }
71
+ if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
72
+ throw new Error("--max-chars 必须是 >= 0 的有限数(0=不截断)")
73
+ }
74
+ return parsed
75
+ }
76
+
77
+ /** 收件人 fail-closed:显式 --user 必须命中名单;缺省仅取 ALLOWED_USERS 唯一项。 */
78
+ export function resolveUser(envAllowed: readonly string[], explicit?: string): string {
79
+ return resolveNotifyRecipients(envAllowed, explicit)
80
+ }
81
+
82
+ /** 正文来源:--text / --file / --stdin;--file - 读 stdin(同步可读)。 */
83
+ function readBody(parsed: ParsedArgs): string {
84
+ if (parsed.text !== undefined) return parsed.text
85
+ if (parsed.filePath !== undefined) {
86
+ if (parsed.filePath === "-") return readFileSync(0 as unknown as number, "utf8")
87
+ if (!existsSync(parsed.filePath)) throw new Error(`--file 不存在:${parsed.filePath}`)
88
+ return readFileSync(parsed.filePath, "utf8")
89
+ }
90
+ if (parsed.stdin) return readFileSync(0 as unknown as number, "utf8")
91
+ return ""
92
+ }
93
+
94
+ export async function runNotifyCli(
95
+ argv: readonly string[],
96
+ options: NotifyCliOptions = {},
97
+ ): Promise<NotifyCliResult> {
98
+ const now = options.now ?? Date.now()
99
+ const parsed = parseArgs(argv)
100
+ if (parsed.help) {
101
+ const help = [
102
+ "用法:openqq notify --text \"…\" | --file <路径> | --stdin",
103
+ " --user <openid> 收件人;缺省取 ALLOWED_USERS 唯一项(多用户必须显式指定)",
104
+ " --id <key> 幂等键(同 key 不重复投递)",
105
+ " --max-chars <n> 截断上限,默认 1500,0 不截断",
106
+ " --ttl-hours <n> 队列等待上限,默认 24(env QQ_NOTIFY_TTL_HOURS 兜底)",
107
+ " --dry-run / --json 不入队 / 机器可读输出",
108
+ ].join("\n")
109
+ console.log(help)
110
+ return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" }
111
+ }
112
+ // .env 注入:bot 进程入口已做;CLI 独立进程需自行加载(ALLOWED_USERS/凭据同源单点)。
113
+ // config.json 先叠加(最低层),.env 后加载自然覆盖它——与 bot 入口同一层级序。
114
+ applyConfigOverlay()
115
+ if (!options.env && existsSync(ENV_FILE)) loadEnvFile(ENV_FILE)
116
+ const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "")
117
+ .split(/[,\s]+/).filter(Boolean)
118
+ const user = resolveUser(allowedUsers, parsed.user)
119
+ if (!user) {
120
+ throw new Error(
121
+ allowedUsers.length === 0
122
+ ? "ALLOWED_USERS 为空——fail-closed 不允许无名单入队(先在 ~/.openqq/.env 配置)"
123
+ : parsed.user
124
+ ? `收件人不在名单:${parsed.user}(ALLOWED_USERS 共 ${allowedUsers.length} 项,--user 必须精确命中;请核对 openid)`
125
+ : "多用户名单必须用 --user <openid> 显式指定收件人",
126
+ )
127
+ }
128
+ const raw = readBody(parsed)
129
+ const max = parsed.maxChars
130
+ const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}…` : raw
131
+ const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`
132
+ const filePath = options.filePath ?? defaultOutboxPath()
133
+ if (parsed.dryRun) {
134
+ return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true, json: parsed.json }
135
+ }
136
+ const ttlHours =
137
+ parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24)
138
+ const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0
139
+ ? now + ttlHours * 60 * 60 * 1000
140
+ : now
141
+ const outbox = createOutbox({ filePath, pollIntervalMs: 0 })
142
+ const entry = await outbox.enqueue({
143
+ ...(parsed.id ? { id: parsed.id } : {}),
144
+ kind: "notify",
145
+ payload: { text: content },
146
+ ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
147
+ sessionId: "",
148
+ nextAttemptAt,
149
+ })
150
+ return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false, json: parsed.json }
151
+ }
152
+
153
+ /** bin/openqq.js 入口:返回进程退出码(0=已入队;1=参数/配置错误)。 */
154
+ export async function main(argv: readonly string[]): Promise<number> {
155
+ try {
156
+ const result = await runNotifyCli(argv)
157
+ if (result.reason === "help") return 0
158
+ if (result.json) {
159
+ console.log(JSON.stringify(result))
160
+ } else if (result.queued && !result.dryRun) {
161
+ console.log(`[notify] 已入队 id=${result.id} user=${result.user} chars=${result.chars}${result.truncated ? "(已截断)" : ""}`)
162
+ } else if (result.dryRun) {
163
+ console.log(`[notify] dry-run:将入队 user=${result.user} chars=${result.chars}${result.truncated ? "(已截断)" : ""}`)
164
+ }
165
+ return result.ok ? 0 : 1
166
+ } catch (error) {
167
+ console.error(`[notify] 入队失败:${error instanceof Error ? error.message : String(error)}`)
168
+ return 1
169
+ }
170
+ }
@@ -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
+ })