@linjz/opencode-qqbot 0.3.2 → 0.3.4

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 CHANGED
@@ -37,10 +37,22 @@
37
37
  ### 安装
38
38
 
39
39
  ```bash
40
- # 方式一:从 GitHub 直装(不依赖 npm registry,推荐)
40
+ # 方式零:opencode 插件形态(最省事)——在 opencode.json(c) 的 plugins 数组加入:
41
+ # "@linjz/opencode-qqbot"
42
+ # 或本机直装(全量包安装,用户拍板形态 2026-11-02):
43
+ # bun run deploy:plugin
44
+ # → ~/.config/opencode/plugins/opencode-qqbot/ = npm 发布包的完整解包
45
+ # (package.json+bin/+src/+dist/+README+LICENSE+tsconfig,另含根 index.js shim)
46
+ # 整个安装物就是一个插件目录;独立服务由插件从包内 dist/openqq-bot.js 拉起,
47
+ # 全部文件自足,不引用任何外部路径。
48
+ # 注意:2.2.1 全局插件目录扫描器只认根级 exports 目标(子路径如 ./dist/x.js 会跳过,
49
+ # deploy 已做 loader 友好化处理);要求 PATH 里有 bun 或 node;
50
+ # bot 的开机自启依赖 serve 服务自启。
51
+
52
+ # 方式一:从 GitHub 直装(不依赖 npm registry,推荐独立部署)
41
53
  npm i -g github:linjz3376/opencode-qqbot
42
54
 
43
- # 方式二:npm registry(发布后可用)
55
+ # 方式二:npm registry
44
56
  npm install -g @linjz/opencode-qqbot
45
57
 
46
58
  # 方式三:源码
@@ -50,7 +62,13 @@ cd opencode-qqbot && bun install
50
62
 
51
63
  ### 配置(`~/.openqq/.env`,单点密钥)
52
64
 
53
- 首次运行缺凭据会交互式引导写入;也可手工创建:
65
+ 首次运行缺凭据会交互式引导写入;也可用手机 QQ 扫码绑定(需先 `npm i -g @tencent-connect/qqbot-connector`):
66
+
67
+ ```bash
68
+ openqq-setup # 终端弹二维码,扫码后凭据自动写入 ~/.openqq/.env
69
+ ```
70
+
71
+ 或手工创建:
54
72
 
55
73
  ```ini
56
74
  QQ_APP_ID=你的AppID
@@ -71,6 +89,8 @@ openqq # npm 全局安装后
71
89
 
72
90
  Windows 常驻:`deploy/` 目录内有任务计划(开机自启、看门狗心跳守护)脚本与说明。
73
91
 
92
+ > **单实例**:bot 启动时持文件锁(`~/.openqq/openqq-<appId>.lock`,10s 心跳、30s 僵尸判定)——双开时后到实例待命,宿主退出后自动接管,避免同 bot 多实例被 QQ 网关互踢。`QQ_INSTANCE_LOCK=false` 可关闭。
93
+
74
94
  > **跨平台**:bot 本体零 OS 分支(纯 TS/Bun + HTTP/WS,与 QQ 官方 SDK 同形态)。Linux/macOS 常驻用 `systemd --user` 或 `nohup bun run src/index.ts &` 即可;端口自动发现在三个系统都可用(Linux 走 `ss -tln`,macOS 走 `netstat -an -p tcp`,Windows 走 `netstat -ano -p tcp`)。
75
95
 
76
96
  ## 指令一览
@@ -98,6 +118,8 @@ Windows 常驻:`deploy/` 目录内有任务计划(开机自启、看门狗
98
118
  | `QQ_STREAM_STAGGER_MS` | 300 | 多片回复片间错峰(0=一次性全发) |
99
119
  | `QQ_SESSION_IDLE_HOURS` | 6 | 闲置会话回收阈值 |
100
120
  | `QQ_INTERACTION_WATCH_SECONDS` | 12 | 常驻交互监听轮询间隔(0=关闭) |
121
+ | `QQ_REDISPATCH_MAX_AGE_MS` | 7200000 | 启动对账时丢失消息的自动重派窗口(0=关闭自动重派只通知;受台账 24h 清账线封顶) |
122
+ | `QQ_EVENT_PROBE` | 关 | 插件侧事件探针(`true` 时全量事件类型落 `~/.openqq/opencode-events.jsonl`,诊断用) |
101
123
  | `OPENCODE_TURN_TIMEOUT_MINUTES` | 30 | 前台回合时限(超时转后台等待) |
102
124
  | `QQ_DIGEST_ANSWER_MAX_CHARS` | 0(全文) | 摘要卡答案截断上限 |
103
125
  | `QQ_HISTORY_USER_CLIP` / `QQ_HISTORY_TEXT_CLIP` | 500 / 1200 | /history 用户/AI 行截断 |
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ // F 项(2026-10-30,吸收竞品 opencode-qq bin/setup.mjs 的零依赖思路):
3
+ // 扫码绑定引导——动态 import 官方 @tencent-connect/qqbot-connector(不进
4
+ // dependencies,守红线:官方包只做参考/用户自选安装),手机 QQ 扫码拿到
5
+ // appId/appSecret 后合并写入 ~/.openqq/.env(保留其余既有配置行)。
6
+ import fs from "node:fs"
7
+ import path from "node:path"
8
+ import os from "node:os"
9
+
10
+ const CONFIG_DIR = path.join(os.homedir(), ".openqq")
11
+ const ENV_FILE = path.join(CONFIG_DIR, ".env")
12
+
13
+ let connector
14
+ try {
15
+ connector = await import("@tencent-connect/qqbot-connector")
16
+ } catch {
17
+ console.error("缺少依赖 @tencent-connect/qqbot-connector")
18
+ console.error("请先执行: npm install -g @tencent-connect/qqbot-connector")
19
+ process.exit(1)
20
+ }
21
+
22
+ console.log("请使用手机 QQ 扫描终端二维码完成绑定…")
23
+ const credsList = await connector.qrConnect({ source: "opencode-qqbot" })
24
+ const creds = credsList?.[0]
25
+ if (!creds?.appId || !creds?.appSecret) {
26
+ console.error("扫码未返回凭据")
27
+ process.exit(1)
28
+ }
29
+
30
+ // 合并写入 .env:替换已有 QQ_APP_ID/QQ_APP_SECRET 行,其余行原样保留
31
+ let lines = []
32
+ try {
33
+ lines = fs.readFileSync(ENV_FILE, "utf8").split("\n")
34
+ } catch {
35
+ /* 首次运行无文件 */
36
+ }
37
+ const seen = new Set()
38
+ const merged = lines.map((line) => {
39
+ const m = /^\s*(QQ_APP_ID|QQ_APP_SECRET)\s*=/.exec(line)
40
+ if (!m) return line
41
+ seen.add(m[1])
42
+ return m[1] === "QQ_APP_ID" ? `QQ_APP_ID=${creds.appId}` : `QQ_APP_SECRET=${creds.appSecret}`
43
+ })
44
+ if (!seen.has("QQ_APP_ID")) merged.push(`QQ_APP_ID=${creds.appId}`)
45
+ if (!seen.has("QQ_APP_SECRET")) merged.push(`QQ_APP_SECRET=${creds.appSecret}`)
46
+
47
+ fs.mkdirSync(CONFIG_DIR, { recursive: true })
48
+ fs.writeFileSync(ENV_FILE, merged.join("\n"))
49
+ console.log(`凭据已写入 ${ENV_FILE}`)
50
+ console.log("现在可以运行 openqq 启动 bot 了。")
package/bin/openqq.js CHANGED
@@ -1,2 +1,47 @@
1
- #!/usr/bin/env bun
2
- import "../src/index.ts"
1
+ #!/usr/bin/env node
2
+ // openqq 入口(2026-11-02 应用者体验补齐):运行时自适应——
3
+ // 有 bun → bun run src/index.ts(源码语义,dev 友好)
4
+ // 无 bun → node dist/openqq-bot.js(发布 bundle,零额外依赖)
5
+ // 应用者 npm i -g 后只有 node 也能跑;开发者有 bun 时始终跑源码。
6
+ // 注意:本文件必须保持纯 JS(无类型标注)——node 用户直接执行它。
7
+ import { spawnSync } from "node:child_process"
8
+ import { existsSync } from "node:fs"
9
+ import { fileURLToPath } from "node:url"
10
+ import { join, dirname } from "node:path"
11
+
12
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..")
13
+
14
+ // bun 探测要覆盖全形态:npm 装的 bun 在 PATH 上只有 bun.ps1(CreateProcess 起不来),
15
+ // 真正可执行体在 npm\bun 包内 bin\bun.exe;官方安装则直接是 bun/bun.exe。
16
+ function detectBun() {
17
+ const candidates = ["bun", "bun.exe", "bun.cmd", "bun.bat"]
18
+ if (process.platform === "win32") {
19
+ const appdata = process.env.APPDATA || join(process.env.USERPROFILE || "", "AppData", "Roaming")
20
+ candidates.push(join(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"))
21
+ } else {
22
+ candidates.push("/usr/local/bin/bun", "/opt/homebrew/bin/bun", join(process.env.HOME || "", ".bun", "bin", "bun"))
23
+ }
24
+ for (const c of candidates) {
25
+ try {
26
+ const r = spawnSync(c, ["--version"], { stdio: "ignore" })
27
+ if (r.status === 0) return c
28
+ } catch {
29
+ /* 下一个 */
30
+ }
31
+ }
32
+ return null
33
+ }
34
+ const bunCmd = detectBun()
35
+
36
+ const entry = bunCmd && existsSync(join(root, "src", "index.ts"))
37
+ ? join(root, "src", "index.ts")
38
+ : join(root, "dist", "openqq-bot.js")
39
+ const cmd = bunCmd && entry.endsWith(".ts") ? bunCmd : "node"
40
+ const args = entry.endsWith(".ts") ? ["run", entry] : [entry]
41
+
42
+ if (!existsSync(entry)) {
43
+ console.error(`[openqq] 入口不存在:${entry}(包安装不完整,请重装 @linjz/opencode-qqbot)`)
44
+ process.exit(1)
45
+ }
46
+ const r = spawnSync(cmd, args, { stdio: "inherit" })
47
+ process.exit(r.status ?? 1)
@@ -0,0 +1,204 @@
1
+ // @bun
2
+ // src/plugin-entry.ts
3
+ import { Plugin } from "@opencode/plugin";
4
+ import { join as join3 } from "path";
5
+ import { homedir as homedir3 } from "os";
6
+ import { appendFileSync, existsSync as existsSync2, renameSync, statSync as statSync2 } from "fs";
7
+ import { fileURLToPath } from "url";
8
+
9
+ // src/core/instance-lock.ts
10
+ import { openSync, writeFileSync, closeSync, unlinkSync, statSync, utimesSync, mkdirSync } from "fs";
11
+ import { join } from "path";
12
+ import { homedir } from "os";
13
+ var LOCK_STALE_MS = 30000;
14
+ function lockPathOf(appId) {
15
+ return join(homedir(), ".openqq", `openqq-${appId}.lock`);
16
+ }
17
+ function isInstanceAlive(appId, staleMs = LOCK_STALE_MS) {
18
+ return isInstanceAliveAt(lockPathOf(appId), staleMs);
19
+ }
20
+ function isInstanceAliveAt(path, staleMs = LOCK_STALE_MS) {
21
+ try {
22
+ return Date.now() - statSync(path).mtimeMs <= staleMs;
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
28
+ // src/core/bot-launcher.ts
29
+ import { spawn, spawnSync } from "child_process";
30
+ import { existsSync, readFileSync } from "fs";
31
+ import { join as join2, dirname } from "path";
32
+ import { homedir as homedir2 } from "os";
33
+ function resolveRuntime(probe = defaultProbe) {
34
+ if (resolveBunCommand(probe))
35
+ return "bun";
36
+ if (probe("node"))
37
+ return "node";
38
+ return null;
39
+ }
40
+ function bunCandidates() {
41
+ const candidates = ["bun", "bun.exe", "bun.cmd", "bun.bat"];
42
+ if (process.platform === "win32") {
43
+ const appdata = process.env.APPDATA || join2(homedir2(), "AppData", "Roaming");
44
+ candidates.push(join2(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"));
45
+ } else {
46
+ candidates.push("/usr/local/bin/bun", "/opt/homebrew/bin/bun", join2(homedir2(), ".bun", "bin", "bun"));
47
+ }
48
+ return candidates;
49
+ }
50
+ function resolveBunCommand(probe = defaultProbe) {
51
+ for (const c of bunCandidates()) {
52
+ if (probe(c))
53
+ return c;
54
+ }
55
+ return null;
56
+ }
57
+ function defaultProbe(cmd) {
58
+ try {
59
+ const r = spawnSync(cmd, ["--version"], { stdio: "ignore" });
60
+ return r.status === 0;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+ function resolveBotEntry(pluginFilePath, exists = existsSync) {
66
+ const dir = dirname(pluginFilePath);
67
+ const candidates = [
68
+ join2(dir, "bot.js"),
69
+ join2(dir, "dist", "openqq-bot.js"),
70
+ join2(homedir2(), ".openqq", "plugin-payload", "bot.js"),
71
+ join2(dir, "..", "dist", "openqq-bot.js"),
72
+ join2(dir, "..", "src", "index.ts")
73
+ ];
74
+ for (const c of candidates)
75
+ if (exists(c))
76
+ return c;
77
+ return null;
78
+ }
79
+ function buildLaunchPlan(runtime, entry, logPath) {
80
+ const env = {
81
+ ...process.env,
82
+ QQ_INSTANCE_LOCK: "try",
83
+ ...logPath ? { QQ_LOG_FILE: logPath } : {}
84
+ };
85
+ if (runtime === "bun") {
86
+ const bunCmd = resolveBunCommand() ?? "bun";
87
+ return { command: bunCmd, args: ["run", entry], env };
88
+ }
89
+ return { command: "node", args: [entry], env };
90
+ }
91
+ function botLogPath() {
92
+ return join2(homedir2(), ".openqq", "bot.out.log");
93
+ }
94
+ function spawnBotDetached(plan) {
95
+ const child = spawn(plan.command, plan.args, {
96
+ detached: true,
97
+ stdio: "ignore",
98
+ env: plan.env,
99
+ windowsHide: true
100
+ });
101
+ child.unref();
102
+ if (typeof child.pid !== "number")
103
+ throw new Error("spawn \u672A\u8FD4\u56DE pid");
104
+ return child.pid;
105
+ }
106
+ function readDotEnvField(envPath, key) {
107
+ try {
108
+ if (!existsSync(envPath))
109
+ return null;
110
+ for (const line of readFileSync(envPath, "utf-8").split(`
111
+ `)) {
112
+ const trimmed = line.trim();
113
+ if (!trimmed || trimmed.startsWith("#"))
114
+ continue;
115
+ const eq = trimmed.indexOf("=");
116
+ if (eq < 0)
117
+ continue;
118
+ if (trimmed.slice(0, eq).trim() === key)
119
+ return trimmed.slice(eq + 1).trim();
120
+ }
121
+ return null;
122
+ } catch {
123
+ return null;
124
+ }
125
+ }
126
+
127
+ // src/plugin-entry.ts
128
+ var ENV_FILE = join3(homedir3(), ".openqq", ".env");
129
+ var CHECK_INTERVAL_MS = 5 * 60 * 1000;
130
+ var PROBE_FILE = join3(homedir3(), ".openqq", "opencode-events.jsonl");
131
+ var PROBE_ROTATE_BYTES = 5 * 1024 * 1024;
132
+ function probeAppend(line) {
133
+ try {
134
+ if (existsSync2(PROBE_FILE) && statSync2(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
135
+ renameSync(PROBE_FILE, PROBE_FILE + ".1");
136
+ }
137
+ appendFileSync(PROBE_FILE, line + `
138
+ `);
139
+ } catch {}
140
+ }
141
+ var plugin_entry_default = Plugin.define({
142
+ id: "opencode-qqbot",
143
+ setup(_ctx) {
144
+ let lastBlocker = null;
145
+ const warnOnce = (key, message) => {
146
+ if (lastBlocker === key)
147
+ return;
148
+ lastBlocker = key;
149
+ console.warn(message);
150
+ };
151
+ const ensure = () => {
152
+ try {
153
+ const appId = readDotEnvField(ENV_FILE, "QQ_APP_ID");
154
+ if (!appId) {
155
+ warnOnce("cred", "[opencode-qqbot] \u672A\u53D1\u73B0 ~/.openqq/.env \u51ED\u636E\u2014\u2014\u5148\u8FD0\u884C npx @linjz/opencode-qqbot setup \u626B\u7801\u7ED1\u5B9A\uFF08\u6216\u53C2\u8003 README \u624B\u5199 .env\uFF09\uFF0C\u5B8C\u6210\u540E\u63D2\u4EF6\u5C06\u5728\u4E0B\u6B21\u5DE1\u68C0\u81EA\u52A8\u62C9\u8D77 bot");
156
+ return;
157
+ }
158
+ if (isInstanceAlive(appId)) {
159
+ lastBlocker = null;
160
+ return;
161
+ }
162
+ const entry = resolveBotEntry(fileURLToPath(import.meta.url));
163
+ if (!entry) {
164
+ warnOnce("entry", "[opencode-qqbot] \u672A\u627E\u5230 bot \u5165\u53E3\uFF08bot.js / dist/openqq-bot.js / src/index.ts \u5168\u7F3A\uFF09\u2014\u2014\u63D2\u4EF6\u5B89\u88C5\u4E0D\u5B8C\u6574");
165
+ return;
166
+ }
167
+ const runtime = resolveRuntime();
168
+ if (!runtime) {
169
+ warnOnce("runtime", "[opencode-qqbot] \u672A\u627E\u5230 bun/node \u8FD0\u884C\u65F6\uFF0C\u65E0\u6CD5\u62C9\u8D77 bot\u2014\u2014\u8BF7\u5B89\u88C5\u5176\u4E2D\u4E4B\u4E00\uFF08https://bun.sh\uFF09");
170
+ return;
171
+ }
172
+ const pid = spawnBotDetached(buildLaunchPlan(runtime, entry, botLogPath()));
173
+ console.log(`[opencode-qqbot] bot \u5DF2\u62C9\u8D77\uFF08pid=${pid}\uFF0Cruntime=${runtime}\uFF0Centry=${entry}\uFF09`);
174
+ lastBlocker = null;
175
+ } catch (error) {
176
+ console.error("[opencode-qqbot] \u62C9\u8D77\u5931\u8D25:", error instanceof Error ? error.message : error);
177
+ }
178
+ };
179
+ ensure();
180
+ const timer = setInterval(ensure, CHECK_INTERVAL_MS);
181
+ let probeAbort = null;
182
+ if (readDotEnvField(ENV_FILE, "QQ_EVENT_PROBE") === "true") {
183
+ probeAbort = new AbortController;
184
+ const signal = probeAbort.signal;
185
+ (async () => {
186
+ probeAppend(JSON.stringify({ ts: new Date().toISOString(), type: "probe.started", sessionID: null }));
187
+ try {
188
+ for await (const event of _ctx.event.subscribe({ signal })) {
189
+ const ev = event;
190
+ probeAppend(JSON.stringify({ ts: new Date().toISOString(), type: ev.type, sessionID: ev.data?.sessionID ?? null }));
191
+ }
192
+ } catch {}
193
+ })();
194
+ console.log("[opencode-qqbot] \u4E8B\u4EF6\u63A2\u9488\u5DF2\u5F00\u542F\uFF08QQ_EVENT_PROBE=true\uFF09");
195
+ }
196
+ return () => {
197
+ clearInterval(timer);
198
+ probeAbort?.abort();
199
+ };
200
+ }
201
+ });
202
+ export {
203
+ plugin_entry_default as default
204
+ };