@linjz/opencode-qqbot 0.3.15 → 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 (50) hide show
  1. package/README.md +42 -5
  2. package/bin/openqq.js +13 -0
  3. package/dist/notify-cli.js +28 -14
  4. package/dist/opencode-qqbot-plugin.js +934 -64
  5. package/dist/openqq-bot.js +3095 -677
  6. package/dist/openqq-cli.js +791 -0
  7. package/dist/openqq-watchdog.js +1063 -0
  8. package/package.json +8 -5
  9. package/src/bridge.ts +1310 -150
  10. package/src/cli/notify.ts +167 -158
  11. package/src/cli/openqq-main.ts +95 -0
  12. package/src/cli/service-main.ts +302 -0
  13. package/src/cli/watchdog-main.ts +77 -0
  14. package/src/commands.ts +644 -554
  15. package/src/config.ts +85 -0
  16. package/src/core/bot-control.ts +148 -0
  17. package/src/core/bot-launcher.ts +106 -13
  18. package/src/core/card-approval.ts +20 -9
  19. package/src/core/delivery.ts +145 -54
  20. package/src/core/discovery.ts +22 -4
  21. package/src/core/file-log.ts +35 -3
  22. package/src/core/form-bridge.ts +14 -5
  23. package/src/core/form-journal.ts +4 -4
  24. package/src/core/gateway-state.ts +3 -3
  25. package/src/core/inflight-journal.ts +214 -36
  26. package/src/core/instance-lock.ts +10 -2
  27. package/src/core/linkwatch.ts +3 -4
  28. package/src/core/markdown.ts +117 -0
  29. package/src/core/message-queue.ts +242 -91
  30. package/src/core/mirror.ts +222 -182
  31. package/src/core/notify-sink.ts +93 -96
  32. package/src/core/outbox.ts +10 -9
  33. package/src/core/permission.ts +627 -303
  34. package/src/core/question-form.ts +230 -0
  35. package/src/core/queue-view.ts +661 -0
  36. package/src/core/send-media.ts +32 -0
  37. package/src/core/storage.ts +34 -0
  38. package/src/core/watchdog.ts +513 -0
  39. package/src/core/zombie-reaper.ts +127 -0
  40. package/src/index.ts +140 -52
  41. package/src/opencode/client.ts +206 -27
  42. package/src/opencode/eventstream.ts +94 -12
  43. package/src/opencode/history.ts +4 -2
  44. package/src/opencode/mirror.ts +15 -2
  45. package/src/opencode/sessions.ts +135 -37
  46. package/src/plugin-entry.ts +120 -115
  47. package/src/qq/api.ts +165 -61
  48. package/src/qq/gateway.ts +79 -16
  49. package/src/qq/sender.ts +30 -18
  50. package/src/qq/types.ts +7 -0
@@ -1,34 +1,245 @@
1
1
  // @bun
2
2
  // src/plugin-entry.ts
3
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";
4
+ import { join as join6 } from "path";
5
+ import { homedir as homedir5 } from "os";
6
+ import { appendFileSync, existsSync as existsSync6, renameSync as renameSync2, statSync as statSync4 } from "fs";
7
+ import { fileURLToPath as fileURLToPath2 } from "url";
8
8
 
9
- // src/core/instance-lock.ts
10
- import { openSync, readFileSync, writeFileSync, closeSync, unlinkSync, statSync, utimesSync, mkdirSync } from "fs";
9
+ // src/core/watchdog.ts
10
+ import { readFileSync, statSync, unlinkSync, writeFileSync } from "fs";
11
11
  import { join } from "path";
12
12
  import { homedir } from "os";
13
- var LOCK_STALE_MS = 30000;
14
- function lockPathOf(appId) {
15
- return join(homedir(), ".openqq", `openqq-${appId}.lock`);
13
+ var HEARTBEAT_STALE_MS = 5 * 60000;
14
+ function botWatchdogPaths(appId) {
15
+ const dir = join(homedir(), ".openqq");
16
+ return { lockPath: join(dir, `openqq-${appId}.lock`), heartbeatPath: join(dir, "heartbeat") };
16
17
  }
17
- function isInstanceAlive(appId, staleMs = LOCK_STALE_MS) {
18
- return isInstanceAliveAt(lockPathOf(appId), staleMs);
18
+ function isPidAlive(pid) {
19
+ if (!Number.isInteger(pid) || pid <= 0)
20
+ return false;
21
+ try {
22
+ process.kill(pid, 0);
23
+ return true;
24
+ } catch (error) {
25
+ return error.code === "EPERM";
26
+ }
19
27
  }
20
- function isInstanceAliveAt(path, staleMs = LOCK_STALE_MS) {
28
+ function ageOf(path, now) {
21
29
  try {
22
- return Date.now() - statSync(path).mtimeMs <= staleMs;
30
+ return Math.max(0, now - statSync(path).mtimeMs);
23
31
  } catch {
24
- return false;
32
+ return null;
33
+ }
34
+ }
35
+ function readBotHealth(paths, now = Date.now()) {
36
+ const lockAgeMs = ageOf(paths.lockPath, now);
37
+ let lockPid = null;
38
+ if (lockAgeMs !== null) {
39
+ try {
40
+ const raw = JSON.parse(readFileSync(paths.lockPath, "utf-8"));
41
+ if (typeof raw.pid === "number" && Number.isInteger(raw.pid))
42
+ lockPid = raw.pid;
43
+ } catch {}
44
+ }
45
+ return {
46
+ lockPid,
47
+ lockAgeMs,
48
+ pidAlive: lockPid === null ? null : isPidAlive(lockPid),
49
+ heartbeatAgeMs: ageOf(paths.heartbeatPath, now)
50
+ };
51
+ }
52
+ function appendWatchdogLog(line) {
53
+ try {
54
+ const dir = join(homedir(), ".openqq");
55
+ writeFileSync(join(dir, "watchdog.log"), `${new Date().toISOString()} ${line}
56
+ `, { flag: "a" });
57
+ } catch {}
58
+ }
59
+ var DEFAULT_SUPERVISOR_POLICY = {
60
+ cooldownMs: 2 * 60000,
61
+ maxRestarts: 3,
62
+ windowMs: 15 * 60000,
63
+ graceMs: 8000,
64
+ claimTtlMs: 90000
65
+ };
66
+ function decideSupervise(health, state, now, policy = DEFAULT_SUPERVISOR_POLICY) {
67
+ const staleHeartbeat = health.heartbeatAgeMs !== null && health.heartbeatAgeMs > HEARTBEAT_STALE_MS;
68
+ const needsRestart = health.lockPid === null || health.pidAlive === false || staleHeartbeat;
69
+ if (!needsRestart)
70
+ return { kind: "ok" };
71
+ const windowStart = now - policy.windowMs;
72
+ const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
73
+ if (recentRestarts >= policy.maxRestarts)
74
+ return { kind: "give-up", restarts: recentRestarts };
75
+ const last = state.restartLog[state.restartLog.length - 1] ?? null;
76
+ if (last !== null && now - last < policy.cooldownMs)
77
+ return { kind: "cooldown", untilMs: last + policy.cooldownMs };
78
+ if (health.lockPid !== null && health.pidAlive !== false && staleHeartbeat) {
79
+ return {
80
+ kind: "grace-kill-spawn",
81
+ killPid: health.lockPid,
82
+ reason: `\u5FC3\u8DF3\u9648\u65E7 ${Math.round((health.heartbeatAgeMs ?? 0) / 60000)} \u5206\u949F\uFF08\u8FDB\u7A0B\u6D3B\u4F46\u4E8B\u4EF6\u5FAA\u73AF\u65E0\u8FDB\u5C55\uFF09`
83
+ };
84
+ }
85
+ return { kind: "spawn", reason: health.lockPid === null ? "\u65E0\u5B9E\u4F8B\u9501\uFF08bot \u672A\u8FD0\u884C\uFF09" : "\u9501\u5B9A\u8FDB\u7A0B\u5DF2\u9000\u51FA" };
86
+ }
87
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
88
+ var defaultSupervisorKill = (pid, signal) => {
89
+ try {
90
+ process.kill(pid, signal);
91
+ } catch {}
92
+ };
93
+ function readJson(path, fallback) {
94
+ try {
95
+ return { ...fallback, ...JSON.parse(readFileSync(path, "utf-8")) };
96
+ } catch {
97
+ return fallback;
98
+ }
99
+ }
100
+ async function superviseOnce(deps) {
101
+ const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY;
102
+ const now = deps.now?.() ?? Date.now();
103
+ const log = deps.log ?? (() => {});
104
+ const sleep = deps.sleep ?? defaultSleep;
105
+ const kill = deps.kill ?? defaultSupervisorKill;
106
+ const isAlive = deps.isAlive ?? isPidAlive;
107
+ const statePath = deps.statePath ?? join(homedir(), ".openqq", "supervisor.json");
108
+ const claimPath = deps.claimPath ?? join(homedir(), ".openqq", "supervisor.lock");
109
+ const audit = (line) => {
110
+ if (deps.auditLogPath) {
111
+ try {
112
+ writeFileSync(deps.auditLogPath, `${new Date().toISOString()} ${line}
113
+ `, { flag: "a" });
114
+ return;
115
+ } catch {}
116
+ }
117
+ appendWatchdogLog(line);
118
+ };
119
+ const claim = readJson(claimPath, { pid: 0, ts: 0 });
120
+ if (claim.ts && now - claim.ts < policy.claimTtlMs && claim.pid !== process.pid) {
121
+ return { action: "yield", detail: `\u76D1\u7763\u8005 pid=${claim.pid} \u6301\u9501\u4E2D`, killedPid: null, spawnedPid: null };
122
+ }
123
+ try {
124
+ writeFileSync(claimPath, JSON.stringify({ pid: process.pid, ts: now }));
125
+ } catch {
126
+ return { action: "yield", detail: "\u8BA4\u9886\u9501\u4E0D\u53EF\u5199", killedPid: null, spawnedPid: null };
127
+ }
128
+ const release = () => {
129
+ try {
130
+ writeFileSync(claimPath, JSON.stringify({ pid: 0, ts: 0 }));
131
+ } catch {}
132
+ };
133
+ try {
134
+ const health = readBotHealth(deps.paths, now);
135
+ const state = readJson(statePath, { restartLog: [] });
136
+ let action = decideSupervise(health, state, now, policy);
137
+ if (deps.request === "manual-restart" && action.kind === "ok") {
138
+ const windowStart = now - policy.windowMs;
139
+ const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
140
+ if (recentRestarts >= policy.maxRestarts) {
141
+ return {
142
+ action: "give-up",
143
+ detail: `15 \u5206\u949F\u5185\u5DF2\u91CD\u542F ${recentRestarts} \u6B21\uFF08\u76D1\u7763\u5F3A\u5EA6\u4E0A\u9650\uFF09\uFF0C\u4EBA\u5DE5\u91CD\u542F\u4EA6\u88AB\u62E6\u622A\uFF0C\u8BF7\u6392\u67E5\u6839\u56E0`,
144
+ killedPid: null,
145
+ spawnedPid: null
146
+ };
147
+ }
148
+ const last = state.restartLog[state.restartLog.length - 1] ?? null;
149
+ if (last !== null && now - last < policy.cooldownMs) {
150
+ return { action: "cooldown", detail: `\u8DDD\u4E0A\u6B21\u91CD\u542F\u4E0D\u8DB3 ${Math.round(policy.cooldownMs / 1000)}s\uFF08\u51B7\u5374\u671F\uFF09\uFF0C\u4EBA\u5DE5\u91CD\u542F\u8DF3\u8FC7`, killedPid: null, spawnedPid: null };
151
+ }
152
+ action = health.lockPid !== null && health.pidAlive !== false ? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "\u4EBA\u5DE5\u8BF7\u6C42\u91CD\u542F\uFF08openqq restart\uFF09" } : { kind: "spawn", reason: "\u4EBA\u5DE5\u8BF7\u6C42\u91CD\u542F\uFF08bot \u672A\u8FD0\u884C\uFF0C\u76F4\u63A5\u62C9\u8D77\uFF09" };
153
+ }
154
+ if (action.kind === "ok")
155
+ return { action: "ok", detail: "\u5065\u5EB7", killedPid: null, spawnedPid: null };
156
+ if (action.kind === "cooldown") {
157
+ log(`[supervisor] \u51B7\u5374\u4E2D\uFF08\u4E0A\u6B21\u91CD\u542F ${Math.round((now - (action.untilMs - policy.cooldownMs)) / 1000)}s \u524D\uFF09\uFF0C\u672C\u8F6E\u8DF3\u8FC7`);
158
+ return { action: "cooldown", detail: "\u51B7\u5374\u8DF3\u8FC7", killedPid: null, spawnedPid: null };
159
+ }
160
+ if (action.kind === "yield") {
161
+ return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null };
162
+ }
163
+ if (action.kind === "give-up") {
164
+ const message = `\u26A0\uFE0F QQBot \u770B\u95E8\u72D7\u5DF2\u653E\u5F03\uFF1A${action.restarts} \u6B21\u91CD\u542F/${Math.round(policy.windowMs / 60000)} \u5206\u949F\u4ECD\u4E0D\u5065\u5EB7\u3002\u7EE7\u7EED\u81EA\u52A8\u91CD\u542F\u6CA1\u6709\u610F\u4E49\uFF08\u540C\u56E0\u53CD\u590D\u6B7B\u4EA1\uFF09\uFF0C\u8BF7\u4EBA\u5DE5\u68C0\u67E5 %TEMP%\\opencode \u4E0B bot.out.log \u4E0E ~/.openqq/watchdog.log\u3002`;
165
+ audit(`give-up\uFF1A${message}`);
166
+ log(`[supervisor] give-up\uFF1A${action.restarts} \u6B21\u91CD\u542F\u4ECD\u5F02\u5E38\uFF0C\u505C\u6B62\u5FAA\u73AF\u5E76\u4E0A\u62A5`);
167
+ const lastAlert = state.alertedAt ?? 0;
168
+ if (now - lastAlert > 30 * 60000) {
169
+ try {
170
+ deps.alert?.(message);
171
+ state.alertedAt = now;
172
+ writeFileSync(statePath, JSON.stringify(state));
173
+ } catch {}
174
+ }
175
+ return { action: "give-up", detail: message, killedPid: null, spawnedPid: null };
176
+ }
177
+ let killedPid = null;
178
+ if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
179
+ const pid = action.killPid;
180
+ if (deps.request !== "manual-restart") {
181
+ await sleep(300);
182
+ const recheck = readBotHealth(deps.paths, Date.now());
183
+ const recheckFresh = recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS;
184
+ if (recheck.pidAlive !== false && recheckFresh) {
185
+ const ageSec = Math.round((recheck.heartbeatAgeMs ?? 0) / 1000);
186
+ audit(`\u6740\u524D\u590D\u6838\u6539\u5224 ok\uFF1Apid=${pid} \u5FC3\u8DF3\u5DF2\u6062\u590D\uFF08\u5E74\u9F84 ${ageSec}s\uFF09\uFF0C\u653E\u5F03\u8BEF\u6740`);
187
+ log(`[supervisor] \u6740\u524D\u590D\u6838\u6539\u5224 ok\uFF1A\u5FC3\u8DF3\u5DF2\u6062\u590D\uFF08${ageSec}s\uFF09\uFF0C\u653E\u5F03\u6740 pid=${pid}`);
188
+ return { action: "ok", detail: `\u6740\u524D\u590D\u6838\uFF1A\u5FC3\u8DF3\u5DF2\u6062\u590D\uFF0C\u653E\u5F03\u8BEF\u6740 pid=${pid}`, killedPid: null, spawnedPid: null };
189
+ }
190
+ }
191
+ kill(pid, "SIGTERM");
192
+ const deadline = now + policy.graceMs;
193
+ let alive = isAlive(pid);
194
+ while (alive && Date.now() < deadline) {
195
+ await sleep(250);
196
+ alive = isAlive(pid);
197
+ }
198
+ if (alive) {
199
+ kill(pid, "SIGKILL");
200
+ const hardDeadline = Date.now() + 3000;
201
+ while (alive && Date.now() < hardDeadline) {
202
+ await sleep(250);
203
+ alive = isAlive(pid);
204
+ }
205
+ }
206
+ if (alive) {
207
+ audit(`give-up-kill\uFF1Apid=${pid} \u65E0\u6CD5\u7EC8\u6B62\uFF08\u6743\u9650/\u7CFB\u7EDF\u7EA7\uFF09\uFF0C\u672C\u6B21\u4E0D\u62C9\u8D77`);
208
+ return { action: "give-up", detail: `pid=${pid} \u65E0\u6CD5\u7EC8\u6B62`, killedPid: null, spawnedPid: null };
209
+ }
210
+ killedPid = pid;
211
+ }
212
+ try {
213
+ if (killedPid !== null || health.lockPid === null || health.pidAlive === false) {
214
+ unlinkSync(deps.paths.lockPath);
215
+ audit(`\u6E05\u9501\uFF1A${deps.paths.lockPath}\uFF08${action.reason}\uFF09`);
216
+ }
217
+ } catch {}
218
+ const spawnedPid = deps.spawn();
219
+ state.restartLog.push(Date.now());
220
+ state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
221
+ try {
222
+ writeFileSync(statePath, JSON.stringify(state));
223
+ } catch {
224
+ log("[supervisor] \u5F3A\u5EA6\u8D26\u843D\u76D8\u5931\u8D25\uFF08\u4E0D\u5F71\u54CD\u672C\u6B21\u62C9\u8D77\uFF09");
225
+ }
226
+ const detail = `${action.reason}\uFF1B${killedPid ? `\u5DF2\u4F18\u96C5\u505C pid=${killedPid}\uFF1B` : ""}\u5DF2\u62C9\u8D77 pid=${spawnedPid}`;
227
+ audit(killedPid ? `\u4E3B\u52A8\u6740\uFF1A${detail}` : `\u9A8C\u5C38\u62C9\u65B0\uFF1A${detail}`);
228
+ return { action: "restart", detail, killedPid, spawnedPid };
229
+ } finally {
230
+ release();
25
231
  }
26
232
  }
27
233
 
234
+ // src/core/bot-control.ts
235
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
236
+ import { dirname as dirname2, join as join3 } from "path";
237
+ import { fileURLToPath } from "url";
238
+
28
239
  // src/core/bot-launcher.ts
29
240
  import { spawn, spawnSync } from "child_process";
30
- import { existsSync, readFileSync as readFileSync2 } from "fs";
31
- import { join as join2, dirname } from "path";
241
+ import { existsSync, readFileSync as readFileSync2, statSync as statSync2 } from "fs";
242
+ import { join as join2, dirname, isAbsolute } from "path";
32
243
  import { homedir as homedir2 } from "os";
33
244
  function resolveRuntime(probe = defaultProbe) {
34
245
  if (resolveBunCommand(probe))
@@ -37,44 +248,103 @@ function resolveRuntime(probe = defaultProbe) {
37
248
  return "node";
38
249
  return null;
39
250
  }
251
+ function isExecutable(p) {
252
+ try {
253
+ const st = statSync2(p);
254
+ return st.isFile() && (process.platform === "win32" || (st.mode & 73) !== 0);
255
+ } catch {
256
+ return false;
257
+ }
258
+ }
259
+ function locateOnPath(cmd, pathEnv = process.env.PATH ?? process.env.Path ?? "") {
260
+ if (isAbsolute(cmd))
261
+ return isExecutable(cmd) ? cmd : null;
262
+ const isWin = process.platform === "win32";
263
+ for (const dir of pathEnv.split(isWin ? ";" : ":")) {
264
+ if (!dir)
265
+ continue;
266
+ const base = isWin && !/\.[a-z]+$/i.test(cmd) ? `${cmd}.exe` : cmd;
267
+ const full = join2(dir, base);
268
+ if (isExecutable(full))
269
+ return full;
270
+ }
271
+ if (isWin)
272
+ return resolveThroughShim(cmd, pathEnv);
273
+ return null;
274
+ }
275
+ var SHIM_PATTERN_LINE = /%~?dp0%?\\?([^"\n]+?\.exe)/;
276
+ var SHIM_PATTERN_ABS = /([A-Za-z]:\\[^\n"]+?\.exe)/;
277
+ function resolveThroughShim(bare, pathEnv = process.env.PATH ?? process.env.Path ?? "") {
278
+ for (const dir of pathEnv.split(";")) {
279
+ if (!dir)
280
+ continue;
281
+ for (const ext of [".cmd", ".bat"]) {
282
+ const shimPath = join2(dir, bare + ext);
283
+ let text;
284
+ try {
285
+ text = readFileSync2(shimPath, "utf-8");
286
+ } catch {
287
+ continue;
288
+ }
289
+ const rel = SHIM_PATTERN_LINE.exec(text);
290
+ if (rel) {
291
+ const full = join2(dir, rel[1]);
292
+ if (isExecutable(full))
293
+ return full;
294
+ }
295
+ const abs = SHIM_PATTERN_ABS.exec(text);
296
+ if (abs) {
297
+ const full = abs[1];
298
+ if (isExecutable(full))
299
+ return full;
300
+ }
301
+ }
302
+ }
303
+ return null;
304
+ }
40
305
  function bunCandidates() {
41
- const candidates = ["bun", "bun.exe", "bun.cmd", "bun.bat"];
42
306
  if (process.platform === "win32") {
43
307
  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"));
308
+ return [
309
+ join2(appdata, "npm", "node_modules", "bun", "bin", "bun.exe"),
310
+ join2(homedir2(), ".bun", "bin", "bun.exe"),
311
+ "bun",
312
+ "bun.exe"
313
+ ];
47
314
  }
48
- return candidates;
315
+ return ["/usr/local/bin/bun", "/opt/homebrew/bin/bun", join2(homedir2(), ".bun", "bin", "bun"), "bun"];
49
316
  }
50
317
  function resolveBunCommand(probe = defaultProbe) {
318
+ if (probe !== defaultProbe) {
319
+ for (const c of bunCandidates()) {
320
+ if (!probe(c))
321
+ continue;
322
+ if (isAbsolute(c))
323
+ return c;
324
+ return locateOnPath(c) ?? resolveThroughShim(c) ?? null;
325
+ }
326
+ return null;
327
+ }
51
328
  for (const c of bunCandidates()) {
52
- if (probe(c))
53
- return c;
329
+ const full = locateOnPath(c) ?? (isAbsolute(c) ? null : resolveThroughShim(c));
330
+ if (full)
331
+ return full;
54
332
  }
55
333
  return null;
56
334
  }
57
335
  function defaultProbe(cmd) {
58
336
  try {
59
- const r = spawnSync(cmd, ["--version"], { stdio: "ignore" });
337
+ const r = spawnSync(cmd, ["--version"], { stdio: "ignore", windowsHide: true });
60
338
  return r.status === 0;
61
339
  } catch {
62
340
  return false;
63
341
  }
64
342
  }
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;
343
+ function resolveRuntimeCommand(runtime) {
344
+ const cmd = runtime === "bun" ? resolveBunCommand() : locateOnPath("node");
345
+ if (!cmd)
346
+ throw new Error(`\u672A\u627E\u5230 ${runtime} \u53EF\u6267\u884C\u4F53\uFF08\u5168\u8DEF\u5F84\u89E3\u6790\u5931\u8D25\uFF09\uFF0C\u62D2\u7EDD\u751F\u6210\u88F8\u540D\u62C9\u8D77\u8BA1\u5212`);
347
+ return cmd;
78
348
  }
79
349
  function buildLaunchPlan(runtime, entry, logPath) {
80
350
  const CONFIG_KEY = [/^QQ_/, /^OPENCODE_/, /^ALLOWED_USERS$/];
@@ -92,10 +362,9 @@ function buildLaunchPlan(runtime, entry, logPath) {
92
362
  ...logPath ? { QQ_LOG_FILE: logPath } : {}
93
363
  };
94
364
  if (runtime === "bun") {
95
- const bunCmd = resolveBunCommand() ?? "bun";
96
- return { command: bunCmd, args: ["run", entry], env };
365
+ return { command: resolveRuntimeCommand("bun"), args: ["run", entry], env };
97
366
  }
98
- return { command: "node", args: [entry], env };
367
+ return { command: resolveRuntimeCommand("node"), args: [entry], env };
99
368
  }
100
369
  function botLogPath() {
101
370
  return join2(homedir2(), ".openqq", "bot.out.log");
@@ -105,7 +374,8 @@ function spawnBotDetached(plan) {
105
374
  detached: true,
106
375
  stdio: "ignore",
107
376
  env: plan.env,
108
- windowsHide: true
377
+ windowsHide: true,
378
+ shell: false
109
379
  });
110
380
  child.unref();
111
381
  if (typeof child.pid !== "number")
@@ -133,18 +403,618 @@ function readDotEnvField(envPath, key) {
133
403
  }
134
404
  }
135
405
 
406
+ // src/core/bot-control.ts
407
+ function resolveInstalledBotEntry(fromUrl, exists = existsSync2) {
408
+ const here = dirname2(fileURLToPath(fromUrl));
409
+ const candidates = [
410
+ join3(here, "openqq-bot.js"),
411
+ join3(here, "..", "dist", "openqq-bot.js"),
412
+ join3(here, "..", "src", "index.ts"),
413
+ join3(here, "..", "..", "src", "index.ts")
414
+ ];
415
+ for (const c of candidates)
416
+ if (exists(c))
417
+ return c;
418
+ return null;
419
+ }
420
+ function startBot(fromUrl, log = () => {}) {
421
+ const entry = resolveInstalledBotEntry(fromUrl);
422
+ if (!entry)
423
+ throw new Error("\u672A\u627E\u5230 bot \u5165\u53E3\uFF08dist/openqq-bot.js \u6216 src/index.ts\uFF09\u2014\u2014\u5B89\u88C5\u4E0D\u5B8C\u6574");
424
+ const runtime = resolveRuntime();
425
+ if (!runtime)
426
+ throw new Error("\u672A\u627E\u5230 bun/node \u8FD0\u884C\u65F6");
427
+ const plan = buildLaunchPlan(runtime, entry, botLogPath());
428
+ const pid = spawnBotDetached(plan);
429
+ log(`[bot-control] \u5DF2\u62C9\u8D77 pid=${pid}\uFF08runtime=${runtime}\uFF0Centry=${entry}\uFF09`);
430
+ return pid;
431
+ }
432
+
433
+ // src/cli/notify.ts
434
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
435
+
436
+ // src/core/storage.ts
437
+ import { homedir as homedir3 } from "os";
438
+ import { join as join4 } from "path";
439
+ var LEGACY_ROOT = join4(homedir3(), ".openqq");
440
+ function storageRoot(appId) {
441
+ const base = (process.env.QQ_DATA_DIR ?? "").trim() || LEGACY_ROOT;
442
+ return appId ? join4(base, "roles", appId) : base;
443
+ }
444
+ function storageFile(name, appId) {
445
+ return join4(storageRoot(appId), name);
446
+ }
447
+
448
+ // src/core/outbox.ts
449
+ import {
450
+ closeSync,
451
+ existsSync as existsSync3,
452
+ mkdirSync,
453
+ openSync,
454
+ readFileSync as readFileSync4,
455
+ renameSync,
456
+ statSync as statSync3,
457
+ unlinkSync as unlinkSync2,
458
+ writeFileSync as writeFileSync2
459
+ } from "fs";
460
+ import { dirname as dirname3 } from "path";
461
+ import { randomUUID } from "crypto";
462
+ var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
463
+ var OUTBOX_SENT_RETENTION_LIMIT = 20;
464
+ var OUTBOX_DEFAULT_RETRY_BASE_MS = 1000;
465
+ var OUTBOX_DEFAULT_RETRY_MAX_MS = 60000;
466
+ var DEFAULT_POLL_INTERVAL_MS = 1000;
467
+ var DEFAULT_LEASE_MS = 30000;
468
+ var DEFAULT_LOCK_WAIT_MS = 5000;
469
+ var DEFAULT_LOCK_STALE_MS = 30000;
470
+ var sleepArray = new Int32Array(new SharedArrayBuffer(4));
471
+ function nonNegative(value, fallback, name) {
472
+ const resolved = value ?? fallback;
473
+ if (!Number.isFinite(resolved) || resolved < 0)
474
+ throw new Error(`${name} \u5FC5\u987B\u662F >= 0 \u7684\u6709\u9650\u6570`);
475
+ return resolved;
476
+ }
477
+ function positive(value, fallback, name) {
478
+ const resolved = nonNegative(value, fallback, name);
479
+ if (resolved === 0)
480
+ throw new Error(`${name} \u5FC5\u987B > 0`);
481
+ return resolved;
482
+ }
483
+ function errorText(error) {
484
+ return error instanceof Error ? error.message : String(error);
485
+ }
486
+ function jsonSnapshot(value, label) {
487
+ const encoded = JSON.stringify(value);
488
+ if (encoded === undefined)
489
+ throw new Error(`Outbox ${label} \u5FC5\u987B\u662F\u53EF JSON \u5E8F\u5217\u5316\u7684\u503C`);
490
+ return JSON.parse(encoded);
491
+ }
492
+ function delay(ms) {
493
+ return new Promise((resolve) => setTimeout(resolve, ms));
494
+ }
495
+ function atomicWrite(filePath, document) {
496
+ mkdirSync(dirname3(filePath), { recursive: true });
497
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
498
+ try {
499
+ writeFileSync2(temporary, JSON.stringify(document, null, 2), { mode: 384 });
500
+ renameSync(temporary, filePath);
501
+ } catch (error) {
502
+ try {
503
+ unlinkSync2(temporary);
504
+ } catch {}
505
+ throw error;
506
+ }
507
+ }
508
+ function readDocument(filePath, now) {
509
+ if (!existsSync3(filePath))
510
+ return { version: 1, entries: [] };
511
+ const raw = JSON.parse(readFileSync4(filePath, "utf8"));
512
+ if (Array.isArray(raw)) {
513
+ return { version: 1, entries: pruneOutboxEntries(raw, now) };
514
+ }
515
+ if (typeof raw !== "object" || raw === null || raw.version !== 1 || !Array.isArray(raw.entries)) {
516
+ throw new Error(`Outbox \u6587\u4EF6\u683C\u5F0F\u65E0\u6548: ${filePath}`);
517
+ }
518
+ const entries = raw.entries;
519
+ return { version: 1, entries: pruneOutboxEntries(entries, now) };
520
+ }
521
+ function pruneOutboxEntries(entries, now = Date.now()) {
522
+ const indexed = entries.map((entry, index) => ({ entry, index }));
523
+ const retainedSent = new Set(indexed.filter(({ entry }) => entry.state === "sent" && now - entry.updatedAt <= OUTBOX_SENT_RETENTION_MS).sort((a, b) => b.entry.updatedAt - a.entry.updatedAt || b.index - a.index).slice(0, OUTBOX_SENT_RETENTION_LIMIT).map(({ index }) => index));
524
+ return indexed.filter(({ entry, index }) => entry.state !== "sent" || retainedSent.has(index)).sort((a, b) => a.entry.createdAt - b.entry.createdAt || a.index - b.index).map(({ entry }) => entry);
525
+ }
526
+ function createOutbox(options = {}) {
527
+ const filePath = options.filePath ?? process.env.QQ_OUTBOX_FILE ?? storageFile("outbox.json");
528
+ const pollIntervalMs = nonNegative(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, "pollIntervalMs");
529
+ const retryBaseMs = nonNegative(options.retryBaseMs, OUTBOX_DEFAULT_RETRY_BASE_MS, "retryBaseMs");
530
+ const retryMaxMs = nonNegative(options.retryMaxMs, OUTBOX_DEFAULT_RETRY_MAX_MS, "retryMaxMs");
531
+ const leaseMs = positive(options.leaseMs, DEFAULT_LEASE_MS, "leaseMs");
532
+ const lockWaitMs = positive(options.lockWaitMs, DEFAULT_LOCK_WAIT_MS, "lockWaitMs");
533
+ const lockStaleMs = positive(options.lockStaleMs, DEFAULT_LOCK_STALE_MS, "lockStaleMs");
534
+ const owner = `${process.pid}:${randomUUID()}`;
535
+ const handlers = new Map;
536
+ const inFlight = new Map;
537
+ const automatic = new Set;
538
+ let timer;
539
+ let stopped = false;
540
+ let flushing;
541
+ function withLock(fn) {
542
+ mkdirSync(dirname3(filePath), { recursive: true });
543
+ const lockPath = `${filePath}.lock`;
544
+ const token = `${owner}:${Date.now()}:${randomUUID()}`;
545
+ const deadline = Date.now() + lockWaitMs;
546
+ for (;; ) {
547
+ try {
548
+ const fd = openSync(lockPath, "wx", 384);
549
+ try {
550
+ writeFileSync2(fd, token);
551
+ } finally {
552
+ closeSync(fd);
553
+ }
554
+ break;
555
+ } catch (error) {
556
+ try {
557
+ if (Date.now() - statSync3(lockPath).mtimeMs > lockStaleMs)
558
+ unlinkSync2(lockPath);
559
+ } catch {}
560
+ if (Date.now() >= deadline)
561
+ throw new Error(`Outbox \u9501\u7B49\u5F85\u8D85\u65F6: ${errorText(error)}`);
562
+ Atomics.wait(sleepArray, 0, 0, 10);
563
+ }
564
+ }
565
+ try {
566
+ return fn();
567
+ } finally {
568
+ try {
569
+ if (readFileSync4(lockPath, "utf8") === token)
570
+ unlinkSync2(lockPath);
571
+ } catch {}
572
+ }
573
+ }
574
+ function mutate(fn) {
575
+ return withLock(() => {
576
+ const document = readDocument(filePath, Date.now());
577
+ const result = fn(document.entries);
578
+ document.entries = pruneOutboxEntries(document.entries);
579
+ atomicWrite(filePath, document);
580
+ return result;
581
+ });
582
+ }
583
+ function clone(entry) {
584
+ return JSON.parse(JSON.stringify(entry));
585
+ }
586
+ function clearLease(entry) {
587
+ delete entry.leaseOwner;
588
+ delete entry.leaseUntil;
589
+ }
590
+ function transitionRecovered(entry, now, maxAttempts) {
591
+ if (entry.state !== "sending")
592
+ return false;
593
+ const exhausted = maxAttempts !== undefined && entry.attempts >= maxAttempts;
594
+ entry.state = exhausted ? "failed" : "pending";
595
+ entry.updatedAt = now;
596
+ entry.nextAttemptAt = now;
597
+ entry.lastError = exhausted ? `${entry.lastError ? `${entry.lastError}; ` : ""}\u5D29\u6E83\u6062\u590D\u540E\u5DF2\u8FBE\u5230 maxAttempts=${maxAttempts}` : "\u8FDB\u7A0B\u5728 sending \u671F\u95F4\u9000\u51FA\uFF0C\u53D1\u9001\u7ED3\u679C\u672A\u77E5\uFF1B\u6309\u81F3\u5C11\u4E00\u6B21\u8BED\u4E49\u6062\u590D";
598
+ clearLease(entry);
599
+ return true;
600
+ }
601
+ async function recover(recoverOptions = {}) {
602
+ const now = Date.now();
603
+ return mutate((entries) => {
604
+ const recovered = [];
605
+ const exhausted = [];
606
+ for (const entry of entries) {
607
+ if (entry.state !== "sending")
608
+ continue;
609
+ if (inFlight.has(entry.id) && entry.leaseOwner?.startsWith(`${owner}:`))
610
+ continue;
611
+ const expired = entry.leaseUntil === undefined || entry.leaseUntil <= now;
612
+ if (!recoverOptions.ignoreLeases && !expired)
613
+ continue;
614
+ transitionRecovered(entry, now, recoverOptions.maxAttempts);
615
+ const snapshot = clone(entry);
616
+ if (snapshot.state === "failed")
617
+ exhausted.push(snapshot);
618
+ else
619
+ recovered.push(snapshot);
620
+ }
621
+ return { recovered, exhausted };
622
+ });
623
+ }
624
+ async function dispatchInternal(id, dispatchOptions) {
625
+ const handlerlessSnapshot = readDocument(filePath, Date.now()).entries.find((entry) => entry.id === id);
626
+ if (!handlerlessSnapshot)
627
+ return null;
628
+ const handler = handlers.get(handlerlessSnapshot.kind);
629
+ if (!handler)
630
+ return clone(handlerlessSnapshot);
631
+ const now = Date.now();
632
+ const token = `${owner}:${randomUUID()}`;
633
+ const claimed = withLock(() => {
634
+ const document = readDocument(filePath, now);
635
+ const entry = document.entries.find((candidate) => candidate.id === id);
636
+ if (!entry)
637
+ return { entry: null };
638
+ if (entry.state === "sent")
639
+ return { entry: clone(entry) };
640
+ if (entry.state === "sending" && entry.leaseUntil !== undefined && entry.leaseUntil > now) {
641
+ return { entry: null };
642
+ }
643
+ if ((entry.state === "pending" || entry.state === "failed" || entry.state === "sending") && !dispatchOptions.force && entry.nextAttemptAt > now) {
644
+ return { entry: clone(entry) };
645
+ }
646
+ const maxAttempts = dispatchOptions.maxAttempts;
647
+ if (maxAttempts !== undefined && entry.attempts >= maxAttempts) {
648
+ if (entry.state !== "failed") {
649
+ entry.state = "failed";
650
+ entry.updatedAt = now;
651
+ clearLease(entry);
652
+ atomicWrite(filePath, document);
653
+ }
654
+ return { entry: clone(entry) };
655
+ }
656
+ entry.state = "sending";
657
+ entry.attempts += 1;
658
+ entry.updatedAt = now;
659
+ entry.leaseOwner = token;
660
+ entry.leaseUntil = now + leaseMs;
661
+ delete entry.lastError;
662
+ atomicWrite(filePath, document);
663
+ return { entry: clone(entry), token };
664
+ });
665
+ if (!claimed.entry || !("token" in claimed))
666
+ return claimed.entry;
667
+ try {
668
+ const receipt = await handler(clone(claimed.entry));
669
+ const persistedReceipt = receipt === undefined ? null : jsonSnapshot(receipt, "receipt");
670
+ return mutate((entries) => {
671
+ const current = entries.find((entry) => entry.id === id);
672
+ if (!current || current.leaseOwner !== token)
673
+ return current ? clone(current) : null;
674
+ const completedAt = Date.now();
675
+ current.state = "sent";
676
+ current.updatedAt = completedAt;
677
+ current.receipt = persistedReceipt;
678
+ delete current.lastError;
679
+ clearLease(current);
680
+ return clone(current);
681
+ });
682
+ } catch (error) {
683
+ const failed = mutate((entries) => {
684
+ const current = entries.find((entry) => entry.id === id);
685
+ if (!current || current.leaseOwner !== token)
686
+ return current ? clone(current) : null;
687
+ const failedAt = Date.now();
688
+ current.state = "failed";
689
+ current.updatedAt = failedAt;
690
+ current.lastError = errorText(error);
691
+ current.nextAttemptAt = failedAt + Math.min(retryMaxMs, retryBaseMs * 2 ** Math.max(0, current.attempts - 1));
692
+ clearLease(current);
693
+ return clone(current);
694
+ });
695
+ if (automatic.has(id))
696
+ return failed;
697
+ throw error;
698
+ }
699
+ }
700
+ function dispatch(id, dispatchOptions = {}) {
701
+ const existing = inFlight.get(id);
702
+ if (existing)
703
+ return existing;
704
+ const promise = dispatchInternal(id, dispatchOptions).finally(() => {
705
+ if (inFlight.get(id) === promise)
706
+ inFlight.delete(id);
707
+ });
708
+ inFlight.set(id, promise);
709
+ return promise;
710
+ }
711
+ async function flush(flushOptions = {}) {
712
+ if (flushing)
713
+ return flushing;
714
+ const run = (async () => {
715
+ const results = new Map;
716
+ for (;; ) {
717
+ await recover({ maxAttempts: flushOptions.maxAttempts });
718
+ const entries = readDocument(filePath, Date.now()).entries;
719
+ const candidates = entries.filter((entry) => {
720
+ if (entry.state !== "pending" && entry.state !== "failed")
721
+ return false;
722
+ if (!handlers.has(entry.kind))
723
+ return false;
724
+ if (flushOptions.maxAttempts !== undefined && entry.attempts >= flushOptions.maxAttempts)
725
+ return false;
726
+ return flushOptions.force || flushOptions.wait || entry.nextAttemptAt <= Date.now();
727
+ });
728
+ const settled = await Promise.all(candidates.map(async (entry) => {
729
+ const result = await dispatch(entry.id, flushOptions);
730
+ if (result)
731
+ results.set(entry.id, result);
732
+ return result;
733
+ }));
734
+ if (!flushOptions.wait)
735
+ break;
736
+ const after = readDocument(filePath, Date.now()).entries;
737
+ const active = after.filter((entry) => (entry.state === "pending" || entry.state === "failed") && handlers.has(entry.kind) && (flushOptions.maxAttempts === undefined || entry.attempts < flushOptions.maxAttempts));
738
+ const waitingLocal = after.some((entry) => entry.state === "sending" && inFlight.has(entry.id));
739
+ if (active.length === 0 && !waitingLocal)
740
+ break;
741
+ if (settled.length === 0 && !waitingLocal) {
742
+ const next = active.reduce((minimum, entry) => Math.min(minimum, entry.nextAttemptAt), Number.POSITIVE_INFINITY);
743
+ if (Number.isFinite(next))
744
+ await delay(Math.max(1, next - Date.now()));
745
+ else
746
+ break;
747
+ } else {
748
+ await delay(1);
749
+ }
750
+ }
751
+ return [...results.values()];
752
+ })();
753
+ flushing = run;
754
+ try {
755
+ return await run;
756
+ } finally {
757
+ if (flushing === run)
758
+ flushing = undefined;
759
+ }
760
+ }
761
+ async function drain() {
762
+ while (inFlight.size > 0) {
763
+ const pending = [...inFlight.values()];
764
+ const outcomes = await Promise.allSettled(pending);
765
+ const rejection = outcomes.find((outcome) => outcome.status === "rejected");
766
+ if (rejection)
767
+ throw rejection.reason;
768
+ }
769
+ }
770
+ return {
771
+ filePath,
772
+ register(kind, handler) {
773
+ if (!kind)
774
+ throw new Error("Outbox kind \u4E0D\u80FD\u4E3A\u7A7A");
775
+ handlers.set(kind, handler);
776
+ return () => {
777
+ if (handlers.get(kind) === handler)
778
+ handlers.delete(kind);
779
+ };
780
+ },
781
+ async enqueue(input) {
782
+ if (!input.kind)
783
+ throw new Error("Outbox kind \u4E0D\u80FD\u4E3A\u7A7A");
784
+ if (input.payload === undefined)
785
+ throw new Error("Outbox payload \u5FC5\u987B\u662F JSON \u503C\uFF0C\u4E0D\u80FD\u4E3A undefined");
786
+ if (input.nextAttemptAt !== undefined && !Number.isFinite(input.nextAttemptAt)) {
787
+ throw new Error("Outbox nextAttemptAt \u5FC5\u987B\u662F\u6709\u9650\u65F6\u95F4\u6233");
788
+ }
789
+ const persistedCtx = jsonSnapshot(input.ctx, "ctx");
790
+ const persistedPayload = jsonSnapshot(input.payload, "payload");
791
+ const now = Date.now();
792
+ const id = input.id ?? randomUUID();
793
+ const entry = mutate((entries) => {
794
+ const existing = entries.find((candidate) => candidate.id === id);
795
+ if (existing)
796
+ return clone(existing);
797
+ const created = {
798
+ id,
799
+ kind: input.kind,
800
+ ctx: persistedCtx,
801
+ payload: persistedPayload,
802
+ ...input.sessionId !== undefined ? { sessionId: input.sessionId } : {},
803
+ ...input.turnId !== undefined ? { turnId: input.turnId } : {},
804
+ state: "pending",
805
+ attempts: 0,
806
+ createdAt: now,
807
+ updatedAt: now,
808
+ nextAttemptAt: input.nextAttemptAt ?? now
809
+ };
810
+ entries.push(created);
811
+ return clone(created);
812
+ });
813
+ automatic.add(id);
814
+ dispatch(id).finally(() => automatic.delete(id)).catch(() => {});
815
+ return entry;
816
+ },
817
+ dispatch,
818
+ recover,
819
+ flush,
820
+ async start(startOptions = {}) {
821
+ stopped = false;
822
+ if (startOptions.recover !== false)
823
+ await recover({ maxAttempts: startOptions.maxAttempts });
824
+ if (pollIntervalMs === 0 || timer)
825
+ return;
826
+ timer = setInterval(() => {
827
+ if (stopped)
828
+ return;
829
+ flush({ maxAttempts: startOptions.maxAttempts }).catch(() => {});
830
+ }, pollIntervalMs);
831
+ timer.unref?.();
832
+ flush({ maxAttempts: startOptions.maxAttempts }).catch(() => {});
833
+ },
834
+ stop() {
835
+ stopped = true;
836
+ if (timer)
837
+ clearInterval(timer);
838
+ timer = undefined;
839
+ },
840
+ drain,
841
+ async list() {
842
+ return readDocument(filePath, Date.now()).entries.map((entry) => clone(entry));
843
+ },
844
+ async get(id) {
845
+ const entry = readDocument(filePath, Date.now()).entries.find((candidate) => candidate.id === id);
846
+ return entry ? clone(entry) : undefined;
847
+ }
848
+ };
849
+ }
850
+
851
+ // src/config.ts
852
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
853
+ import { join as join5 } from "path";
854
+ import { homedir as homedir4 } from "os";
855
+ var CONFIG_DIR = join5(homedir4(), ".openqq");
856
+ var ENV_FILE = join5(CONFIG_DIR, ".env");
857
+ function loadEnvFile(path) {
858
+ const content = readFileSync5(path, "utf-8");
859
+ for (const line of content.split(`
860
+ `)) {
861
+ const trimmed = line.trim();
862
+ if (!trimmed || trimmed.startsWith("#"))
863
+ continue;
864
+ const eqIdx = trimmed.indexOf("=");
865
+ if (eqIdx < 0)
866
+ continue;
867
+ const key = trimmed.slice(0, eqIdx).trim();
868
+ const val = trimmed.slice(eqIdx + 1).trim();
869
+ if (!process.env[key]) {
870
+ process.env[key] = val;
871
+ }
872
+ }
873
+ }
874
+
875
+ // src/core/notify-sink.ts
876
+ function resolveNotifyRecipients(configured, explicit) {
877
+ const users = [...configured];
878
+ if (explicit)
879
+ return users.includes(explicit) ? explicit : "";
880
+ return users.length === 1 ? users[0] : "";
881
+ }
882
+ function defaultOutboxPath() {
883
+ return storageFile("outbox.json");
884
+ }
885
+
886
+ // src/cli/notify.ts
887
+ var NOTIFY_DEFAULT_MAX_CHARS = 1500;
888
+ function parseArgs(argv) {
889
+ const parsed = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false };
890
+ for (let i = 0;i < argv.length; i++) {
891
+ const a = argv[i];
892
+ const next = argv[i + 1];
893
+ switch (a) {
894
+ case "--text":
895
+ parsed.text = next;
896
+ i++;
897
+ break;
898
+ case "--file":
899
+ parsed.filePath = next;
900
+ i++;
901
+ break;
902
+ case "--stdin":
903
+ parsed.stdin = true;
904
+ break;
905
+ case "--user":
906
+ parsed.user = next;
907
+ i++;
908
+ break;
909
+ case "--id":
910
+ parsed.id = next;
911
+ i++;
912
+ break;
913
+ case "--max-chars":
914
+ parsed.maxChars = Number(next);
915
+ i++;
916
+ break;
917
+ case "--ttl-hours":
918
+ parsed.ttlHours = Number(next);
919
+ i++;
920
+ break;
921
+ case "--dry-run":
922
+ parsed.dryRun = true;
923
+ break;
924
+ case "--json":
925
+ parsed.json = true;
926
+ break;
927
+ case "--help":
928
+ case "-h":
929
+ parsed.help = true;
930
+ i++;
931
+ break;
932
+ default:
933
+ throw new Error(`\u672A\u77E5\u53C2\u6570\uFF1A${a}\uFF08\u7528\u6CD5\uFF1Aopenqq notify --text "\u2026" | --file <p> | --stdin\uFF09`);
934
+ }
935
+ }
936
+ if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
937
+ throw new Error("\u5FC5\u987B\u63D0\u4F9B\u6B63\u6587\u6765\u6E90\uFF1A--text / --file / --stdin \u4E09\u9009\u4E00");
938
+ }
939
+ if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
940
+ throw new Error("--max-chars \u5FC5\u987B\u662F >= 0 \u7684\u6709\u9650\u6570\uFF080=\u4E0D\u622A\u65AD\uFF09");
941
+ }
942
+ return parsed;
943
+ }
944
+ function resolveUser(envAllowed, explicit) {
945
+ return resolveNotifyRecipients(envAllowed, explicit);
946
+ }
947
+ function readBody(parsed) {
948
+ if (parsed.text !== undefined)
949
+ return parsed.text;
950
+ if (parsed.filePath !== undefined) {
951
+ if (parsed.filePath === "-")
952
+ return readFileSync6(0, "utf8");
953
+ if (!existsSync5(parsed.filePath))
954
+ throw new Error(`--file \u4E0D\u5B58\u5728\uFF1A${parsed.filePath}`);
955
+ return readFileSync6(parsed.filePath, "utf8");
956
+ }
957
+ if (parsed.stdin)
958
+ return readFileSync6(0, "utf8");
959
+ return "";
960
+ }
961
+ async function runNotifyCli(argv, options = {}) {
962
+ const now = options.now ?? Date.now();
963
+ const parsed = parseArgs(argv);
964
+ if (parsed.help) {
965
+ const help = [
966
+ '\u7528\u6CD5\uFF1Aopenqq notify --text "\u2026" | --file <\u8DEF\u5F84> | --stdin',
967
+ " --user <openid> \u6536\u4EF6\u4EBA\uFF1B\u7F3A\u7701\u53D6 ALLOWED_USERS \u552F\u4E00\u9879\uFF08\u591A\u7528\u6237\u5FC5\u987B\u663E\u5F0F\u6307\u5B9A\uFF09",
968
+ " --id <key> \u5E42\u7B49\u952E\uFF08\u540C key \u4E0D\u91CD\u590D\u6295\u9012\uFF09",
969
+ " --max-chars <n> \u622A\u65AD\u4E0A\u9650\uFF0C\u9ED8\u8BA4 1500\uFF0C0 \u4E0D\u622A\u65AD",
970
+ " --ttl-hours <n> \u961F\u5217\u7B49\u5F85\u4E0A\u9650\uFF0C\u9ED8\u8BA4 24\uFF08env QQ_NOTIFY_TTL_HOURS \u515C\u5E95\uFF09",
971
+ " --dry-run / --json \u4E0D\u5165\u961F / \u673A\u5668\u53EF\u8BFB\u8F93\u51FA"
972
+ ].join(`
973
+ `);
974
+ console.log(help);
975
+ return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" };
976
+ }
977
+ if (!options.env && existsSync5(ENV_FILE))
978
+ loadEnvFile(ENV_FILE);
979
+ const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "").split(/[,\s]+/).filter(Boolean);
980
+ const user = resolveUser(allowedUsers, parsed.user);
981
+ if (!user) {
982
+ throw new Error(allowedUsers.length === 0 ? "ALLOWED_USERS \u4E3A\u7A7A\u2014\u2014fail-closed \u4E0D\u5141\u8BB8\u65E0\u540D\u5355\u5165\u961F\uFF08\u5148\u5728 ~/.openqq/.env \u914D\u7F6E\uFF09" : parsed.user ? `\u6536\u4EF6\u4EBA\u4E0D\u5728\u540D\u5355\uFF1A${parsed.user}\uFF08ALLOWED_USERS \u5171 ${allowedUsers.length} \u9879\uFF0C--user \u5FC5\u987B\u7CBE\u786E\u547D\u4E2D\uFF1B\u8BF7\u6838\u5BF9 openid\uFF09` : "\u591A\u7528\u6237\u540D\u5355\u5FC5\u987B\u7528 --user <openid> \u663E\u5F0F\u6307\u5B9A\u6536\u4EF6\u4EBA");
983
+ }
984
+ const raw = readBody(parsed);
985
+ const max = parsed.maxChars;
986
+ const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}\u2026` : raw;
987
+ const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
988
+ const filePath = options.filePath ?? defaultOutboxPath();
989
+ if (parsed.dryRun) {
990
+ return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true, json: parsed.json };
991
+ }
992
+ const ttlHours = parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24);
993
+ const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0 ? now + ttlHours * 60 * 60 * 1000 : now;
994
+ const outbox = createOutbox({ filePath, pollIntervalMs: 0 });
995
+ const entry = await outbox.enqueue({
996
+ ...parsed.id ? { id: parsed.id } : {},
997
+ kind: "notify",
998
+ payload: { text: content },
999
+ ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
1000
+ sessionId: "",
1001
+ nextAttemptAt
1002
+ });
1003
+ return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false, json: parsed.json };
1004
+ }
1005
+
136
1006
  // src/plugin-entry.ts
137
- var ENV_FILE = join3(homedir3(), ".openqq", ".env");
1007
+ var ENV_FILE2 = join6(homedir5(), ".openqq", ".env");
138
1008
  var CHECK_INTERVAL_MS = (() => {
139
1009
  const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000");
140
1010
  return Number.isFinite(n) && n > 0 ? n : 300000;
141
1011
  })();
142
- var PROBE_FILE = join3(homedir3(), ".openqq", "opencode-events.jsonl");
1012
+ var PROBE_FILE = join6(homedir5(), ".openqq", "opencode-events.jsonl");
143
1013
  var PROBE_ROTATE_BYTES = 5 * 1024 * 1024;
144
1014
  function probeAppend(line) {
145
1015
  try {
146
- if (existsSync2(PROBE_FILE) && statSync2(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
147
- renameSync(PROBE_FILE, PROBE_FILE + ".1");
1016
+ if (existsSync6(PROBE_FILE) && statSync4(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
1017
+ renameSync2(PROBE_FILE, PROBE_FILE + ".1");
148
1018
  }
149
1019
  appendFileSync(PROBE_FILE, line + `
150
1020
  `);
@@ -162,28 +1032,28 @@ var plugin_entry_default = Plugin.define({
162
1032
  };
163
1033
  const ensure = () => {
164
1034
  try {
165
- const appId = readDotEnvField(ENV_FILE, "QQ_APP_ID");
1035
+ const appId = readDotEnvField(ENV_FILE2, "QQ_APP_ID");
166
1036
  if (!appId) {
167
1037
  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");
168
1038
  return;
169
1039
  }
170
- if (isInstanceAlive(appId)) {
171
- lastBlocker = null;
172
- return;
173
- }
174
- const entry = resolveBotEntry(fileURLToPath(import.meta.url));
175
- if (!entry) {
176
- 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");
177
- return;
178
- }
179
- const runtime = resolveRuntime();
180
- if (!runtime) {
181
- 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");
182
- return;
183
- }
184
- const pid = spawnBotDetached(buildLaunchPlan(runtime, entry, botLogPath()));
185
- console.log(`[opencode-qqbot] bot \u5DF2\u62C9\u8D77\uFF08pid=${pid}\uFF0Cruntime=${runtime}\uFF0Centry=${entry}\uFF09`);
186
- lastBlocker = null;
1040
+ superviseOnce({
1041
+ paths: botWatchdogPaths(appId),
1042
+ spawn: () => startBot(fileURLToPath2(import.meta.url), (line) => console.log(line)),
1043
+ log: (line) => console.log(line),
1044
+ alert: (message) => {
1045
+ console.warn(message);
1046
+ runNotifyCli(["--text", message, "--id", `supervisor-giveup-${Date.now()}`]).catch(() => {});
1047
+ }
1048
+ }).then((result) => {
1049
+ if (result.action === "restart") {
1050
+ console.log(`[opencode-qqbot] bot \u5DF2\u62C9\u8D77\uFF08${result.detail}\uFF09`);
1051
+ }
1052
+ if (result.action === "ok" || result.action === "restart")
1053
+ lastBlocker = null;
1054
+ }).catch((error) => {
1055
+ console.error("[opencode-qqbot] \u5DE1\u68C0\u5931\u8D25:", error instanceof Error ? error.message : error);
1056
+ });
187
1057
  } catch (error) {
188
1058
  console.error("[opencode-qqbot] \u62C9\u8D77\u5931\u8D25:", error instanceof Error ? error.message : error);
189
1059
  }
@@ -191,7 +1061,7 @@ var plugin_entry_default = Plugin.define({
191
1061
  ensure();
192
1062
  const timer = setInterval(ensure, CHECK_INTERVAL_MS);
193
1063
  let probeAbort = null;
194
- if (readDotEnvField(ENV_FILE, "QQ_EVENT_PROBE") === "true") {
1064
+ if (readDotEnvField(ENV_FILE2, "QQ_EVENT_PROBE") === "true") {
195
1065
  probeAbort = new AbortController;
196
1066
  const signal = probeAbort.signal;
197
1067
  (async () => {