@linjz/opencode-qqbot 0.3.4 → 0.3.6

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 (42) hide show
  1. package/README.md +74 -37
  2. package/bin/openqq-setup.mjs +50 -50
  3. package/bin/openqq.js +47 -47
  4. package/dist/opencode-qqbot-plugin.js +10 -1
  5. package/dist/openqq-bot.js +360 -69
  6. package/package.json +69 -59
  7. package/src/_FOLDER.md +19 -19
  8. package/src/bridge.ts +934 -796
  9. package/src/commands.ts +554 -514
  10. package/src/config.ts +121 -121
  11. package/src/core/bot-launcher.ts +146 -134
  12. package/src/core/card-approval.ts +146 -146
  13. package/src/core/context-buffer.ts +78 -78
  14. package/src/core/delivery.ts +284 -284
  15. package/src/core/discovery.ts +151 -151
  16. package/src/core/error-rescue.ts +33 -0
  17. package/src/core/file-log.ts +45 -45
  18. package/src/core/form-bridge.ts +304 -304
  19. package/src/core/inflight-journal.ts +212 -151
  20. package/src/core/instance-lock.ts +122 -122
  21. package/src/core/linkwatch.ts +195 -195
  22. package/src/core/message-queue.ts +80 -0
  23. package/src/core/mirror.ts +173 -173
  24. package/src/core/permission.ts +301 -301
  25. package/src/core/reply-limiter.ts +106 -106
  26. package/src/core/send-media.ts +90 -90
  27. package/src/core/util.ts +8 -8
  28. package/src/index.ts +162 -162
  29. package/src/opencode/_FOLDER.md +11 -11
  30. package/src/opencode/client.ts +387 -386
  31. package/src/opencode/eventstream.ts +138 -138
  32. package/src/opencode/history.ts +143 -143
  33. package/src/opencode/mirror.ts +65 -65
  34. package/src/opencode/sessions.ts +158 -158
  35. package/src/plugin-entry.ts +112 -112
  36. package/src/qq/_FOLDER.md +13 -13
  37. package/src/qq/api.ts +539 -539
  38. package/src/qq/gateway.ts +492 -492
  39. package/src/qq/media.ts +219 -204
  40. package/src/qq/sender.ts +300 -300
  41. package/src/qq/types.ts +154 -152
  42. package/tsconfig.json +24 -24
package/src/config.ts CHANGED
@@ -1,121 +1,121 @@
1
- // @input: process.env, ~/.openqq/.env
2
- // @output: Config, loadConfig, ensureConfig
3
- // @pos: 根层 - 环境变量加载 + 首次运行交互式引导
4
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
5
- import { join } from "path"
6
- import { homedir } from "os"
7
- import { createInterface } from "readline"
8
-
9
- export interface Config {
10
- qq: {
11
- appId: string
12
- clientSecret: string
13
- sandbox: boolean
14
- }
15
- opencode: {
16
- baseUrl: string
17
- externalUrl: boolean
18
- }
19
- allowedUsers: string[]
20
- maxReplyLength: number
21
- }
22
-
23
- const CONFIG_DIR = join(homedir(), ".openqq")
24
- const ENV_FILE = join(CONFIG_DIR, ".env")
25
-
26
- function askTwo(q1: string, q2: string): Promise<[string, string]> {
27
- return new Promise((resolve, reject) => {
28
- let done = false
29
- const rl = createInterface({ input: process.stdin, output: process.stdout })
30
- rl.on("close", () => { if (!done) reject(new Error("输入被中断")) })
31
- rl.question(q1, (a1) => {
32
- rl.question(q2, (a2) => {
33
- done = true
34
- rl.close()
35
- resolve([a1.trim(), a2.trim()])
36
- })
37
- })
38
- })
39
- }
40
-
41
- export async function ensureConfig(): Promise<void> {
42
- if (process.env.QQ_APP_ID && process.env.QQ_APP_SECRET) return
43
-
44
- if (existsSync(ENV_FILE)) {
45
- loadEnvFile(ENV_FILE)
46
- if (process.env.QQ_APP_ID && process.env.QQ_APP_SECRET) return
47
- }
48
-
49
- const localEnv = join(process.cwd(), ".env")
50
- if (existsSync(localEnv)) {
51
- loadEnvFile(localEnv)
52
- if (process.env.QQ_APP_ID && process.env.QQ_APP_SECRET) return
53
- }
54
-
55
- console.log("首次运行,需要配置 QQ 机器人凭证")
56
- console.log("(从 https://q.qq.com 机器人管理 -> 开发设置 获取)\n")
57
-
58
- const [appId, appSecret] = await askTwo("QQ App ID: ", "QQ App Secret: ")
59
-
60
- if (!appId || !appSecret) {
61
- throw new Error("App ID 和 App Secret 不能为空")
62
- }
63
-
64
- mkdirSync(CONFIG_DIR, { recursive: true })
65
- const envContent = [
66
- `QQ_APP_ID=${appId}`,
67
- `QQ_APP_SECRET=${appSecret}`,
68
- `QQ_SANDBOX=false`,
69
- `# OPENCODE_BASE_URL=http://127.0.0.1:<端口>/api(桌面 2.1.x 端口动态,失联时启动流程会自动发现)`,
70
- `ALLOWED_USERS=`,
71
- `MAX_REPLY_LENGTH=3000`,
72
- ].join("\n") + "\n"
73
-
74
- writeFileSync(ENV_FILE, envContent)
75
- console.log(`\n配置已保存到 ${ENV_FILE}`)
76
-
77
- process.env.QQ_APP_ID = appId
78
- process.env.QQ_APP_SECRET = appSecret
79
- }
80
-
81
- function loadEnvFile(path: string): void {
82
- const content = readFileSync(path, "utf-8")
83
- for (const line of content.split("\n")) {
84
- const trimmed = line.trim()
85
- if (!trimmed || trimmed.startsWith("#")) continue
86
- const eqIdx = trimmed.indexOf("=")
87
- if (eqIdx < 0) continue
88
- const key = trimmed.slice(0, eqIdx).trim()
89
- const val = trimmed.slice(eqIdx + 1).trim()
90
- if (!process.env[key]) {
91
- process.env[key] = val
92
- }
93
- }
94
- }
95
-
96
- export function loadConfig(): Config {
97
- const appId = process.env.QQ_APP_ID
98
- const clientSecret = process.env.QQ_APP_SECRET
99
-
100
- if (!appId) throw new Error("缺少 QQ_APP_ID,运行 openqq 重新配置")
101
- if (!clientSecret) throw new Error("缺少 QQ_APP_SECRET,运行 openqq 重新配置")
102
-
103
- const allowedRaw = process.env.ALLOWED_USERS?.trim() ?? ""
104
- const allowedUsers = allowedRaw
105
- ? allowedRaw.split(",").map((s: string) => s.trim()).filter(Boolean)
106
- : []
107
-
108
- return {
109
- qq: {
110
- appId,
111
- clientSecret,
112
- sandbox: process.env.QQ_SANDBOX === "true",
113
- },
114
- opencode: {
115
- baseUrl: process.env.OPENCODE_BASE_URL?.trim() || "",
116
- externalUrl: !!process.env.OPENCODE_BASE_URL?.trim(),
117
- },
118
- allowedUsers,
119
- maxReplyLength: parseInt(process.env.MAX_REPLY_LENGTH ?? "3000", 10),
120
- }
121
- }
1
+ // @input: process.env, ~/.openqq/.env
2
+ // @output: Config, loadConfig, ensureConfig
3
+ // @pos: 根层 - 环境变量加载 + 首次运行交互式引导
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
5
+ import { join } from "path"
6
+ import { homedir } from "os"
7
+ import { createInterface } from "readline"
8
+
9
+ export interface Config {
10
+ qq: {
11
+ appId: string
12
+ clientSecret: string
13
+ sandbox: boolean
14
+ }
15
+ opencode: {
16
+ baseUrl: string
17
+ externalUrl: boolean
18
+ }
19
+ allowedUsers: string[]
20
+ maxReplyLength: number
21
+ }
22
+
23
+ const CONFIG_DIR = join(homedir(), ".openqq")
24
+ const ENV_FILE = join(CONFIG_DIR, ".env")
25
+
26
+ function askTwo(q1: string, q2: string): Promise<[string, string]> {
27
+ return new Promise((resolve, reject) => {
28
+ let done = false
29
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
30
+ rl.on("close", () => { if (!done) reject(new Error("输入被中断")) })
31
+ rl.question(q1, (a1) => {
32
+ rl.question(q2, (a2) => {
33
+ done = true
34
+ rl.close()
35
+ resolve([a1.trim(), a2.trim()])
36
+ })
37
+ })
38
+ })
39
+ }
40
+
41
+ export async function ensureConfig(): Promise<void> {
42
+ if (process.env.QQ_APP_ID && process.env.QQ_APP_SECRET) return
43
+
44
+ if (existsSync(ENV_FILE)) {
45
+ loadEnvFile(ENV_FILE)
46
+ if (process.env.QQ_APP_ID && process.env.QQ_APP_SECRET) return
47
+ }
48
+
49
+ const localEnv = join(process.cwd(), ".env")
50
+ if (existsSync(localEnv)) {
51
+ loadEnvFile(localEnv)
52
+ if (process.env.QQ_APP_ID && process.env.QQ_APP_SECRET) return
53
+ }
54
+
55
+ console.log("首次运行,需要配置 QQ 机器人凭证")
56
+ console.log("(从 https://q.qq.com 机器人管理 -> 开发设置 获取)\n")
57
+
58
+ const [appId, appSecret] = await askTwo("QQ App ID: ", "QQ App Secret: ")
59
+
60
+ if (!appId || !appSecret) {
61
+ throw new Error("App ID 和 App Secret 不能为空")
62
+ }
63
+
64
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }) // POSIX 凭据目录仅本人可入
65
+ const envContent = [
66
+ `QQ_APP_ID=${appId}`,
67
+ `QQ_APP_SECRET=${appSecret}`,
68
+ `QQ_SANDBOX=false`,
69
+ `# OPENCODE_BASE_URL=http://127.0.0.1:<端口>/api(桌面 2.1.x 端口动态,失联时启动流程会自动发现)`,
70
+ `ALLOWED_USERS=`,
71
+ `MAX_REPLY_LENGTH=3000`,
72
+ ].join("\n") + "\n"
73
+
74
+ writeFileSync(ENV_FILE, envContent, { mode: 0o600 }) // POSIX 凭据文件仅本人可读
75
+ console.log(`\n配置已保存到 ${ENV_FILE}`)
76
+
77
+ process.env.QQ_APP_ID = appId
78
+ process.env.QQ_APP_SECRET = appSecret
79
+ }
80
+
81
+ function loadEnvFile(path: string): void {
82
+ const content = readFileSync(path, "utf-8")
83
+ for (const line of content.split("\n")) {
84
+ const trimmed = line.trim()
85
+ if (!trimmed || trimmed.startsWith("#")) continue
86
+ const eqIdx = trimmed.indexOf("=")
87
+ if (eqIdx < 0) continue
88
+ const key = trimmed.slice(0, eqIdx).trim()
89
+ const val = trimmed.slice(eqIdx + 1).trim()
90
+ if (!process.env[key]) {
91
+ process.env[key] = val
92
+ }
93
+ }
94
+ }
95
+
96
+ export function loadConfig(): Config {
97
+ const appId = process.env.QQ_APP_ID
98
+ const clientSecret = process.env.QQ_APP_SECRET
99
+
100
+ if (!appId) throw new Error("缺少 QQ_APP_ID,运行 openqq 重新配置")
101
+ if (!clientSecret) throw new Error("缺少 QQ_APP_SECRET,运行 openqq 重新配置")
102
+
103
+ const allowedRaw = process.env.ALLOWED_USERS?.trim() ?? ""
104
+ const allowedUsers = allowedRaw
105
+ ? allowedRaw.split(",").map((s: string) => s.trim()).filter(Boolean)
106
+ : []
107
+
108
+ return {
109
+ qq: {
110
+ appId,
111
+ clientSecret,
112
+ sandbox: process.env.QQ_SANDBOX === "true",
113
+ },
114
+ opencode: {
115
+ baseUrl: process.env.OPENCODE_BASE_URL?.trim() || "",
116
+ externalUrl: !!process.env.OPENCODE_BASE_URL?.trim(),
117
+ },
118
+ allowedUsers,
119
+ maxReplyLength: parseInt(process.env.MAX_REPLY_LENGTH ?? "3000", 10),
120
+ }
121
+ }
@@ -1,134 +1,146 @@
1
- // @input: fs/child_process/os(运行时探测、detached 拉起)
2
- // @output: resolveRuntime, buildLaunchPlan, spawnBotDetached, readDotEnvField
3
- // @pos: core - bot 进程拉起器(D 路径:插件引导器的服务端;跨平台 Windows/Linux/macOS)
4
- //
5
- // 设计:插件(opencode serve 内)检测 bot 不存活时,以 detached 子进程拉起——
6
- // 子进程脱离 serve 生命周期(serve 重载/重启不碰 bot)。运行时解析 bun→node:
7
- // bun 直接跑源码(.js→.ts 映射);node 跑发布时预打的 dist/openqq-bot.js bundle。
8
- import { spawn, spawnSync } from "child_process"
9
- import { existsSync, readFileSync } from "fs"
10
- import { join, dirname } from "path"
11
- import { homedir } from "os"
12
-
13
- export type Runtime = "bun" | "node"
14
-
15
- /** 探测命令可用性(跨平台:spawnSync ENOENT=不存在) */
16
- export function resolveRuntime(probe: (cmd: string) => boolean = defaultProbe): Runtime | null {
17
- if (resolveBunCommand(probe)) return "bun"
18
- if (probe("node")) return "node"
19
- return null
20
- }
21
-
22
- function bunCandidates(): string[] {
23
- const candidates = ["bun", "bun.exe", "bun.cmd", "bun.bat"]
24
- if (process.platform === "win32") {
25
- const appdata = process.env.APPDATA || join(homedir(), "AppData", "Roaming")
26
- candidates.push(join(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"))
27
- } else {
28
- candidates.push("/usr/local/bin/bun", "/opt/homebrew/bin/bun", join(homedir(), ".bun", "bin", "bun"))
29
- }
30
- return candidates
31
- }
32
-
33
- /** 解析可用 bun 命令(覆盖 npm 安装形态:PATH 上只有 bun.ps1,可执行体在包内) */
34
- export function resolveBunCommand(probe: (cmd: string) => boolean = defaultProbe): string | null {
35
- for (const c of bunCandidates()) {
36
- if (probe(c)) return c
37
- }
38
- return null
39
- }
40
-
41
- function defaultProbe(cmd: string): boolean {
42
- try {
43
- const r = spawnSync(cmd, ["--version"], { stdio: "ignore" })
44
- return r.status === 0
45
- } catch {
46
- return false
47
- }
48
- }
49
-
50
- export interface LaunchPlan {
51
- command: string
52
- args: string[]
53
- /** 子进程环境:继承当前环境 + try 模式单实例锁 */
54
- env: NodeJS.ProcessEnv
55
- }
56
-
57
- /**
58
- * 解析 bot 入口文件(按安装形态探测,纯函数供测试):
59
- * 1. 插件同目录 bot.js(plugins 目录自包含安装形态——官方规范的一键安装)
60
- * 2. 包根 dist/openqq-bot.js(npm 包形态,prepublish 预打)
61
- * 3. 包根 src/index.ts(dev 形态,需 bun 直跑 TS)
62
- * 全缺 → null(调用方给指引)
63
- */
64
- export function resolveBotEntry(
65
- pluginFilePath: string,
66
- exists: (p: string) => boolean = existsSync,
67
- ): string | null {
68
- const dir = dirname(pluginFilePath)
69
- const candidates = [
70
- join(dir, "bot.js"), // 旧双 bundle 形态(兼容已装实例)
71
- join(dir, "dist", "openqq-bot.js"), // 形态 1:全量包安装(插件目录=完整 npm 包)
72
- join(homedir(), ".openqq", "plugin-payload", "bot.js"), // 单文件形态的有效载荷位
73
- join(dir, "..", "dist", "openqq-bot.js"), // 形态 2:npm 包(plugin-entry 在 src/ 下)
74
- join(dir, "..", "src", "index.ts"), // 形态 3:dev 源码
75
- ]
76
- for (const c of candidates) if (exists(c)) return c
77
- return null
78
- }
79
-
80
- /** 构造拉起计划(纯函数供测试)。entry 由 resolveBotEntry 解析。 */
81
- export function buildLaunchPlan(runtime: Runtime, entry: string, logPath?: string): LaunchPlan {
82
- // QQ_INSTANCE_LOCK=try:拉起即抢锁,抢不到自动退出(多 location 并发拉起防堆积)
83
- // QQ_LOG_FILE:bot 进程内文件日志双写(detached 后无控制台,fd 重定向不可靠)
84
- const env = {
85
- ...process.env,
86
- QQ_INSTANCE_LOCK: "try",
87
- ...(logPath ? { QQ_LOG_FILE: logPath } : {}),
88
- }
89
- if (runtime === "bun") {
90
- const bunCmd = resolveBunCommand() ?? "bun"
91
- return { command: bunCmd, args: ["run", entry], env }
92
- }
93
- return { command: "node", args: [entry], env }
94
- }
95
-
96
- /** bot 输出日志(detached 后 stdout/stderr 的唯一去向) */
97
- export function botLogPath(): string {
98
- return join(homedir(), ".openqq", "bot.out.log")
99
- }
100
-
101
- /**
102
- * detached 拉起 bot(跨平台同 API;Windows 隐藏控制台窗口)。
103
- * 日志由 bot 进程内文件双写承担(QQ_LOG_FILE,见 buildLaunchPlan)——
104
- * spawn 侧 fd 重定向在 bun 下实测不落盘(2026-10-30 清债 P2),不再依赖。
105
- * 返回 pid;拉起失败抛错(调用方记日志)。
106
- */
107
- export function spawnBotDetached(plan: LaunchPlan): number {
108
- const child = spawn(plan.command, plan.args, {
109
- detached: true,
110
- stdio: "ignore",
111
- env: plan.env,
112
- windowsHide: true,
113
- })
114
- child.unref() // 父进程(serve)退出不带走 bot
115
- if (typeof child.pid !== "number") throw new Error("spawn 未返回 pid")
116
- return child.pid
117
- }
118
-
119
- /** 极简 .env 字段读取(插件侧用,不经 config 模块——避免其 process.env 副作用与 throw) */
120
- export function readDotEnvField(envPath: string, key: string): string | null {
121
- try {
122
- if (!existsSync(envPath)) return null
123
- for (const line of readFileSync(envPath, "utf-8").split("\n")) {
124
- const trimmed = line.trim()
125
- if (!trimmed || trimmed.startsWith("#")) continue
126
- const eq = trimmed.indexOf("=")
127
- if (eq < 0) continue
128
- if (trimmed.slice(0, eq).trim() === key) return trimmed.slice(eq + 1).trim()
129
- }
130
- return null
131
- } catch {
132
- return null
133
- }
134
- }
1
+ // @input: fs/child_process/os(运行时探测、detached 拉起)
2
+ // @output: resolveRuntime, buildLaunchPlan, spawnBotDetached, readDotEnvField
3
+ // @pos: core - bot 进程拉起器(D 路径:插件引导器的服务端;跨平台 Windows/Linux/macOS)
4
+ //
5
+ // 设计:插件(opencode serve 内)检测 bot 不存活时,以 detached 子进程拉起——
6
+ // 子进程脱离 serve 生命周期(serve 重载/重启不碰 bot)。运行时解析 bun→node:
7
+ // bun 直接跑源码(.js→.ts 映射);node 跑发布时预打的 dist/openqq-bot.js bundle。
8
+ import { spawn, spawnSync } from "child_process"
9
+ import { existsSync, readFileSync } from "fs"
10
+ import { join, dirname } from "path"
11
+ import { homedir } from "os"
12
+
13
+ export type Runtime = "bun" | "node"
14
+
15
+ /** 探测命令可用性(跨平台:spawnSync ENOENT=不存在) */
16
+ export function resolveRuntime(probe: (cmd: string) => boolean = defaultProbe): Runtime | null {
17
+ if (resolveBunCommand(probe)) return "bun"
18
+ if (probe("node")) return "node"
19
+ return null
20
+ }
21
+
22
+ function bunCandidates(): string[] {
23
+ const candidates = ["bun", "bun.exe", "bun.cmd", "bun.bat"]
24
+ if (process.platform === "win32") {
25
+ const appdata = process.env.APPDATA || join(homedir(), "AppData", "Roaming")
26
+ candidates.push(join(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"))
27
+ } else {
28
+ candidates.push("/usr/local/bin/bun", "/opt/homebrew/bin/bun", join(homedir(), ".bun", "bin", "bun"))
29
+ }
30
+ return candidates
31
+ }
32
+
33
+ /** 解析可用 bun 命令(覆盖 npm 安装形态:PATH 上只有 bun.ps1,可执行体在包内) */
34
+ export function resolveBunCommand(probe: (cmd: string) => boolean = defaultProbe): string | null {
35
+ for (const c of bunCandidates()) {
36
+ if (probe(c)) return c
37
+ }
38
+ return null
39
+ }
40
+
41
+ function defaultProbe(cmd: string): boolean {
42
+ try {
43
+ const r = spawnSync(cmd, ["--version"], { stdio: "ignore" })
44
+ return r.status === 0
45
+ } catch {
46
+ return false
47
+ }
48
+ }
49
+
50
+ export interface LaunchPlan {
51
+ command: string
52
+ args: string[]
53
+ /** 子进程环境:继承当前环境 + try 模式单实例锁 */
54
+ env: NodeJS.ProcessEnv
55
+ }
56
+
57
+ /**
58
+ * 解析 bot 入口文件(按安装形态探测,纯函数供测试):
59
+ * 1. 插件同目录 bot.js(plugins 目录自包含安装形态——官方规范的一键安装)
60
+ * 2. 包根 dist/openqq-bot.js(npm 包形态,prepublish 预打)
61
+ * 3. 包根 src/index.ts(dev 形态,需 bun 直跑 TS)
62
+ * 全缺 → null(调用方给指引)
63
+ */
64
+ export function resolveBotEntry(
65
+ pluginFilePath: string,
66
+ exists: (p: string) => boolean = existsSync,
67
+ ): string | null {
68
+ const dir = dirname(pluginFilePath)
69
+ const candidates = [
70
+ join(dir, "bot.js"), // 旧双 bundle 形态(兼容已装实例)
71
+ join(dir, "dist", "openqq-bot.js"), // 形态 1:全量包安装(插件目录=完整 npm 包)
72
+ join(homedir(), ".openqq", "plugin-payload", "bot.js"), // 单文件形态的有效载荷位
73
+ join(dir, "..", "dist", "openqq-bot.js"), // 形态 2:npm 包(plugin-entry 在 src/ 下)
74
+ join(dir, "..", "src", "index.ts"), // 形态 3:dev 源码
75
+ ]
76
+ for (const c of candidates) if (exists(c)) return c
77
+ return null
78
+ }
79
+
80
+ /** 构造拉起计划(纯函数供测试)。entry 由 resolveBotEntry 解析。 */
81
+ export function buildLaunchPlan(runtime: Runtime, entry: string, logPath?: string): LaunchPlan {
82
+ // T 项(2026-11-02 沙箱时序深度自检):插件拉起通道剥离我方配置命名空间——
83
+ // 继承的宿主(serve)环境可能残留 QQ_*/OPENCODE_*(沙箱开关尤甚),而 bot 侧
84
+ // .env 加载规则是"继承环境优先于文件",不剥离会让宿主环境静默覆盖单点配置
85
+ // (反向时序坑:宿主设了沙箱,.env 改回正式反而不生效)。独立部署形态
86
+ // (用户显式跑 openqq)不受影响——那边环境覆盖是合理诉求。
87
+ const CONFIG_KEY = [/^QQ_/, /^OPENCODE_/, /^ALLOWED_USERS$/, /^MAX_REPLY_LENGTH$/]
88
+ const inherited: NodeJS.ProcessEnv = {}
89
+ for (const [k, v] of Object.entries(process.env)) {
90
+ if (v === undefined) continue
91
+ if (CONFIG_KEY.some((r) => r.test(k))) continue
92
+ inherited[k] = v
93
+ }
94
+ // QQ_INSTANCE_LOCK=try:拉起即抢锁,抢不到自动退出(多 location 并发拉起防堆积)
95
+ // QQ_LOG_FILE:bot 进程内文件日志双写(detached 后无控制台,fd 重定向不可靠)
96
+ const env = {
97
+ ...inherited,
98
+ QQ_INSTANCE_LOCK: "try",
99
+ ...(logPath ? { QQ_LOG_FILE: logPath } : {}),
100
+ }
101
+ if (runtime === "bun") {
102
+ const bunCmd = resolveBunCommand() ?? "bun"
103
+ return { command: bunCmd, args: ["run", entry], env }
104
+ }
105
+ return { command: "node", args: [entry], env }
106
+ }
107
+
108
+ /** bot 输出日志(detached 后 stdout/stderr 的唯一去向) */
109
+ export function botLogPath(): string {
110
+ return join(homedir(), ".openqq", "bot.out.log")
111
+ }
112
+
113
+ /**
114
+ * detached 拉起 bot(跨平台同 API;Windows 隐藏控制台窗口)。
115
+ * 日志由 bot 进程内文件双写承担(QQ_LOG_FILE,见 buildLaunchPlan)——
116
+ * spawn 侧 fd 重定向在 bun 下实测不落盘(2026-10-30 清债 P2),不再依赖。
117
+ * 返回 pid;拉起失败抛错(调用方记日志)。
118
+ */
119
+ export function spawnBotDetached(plan: LaunchPlan): number {
120
+ const child = spawn(plan.command, plan.args, {
121
+ detached: true,
122
+ stdio: "ignore",
123
+ env: plan.env,
124
+ windowsHide: true,
125
+ })
126
+ child.unref() // 父进程(serve)退出不带走 bot
127
+ if (typeof child.pid !== "number") throw new Error("spawn 未返回 pid")
128
+ return child.pid
129
+ }
130
+
131
+ /** 极简 .env 字段读取(插件侧用,不经 config 模块——避免其 process.env 副作用与 throw) */
132
+ export function readDotEnvField(envPath: string, key: string): string | null {
133
+ try {
134
+ if (!existsSync(envPath)) return null
135
+ for (const line of readFileSync(envPath, "utf-8").split("\n")) {
136
+ const trimmed = line.trim()
137
+ if (!trimmed || trimmed.startsWith("#")) continue
138
+ const eq = trimmed.indexOf("=")
139
+ if (eq < 0) continue
140
+ if (trimmed.slice(0, eq).trim() === key) return trimmed.slice(eq + 1).trim()
141
+ }
142
+ return null
143
+ } catch {
144
+ return null
145
+ }
146
+ }