@linjz/opencode-qqbot 0.3.3 → 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
@@ -39,12 +39,15 @@
39
39
  ```bash
40
40
  # 方式零:opencode 插件形态(最省事)——在 opencode.json(c) 的 plugins 数组加入:
41
41
  # "@linjz/opencode-qqbot"
42
- # 或本机直装(自包含目录,官方插件规范):
43
- # bun run deploy:plugin → ~/.config/opencode/plugins/opencode-qqbot/(index.js+bot.js+package.json)
44
- # serve 服务自动加载;插件每 5 分钟巡检 bot 存活,不在就以独立进程拉起(bot 不受
45
- # serve 重载/重启影响,拉起的是插件同目录的 bot.js,不依赖任何外部路径)。
46
- # 凭据缺失时插件只在 opencode 日志里提示,不会乱拉。
47
- # 注意:此形态要求 PATH 里有 bun 或 node;bot 的开机自启依赖 serve 服务自启。
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 服务自启。
48
51
 
49
52
  # 方式一:从 GitHub 直装(不依赖 npm registry,推荐独立部署)
50
53
  npm i -g github:linjz3376/opencode-qqbot
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)
@@ -27,16 +27,33 @@ function isInstanceAliveAt(path, staleMs = LOCK_STALE_MS) {
27
27
 
28
28
  // src/core/bot-launcher.ts
29
29
  import { spawn, spawnSync } from "child_process";
30
- import { existsSync, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync } from "fs";
30
+ import { existsSync, readFileSync } from "fs";
31
31
  import { join as join2, dirname } from "path";
32
32
  import { homedir as homedir2 } from "os";
33
33
  function resolveRuntime(probe = defaultProbe) {
34
- if (probe("bun"))
34
+ if (resolveBunCommand(probe))
35
35
  return "bun";
36
36
  if (probe("node"))
37
37
  return "node";
38
38
  return null;
39
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
+ }
40
57
  function defaultProbe(cmd) {
41
58
  try {
42
59
  const r = spawnSync(cmd, ["--version"], { stdio: "ignore" });
@@ -49,6 +66,7 @@ function resolveBotEntry(pluginFilePath, exists = existsSync) {
49
66
  const dir = dirname(pluginFilePath);
50
67
  const candidates = [
51
68
  join2(dir, "bot.js"),
69
+ join2(dir, "dist", "openqq-bot.js"),
52
70
  join2(homedir2(), ".openqq", "plugin-payload", "bot.js"),
53
71
  join2(dir, "..", "dist", "openqq-bot.js"),
54
72
  join2(dir, "..", "src", "index.ts")
@@ -58,21 +76,25 @@ function resolveBotEntry(pluginFilePath, exists = existsSync) {
58
76
  return c;
59
77
  return null;
60
78
  }
61
- function buildLaunchPlan(runtime, entry) {
62
- const env = { ...process.env, QQ_INSTANCE_LOCK: "try" };
63
- if (runtime === "bun")
64
- return { command: "bun", args: ["run", entry], env };
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
+ }
65
89
  return { command: "node", args: [entry], env };
66
90
  }
67
91
  function botLogPath() {
68
92
  return join2(homedir2(), ".openqq", "bot.out.log");
69
93
  }
70
- function spawnBotDetached(plan, logPath = botLogPath()) {
71
- mkdirSync2(join2(logPath, ".."), { recursive: true });
72
- const out = openSync2(logPath, "a");
94
+ function spawnBotDetached(plan) {
73
95
  const child = spawn(plan.command, plan.args, {
74
96
  detached: true,
75
- stdio: ["ignore", out, out],
97
+ stdio: "ignore",
76
98
  env: plan.env,
77
99
  windowsHide: true
78
100
  });
@@ -119,27 +141,37 @@ function probeAppend(line) {
119
141
  var plugin_entry_default = Plugin.define({
120
142
  id: "opencode-qqbot",
121
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
+ };
122
151
  const ensure = () => {
123
152
  try {
124
153
  const appId = readDotEnvField(ENV_FILE, "QQ_APP_ID");
125
154
  if (!appId) {
126
- console.warn("[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");
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");
127
156
  return;
128
157
  }
129
- if (isInstanceAlive(appId))
158
+ if (isInstanceAlive(appId)) {
159
+ lastBlocker = null;
130
160
  return;
161
+ }
131
162
  const entry = resolveBotEntry(fileURLToPath(import.meta.url));
132
163
  if (!entry) {
133
- console.warn("[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");
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");
134
165
  return;
135
166
  }
136
167
  const runtime = resolveRuntime();
137
168
  if (!runtime) {
138
- console.warn("[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");
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");
139
170
  return;
140
171
  }
141
- const pid = spawnBotDetached(buildLaunchPlan(runtime, entry));
172
+ const pid = spawnBotDetached(buildLaunchPlan(runtime, entry, botLogPath()));
142
173
  console.log(`[opencode-qqbot] bot \u5DF2\u62C9\u8D77\uFF08pid=${pid}\uFF0Cruntime=${runtime}\uFF0Centry=${entry}\uFF09`);
174
+ lastBlocker = null;
143
175
  } catch (error) {
144
176
  console.error("[opencode-qqbot] \u62C9\u8D77\u5931\u8D25:", error instanceof Error ? error.message : error);
145
177
  }
@@ -32,6 +32,17 @@ var __toESM = (mod, isNodeMode, target) => {
32
32
  return to;
33
33
  };
34
34
  var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
35
+ var __esm = (fn, res, err) => () => {
36
+ if (fn)
37
+ try {
38
+ res = fn(fn = 0);
39
+ } catch (e) {
40
+ err = [e];
41
+ }
42
+ if (err)
43
+ throw err[0];
44
+ return res;
45
+ };
35
46
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
36
47
 
37
48
  // node_modules/ws/lib/constants.js
@@ -2927,6 +2938,51 @@ var require_websocket_server = __commonJS(function(exports, module) {
2927
2938
  }
2928
2939
  });
2929
2940
 
2941
+ // src/core/file-log.ts
2942
+ import { appendFileSync, existsSync as existsSync9, mkdirSync as mkdirSync9, renameSync as renameSync2, statSync as statSync4 } from "fs";
2943
+ import { join as join12 } from "path";
2944
+ function installFileLog(logPath) {
2945
+ try {
2946
+ mkdirSync9(join12(logPath, ".."), { recursive: true });
2947
+ } catch {}
2948
+ const write = (level, args) => {
2949
+ try {
2950
+ if (existsSync9(logPath) && statSync4(logPath).size > ROTATE_BYTES) {
2951
+ renameSync2(logPath, `${logPath}.1`);
2952
+ }
2953
+ const line = args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ");
2954
+ appendFileSync(logPath, `${new Date().toISOString()} [${level}] ${line}
2955
+ `);
2956
+ } catch {}
2957
+ };
2958
+ const orig = {
2959
+ log: console.log.bind(console),
2960
+ warn: console.warn.bind(console),
2961
+ error: console.error.bind(console)
2962
+ };
2963
+ console.log = (...args) => {
2964
+ orig.log(...args);
2965
+ write("log", args);
2966
+ };
2967
+ console.warn = (...args) => {
2968
+ orig.warn(...args);
2969
+ write("warn", args);
2970
+ };
2971
+ console.error = (...args) => {
2972
+ orig.error(...args);
2973
+ write("error", args);
2974
+ };
2975
+ return () => {
2976
+ console.log = orig.log;
2977
+ console.warn = orig.warn;
2978
+ console.error = orig.error;
2979
+ };
2980
+ }
2981
+ var ROTATE_BYTES;
2982
+ var init_file_log = __esm(() => {
2983
+ ROTATE_BYTES = 5 * 1024 * 1024;
2984
+ });
2985
+
2930
2986
  // src/config.ts
2931
2987
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
2932
2988
  import { join } from "path";
@@ -3031,8 +3087,8 @@ function loadConfig() {
3031
3087
  }
3032
3088
 
3033
3089
  // src/index.ts
3034
- import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync12 } from "fs";
3035
- import { join as join12 } from "path";
3090
+ import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync12 } from "fs";
3091
+ import { join as join13 } from "path";
3036
3092
  import { homedir as homedir11 } from "os";
3037
3093
 
3038
3094
  // src/opencode/client.ts
@@ -6388,7 +6444,10 @@ function load() {
6388
6444
  } catch {
6389
6445
  entries = [];
6390
6446
  }
6391
- cache = entries.filter((e) => e.state === "inflight" || Date.now() - e.at <= INFLIGHT_MAX_AGE_MS);
6447
+ const pruned = entries.filter((e) => e.state === "inflight" || Date.now() - e.at <= INFLIGHT_MAX_AGE_MS);
6448
+ cache = pruned;
6449
+ if (pruned.length !== entries.length)
6450
+ save();
6392
6451
  return cache;
6393
6452
  }
6394
6453
  function save() {
@@ -7071,12 +7130,17 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
7071
7130
  function acquireInstanceLock(appId) {
7072
7131
  return acquireInstanceLockAt(lockPathOf(appId));
7073
7132
  }
7133
+ function shouldLogStandby(attempt) {
7134
+ return attempt === 0 || attempt % 120 === 0;
7135
+ }
7074
7136
  async function waitInstanceLock(appId) {
7075
- for (;; ) {
7137
+ for (let attempt = 0;; attempt++) {
7076
7138
  const lock = acquireInstanceLock(appId);
7077
7139
  if (lock)
7078
7140
  return lock;
7079
- console.log(`[instance-lock] 已有实例在运行,本实例待命(每 ${LOCK_RETRY_MS / 1000}s 重试抢锁)`);
7141
+ if (shouldLogStandby(attempt)) {
7142
+ console.log(`[instance-lock] 已有实例在运行,本实例待命(每 ${LOCK_RETRY_MS / 1000}s 重试抢锁,日志已节流)`);
7143
+ }
7080
7144
  await new Promise((r) => setTimeout(r, LOCK_RETRY_MS));
7081
7145
  }
7082
7146
  }
@@ -7110,6 +7174,10 @@ async function waitForOpencode(clientFactory, initialUrl) {
7110
7174
  }
7111
7175
  }
7112
7176
  async function main() {
7177
+ if (process.env.QQ_LOG_FILE) {
7178
+ await Promise.resolve().then(() => init_file_log());
7179
+ installFileLog(process.env.QQ_LOG_FILE);
7180
+ }
7113
7181
  await ensureConfig();
7114
7182
  const config = loadConfig();
7115
7183
  let instanceLock = null;
@@ -7156,10 +7224,10 @@ async function main() {
7156
7224
  });
7157
7225
  console.log("[index] OpenCode QQ Bot 已启动");
7158
7226
  bridge.recoverInflightRounds();
7159
- const heartbeatFile = join12(homedir11(), ".openqq", "heartbeat");
7227
+ const heartbeatFile = join13(homedir11(), ".openqq", "heartbeat");
7160
7228
  const touchHeartbeat = () => {
7161
7229
  try {
7162
- mkdirSync9(join12(homedir11(), ".openqq"), { recursive: true });
7230
+ mkdirSync10(join13(homedir11(), ".openqq"), { recursive: true });
7163
7231
  writeFileSync12(heartbeatFile, String(Date.now()));
7164
7232
  } catch (error) {
7165
7233
  console.error("[index] 心跳写入失败:", error);
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@linjz/opencode-qqbot",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "type": "module",
5
5
  "description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
6
6
  "exports": {
7
- ".": "./src/plugin-entry.ts"
7
+ ".": "./dist/opencode-qqbot-plugin.js"
8
8
  },
9
9
  "bin": {
10
10
  "openqq": "./bin/openqq.js",
@@ -6,7 +6,7 @@
6
6
  // 子进程脱离 serve 生命周期(serve 重载/重启不碰 bot)。运行时解析 bun→node:
7
7
  // bun 直接跑源码(.js→.ts 映射);node 跑发布时预打的 dist/openqq-bot.js bundle。
8
8
  import { spawn, spawnSync } from "child_process"
9
- import { existsSync, mkdirSync, openSync, readFileSync } from "fs"
9
+ import { existsSync, readFileSync } from "fs"
10
10
  import { join, dirname } from "path"
11
11
  import { homedir } from "os"
12
12
 
@@ -14,11 +14,30 @@ export type Runtime = "bun" | "node"
14
14
 
15
15
  /** 探测命令可用性(跨平台:spawnSync ENOENT=不存在) */
16
16
  export function resolveRuntime(probe: (cmd: string) => boolean = defaultProbe): Runtime | null {
17
- if (probe("bun")) return "bun"
17
+ if (resolveBunCommand(probe)) return "bun"
18
18
  if (probe("node")) return "node"
19
19
  return null
20
20
  }
21
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
+
22
41
  function defaultProbe(cmd: string): boolean {
23
42
  try {
24
43
  const r = spawnSync(cmd, ["--version"], { stdio: "ignore" })
@@ -48,8 +67,9 @@ export function resolveBotEntry(
48
67
  ): string | null {
49
68
  const dir = dirname(pluginFilePath)
50
69
  const candidates = [
51
- join(dir, "bot.js"), // 形态 1:自包含插件目录(bot.js 是同目录兄弟)
52
- join(homedir(), ".openqq", "plugin-payload", "bot.js"), // 形态 1b:单文件形态的有效载荷位
70
+ join(dir, "bot.js"), // 旧双 bundle 形态(兼容已装实例)
71
+ join(dir, "dist", "openqq-bot.js"), // 形态 1:全量包安装(插件目录=完整 npm 包)
72
+ join(homedir(), ".openqq", "plugin-payload", "bot.js"), // 单文件形态的有效载荷位
53
73
  join(dir, "..", "dist", "openqq-bot.js"), // 形态 2:npm 包(plugin-entry 在 src/ 下)
54
74
  join(dir, "..", "src", "index.ts"), // 形态 3:dev 源码
55
75
  ]
@@ -58,9 +78,18 @@ export function resolveBotEntry(
58
78
  }
59
79
 
60
80
  /** 构造拉起计划(纯函数供测试)。entry 由 resolveBotEntry 解析。 */
61
- export function buildLaunchPlan(runtime: Runtime, entry: string): LaunchPlan {
62
- const env = { ...process.env, QQ_INSTANCE_LOCK: "try" } // 拉起即抢锁,抢不到自动退出
63
- if (runtime === "bun") return { command: "bun", args: ["run", entry], env }
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
+ }
64
93
  return { command: "node", args: [entry], env }
65
94
  }
66
95
 
@@ -71,14 +100,14 @@ export function botLogPath(): string {
71
100
 
72
101
  /**
73
102
  * detached 拉起 bot(跨平台同 API;Windows 隐藏控制台窗口)。
103
+ * 日志由 bot 进程内文件双写承担(QQ_LOG_FILE,见 buildLaunchPlan)——
104
+ * spawn 侧 fd 重定向在 bun 下实测不落盘(2026-10-30 清债 P2),不再依赖。
74
105
  * 返回 pid;拉起失败抛错(调用方记日志)。
75
106
  */
76
- export function spawnBotDetached(plan: LaunchPlan, logPath: string = botLogPath()): number {
77
- mkdirSync(join(logPath, ".."), { recursive: true })
78
- const out = openSync(logPath, "a")
107
+ export function spawnBotDetached(plan: LaunchPlan): number {
79
108
  const child = spawn(plan.command, plan.args, {
80
109
  detached: true,
81
- stdio: ["ignore", out, out],
110
+ stdio: "ignore",
82
111
  env: plan.env,
83
112
  windowsHide: true,
84
113
  })
@@ -0,0 +1,45 @@
1
+ // @input: fs(追加写)
2
+ // @output: installFileLog
3
+ // @pos: core - 可选文件日志双写(QQ_LOG_FILE 环境变量开启)
4
+ //
5
+ // 背景(2026-10-30 清债 P2):插件拉起的 detached bot 无控制台,bun 子进程 fd
6
+ // 重定向实测不落盘(bot.out.log 0 字节)——改为 bot 进程内 console 双写,
7
+ // 不依赖 spawn 侧 fd 语义,跨运行时(bun/node)确定生效。
8
+ // 轮转:超 5MB 改名 .1(单代备份足够排障)。
9
+ import { appendFileSync, existsSync, mkdirSync, renameSync, statSync } from "fs"
10
+ import { join } from "path"
11
+
12
+ const ROTATE_BYTES = 5 * 1024 * 1024
13
+
14
+ /** console.log/warn/error 双写到文件;返回卸载函数(测试用) */
15
+ export function installFileLog(logPath: string): () => void {
16
+ try {
17
+ mkdirSync(join(logPath, ".."), { recursive: true })
18
+ } catch {
19
+ /* 目录已存在或不可建——写时再兜底 */
20
+ }
21
+ const write = (level: string, args: unknown[]): void => {
22
+ try {
23
+ if (existsSync(logPath) && statSync(logPath).size > ROTATE_BYTES) {
24
+ renameSync(logPath, `${logPath}.1`)
25
+ }
26
+ const line = args.map((a) => (typeof a === "string" ? a : JSON.stringify(a))).join(" ")
27
+ appendFileSync(logPath, `${new Date().toISOString()} [${level}] ${line}\n`)
28
+ } catch {
29
+ // 日志绝不阻断主流程
30
+ }
31
+ }
32
+ const orig = {
33
+ log: console.log.bind(console),
34
+ warn: console.warn.bind(console),
35
+ error: console.error.bind(console),
36
+ }
37
+ console.log = (...args: unknown[]) => { orig.log(...args); write("log", args) }
38
+ console.warn = (...args: unknown[]) => { orig.warn(...args); write("warn", args) }
39
+ console.error = (...args: unknown[]) => { orig.error(...args); write("error", args) }
40
+ return () => {
41
+ console.log = orig.log
42
+ console.warn = orig.warn
43
+ console.error = orig.error
44
+ }
45
+ }
@@ -50,8 +50,10 @@ function load(): InflightEntry[] {
50
50
  } catch {
51
51
  entries = [] // 损坏即空,不阻塞启动
52
52
  }
53
- // 修剪:已销账超 24h 的不再保留
54
- cache = entries.filter((e) => e.state === "inflight" || Date.now() - e.at <= INFLIGHT_MAX_AGE_MS)
53
+ // 修剪:已销账超 24h 的不再保留;有修剪即落盘(防 settled 条目只进不出)
54
+ const pruned = entries.filter((e) => e.state === "inflight" || Date.now() - e.at <= INFLIGHT_MAX_AGE_MS)
55
+ cache = pruned
56
+ if (pruned.length !== entries.length) save()
55
57
  return cache
56
58
  }
57
59
 
@@ -100,15 +100,23 @@ export function isInstanceAliveAt(path: string, staleMs: number = LOCK_STALE_MS)
100
100
  }
101
101
  }
102
102
 
103
+ // 待命日志节流(2026-10-30 清债 P3):首次 + 之后每 120 次(=10 分钟)打一条,
104
+ // 长期待命不刷爆日志。纯函数导出供测试。
105
+ export function shouldLogStandby(attempt: number): boolean {
106
+ return attempt === 0 || attempt % 120 === 0
107
+ }
108
+
103
109
  /**
104
110
  * 阻塞式抢锁:抢不到就每 5s 重试,直到成为宿主。
105
111
  * 用于启动入口——双开时后到实例待命,宿主退出后自动接管。
106
112
  */
107
113
  export async function waitInstanceLock(appId: string): Promise<InstanceLock> {
108
- for (;;) {
114
+ for (let attempt = 0; ; attempt++) {
109
115
  const lock = acquireInstanceLock(appId)
110
116
  if (lock) return lock
111
- console.log(`[instance-lock] 已有实例在运行,本实例待命(每 ${LOCK_RETRY_MS / 1000}s 重试抢锁)`)
117
+ if (shouldLogStandby(attempt)) {
118
+ console.log(`[instance-lock] 已有实例在运行,本实例待命(每 ${LOCK_RETRY_MS / 1000}s 重试抢锁,日志已节流)`)
119
+ }
112
120
  await new Promise((r) => setTimeout(r, LOCK_RETRY_MS))
113
121
  }
114
122
  }
package/src/index.ts CHANGED
@@ -54,6 +54,12 @@ async function waitForOpencode(
54
54
  }
55
55
 
56
56
  async function main(): Promise<void> {
57
+ // P2(2026-10-30 清债):插件拉起等无控制台场景的文件日志双写(bun fd 重定向
58
+ // 实测不落盘,改为进程内 tee)。计划任务通道有 PowerShell 重定向,不受影响。
59
+ if (process.env.QQ_LOG_FILE) {
60
+ const { installFileLog } = await import("./core/file-log.js")
61
+ installFileLog(process.env.QQ_LOG_FILE)
62
+ }
57
63
  await ensureConfig()
58
64
  const config = loadConfig()
59
65
 
@@ -13,7 +13,7 @@ import { homedir } from "os"
13
13
  import { appendFileSync, existsSync, renameSync, statSync } from "fs"
14
14
  import { fileURLToPath } from "url"
15
15
  import { isInstanceAlive } from "./core/instance-lock.js"
16
- import { resolveRuntime, buildLaunchPlan, spawnBotDetached, resolveBotEntry, readDotEnvField } from "./core/bot-launcher.js"
16
+ import { resolveRuntime, buildLaunchPlan, spawnBotDetached, resolveBotEntry, readDotEnvField, botLogPath } from "./core/bot-launcher.js"
17
17
 
18
18
  const ENV_FILE = join(homedir(), ".openqq", ".env")
19
19
  const CHECK_INTERVAL_MS = 5 * 60 * 1000 // 看门狗巡检间隔(插件重载会重置,兜底是每小时 reload)
@@ -39,28 +39,41 @@ function probeAppend(line: string): void {
39
39
  export default Plugin.define({
40
40
  id: "opencode-qqbot",
41
41
  setup(_ctx) {
42
+ // P3(2026-10-30 清债):阻塞原因告警只在"状态变化"时打——插件每小时重载
43
+ // + 5min 巡检,缺凭据/无运行时不处理会重复喷日志。恢复畅通时复位。
44
+ let lastBlocker: string | null = null
45
+ const warnOnce = (key: string, message: string): void => {
46
+ if (lastBlocker === key) return
47
+ lastBlocker = key
48
+ console.warn(message)
49
+ }
42
50
  const ensure = (): void => {
43
51
  try {
44
52
  const appId = readDotEnvField(ENV_FILE, "QQ_APP_ID")
45
53
  if (!appId) {
46
- console.warn(
54
+ warnOnce(
55
+ "cred",
47
56
  "[opencode-qqbot] 未发现 ~/.openqq/.env 凭据——先运行 npx @linjz/opencode-qqbot setup 扫码绑定(或参考 README 手写 .env),完成后插件将在下次巡检自动拉起 bot",
48
57
  )
49
58
  return
50
59
  }
51
- if (isInstanceAlive(appId)) return // 活着,不动
60
+ if (isInstanceAlive(appId)) {
61
+ lastBlocker = null // 畅通复位
62
+ return
63
+ }
52
64
  const entry = resolveBotEntry(fileURLToPath(import.meta.url))
53
65
  if (!entry) {
54
- console.warn("[opencode-qqbot] 未找到 bot 入口(bot.js / dist/openqq-bot.js / src/index.ts 全缺)——插件安装不完整")
66
+ warnOnce("entry", "[opencode-qqbot] 未找到 bot 入口(bot.js / dist/openqq-bot.js / src/index.ts 全缺)——插件安装不完整")
55
67
  return
56
68
  }
57
69
  const runtime = resolveRuntime()
58
70
  if (!runtime) {
59
- console.warn("[opencode-qqbot] 未找到 bun/node 运行时,无法拉起 bot——请安装其中之一(https://bun.sh)")
71
+ warnOnce("runtime", "[opencode-qqbot] 未找到 bun/node 运行时,无法拉起 bot——请安装其中之一(https://bun.sh)")
60
72
  return
61
73
  }
62
- const pid = spawnBotDetached(buildLaunchPlan(runtime, entry))
74
+ const pid = spawnBotDetached(buildLaunchPlan(runtime, entry, botLogPath()))
63
75
  console.log(`[opencode-qqbot] bot 已拉起(pid=${pid},runtime=${runtime},entry=${entry})`)
76
+ lastBlocker = null
64
77
  } catch (error) {
65
78
  // 引导器永不阻断宿主
66
79
  console.error("[opencode-qqbot] 拉起失败:", error instanceof Error ? error.message : error)