@linjz/opencode-qqbot 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +74 -37
  2. package/bin/openqq-setup.mjs +50 -50
  3. package/bin/openqq.js +47 -47
  4. package/dist/opencode-qqbot-plugin.js +10 -1
  5. package/dist/openqq-bot.js +360 -69
  6. package/package.json +69 -59
  7. package/src/_FOLDER.md +19 -19
  8. package/src/bridge.ts +934 -796
  9. package/src/commands.ts +554 -514
  10. package/src/config.ts +121 -121
  11. package/src/core/bot-launcher.ts +146 -134
  12. package/src/core/card-approval.ts +146 -146
  13. package/src/core/context-buffer.ts +78 -78
  14. package/src/core/delivery.ts +284 -284
  15. package/src/core/discovery.ts +151 -151
  16. package/src/core/error-rescue.ts +33 -0
  17. package/src/core/file-log.ts +45 -45
  18. package/src/core/form-bridge.ts +304 -304
  19. package/src/core/inflight-journal.ts +212 -151
  20. package/src/core/instance-lock.ts +122 -122
  21. package/src/core/linkwatch.ts +195 -195
  22. package/src/core/message-queue.ts +80 -0
  23. package/src/core/mirror.ts +173 -173
  24. package/src/core/permission.ts +301 -301
  25. package/src/core/reply-limiter.ts +106 -106
  26. package/src/core/send-media.ts +90 -90
  27. package/src/core/util.ts +8 -8
  28. package/src/index.ts +162 -162
  29. package/src/opencode/_FOLDER.md +11 -11
  30. package/src/opencode/client.ts +387 -386
  31. package/src/opencode/eventstream.ts +138 -138
  32. package/src/opencode/history.ts +143 -143
  33. package/src/opencode/mirror.ts +65 -65
  34. package/src/opencode/sessions.ts +158 -158
  35. package/src/plugin-entry.ts +112 -112
  36. package/src/qq/_FOLDER.md +13 -13
  37. package/src/qq/api.ts +539 -539
  38. package/src/qq/gateway.ts +492 -492
  39. package/src/qq/media.ts +219 -204
  40. package/src/qq/sender.ts +300 -300
  41. package/src/qq/types.ts +154 -152
  42. package/tsconfig.json +24 -24
@@ -2939,7 +2939,7 @@ var require_websocket_server = __commonJS(function(exports, module) {
2939
2939
  });
2940
2940
 
2941
2941
  // src/core/file-log.ts
2942
- import { appendFileSync, existsSync as existsSync9, mkdirSync as mkdirSync9, renameSync as renameSync2, statSync as statSync4 } from "fs";
2942
+ import { appendFileSync, existsSync as existsSync9, mkdirSync as mkdirSync9, renameSync as renameSync2, statSync as statSync5 } from "fs";
2943
2943
  import { join as join12 } from "path";
2944
2944
  function installFileLog(logPath) {
2945
2945
  try {
@@ -2947,12 +2947,12 @@ function installFileLog(logPath) {
2947
2947
  } catch {}
2948
2948
  const write = (level, args) => {
2949
2949
  try {
2950
- if (existsSync9(logPath) && statSync4(logPath).size > ROTATE_BYTES) {
2950
+ if (existsSync9(logPath) && statSync5(logPath).size > ROTATE_BYTES) {
2951
2951
  renameSync2(logPath, `${logPath}.1`);
2952
2952
  }
2953
2953
  const line = args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ");
2954
2954
  appendFileSync(logPath, `${new Date().toISOString()} [${level}] ${line}
2955
- `);
2955
+ `, { mode: 384 });
2956
2956
  } catch {}
2957
2957
  };
2958
2958
  const orig = {
@@ -3028,7 +3028,7 @@ async function ensureConfig() {
3028
3028
  if (!appId || !appSecret) {
3029
3029
  throw new Error("App ID 和 App Secret 不能为空");
3030
3030
  }
3031
- mkdirSync(CONFIG_DIR, { recursive: true });
3031
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
3032
3032
  const envContent = [
3033
3033
  `QQ_APP_ID=${appId}`,
3034
3034
  `QQ_APP_SECRET=${appSecret}`,
@@ -3039,7 +3039,7 @@ async function ensureConfig() {
3039
3039
  ].join(`
3040
3040
  `) + `
3041
3041
  `;
3042
- writeFileSync(ENV_FILE, envContent);
3042
+ writeFileSync(ENV_FILE, envContent, { mode: 384 });
3043
3043
  console.log(`
3044
3044
  配置已保存到 ${ENV_FILE}`);
3045
3045
  process.env.QQ_APP_ID = appId;
@@ -3121,7 +3121,8 @@ function createClient(baseUrl) {
3121
3121
  async function json(res) {
3122
3122
  if (!res.ok) {
3123
3123
  const txt = await res.text().catch(() => "");
3124
- throw new Error(`OpenCode API ${res.status}: ${txt.substring(0, 200)}`);
3124
+ const excerpt = txt.length > 200 ? `${txt.substring(0, 200)}…` : txt;
3125
+ throw new Error(`OpenCode API ${res.status}: ${excerpt}`);
3125
3126
  }
3126
3127
  if (res.status === 204)
3127
3128
  return null;
@@ -3469,7 +3470,7 @@ function startLinkWatch(deps) {
3469
3470
  inc.lastCheck = nowIso();
3470
3471
  if (!alarmOpenSent) {
3471
3472
  alarmOpenSent = true;
3472
- await fire(`⚠️ OpenCode 链路失联(自 ${inc.since.slice(11, 16)} 起,错误:${msg.slice(0, 80)})。已转入自动自愈:发现新端口会自动切换并通知。`);
3473
+ await fire(`⚠️ OpenCode 链路失联(自 ${inc.since.slice(11, 16)} 起,错误:${msg.length > 80 ? `${msg.slice(0, 80)}…` : msg})。已转入自动自愈:发现新端口会自动切换并通知。`);
3473
3474
  }
3474
3475
  const found = await discover(password);
3475
3476
  if (found && found.baseUrl !== deps.client.baseUrl) {
@@ -4327,12 +4328,12 @@ async function startGateway(options) {
4327
4328
  }
4328
4329
 
4329
4330
  // src/bridge.ts
4330
- import { existsSync as existsSync8, readFileSync as readFileSync9, mkdirSync as mkdirSync7, writeFileSync as writeFileSync10 } from "fs";
4331
+ import { existsSync as existsSync8, readFileSync as readFileSync10, mkdirSync as mkdirSync7, writeFileSync as writeFileSync10 } from "fs";
4331
4332
  import { join as join10 } from "path";
4332
4333
  import { homedir as homedir9 } from "os";
4333
4334
 
4334
4335
  // src/qq/media.ts
4335
- import { mkdirSync as mkdirSync4, readdirSync, statSync, unlinkSync, writeFileSync as writeFileSync5 } from "node:fs";
4336
+ import { mkdirSync as mkdirSync4, readdirSync, statSync, unlinkSync, writeFileSync as writeFileSync5, readFileSync as readFileSync4 } from "node:fs";
4336
4337
  import { join as join5 } from "node:path";
4337
4338
  import { tmpdir } from "node:os";
4338
4339
  function extForImageMime(mime) {
@@ -4439,7 +4440,8 @@ function groupOutcomes(outcomes) {
4439
4440
  const notes = [];
4440
4441
  for (const o of outcomes) {
4441
4442
  if ("path" in o) {
4442
- files.push({ uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name });
4443
+ const dataUrl = tryImageDataUrl(o.path, 2 * 1024 * 1024);
4444
+ files.push(dataUrl ? { uri: dataUrl, name: o.name } : { uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name });
4443
4445
  } else if ("voice" in o) {
4444
4446
  notes.push(`(语音转写:${o.voice})`);
4445
4447
  } else if ("failed" in o) {
@@ -4450,6 +4452,17 @@ function groupOutcomes(outcomes) {
4450
4452
  }
4451
4453
  return { files, notes };
4452
4454
  }
4455
+ function tryImageDataUrl(path, maxBytes) {
4456
+ try {
4457
+ const st = statSync(path);
4458
+ if (st.size > maxBytes)
4459
+ return null;
4460
+ const b = readFileSync4(path);
4461
+ return `data:image/png;base64,${b.toString("base64")}`;
4462
+ } catch {
4463
+ return null;
4464
+ }
4465
+ }
4453
4466
  function augmentPromptWithAttachments(rawContent, prepared) {
4454
4467
  const base = rawContent.trim();
4455
4468
  const { files, notes } = prepared;
@@ -4712,8 +4725,8 @@ function clip(value, max) {
4712
4725
  }
4713
4726
 
4714
4727
  // src/core/send-media.ts
4715
- import { readFileSync as readFileSync4, statSync as statSync2 } from "node:fs";
4716
- import { resolve, extname, basename } from "node:path";
4728
+ import { readFileSync as readFileSync5, statSync as statSync2 } from "node:fs";
4729
+ import { resolve, extname, basename, sep } from "node:path";
4717
4730
  var MAX_SEND_BYTES = 20 * 1024 * 1024;
4718
4731
  function allowedSendRoots(extraEnv = process.env.QQ_SEND_EXTRA_ROOTS) {
4719
4732
  const roots = [imageDir(), process.cwd()];
@@ -4725,7 +4738,7 @@ function allowedSendRoots(extraEnv = process.env.QQ_SEND_EXTRA_ROOTS) {
4725
4738
  }
4726
4739
  function isAllowedSendPath(filePath, roots = allowedSendRoots()) {
4727
4740
  const full = resolve(filePath.trim().replace(/^"|"$/g, ""));
4728
- return roots.some((root) => full === root || full.startsWith(root + "\\") || full.startsWith(root + "/"));
4741
+ return roots.some((root) => full === root || full.startsWith(root + sep));
4729
4742
  }
4730
4743
  function fileTypeForPath(filePath) {
4731
4744
  const ext = extname(filePath).toLowerCase();
@@ -4777,7 +4790,7 @@ async function sendLocalFile(ctx, filePath, deps) {
4777
4790
  const name = basename(trimmed);
4778
4791
  const uploaded = await uploadQQMedia(token, ctx, {
4779
4792
  fileType,
4780
- fileData: readFileSync4(trimmed).toString("base64"),
4793
+ fileData: readFileSync5(trimmed).toString("base64"),
4781
4794
  fileName: fileType === MediaFileType.FILE ? name : undefined
4782
4795
  });
4783
4796
  await sendQQMediaMessage(token, ctx, uploaded.file_info, name);
@@ -4799,7 +4812,12 @@ async function handleCommand(ctx, cmdCtx) {
4799
4812
  case "new":
4800
4813
  return handleNew(ctx, cmdCtx);
4801
4814
  case "stop":
4815
+ case "cancel":
4802
4816
  return handleStop(ctx, cmdCtx);
4817
+ case "queue":
4818
+ return handleQueue(ctx, parsed.args, cmdCtx);
4819
+ case "progress":
4820
+ return cmdCtx.progress.query(ctx.userId);
4803
4821
  case "status":
4804
4822
  return handleStatus(ctx, cmdCtx);
4805
4823
  case "sessions":
@@ -4889,11 +4907,27 @@ async function handleSend(ctx, args, cmdCtx) {
4889
4907
  }
4890
4908
  async function handleStop(ctx, cmdCtx) {
4891
4909
  const session = cmdCtx.sessions.getSession(ctx.userId);
4910
+ const cleared = cmdCtx.queue.clear(ctx.userId);
4911
+ const suffix = cleared > 0 ? `,队列中的 ${cleared} 条已清空` : "";
4892
4912
  if (!session) {
4893
- return "当前还没有会话可停止";
4913
+ return cleared > 0 ? `当前没有会话可停止${suffix}` : "当前还没有会话可停止";
4894
4914
  }
4895
4915
  await cmdCtx.client.session.abort({ path: { id: session.sessionId } });
4896
- return `已发送停止请求:${session.title ?? session.sessionId}`;
4916
+ return `已发送停止请求:${session.title ?? session.sessionId}${suffix}`;
4917
+ }
4918
+ function handleQueue(ctx, args, cmdCtx) {
4919
+ const sub = args.trim().split(/\s+/)[0]?.toLowerCase() ?? "";
4920
+ if (sub === "clear") {
4921
+ const n = cmdCtx.queue.clear(ctx.userId);
4922
+ return n > 0 ? `已清空队列(${n} 条)` : "队列本来就是空的";
4923
+ }
4924
+ if (sub === "drop") {
4925
+ const id = Number(args.trim().split(/\s+/)[1]);
4926
+ if (!Number.isInteger(id) || id <= 0)
4927
+ return "用法:/queue drop <编号>";
4928
+ return cmdCtx.queue.drop(ctx.userId, id);
4929
+ }
4930
+ return cmdCtx.queue.list(ctx.userId);
4897
4931
  }
4898
4932
  async function handleStatus(ctx, cmdCtx) {
4899
4933
  const session = cmdCtx.sessions.getSession(ctx.userId);
@@ -5140,6 +5174,9 @@ function buildHelpText() {
5140
5174
  "/watch - 观察当前会话实时过程(工具调用/完成会推送摘要)",
5141
5175
  "/watch <会话ID> - 观察指定会话",
5142
5176
  "/watch off - 停止观察",
5177
+ "/progress - 手动进度查询(工具调用/失败统计、在途状态,本地事件源零模型调用)",
5178
+ "/queue - 忙碌队列查看;/queue clear 清空;/queue drop <编号> 定点删除",
5179
+ "/cancel - 同 /stop:中止当前 AI 运行并清空忙碌队列",
5143
5180
  "/mirror [on|off] - 桌面问答摘要镜像开关(会话轮次完成推送问答摘要)",
5144
5181
  "",
5145
5182
  "权限审批(AI 请求权限时):",
@@ -5175,7 +5212,7 @@ function toErrorMessage(error) {
5175
5212
  }
5176
5213
 
5177
5214
  // src/core/mirror.ts
5178
- import { existsSync as existsSync4, readFileSync as readFileSync5, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "fs";
5215
+ import { existsSync as existsSync4, readFileSync as readFileSync6, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "fs";
5179
5216
  import { join as join6 } from "path";
5180
5217
  import { homedir as homedir5 } from "os";
5181
5218
 
@@ -5235,7 +5272,7 @@ var MIRROR_SETTINGS_FILE = join6(homedir5(), ".openqq", "settings.json");
5235
5272
  function loadMirrorEnabled() {
5236
5273
  try {
5237
5274
  if (existsSync4(MIRROR_SETTINGS_FILE)) {
5238
- const raw = readFileSync5(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
5275
+ const raw = readFileSync6(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
5239
5276
  const parsed = JSON.parse(raw);
5240
5277
  if (typeof parsed?.mirror === "boolean")
5241
5278
  return parsed.mirror;
@@ -5249,7 +5286,7 @@ function saveMirrorEnabled(enabled) {
5249
5286
  let existing = {};
5250
5287
  if (existsSync4(MIRROR_SETTINGS_FILE)) {
5251
5288
  try {
5252
- const raw = readFileSync5(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
5289
+ const raw = readFileSync6(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
5253
5290
  const parsed = JSON.parse(raw);
5254
5291
  if (parsed && typeof parsed === "object")
5255
5292
  existing = parsed;
@@ -5352,8 +5389,98 @@ function createMirror(deps) {
5352
5389
  };
5353
5390
  }
5354
5391
 
5392
+ // src/core/message-queue.ts
5393
+ var PREVIEW_MAX = 48;
5394
+ function previewText(text, max = PREVIEW_MAX) {
5395
+ const flat = text.replace(/\s+/g, " ").trim();
5396
+ return flat.length > max ? `${flat.slice(0, max)}…` : flat || "(空消息)";
5397
+ }
5398
+ function agoLabel(at, now = Date.now()) {
5399
+ const seconds = Math.max(0, Math.round((now - at) / 1000));
5400
+ if (seconds < 60)
5401
+ return `${seconds}s 前`;
5402
+ const minutes = Math.floor(seconds / 60);
5403
+ if (minutes < 60)
5404
+ return `${minutes}m 前`;
5405
+ return `${Math.floor(minutes / 60)}h 前`;
5406
+ }
5407
+
5408
+ class MessageQueue {
5409
+ limit;
5410
+ jobs = new Map;
5411
+ nextId = 1;
5412
+ constructor(limit = 20) {
5413
+ this.limit = limit;
5414
+ }
5415
+ push(userId, ctx) {
5416
+ const list = this.jobs.get(userId) ?? [];
5417
+ if (list.length >= this.limit)
5418
+ return null;
5419
+ const job = { id: this.nextId++, userId, ctx, text: ctx.content, enqueuedAt: Date.now() };
5420
+ list.push(job);
5421
+ this.jobs.set(userId, list);
5422
+ return { job, ahead: list.length - 1 };
5423
+ }
5424
+ shift(userId) {
5425
+ const list = this.jobs.get(userId);
5426
+ const job = list?.shift();
5427
+ if (list && list.length === 0)
5428
+ this.jobs.delete(userId);
5429
+ return job;
5430
+ }
5431
+ list(userId) {
5432
+ return this.jobs.get(userId) ?? [];
5433
+ }
5434
+ drop(userId, id) {
5435
+ const list = this.jobs.get(userId);
5436
+ if (!list)
5437
+ return false;
5438
+ const idx = list.findIndex((j) => j.id === id);
5439
+ if (idx < 0)
5440
+ return false;
5441
+ list.splice(idx, 1);
5442
+ if (list.length === 0)
5443
+ this.jobs.delete(userId);
5444
+ return true;
5445
+ }
5446
+ clear(userId) {
5447
+ const n = this.jobs.get(userId)?.length ?? 0;
5448
+ this.jobs.delete(userId);
5449
+ return n;
5450
+ }
5451
+ size(userId) {
5452
+ return this.jobs.get(userId)?.length ?? 0;
5453
+ }
5454
+ }
5455
+
5456
+ // src/core/error-rescue.ts
5457
+ function classifyProviderError(message) {
5458
+ const m = message.toLowerCase();
5459
+ if (/\b402\b|insufficient|balance|余额|额度不足|quota exceeded|credit/i.test(m))
5460
+ return "billing";
5461
+ if (/\b401\b|unauthorized|invalid.{0,20}(key|token)|鉴权|密钥错误|api.?key/i.test(m))
5462
+ return "auth";
5463
+ return null;
5464
+ }
5465
+ function rescueText(kind, rawMessage) {
5466
+ if (!kind)
5467
+ return null;
5468
+ const clipped = rawMessage.replace(/\s+/g, " ").trim();
5469
+ const raw = clipped.length > 200 ? `${clipped.slice(0, 200)}…` : clipped;
5470
+ const head = kind === "billing" ? "❌ 当前模型的余额/额度不足,暂时无法继续对话" : "❌ 当前模型的鉴权信息失效(401/key 无效)";
5471
+ return [
5472
+ head,
5473
+ `服务端原文:${raw}`,
5474
+ "",
5475
+ "恢复方式(都不用等模型在线)——",
5476
+ "1. 换现成模型:发 /model 看列表,或 /model provider/id 直接切换",
5477
+ "2. 更新 key:在桌面端 opencode 里更新该服务的 key 后,直接重发你的问题"
5478
+ ].join(`
5479
+ `);
5480
+ }
5481
+
5355
5482
  // src/core/permission.ts
5356
- import { existsSync as existsSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync7 } from "fs";
5483
+ import { existsSync as existsSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync7 } from "fs";
5357
5484
  import { join as join7 } from "path";
5358
5485
  import { homedir as homedir6 } from "os";
5359
5486
 
@@ -5374,7 +5501,7 @@ var PENDING_PERM_FILE = join7(homedir6(), ".openqq", "pending-permissions.json")
5374
5501
  function loadPendingPermMap() {
5375
5502
  try {
5376
5503
  if (existsSync5(PENDING_PERM_FILE)) {
5377
- const raw = readFileSync6(PENDING_PERM_FILE, "utf-8");
5504
+ const raw = readFileSync7(PENDING_PERM_FILE, "utf-8");
5378
5505
  const obj = JSON.parse(raw);
5379
5506
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
5380
5507
  const out = {};
@@ -5563,7 +5690,7 @@ function formatPermissionPrompt(request, mainSessionId) {
5563
5690
  }
5564
5691
 
5565
5692
  // src/core/delivery.ts
5566
- import { existsSync as existsSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync8 } from "fs";
5693
+ import { existsSync as existsSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync8 } from "fs";
5567
5694
  import { join as join8 } from "path";
5568
5695
  import { homedir as homedir7 } from "os";
5569
5696
 
@@ -5899,8 +6026,8 @@ function extractEmbeddedQuote(event) {
5899
6026
  };
5900
6027
  walk(event.msg_elements, 0);
5901
6028
  const text = out.join(`
5902
- `).trim().slice(0, 2000);
5903
- return text || null;
6029
+ `).trim();
6030
+ return (text.length > 2000 ? `${text.slice(0, 2000)}…` : text) || null;
5904
6031
  }
5905
6032
 
5906
6033
  // src/core/delivery.ts
@@ -5908,7 +6035,7 @@ var QUOTA_FILE = join8(homedir7(), ".openqq", "quota.json");
5908
6035
  function loadQuotaMap() {
5909
6036
  try {
5910
6037
  if (existsSync6(QUOTA_FILE)) {
5911
- const raw = readFileSync7(QUOTA_FILE, "utf-8");
6038
+ const raw = readFileSync8(QUOTA_FILE, "utf-8");
5912
6039
  const obj = JSON.parse(raw);
5913
6040
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
5914
6041
  const out = {};
@@ -6352,7 +6479,7 @@ function createFormBridge(deps) {
6352
6479
  if (msg.includes("AlreadySettled") || msg.includes("already")) {
6353
6480
  deps.safeDeliver(ctx, "该选择已在桌面端处理过,任务应已继续").catch(() => {});
6354
6481
  } else {
6355
- deps.safeDeliver(ctx, `⚠️ 提交失败:${msg.slice(0, 120)}`).catch(() => {});
6482
+ deps.safeDeliver(ctx, `⚠️ 提交失败:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`).catch(() => {});
6356
6483
  }
6357
6484
  }
6358
6485
  })();
@@ -6419,7 +6546,7 @@ function createFormBridge(deps) {
6419
6546
  }
6420
6547
 
6421
6548
  // src/core/inflight-journal.ts
6422
- import { existsSync as existsSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync9, mkdirSync as mkdirSync6, renameSync } from "fs";
6549
+ import { existsSync as existsSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync9, mkdirSync as mkdirSync6, renameSync, openSync, closeSync, unlinkSync as unlinkSync2, statSync as statSync3 } from "fs";
6423
6550
  import { join as join9 } from "path";
6424
6551
  import { homedir as homedir8 } from "os";
6425
6552
  var INFLIGHT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
@@ -6430,50 +6557,104 @@ function redispatchMaxAgeMs() {
6430
6557
  function journalPath() {
6431
6558
  return process.env.QQ_INFLIGHT_FILE || join9(homedir8(), ".openqq", "inflight.json");
6432
6559
  }
6433
- var cache = null;
6434
6560
  function load() {
6435
- if (cache)
6436
- return cache;
6437
6561
  let entries = [];
6438
6562
  try {
6439
6563
  if (existsSync7(journalPath())) {
6440
- const raw = JSON.parse(readFileSync8(journalPath(), "utf-8"));
6564
+ const raw = JSON.parse(readFileSync9(journalPath(), "utf-8"));
6441
6565
  if (Array.isArray(raw))
6442
6566
  entries = raw;
6443
6567
  }
6444
6568
  } catch {
6445
6569
  entries = [];
6446
6570
  }
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();
6451
- return cache;
6571
+ return entries.filter((e) => e.state === "inflight" || Date.now() - e.at <= INFLIGHT_MAX_AGE_MS);
6452
6572
  }
6453
- function save() {
6454
- if (!cache)
6455
- return;
6573
+ function save(entries) {
6574
+ const path = journalPath();
6575
+ mkdirSync6(join9(path, ".."), { recursive: true });
6576
+ const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
6456
6577
  try {
6457
- const path = journalPath();
6458
- mkdirSync6(join9(path, ".."), { recursive: true });
6459
- const tmp = `${path}.tmp`;
6460
- writeFileSync9(tmp, JSON.stringify(cache, null, 2));
6578
+ writeFileSync9(tmp, JSON.stringify(entries, null, 2), { mode: 384 });
6461
6579
  renameSync(tmp, path);
6462
6580
  } catch (error) {
6463
- console.warn("[inflight] 台账落盘失败:", error instanceof Error ? error.message : error);
6581
+ try {
6582
+ unlinkSync2(tmp);
6583
+ } catch {}
6584
+ throw error;
6585
+ }
6586
+ }
6587
+ var JOURNAL_LOCK_STALE_MS = 30000;
6588
+ var JOURNAL_LOCK_WAIT_MS = 5000;
6589
+ var sleepArray = new Int32Array(new SharedArrayBuffer(4));
6590
+ function withJournalLock(fn) {
6591
+ const path = journalPath();
6592
+ mkdirSync6(join9(path, ".."), { recursive: true });
6593
+ const lockPath = `${path}.lock`;
6594
+ const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
6595
+ const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
6596
+ for (;; ) {
6597
+ try {
6598
+ const fd = openSync(lockPath, "wx", 384);
6599
+ try {
6600
+ writeFileSync9(fd, token);
6601
+ } finally {
6602
+ closeSync(fd);
6603
+ }
6604
+ break;
6605
+ } catch (error) {
6606
+ try {
6607
+ if (Date.now() - statSync3(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
6608
+ unlinkSync2(lockPath);
6609
+ } catch {}
6610
+ if (Date.now() >= deadline) {
6611
+ throw new Error(`在途台账锁等待超时: ${error instanceof Error ? error.message : error}`);
6612
+ }
6613
+ Atomics.wait(sleepArray, 0, 0, 10);
6614
+ }
6615
+ }
6616
+ try {
6617
+ return fn();
6618
+ } finally {
6619
+ try {
6620
+ if (readFileSync9(lockPath, "utf-8") === token)
6621
+ unlinkSync2(lockPath);
6622
+ } catch {}
6464
6623
  }
6465
6624
  }
6625
+ function mutate(fn) {
6626
+ return withJournalLock(() => {
6627
+ const entries = load();
6628
+ const result = fn(entries);
6629
+ save(entries);
6630
+ return result;
6631
+ });
6632
+ }
6633
+ function claimInflight(entry) {
6634
+ return mutate((entries) => {
6635
+ if (entries.some((e) => e.msgId === entry.msgId))
6636
+ return false;
6637
+ entries.push({ ...entry, state: "inflight" });
6638
+ return true;
6639
+ });
6640
+ }
6466
6641
  function recordInflight(entry) {
6467
- const entries = load();
6468
- entries.push({ ...entry, state: "inflight" });
6469
- save();
6642
+ mutate((entries) => {
6643
+ const existing = entries.find((e) => e.msgId === entry.msgId);
6644
+ if (existing) {
6645
+ if (!existing.sessionId && entry.sessionId)
6646
+ existing.sessionId = entry.sessionId;
6647
+ return;
6648
+ }
6649
+ entries.push({ ...entry, state: "inflight" });
6650
+ });
6470
6651
  }
6471
6652
  function settleInflight(msgId) {
6472
- const entry = load().find((e) => e.msgId === msgId && e.state === "inflight");
6473
- if (!entry)
6474
- return;
6475
- entry.state = "settled";
6476
- save();
6653
+ mutate((entries) => {
6654
+ const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight");
6655
+ if (entry)
6656
+ entry.state = "settled";
6657
+ });
6477
6658
  }
6478
6659
  function pendingInflight() {
6479
6660
  return load().filter((e) => e.state === "inflight");
@@ -6510,6 +6691,7 @@ function classifyInflight(entry, messages) {
6510
6691
  }
6511
6692
 
6512
6693
  // src/bridge.ts
6694
+ var QUEUE_MAX = 20;
6513
6695
  function evictableIdleSessions(lastActivity, watched, now, idleMs) {
6514
6696
  const out = [];
6515
6697
  for (const [sid, at] of lastActivity) {
@@ -6529,6 +6711,9 @@ function stallNudgeDecision(startedAt, lastProgressAt, nudges, now, firstMs, int
6529
6711
  }
6530
6712
  function createBridge(config, client, sessions) {
6531
6713
  const busyUsers = new Set;
6714
+ const claimedContexts = new WeakSet;
6715
+ const msgQueue = new MessageQueue(QUEUE_MAX);
6716
+ const draining = new Set;
6532
6717
  const greeted = loadGreetedSet();
6533
6718
  const pendingSelections = new Map;
6534
6719
  const eventStream = createEventStream(client.baseUrl);
@@ -6538,6 +6723,7 @@ function createBridge(config, client, sessions) {
6538
6723
  const lastCtx = new Map;
6539
6724
  const bgWaits = new Map;
6540
6725
  const callCache = new Map;
6726
+ const turnStats = new Map;
6541
6727
  const sessionLastActivity = new Map;
6542
6728
  const IDLE_EVICT_MS = (() => {
6543
6729
  const h = Number(process.env.QQ_SESSION_IDLE_HOURS ?? "6");
@@ -6575,6 +6761,22 @@ function createBridge(config, client, sessions) {
6575
6761
  }
6576
6762
  function onSessionEvent(sessionID, ev) {
6577
6763
  sessionLastActivity.set(sessionID, Date.now());
6764
+ const d = ev.data ?? {};
6765
+ if (ev.type === "session.tool.called" || ev.type === "session.tool.success") {
6766
+ const cmd = typeof d.input === "string" ? d.input : d.input?.command;
6767
+ const actionable = ev.type === "session.tool.success" || typeof cmd === "string" && cmd.trim();
6768
+ if (actionable) {
6769
+ const st = turnStats.get(sessionID) ?? { tools: 0, failed: 0, lastTool: "", lastAt: 0 };
6770
+ if (ev.type === "session.tool.called") {
6771
+ st.tools++;
6772
+ st.lastTool = cmd.length > 60 ? `${String(cmd).slice(0, 60)}…` : String(cmd);
6773
+ } else if (typeof d.metadata?.exit === "number" && d.metadata.exit !== 0) {
6774
+ st.failed++;
6775
+ }
6776
+ st.lastAt = Date.now();
6777
+ turnStats.set(sessionID, st);
6778
+ }
6779
+ }
6578
6780
  const line = formatMilestone(ev, callCache);
6579
6781
  if (!line)
6580
6782
  return;
@@ -6608,6 +6810,7 @@ function createBridge(config, client, sessions) {
6608
6810
  cleanup();
6609
6811
  if (trackId)
6610
6812
  settleInflight(trackId);
6813
+ drainQueue(ctx.userId);
6611
6814
  if (kind === "giveup") {
6612
6815
  await safeDeliver(ctx, "⚠️ 后台任务 24 小时仍未完成,停止自动跟进;结果可随时用 /history 查询");
6613
6816
  return;
@@ -6761,6 +6964,45 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
6761
6964
  console.log(`[interaction-watch] 常驻交互监听已启动(每 ${INTERACTION_WATCH_MS / 1000}s 轮询权限+表单)`);
6762
6965
  }
6763
6966
  const mirrorApi = mirror.api;
6967
+ const queueApi = {
6968
+ list: (userId) => {
6969
+ const jobs = msgQueue.list(userId);
6970
+ const busy = busyUsers.has(userId) ? "当前任务:处理中(发 /cancel 可中断)" : "当前任务:空闲";
6971
+ if (jobs.length === 0)
6972
+ return `${busy}
6973
+ 队列:空`;
6974
+ const lines = jobs.map((j) => ` #${j.id} · ${agoLabel(j.enqueuedAt)} · ${previewText(j.text)}`);
6975
+ return [
6976
+ busy,
6977
+ `队列:${jobs.length} 条(上限 ${QUEUE_MAX})`,
6978
+ ...lines,
6979
+ "发 /queue clear 清空,/queue drop <编号> 删除一条。"
6980
+ ].join(`
6981
+ `);
6982
+ },
6983
+ clear: (userId) => msgQueue.clear(userId),
6984
+ drop: (userId, id) => msgQueue.drop(userId, id) ? `已删除队列 #${id}` : `队列里没有 #${id}`
6985
+ };
6986
+ const progressApi = {
6987
+ query: (userId) => {
6988
+ const session = sessions.getSession(userId);
6989
+ if (!session)
6990
+ return "当前还没有会话,发消息即可开始";
6991
+ const st = turnStats.get(session.sessionId);
6992
+ const busy = busyUsers.has(userId) ? "处理中" : "空闲";
6993
+ const bg = bgWaits.has(session.sessionId) ? " · 后台等待在途" : "";
6994
+ if (!st)
6995
+ return `当前会话:${busy}${bg}
6996
+ 暂无工具调用记录(本会话新起或尚无动作类里程碑)`;
6997
+ return [
6998
+ `当前会话:${busy}${bg}`,
6999
+ `工具调用 ${st.tools} 次(失败 ${st.failed})`,
7000
+ st.lastTool ? `最近:${st.lastTool}` : "",
7001
+ st.lastAt ? `最近活动:${agoLabel(st.lastAt)}` : ""
7002
+ ].filter(Boolean).join(`
7003
+ `);
7004
+ }
7005
+ };
6764
7006
  const commandContext = {
6765
7007
  config,
6766
7008
  client,
@@ -6768,7 +7010,9 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
6768
7010
  getAccessToken: () => getAccessToken(config.qq.appId, config.qq.clientSecret),
6769
7011
  pendingSelections,
6770
7012
  watch: watchApi,
6771
- mirror: mirrorApi
7013
+ mirror: mirrorApi,
7014
+ queue: queueApi,
7015
+ progress: progressApi
6772
7016
  };
6773
7017
  if (config.allowedUsers.length === 0) {
6774
7018
  console.warn("[security] ALLOWED_USERS 为空 → 所有消息将被拒绝(fail-closed);请在 ~/.openqq/.env 配置白名单");
@@ -6793,6 +7037,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
6793
7037
  mirror.ensureSubs();
6794
7038
  purgeOldQQImages();
6795
7039
  const handleMessage = async (ctx) => {
7040
+ let claimedMsgId = "";
6796
7041
  try {
6797
7042
  if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
6798
7043
  await sendReply(ctx, "你不在允许使用的名单里");
@@ -6803,7 +7048,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
6803
7048
  return;
6804
7049
  }
6805
7050
  lastCtx.set(ctx.userId, ctx);
6806
- if (!greeted.has(ctx.userId)) {
7051
+ if (!greeted.has(ctx.userId) && !isCommand(content)) {
6807
7052
  greeted.add(ctx.userId);
6808
7053
  saveGreetedSet(greeted);
6809
7054
  await sendReply(ctx, buildHelpText());
@@ -6831,8 +7076,30 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
6831
7076
  await sendReply(ctx, formatPermissionPrompt(pendingPerm.request, pendingPerm.mainSessionId));
6832
7077
  return;
6833
7078
  }
7079
+ if (ctx.msgId) {
7080
+ if (!claimedContexts.has(ctx)) {
7081
+ const claimed = claimInflight({ msgId: ctx.msgId, userId: ctx.userId, sessionId: "", text: content.slice(0, 300), at: Date.now() });
7082
+ if (!claimed) {
7083
+ console.log(`[bridge] 重复消息已跳过 msgId=${ctx.msgId}`);
7084
+ return;
7085
+ }
7086
+ claimedContexts.add(ctx);
7087
+ }
7088
+ claimedMsgId = ctx.msgId;
7089
+ }
6834
7090
  if (busyUsers.has(ctx.userId)) {
6835
- await sendReply(ctx, "上一条消息还在处理中,请稍候再试");
7091
+ if (ctx.attachments?.length && !ctx.preparedAttachments) {
7092
+ ctx.preparedAttachments = await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
7093
+ }
7094
+ const queued = msgQueue.push(ctx.userId, ctx);
7095
+ if (!queued) {
7096
+ if (claimedMsgId)
7097
+ settleInflight(claimedMsgId);
7098
+ await sendReply(ctx, `排队已满(${QUEUE_MAX} 条),请稍候再试或 /cancel 中止当前任务`);
7099
+ return;
7100
+ }
7101
+ await sendReply(ctx, `已排队 #${queued.job.id}${queued.ahead > 0 ? `(前面还有 ${queued.ahead} 条)` : ""},当前任务结束后自动执行。
7102
+ 发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`);
6836
7103
  return;
6837
7104
  }
6838
7105
  busyUsers.add(ctx.userId);
@@ -6855,7 +7122,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
6855
7122
  subscribeSession(sessionId, ctx.userId);
6856
7123
  mirror.beginTurn(sessionId);
6857
7124
  turnStart = Date.now();
6858
- const prepared = await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
7125
+ const prepared = ctx.preparedAttachments ?? await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
6859
7126
  const { text: promptBody, files } = augmentPromptWithAttachments(content, prepared);
6860
7127
  const promptText = ctx.quoteText ? `> 引用上文:${ctx.quoteText}
6861
7128
 
@@ -6893,7 +7160,9 @@ ${promptBody}` : promptBody;
6893
7160
  await safeDeliver(ctx, "⏳ 回合超过前台时限,已转后台等待:任务继续执行,完成即回传结果(最长 24 小时)。期间可用 /history 查看进展。");
6894
7161
  startBackgroundWait(sessionId, ctx, turnStart, trackId);
6895
7162
  } else {
6896
- await safeDeliver(ctx, `处理失败:${toErrorMessage2(error)}`);
7163
+ const errText = toErrorMessage2(error);
7164
+ const rescue = rescueText(classifyProviderError(errText), errText);
7165
+ await safeDeliver(ctx, rescue ?? `处理失败:${errText}`);
6897
7166
  settleInflight(trackId);
6898
7167
  }
6899
7168
  } finally {
@@ -6902,8 +7171,12 @@ ${promptBody}` : promptBody;
6902
7171
  if (sessionId && !bgWaits.has(sessionId))
6903
7172
  mirror.scheduleUnlock(sessionId);
6904
7173
  busyUsers.delete(ctx.userId);
7174
+ if (sessionId && !bgWaits.has(sessionId))
7175
+ drainQueue(ctx.userId);
6905
7176
  }
6906
7177
  } catch (error) {
7178
+ if (claimedMsgId)
7179
+ settleInflight(claimedMsgId);
6907
7180
  console.error("[bridge] handleMessage failed:", error);
6908
7181
  try {
6909
7182
  await sendReply(ctx, `处理消息失败:${toErrorMessage2(error)}`);
@@ -6939,11 +7212,11 @@ ${cls.answer}`);
6939
7212
  console.log(`[bridge] 启动对账:在途任务已重挂后台等待 msgId=${entry.msgId}`);
6940
7213
  } else if (ageMs <= redispatchMaxAgeMs()) {
6941
7214
  settleInflight(entry.msgId);
6942
- await deliver(ctx, `\uD83D\uDD04 重启恢复:重新处理你之前的消息「${entry.text.slice(0, 50)}」`);
7215
+ await deliver(ctx, `\uD83D\uDD04 重启恢复:重新处理你之前的消息「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」`);
6943
7216
  handleMessage(ctx);
6944
7217
  console.log(`[bridge] 启动对账:丢失消息已重派 msgId=${entry.msgId}`);
6945
7218
  } else {
6946
- await deliver(ctx, `⚠️ 此前重启期间丢失一条你的消息「${entry.text.slice(0, 50)}」(超过自动重派窗口未重发),需要的话请重发一次`);
7219
+ await deliver(ctx, `⚠️ 此前重启期间丢失一条你的消息「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」(超过自动重派窗口未重发),需要的话请重发一次`);
6947
7220
  settleInflight(entry.msgId);
6948
7221
  console.log(`[bridge] 启动对账:超期消息仅通知 msgId=${entry.msgId}`);
6949
7222
  }
@@ -6952,6 +7225,24 @@ ${cls.answer}`);
6952
7225
  }
6953
7226
  }
6954
7227
  }
7228
+ async function drainQueue(userId) {
7229
+ if (draining.has(userId) || busyUsers.has(userId))
7230
+ return;
7231
+ const job = msgQueue.shift(userId);
7232
+ if (!job)
7233
+ return;
7234
+ draining.add(userId);
7235
+ try {
7236
+ await sendReply(job.ctx, `开始执行队列 #${job.id}`);
7237
+ await handleMessage(job.ctx);
7238
+ } catch (error) {
7239
+ console.error("[bridge] 队列执行失败:", error);
7240
+ } finally {
7241
+ draining.delete(userId);
7242
+ if (msgQueue.size(userId) > 0 && !busyUsers.has(userId))
7243
+ drainQueue(userId);
7244
+ }
7245
+ }
6955
7246
  return {
6956
7247
  handleMessage,
6957
7248
  eventStream,
@@ -6987,7 +7278,7 @@ var WATCH_FILE = join10(homedir9(), ".openqq", "watch.json");
6987
7278
  function loadWatchedMap(file = WATCH_FILE) {
6988
7279
  try {
6989
7280
  if (existsSync8(file)) {
6990
- const raw = readFileSync9(file, "utf-8");
7281
+ const raw = readFileSync10(file, "utf-8");
6991
7282
  const obj = JSON.parse(raw);
6992
7283
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
6993
7284
  const out = {};
@@ -7011,7 +7302,7 @@ var GREETED_FILE = join10(homedir9(), ".openqq", "greeted.json");
7011
7302
  function loadGreetedSet() {
7012
7303
  try {
7013
7304
  if (existsSync8(GREETED_FILE)) {
7014
- const raw = readFileSync9(GREETED_FILE, "utf-8");
7305
+ const raw = readFileSync10(GREETED_FILE, "utf-8");
7015
7306
  const arr = JSON.parse(raw);
7016
7307
  if (Array.isArray(arr)) {
7017
7308
  return new Set(arr.filter((x) => typeof x === "string"));
@@ -7074,7 +7365,7 @@ function toErrorMessage2(error) {
7074
7365
  }
7075
7366
 
7076
7367
  // src/core/instance-lock.ts
7077
- import { openSync, writeFileSync as writeFileSync11, closeSync, unlinkSync as unlinkSync2, statSync as statSync3, utimesSync, mkdirSync as mkdirSync8 } from "fs";
7368
+ import { openSync as openSync2, writeFileSync as writeFileSync11, closeSync as closeSync2, unlinkSync as unlinkSync3, statSync as statSync4, utimesSync, mkdirSync as mkdirSync8 } from "fs";
7078
7369
  import { join as join11 } from "path";
7079
7370
  import { homedir as homedir10 } from "os";
7080
7371
  var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
@@ -7091,18 +7382,18 @@ function touch(path) {
7091
7382
  function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
7092
7383
  try {
7093
7384
  mkdirSync8(join11(path, ".."), { recursive: true });
7094
- const fd = openSync(path, "wx");
7385
+ const fd = openSync2(path, "wx");
7095
7386
  writeFileSync11(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
7096
- closeSync(fd);
7387
+ closeSync2(fd);
7097
7388
  } catch {
7098
7389
  try {
7099
- const age = Date.now() - statSync3(path).mtimeMs;
7390
+ const age = Date.now() - statSync4(path).mtimeMs;
7100
7391
  if (age <= staleMs)
7101
7392
  return null;
7102
- unlinkSync2(path);
7103
- const fd = openSync(path, "wx");
7393
+ unlinkSync3(path);
7394
+ const fd = openSync2(path, "wx");
7104
7395
  writeFileSync11(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
7105
- closeSync(fd);
7396
+ closeSync2(fd);
7106
7397
  console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
7107
7398
  } catch {
7108
7399
  return null;
@@ -7122,7 +7413,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
7122
7413
  released = true;
7123
7414
  clearInterval(heartbeat);
7124
7415
  try {
7125
- unlinkSync2(path);
7416
+ unlinkSync3(path);
7126
7417
  } catch {}
7127
7418
  }
7128
7419
  };