@linjz/opencode-qqbot 0.3.20 → 0.3.21

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.
@@ -4,7 +4,7 @@ import { dirname as dirname4, join as join6 } from "path";
4
4
  import { fileURLToPath as fileURLToPath2 } from "url";
5
5
 
6
6
  // src/core/bot-control.ts
7
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
7
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "fs";
8
8
  import { dirname as dirname3, join as join4 } from "path";
9
9
  import { homedir as homedir3 } from "os";
10
10
  import { fileURLToPath } from "url";
@@ -354,6 +354,33 @@ function readJson(path, fallback) {
354
354
  return fallback;
355
355
  }
356
356
  }
357
+ function defaultHoldPath() {
358
+ return join3(homedir2(), ".openqq", "supervisor-hold.json");
359
+ }
360
+ function readSupervisorHold(path = defaultHoldPath()) {
361
+ try {
362
+ const raw = JSON.parse(readFileSync3(path, "utf-8"));
363
+ if (raw?.version === 1 && typeof raw.reason === "string" && typeof raw.by === "string" && typeof raw.at === "number") {
364
+ return raw;
365
+ }
366
+ } catch {}
367
+ return null;
368
+ }
369
+ function writeSupervisorHold(path, reason, by) {
370
+ try {
371
+ writeFileSync2(path, JSON.stringify({ version: 1, reason, by, at: Date.now() }));
372
+ } catch {}
373
+ }
374
+ function clearSupervisorHold(path) {
375
+ try {
376
+ if (!existsSync3(path))
377
+ return false;
378
+ unlinkSync2(path);
379
+ return true;
380
+ } catch {
381
+ return false;
382
+ }
383
+ }
357
384
  async function superviseOnce(deps) {
358
385
  const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY;
359
386
  const now = deps.now?.() ?? Date.now();
@@ -390,7 +417,25 @@ async function superviseOnce(deps) {
390
417
  try {
391
418
  const health = readBotHealth(deps.paths, now);
392
419
  const state = readJson(statePath, { restartLog: [] });
420
+ const holdPath = deps.holdPath ?? defaultHoldPath();
421
+ const hold = readSupervisorHold(holdPath);
422
+ if (hold && (!deps.request || deps.request === "health-check")) {
423
+ if (health.lockPid === null || health.pidAlive === false) {
424
+ log(`[supervisor] manual-stop hold 生效(${hold.reason}),跳过拉起`);
425
+ return { action: "yield", detail: `manual-stop hold 生效:${hold.reason}`, killedPid: null, spawnedPid: null };
426
+ }
427
+ if (clearSupervisorHold(holdPath)) {
428
+ log(`[supervisor] manual-stop hold 失效:bot 已在运行,恢复常规监督`);
429
+ }
430
+ }
431
+ if (deps.request === "manual-restart" && hold) {
432
+ if (clearSupervisorHold(holdPath))
433
+ log(`[supervisor] manual-stop hold 已解除(openqq restart)`);
434
+ }
393
435
  let action = decideSupervise(health, state, now, policy);
436
+ if (deps.request === "manual-stop") {
437
+ action = health.lockPid !== null && health.pidAlive !== false ? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求停止(openqq stop)" } : { kind: "spawn", reason: "人工请求停止(bot 未运行,仅清锁)" };
438
+ }
394
439
  if (deps.request === "manual-restart" && action.kind === "ok") {
395
440
  const windowStart = now - policy.windowMs;
396
441
  const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
@@ -434,7 +479,7 @@ async function superviseOnce(deps) {
434
479
  let killedPid = null;
435
480
  if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
436
481
  const pid = action.killPid;
437
- if (deps.request !== "manual-restart") {
482
+ if (deps.request !== "manual-restart" && deps.request !== "manual-stop") {
438
483
  await sleep(300);
439
484
  const recheck = readBotHealth(deps.paths, Date.now());
440
485
  const recheckFresh = recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS;
@@ -484,6 +529,31 @@ async function superviseOnce(deps) {
484
529
  if (cleared.length > 0)
485
530
  audit(`清锁:${cleared.join("、")}(${action.reason})`);
486
531
  } catch {}
532
+ if (deps.request === "manual-stop") {
533
+ writeSupervisorHold(holdPath, action.reason, "openqq stop");
534
+ const detail = killedPid ? `${action.reason};已优雅停 pid=${killedPid};锁已清;hold 已立(巡检不拉起)` : `${action.reason};锁已清;hold 已立(巡检不拉起)`;
535
+ if (killedPid !== null) {
536
+ appendKillLog({
537
+ kind: "decision",
538
+ reason: action.reason,
539
+ health: {
540
+ lockPid: health.lockPid,
541
+ pidAlive: health.pidAlive,
542
+ heartbeatAgeMs: health.heartbeatAgeMs,
543
+ lockAgeMs: health.lockAgeMs
544
+ },
545
+ killedPid,
546
+ killEscalation: "TERM",
547
+ spawnedPid: null,
548
+ restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
549
+ livenessVerdict: "stopped",
550
+ at: Date.now()
551
+ });
552
+ }
553
+ audit(`主动停:${detail}`);
554
+ log(`[supervisor] 主动停:${detail}`);
555
+ return { action: "stopped", detail, killedPid, spawnedPid: null };
556
+ }
487
557
  const spawnedPid = deps.spawn();
488
558
  state.restartLog.push(Date.now());
489
559
  state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
@@ -598,18 +668,30 @@ function readAppId(envPath = join4(homedir3(), ".openqq", ".env")) {
598
668
  }
599
669
  return null;
600
670
  }
601
- function inflightPath() {
602
- return join4(homedir3(), ".openqq", "inflight.json");
603
- }
604
- function countInflight(path = inflightPath()) {
671
+ function inflightPaths() {
672
+ const root = join4(homedir3(), ".openqq");
673
+ const paths = [join4(root, "inflight.json")];
605
674
  try {
606
- const raw = JSON.parse(readFileSync4(path, "utf-8"));
607
- if (!Array.isArray(raw))
608
- return 0;
609
- return raw.filter((e) => e.state === "inflight").length;
610
- } catch {
611
- return 0;
675
+ for (const name of readdirSync2(join4(root, "roles"))) {
676
+ const path = join4(root, "roles", name, "inflight.json");
677
+ if (existsSync4(path))
678
+ paths.push(path);
679
+ }
680
+ } catch {}
681
+ return paths;
682
+ }
683
+ function countInflight(paths = inflightPaths()) {
684
+ const list = Array.isArray(paths) ? paths : [paths];
685
+ let total = 0;
686
+ for (const path of list) {
687
+ try {
688
+ const raw = JSON.parse(readFileSync4(path, "utf-8"));
689
+ if (!Array.isArray(raw))
690
+ continue;
691
+ total += raw.filter((e) => e.state === "inflight").length;
692
+ } catch {}
612
693
  }
694
+ return total;
613
695
  }
614
696
  async function waitUntilIdle(opts) {
615
697
  const timeoutMs = opts?.timeoutMs ?? 60 * 60000;
@@ -672,6 +754,36 @@ async function restartBot(opts) {
672
754
  return { action: "skipped", killedPid: null, spawnedPid: null, reason: `无需动作:${r.detail}` };
673
755
  }
674
756
  }
757
+ async function stopBot(opts = {}) {
758
+ const log = opts.log ?? (() => {});
759
+ const appId = readAppId();
760
+ if (!appId)
761
+ throw new Error("缺少 ~/.openqq/.env 的角色凭据(QQ_APP_ID 或 QQ_BOTS 首角色),无法定位实例锁");
762
+ const idle = await waitUntilIdle({
763
+ timeoutMs: opts.timeoutMs,
764
+ onWait: (n, elapsed) => log(`[bot-control] 仍在途 ${n} 条(已等 ${Math.round(elapsed / 1000)}s),继续等待空闲后停止`)
765
+ });
766
+ if (!idle) {
767
+ log("[bot-control] 等待空闲超时:本次不停止(请稍后重试,或先处理在途回合)");
768
+ return { action: "skipped", killedPid: null, reason: "等待空闲超时" };
769
+ }
770
+ const r = await superviseOnce({
771
+ paths: botWatchdogPaths(appId),
772
+ request: "manual-stop",
773
+ spawn: () => {
774
+ throw new Error("manual-stop 不应拉起 bot");
775
+ },
776
+ log
777
+ });
778
+ if (r.action === "stopped") {
779
+ return {
780
+ action: "stopped",
781
+ killedPid: r.killedPid,
782
+ reason: r.killedPid ? "已优雅停止并持有(巡检不拉起,restart 解除)" : "bot 未运行,已清锁并持有(巡检不拉起)"
783
+ };
784
+ }
785
+ return { action: "skipped", killedPid: null, reason: r.detail };
786
+ }
675
787
 
676
788
  // src/cli/service-main.ts
677
789
  import { spawnSync as spawnSync2 } from "child_process";
@@ -948,6 +1060,16 @@ async function main() {
948
1060
  process.exitCode = res.action === "restarted" ? 0 : 2;
949
1061
  return;
950
1062
  }
1063
+ if (cmd === "stop") {
1064
+ const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"));
1065
+ const res = await stopBot({
1066
+ timeoutMs: Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60000 : undefined,
1067
+ log: (line) => console.log(line)
1068
+ });
1069
+ console.log(`[stop] ${res.action}(${res.reason})killed=${res.killedPid ?? "-"}`);
1070
+ process.exitCode = res.action === "stopped" ? 0 : 2;
1071
+ return;
1072
+ }
951
1073
  if (cmd === "service") {
952
1074
  const spec = {
953
1075
  runtimeCmd: runtimeCommand(),
@@ -956,8 +1078,22 @@ async function main() {
956
1078
  };
957
1079
  if (sub === "install")
958
1080
  return printResult("service install", serviceInstall(spec));
959
- if (sub === "uninstall")
960
- return printResult("service uninstall", serviceUninstall());
1081
+ if (sub === "uninstall") {
1082
+ const uninstall = serviceUninstall();
1083
+ printResult("service uninstall", uninstall);
1084
+ if (!process.argv.includes("--stop-bot"))
1085
+ return;
1086
+ const stop = await stopBot({
1087
+ timeoutMs: (() => {
1088
+ const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"));
1089
+ return Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60000 : undefined;
1090
+ })(),
1091
+ log: (line) => console.log(line)
1092
+ });
1093
+ console.log(`[stop] ${stop.action}(${stop.reason})killed=${stop.killedPid ?? "-"}`);
1094
+ process.exitCode = stop.action === "stopped" ? uninstall.ok ? 0 : 1 : 2;
1095
+ return;
1096
+ }
961
1097
  if (sub === "status") {
962
1098
  const r = serviceStatus();
963
1099
  return printResult("service status", {
@@ -967,11 +1103,11 @@ script=${spec.scriptPath}
967
1103
  ${r.detail}`
968
1104
  });
969
1105
  }
970
- console.error("用法:openqq service install|uninstall|status");
1106
+ console.error("用法:openqq service install|uninstall [--stop-bot]|status");
971
1107
  process.exitCode = 2;
972
1108
  return;
973
1109
  }
974
- console.error("用法:openqq-cli restart [--force] [--timeout-min N] | service install|uninstall|status");
1110
+ console.error("用法:openqq-cli restart [--force] [--timeout-min N] | stop [--timeout-min N] | service install|uninstall [--stop-bot]|status");
975
1111
  process.exitCode = 2;
976
1112
  }
977
1113
  main().catch((error) => {
@@ -199,6 +199,33 @@ function readJson(path, fallback) {
199
199
  return fallback;
200
200
  }
201
201
  }
202
+ function defaultHoldPath() {
203
+ return join2(homedir(), ".openqq", "supervisor-hold.json");
204
+ }
205
+ function readSupervisorHold(path = defaultHoldPath()) {
206
+ try {
207
+ const raw = JSON.parse(readFileSync2(path, "utf-8"));
208
+ if (raw?.version === 1 && typeof raw.reason === "string" && typeof raw.by === "string" && typeof raw.at === "number") {
209
+ return raw;
210
+ }
211
+ } catch {}
212
+ return null;
213
+ }
214
+ function writeSupervisorHold(path, reason, by) {
215
+ try {
216
+ writeFileSync2(path, JSON.stringify({ version: 1, reason, by, at: Date.now() }));
217
+ } catch {}
218
+ }
219
+ function clearSupervisorHold(path) {
220
+ try {
221
+ if (!existsSync2(path))
222
+ return false;
223
+ unlinkSync2(path);
224
+ return true;
225
+ } catch {
226
+ return false;
227
+ }
228
+ }
202
229
  async function superviseOnce(deps) {
203
230
  const policy = deps.policy ?? DEFAULT_SUPERVISOR_POLICY;
204
231
  const now = deps.now?.() ?? Date.now();
@@ -235,7 +262,25 @@ async function superviseOnce(deps) {
235
262
  try {
236
263
  const health = readBotHealth(deps.paths, now);
237
264
  const state = readJson(statePath, { restartLog: [] });
265
+ const holdPath = deps.holdPath ?? defaultHoldPath();
266
+ const hold = readSupervisorHold(holdPath);
267
+ if (hold && (!deps.request || deps.request === "health-check")) {
268
+ if (health.lockPid === null || health.pidAlive === false) {
269
+ log(`[supervisor] manual-stop hold 生效(${hold.reason}),跳过拉起`);
270
+ return { action: "yield", detail: `manual-stop hold 生效:${hold.reason}`, killedPid: null, spawnedPid: null };
271
+ }
272
+ if (clearSupervisorHold(holdPath)) {
273
+ log(`[supervisor] manual-stop hold 失效:bot 已在运行,恢复常规监督`);
274
+ }
275
+ }
276
+ if (deps.request === "manual-restart" && hold) {
277
+ if (clearSupervisorHold(holdPath))
278
+ log(`[supervisor] manual-stop hold 已解除(openqq restart)`);
279
+ }
238
280
  let action = decideSupervise(health, state, now, policy);
281
+ if (deps.request === "manual-stop") {
282
+ action = health.lockPid !== null && health.pidAlive !== false ? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求停止(openqq stop)" } : { kind: "spawn", reason: "人工请求停止(bot 未运行,仅清锁)" };
283
+ }
239
284
  if (deps.request === "manual-restart" && action.kind === "ok") {
240
285
  const windowStart = now - policy.windowMs;
241
286
  const recentRestarts = state.restartLog.filter((t) => t > windowStart).length;
@@ -279,7 +324,7 @@ async function superviseOnce(deps) {
279
324
  let killedPid = null;
280
325
  if (action.kind === "grace-kill-spawn" && action.killPid !== process.pid) {
281
326
  const pid = action.killPid;
282
- if (deps.request !== "manual-restart") {
327
+ if (deps.request !== "manual-restart" && deps.request !== "manual-stop") {
283
328
  await sleep(300);
284
329
  const recheck = readBotHealth(deps.paths, Date.now());
285
330
  const recheckFresh = recheck.heartbeatAgeMs !== null && recheck.heartbeatAgeMs <= HEARTBEAT_STALE_MS;
@@ -329,6 +374,31 @@ async function superviseOnce(deps) {
329
374
  if (cleared.length > 0)
330
375
  audit(`清锁:${cleared.join("、")}(${action.reason})`);
331
376
  } catch {}
377
+ if (deps.request === "manual-stop") {
378
+ writeSupervisorHold(holdPath, action.reason, "openqq stop");
379
+ const detail = killedPid ? `${action.reason};已优雅停 pid=${killedPid};锁已清;hold 已立(巡检不拉起)` : `${action.reason};锁已清;hold 已立(巡检不拉起)`;
380
+ if (killedPid !== null) {
381
+ appendKillLog({
382
+ kind: "decision",
383
+ reason: action.reason,
384
+ health: {
385
+ lockPid: health.lockPid,
386
+ pidAlive: health.pidAlive,
387
+ heartbeatAgeMs: health.heartbeatAgeMs,
388
+ lockAgeMs: health.lockAgeMs
389
+ },
390
+ killedPid,
391
+ killEscalation: "TERM",
392
+ spawnedPid: null,
393
+ restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
394
+ livenessVerdict: "stopped",
395
+ at: Date.now()
396
+ });
397
+ }
398
+ audit(`主动停:${detail}`);
399
+ log(`[supervisor] 主动停:${detail}`);
400
+ return { action: "stopped", detail, killedPid, spawnedPid: null };
401
+ }
332
402
  const spawnedPid = deps.spawn();
333
403
  state.restartLog.push(Date.now());
334
404
  state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2);
@@ -399,7 +469,7 @@ async function superviseOnce(deps) {
399
469
  }
400
470
 
401
471
  // src/core/bot-control.ts
402
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
472
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "fs";
403
473
  import { dirname as dirname3, join as join4 } from "path";
404
474
  import { homedir as homedir3 } from "os";
405
475
  import { fileURLToPath } from "url";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
- {
1
+ {
2
2
  "name": "@linjz/opencode-qqbot",
3
- "version": "0.3.20",
3
+ "version": "0.3.21",
4
4
  "type": "module",
5
5
  "description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
6
6
  "exports": {
package/src/bridge.ts CHANGED
@@ -9,7 +9,7 @@ import { homedir } from "os"
9
9
  import type { Config } from "./config.js"
10
10
  import type { MessageContext } from "./qq/types.js"
11
11
  import { getAccessToken, sendC2CInputNotify, sendC2CMessage, sendGroupMessage } from "./qq/api.js"
12
- import { prepareQQAttachments, augmentPromptWithAttachments, purgeOldQQImages } from "./qq/media.js"
12
+ import { prepareQQAttachments, augmentPromptWithAttachments, purgeOldQQImages, purgeOldQQFiles } from "./qq/media.js"
13
13
  import { normalizeForCommandGate } from "./qq/gateway.js"
14
14
  import type { OpencodeClient, SessionMessage, PermissionRequest } from "./opencode/client.js"
15
15
  import {
@@ -1095,9 +1095,17 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1095
1095
  // 会话隔离:审批裁决放行该用户全部有货 lane(drainQueue 自身对忙 lane 空转安全)
1096
1096
  for (const lk of msgQueue.laneKeysOf(userId)) void drainQueue(userId, sessionIdOfLane(lk))
1097
1097
  },
1098
- // A 项:审批卡片发送(失败自动降级文字菜单,permission 域内处理);origin 穿透到卡片正文
1099
- sendApprovalPrompt: (ctx, request, mainSessionId, origin) =>
1100
- sendApprovalCard({ appId: config.qq.appId, clientSecret: config.qq.clientSecret }, ctx, request, mainSessionId, origin),
1098
+ // A 项:审批卡片发送(失败自动降级文字菜单,permission 域内处理);origin 穿透到卡片正文;
1099
+ // isCancelled 穿透到发送层——token 后/QQ API 前再查,死卡不发。
1100
+ sendApprovalPrompt: (ctx, request, mainSessionId, origin, isCancelled) =>
1101
+ sendApprovalCard(
1102
+ { appId: config.qq.appId, clientSecret: config.qq.clientSecret },
1103
+ ctx,
1104
+ request,
1105
+ mainSessionId,
1106
+ origin,
1107
+ isCancelled,
1108
+ ),
1101
1109
  // 多角色:审批态按角色分文件(缺省 legacy 全局)
1102
1110
  persistFile: storageAppId ? roleFile("pending-permissions.json") : undefined,
1103
1111
  })
@@ -1259,7 +1267,14 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1259
1267
  console.log(`[push-gate] 审批卡拦截(轮询兜底):绑定已切走 uid=${uid.slice(0, 8)}… sid=${shortId(req.sessionID)}`)
1260
1268
  continue
1261
1269
  }
1262
- perm.pushExternal(uid, ctxForUser(uid), req, req.sessionID)
1270
+ // 统一发卡时序(2026-11-28 架构收口):轮询兜底发现与 SSE asked 走同一延迟闸——
1271
+ // defer 窗内被桌面自动审批处置的请求不推卡(此前轮询直推绕过延迟闸,109ms 推卡实证,
1272
+ // 1000-1500ms 延迟带的决议会漏成死卡);闸按 uid+requestID 去重,与 SSE 路径互不重复;
1273
+ // flushPermPush 内仍做悬置复查+回合归属标注,SSE 断线时本路径仍是兜底(REST 复查 fail-open)。
1274
+ console.log(
1275
+ `[perm-event] 轮询兜底发现待审(延迟 ${PERM_DEFER_MS}ms 判定)user=${uid.slice(0, 8)}… request=${req.id}`,
1276
+ )
1277
+ permPushGate.schedule(uid, req.id, () => void flushPermPush(uid, req))
1263
1278
  }
1264
1279
  }
1265
1280
  }
@@ -1335,6 +1350,10 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1335
1350
  // DEF-qqbot-20261112-1:反查必须带会话自身目录——引擎待审按 location 实例分仓,
1336
1351
  // 裸查只命中服务端 cwd 实例,项目会话的请求永远查空 → 恒弃推(ZERO2 实证挂起 5h24m 被误弃)。
1337
1352
  async function flushPermPush(uid: string, req: PermissionRequest): Promise<void> {
1353
+ if (perm.wasResolvedRecently(req.id)) {
1354
+ console.log(`[perm-event] 延迟判定:请求近期已解决,弃推 user=${uid.slice(0, 8)}… request=${req.id}`)
1355
+ return
1356
+ }
1338
1357
  const bound = sessions.getSession(uid)
1339
1358
  try {
1340
1359
  const res = await client.permission.list({ directory: bound?.directory })
@@ -1941,8 +1960,9 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1941
1960
 
1942
1961
  // 摘要镜像:启动时对全部映射会话挂常驻订阅
1943
1962
  mirror.ensureSubs()
1944
- // 图片落盘:清理 7 天前的 QQ 图片(原生附件接入)
1963
+ // 附件落盘:清理 7 天前的 QQ 图片与文件附件(原生附件接入)
1945
1964
  purgeOldQQImages()
1965
+ purgeOldQQFiles()
1946
1966
 
1947
1967
  const handleMessage = async (ctx: MessageContext): Promise<void> => {
1948
1968
  let claimedMsgId = ""
@@ -4,12 +4,13 @@
4
4
  //
5
5
  // 用法:
6
6
  // node dist/openqq-cli.js restart [--force] [--timeout-min 60]
7
- // node dist/openqq-cli.js service install|uninstall|status
7
+ // node dist/openqq-cli.js stop [--timeout-min 60]
8
+ // node dist/openqq-cli.js service install|uninstall [--stop-bot] |status
8
9
  // 2026-11-09 架构红线:取代 safe-restart.ps1 / start-openqq.ps1 / watchdog.ps1,全 TS 跨平台。
9
10
  import { existsSync } from "fs"
10
11
  import { dirname, join } from "path"
11
12
  import { fileURLToPath } from "url"
12
- import { restartBot } from "../core/bot-control.js"
13
+ import { restartBot, stopBot } from "../core/bot-control.js"
13
14
  import {
14
15
  serviceInstall,
15
16
  serviceStatus,
@@ -65,6 +66,17 @@ async function main(): Promise<void> {
65
66
  return
66
67
  }
67
68
 
69
+ if (cmd === "stop") {
70
+ const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"))
71
+ const res = await stopBot({
72
+ timeoutMs: Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60_000 : undefined,
73
+ log: (line) => console.log(line),
74
+ })
75
+ console.log(`[stop] ${res.action}(${res.reason})killed=${res.killedPid ?? "-"}`)
76
+ process.exitCode = res.action === "stopped" ? 0 : 2
77
+ return
78
+ }
79
+
68
80
  if (cmd === "service") {
69
81
  const spec: ServiceSpec = {
70
82
  runtimeCmd: runtimeCommand(),
@@ -72,7 +84,23 @@ async function main(): Promise<void> {
72
84
  intervalMin: DEFAULT_INTERVAL_MIN,
73
85
  }
74
86
  if (sub === "install") return printResult("service install", serviceInstall(spec))
75
- if (sub === "uninstall") return printResult("service uninstall", serviceUninstall())
87
+ if (sub === "uninstall") {
88
+ const uninstall = serviceUninstall()
89
+ printResult("service uninstall", uninstall)
90
+ if (!process.argv.includes("--stop-bot")) return
91
+ // --stop-bot 是完整停用语义:自启注销失败(含任务本就不存在)不得阻断 bot 停止;
92
+ // 退出码反映两步结果——都成 0,仅停止成 1,停止未成 2。
93
+ const stop = await stopBot({
94
+ timeoutMs: (() => {
95
+ const timeoutMin = Number(parseFlag(process.argv.slice(2), "--timeout-min"))
96
+ return Number.isFinite(timeoutMin) && timeoutMin > 0 ? timeoutMin * 60_000 : undefined
97
+ })(),
98
+ log: (line) => console.log(line),
99
+ })
100
+ console.log(`[stop] ${stop.action}(${stop.reason})killed=${stop.killedPid ?? "-"}`)
101
+ process.exitCode = stop.action === "stopped" ? (uninstall.ok ? 0 : 1) : 2
102
+ return
103
+ }
76
104
  if (sub === "status") {
77
105
  const r = serviceStatus()
78
106
  return printResult("service status", {
@@ -80,12 +108,12 @@ async function main(): Promise<void> {
80
108
  detail: `runtime=${spec.runtimeCmd}\nscript=${spec.scriptPath}\n${r.detail}`,
81
109
  })
82
110
  }
83
- console.error("用法:openqq service install|uninstall|status")
111
+ console.error("用法:openqq service install|uninstall [--stop-bot]|status")
84
112
  process.exitCode = 2
85
113
  return
86
114
  }
87
115
 
88
- console.error("用法:openqq-cli restart [--force] [--timeout-min N] | service install|uninstall|status")
116
+ console.error("用法:openqq-cli restart [--force] [--timeout-min N] | stop [--timeout-min N] | service install|uninstall [--stop-bot]|status")
89
117
  process.exitCode = 2
90
118
  }
91
119
 
@@ -1,6 +1,6 @@
1
1
  // @input: ~/.openqq/.env、实例锁、在途台账、core/bot-launcher(运行时解析与 detached 拉起)、
2
2
  // core/watchdog(superviseOnce 杀/拉唯一权威)
3
- // @output: resolveInstalledBotEntry, readAppId, countInflight, waitUntilIdle, startBot, restartBot
3
+ // @output: resolveInstalledBotEntry, readAppId, countInflight, waitUntilIdle, startBot, restartBot, stopBot
4
4
  // @pos: core - bot 生命周期控制(跨平台;替代 safe-restart.ps1 / start-openqq.ps1)
5
5
  //
6
6
  // 2026-11-09 架构红线:重启是运维代码,必须随插件包分发且跨平台。
@@ -8,7 +8,7 @@
8
8
  // 2026-11-10 design §3.9.1 归一:杀/拉唯一权威 = superviseOnce。restartBot 只是它的
9
9
  // 调用方(等空闲 → 同一 grace-kill+spawn 原语 + supervisor.json 强度账 + 审计分家 +
10
10
  // 认领互斥),本文件不再实现任何独立杀逻辑(原 stopLockedBot 已删除)。
11
- import { existsSync, readFileSync } from "fs"
11
+ import { existsSync, readFileSync, readdirSync } from "fs"
12
12
  import { dirname, join } from "path"
13
13
  import { homedir } from "os"
14
14
  import { fileURLToPath } from "url"
@@ -69,15 +69,35 @@ export function inflightPath(): string {
69
69
  return join(homedir(), ".openqq", "inflight.json")
70
70
  }
71
71
 
72
- /** 在途回合数(safe-restart 的空闲判据:state=inflight 即算活跃) */
73
- export function countInflight(path = inflightPath()): number {
72
+ /** 全部角色在途台账路径:legacy 根 + roles/<appId>/(多角色停止/重启的空闲判据必须看全量)。 */
73
+ export function inflightPaths(): string[] {
74
+ const root = join(homedir(), ".openqq")
75
+ const paths = [join(root, "inflight.json")]
74
76
  try {
75
- const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown
76
- if (!Array.isArray(raw)) return 0
77
- return raw.filter((e) => (e as { state?: string }).state === "inflight").length
77
+ for (const name of readdirSync(join(root, "roles"))) {
78
+ const path = join(root, "roles", name, "inflight.json")
79
+ if (existsSync(path)) paths.push(path)
80
+ }
78
81
  } catch {
79
- return 0
82
+ /* 无 roles 目录=legacy 单角色 */
83
+ }
84
+ return paths
85
+ }
86
+
87
+ /** 在途回合数(safe-restart/stop 的空闲判据:state=inflight 即算活跃;默认全角色合计)。 */
88
+ export function countInflight(paths: string | string[] = inflightPaths()): number {
89
+ const list = Array.isArray(paths) ? paths : [paths]
90
+ let total = 0
91
+ for (const path of list) {
92
+ try {
93
+ const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown
94
+ if (!Array.isArray(raw)) continue
95
+ total += raw.filter((e) => (e as { state?: string }).state === "inflight").length
96
+ } catch {
97
+ /* 单文件损坏不阻断其他角色判活 */
98
+ }
80
99
  }
100
+ return total
81
101
  }
82
102
 
83
103
  export async function waitUntilIdle(opts?: {
@@ -164,3 +184,48 @@ export async function restartBot(opts: RestartOptions): Promise<RestartResult> {
164
184
  return { action: "skipped", killedPid: null, spawnedPid: null, reason: `无需动作:${r.detail}` }
165
185
  }
166
186
  }
187
+
188
+ export interface StopOptions {
189
+ timeoutMs?: number
190
+ log?: (line: string) => void
191
+ }
192
+
193
+ export interface StopResult {
194
+ action: "stopped" | "skipped"
195
+ killedPid: number | null
196
+ reason: string
197
+ }
198
+
199
+ /**
200
+ * 受控停止:默认等空闲;复用 superviseOnce 的 manual-stop(认领互斥 + 优雅杀 + 清锁 + 审计),
201
+ * 不拉起、不计重启强度账。bot 独立存活是故障隔离,不是脱离用户控制——stop 是显式生命周期终点。
202
+ */
203
+ export async function stopBot(opts: StopOptions = {}): Promise<StopResult> {
204
+ const log = opts.log ?? (() => {})
205
+ const appId = readAppId()
206
+ if (!appId) throw new Error("缺少 ~/.openqq/.env 的角色凭据(QQ_APP_ID 或 QQ_BOTS 首角色),无法定位实例锁")
207
+ const idle = await waitUntilIdle({
208
+ timeoutMs: opts.timeoutMs,
209
+ onWait: (n, elapsed) => log(`[bot-control] 仍在途 ${n} 条(已等 ${Math.round(elapsed / 1000)}s),继续等待空闲后停止`),
210
+ })
211
+ if (!idle) {
212
+ log("[bot-control] 等待空闲超时:本次不停止(请稍后重试,或先处理在途回合)")
213
+ return { action: "skipped", killedPid: null, reason: "等待空闲超时" }
214
+ }
215
+ const r = await superviseOnce({
216
+ paths: botWatchdogPaths(appId),
217
+ request: "manual-stop",
218
+ spawn: () => {
219
+ throw new Error("manual-stop 不应拉起 bot")
220
+ },
221
+ log,
222
+ })
223
+ if (r.action === "stopped") {
224
+ return {
225
+ action: "stopped",
226
+ killedPid: r.killedPid,
227
+ reason: r.killedPid ? "已优雅停止并持有(巡检不拉起,restart 解除)" : "bot 未运行,已清锁并持有(巡检不拉起)",
228
+ }
229
+ }
230
+ return { action: "skipped", killedPid: null, reason: r.detail }
231
+ }
@@ -105,12 +105,22 @@ export async function sendApprovalCard(
105
105
  request: PermissionRequest,
106
106
  mainSessionId: string,
107
107
  origin?: PermOrigin,
108
+ isCancelled?: () => boolean,
108
109
  ): Promise<boolean> {
109
110
  try {
110
111
  const token = await getAccessToken(deps.appId, deps.clientSecret)
112
+ // 死卡竞态防线:token 获取可能耗时,期间桌面端/引擎已处理——QQ API 前必须再查。
113
+ if (isCancelled?.()) {
114
+ console.log(`[card-approval] 发卡取消:请求已解决 user=${ctx.userId.slice(0, 8)}… request=${request.id}`)
115
+ return false
116
+ }
111
117
  const keyboard = buildApprovalKeyboard(request, ctx.userId)
112
118
  // 正文复用现有格式化(用户看到的字段与文字菜单完全一致);origin 标注发起来源
113
119
  const text = formatPermissionPrompt(request, mainSessionId, origin)
120
+ if (isCancelled?.()) {
121
+ console.log(`[card-approval] 发卡取消:请求已解决 user=${ctx.userId.slice(0, 8)}… request=${request.id}`)
122
+ return false
123
+ }
114
124
  if (ctx.type === "group" && ctx.groupId) {
115
125
  await sendGroupMessage(token, ctx.groupId, text, ctx.msgId, undefined, true, keyboard)
116
126
  } else {