@linjz/opencode-qqbot 0.3.16 → 0.3.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linjz/opencode-qqbot",
3
- "version": "0.3.16",
3
+ "version": "0.3.17",
4
4
  "type": "module",
5
5
  "description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
6
6
  "exports": {
@@ -14,7 +14,7 @@
14
14
  "dev": "bun run --watch src/index.ts",
15
15
  "start": "bun run src/index.ts",
16
16
  "typecheck": "tsc --noEmit",
17
- "test": "bun run test/decision-cases.ts && bun run test/milestone-cases.ts && bun run test/attachment-cases.ts && bun run test/r2-hardening-cases.ts && bun run test/e1-mirror-digest.ts && bun run test/mask-headers-cases.ts && bun run test/perm-mock.ts && bun run test/discovery-cases.ts && bun run test/linkwatch-cases.ts && bun run test/reply-limiter-cases.ts && bun run test/card-approval-cases.ts && bun run test/message-split-cases.ts && bun run test/sync-batch1-cases.ts && bun run test/delivery-dedupe-cases.ts && bun run test/stream-stagger-cases.ts && bun run test/history-render-cases.ts && bun run test/stall-nudge-cases.ts && bun run test/interaction-watch-cases.ts && bun run test/form-command-gate-cases.ts && bun run test/quote-voice-dedup-cases.ts && bun run test/send-media-cases.ts && bun run test/rival-absorb-cases.ts && bun run test/inflight-recovery-cases.ts && bun run test/plugin-launcher-cases.ts && bun run test/pi-absorb-cases.ts && bun run test/recovery-history-cases.ts && bun run test/inbound-dedupe-cases.ts && bun run test/gateway-state-cases.ts && bun run test/turn-attribution-cases.ts && bun run test/qq-render-cases.ts && bun run test/instance-lock-cases.ts && bun run test/outbox-cases.ts && bun run test/notify-cases.ts && bun run test/queue-observability-cases.ts && bun run test/queue-session-isolation-cases.ts && bun run test/zombie-reaper-cases.ts && bun run test/question-form-cases.ts && bun run test/interaction-ack-cases.ts && bun run test/eventstream-flood-cases.ts && bun run test/watchdog-cases.ts && bun run test/service-cases.ts && bun run test/launcher-silent-cases.ts && bun run test/status-title-cases.ts && bun run test/permission-sync-cases.ts && bun run test/perm-location-cases.ts && bun run test/session-model-cases.ts && bun run test/supervise-hardening-cases.ts && bun run test/emoji-gate-cases.ts && bun run test/markdown-safe-cases.ts && bun run test/multibot-cases.ts && bun run test/lane-scope-cases.ts && bun run test/active-quota-cases.ts && bun run test/bg-stream-liveness-cases.ts && bun run test/bg-resume-cases.ts",
17
+ "test": "bun run test/decision-cases.ts && bun run test/milestone-cases.ts && bun run test/attachment-cases.ts && bun run test/r2-hardening-cases.ts && bun run test/e1-mirror-digest.ts && bun run test/mask-headers-cases.ts && bun run test/perm-mock.ts && bun run test/discovery-cases.ts && bun run test/linkwatch-cases.ts && bun run test/reply-limiter-cases.ts && bun run test/card-approval-cases.ts && bun run test/message-split-cases.ts && bun run test/sync-batch1-cases.ts && bun run test/delivery-dedupe-cases.ts && bun run test/stream-stagger-cases.ts && bun run test/history-render-cases.ts && bun run test/stall-nudge-cases.ts && bun run test/interaction-watch-cases.ts && bun run test/form-command-gate-cases.ts && bun run test/quote-voice-dedup-cases.ts && bun run test/send-media-cases.ts && bun run test/rival-absorb-cases.ts && bun run test/inflight-recovery-cases.ts && bun run test/plugin-launcher-cases.ts && bun run test/pi-absorb-cases.ts && bun run test/recovery-history-cases.ts && bun run test/inbound-dedupe-cases.ts && bun run test/gateway-state-cases.ts && bun run test/turn-attribution-cases.ts && bun run test/qq-render-cases.ts && bun run test/instance-lock-cases.ts && bun run test/outbox-cases.ts && bun run test/notify-cases.ts && bun run test/queue-observability-cases.ts && bun run test/queue-session-isolation-cases.ts && bun run test/zombie-reaper-cases.ts && bun run test/question-form-cases.ts && bun run test/interaction-ack-cases.ts && bun run test/eventstream-flood-cases.ts && bun run test/kill-audit-cases.ts && bun run test/sender-path-cases.ts && bun run test/notices-cases.ts && bun run test/config-overlay-cases.ts && bun run test/outbound-storm-cases.ts && bun run test/stt-cron-cases.ts && bun run test/watchdog-cases.ts && bun run test/service-cases.ts && bun run test/launcher-silent-cases.ts && bun run test/status-title-cases.ts && bun run test/permission-sync-cases.ts && bun run test/perm-location-cases.ts && bun run test/session-model-cases.ts && bun run test/supervise-hardening-cases.ts && bun run test/emoji-gate-cases.ts && bun run test/markdown-safe-cases.ts && bun run test/multibot-cases.ts && bun run test/lane-scope-cases.ts && bun run test/active-quota-cases.ts && bun run test/bg-stream-liveness-cases.ts && bun run test/bg-resume-cases.ts && bun run test/startup-resilience-cases.ts && bun run test/log-rotate-cases.ts && bun run test/lock-sweep-cases.ts && bun run test/supervisor-election-cases.ts && bun run test/config-roles-cases.ts && bun run test/filelog-format-cases.ts",
18
18
  "test:e2e": "bun run test/watch-history-e2e.ts && bun run test/d1-subagent-ask-e2e.ts && bun run test/d2-conflict-e2e.ts && bun run test/perm-e2e.ts && bun run test/perm-real-e2e.ts",
19
19
  "verify": "bun run typecheck && bun run test",
20
20
  "verify:full": "bun run verify && bun run test:e2e",
package/src/bridge.ts CHANGED
@@ -40,6 +40,8 @@ import {
40
40
  import { createMirror } from "./core/mirror.js"
41
41
  import { MessageQueue, laneKeyOf, laneScope, sessionIdOfLane, userIdOfLane, previewText, agoLabel, intentKeyOf } from "./core/message-queue.js"
42
42
  import { classifyProviderError, rescueText } from "./core/error-rescue.js"
43
+ import { NOTICE } from "./core/notices.js"
44
+ import { parseCronReminder, ReminderScheduler } from "./core/cron-reminders.js"
43
45
 
44
46
  const QUEUE_MAX = 20 // Q1:忙碌队列上限(学习 pi-qqbot queue.max 默认)
45
47
  // 2026-11-05:队列完成回执("队列 #N 完成(剩余 M 条)")默认关闭——批量排空时
@@ -243,6 +245,60 @@ export function resumeDecision(resumeCount: number, max: number): "resume" | "gi
243
245
  return max > 0 && resumeCount < max ? "resume" : "giveup"
244
246
  }
245
247
 
248
+ // ===== /amend(steer 降级版,2026-11-22 owner 裁定参考 Hermes update_prompt)=====
249
+
250
+ /**
251
+ * 忙时投递默认(纯函数供测试):owner 2026-11-23 裁定「默认对齐官方 TUI——忙时
252
+ * Enter steers」——steer=新消息并入在途回合;queue=客户端 FIFO 排队(旧行为)。
253
+ * 默认 steer;显式 "queue" 切回排队;非法值回退 steer(官方语义优先)。
254
+ */
255
+ export function resolveBusyMode(envValue: string | undefined): "steer" | "queue" {
256
+ return envValue?.trim().toLowerCase() === "queue" ? "queue" : "steer"
257
+ }
258
+
259
+ /** 并入 prompt 构造(纯函数供测试):原 prompt + 补充指令块,模型读历史接着做。 */
260
+ export function buildAmendPrompt(original: string, amendment: string): string {
261
+ return `${original}\n\n【补充指令】${amendment.trim()}`
262
+ }
263
+
264
+ /**
265
+ * 并入目标选择(纯函数供测试):本用户该会话最新一条已落 promptId 且有原文的
266
+ * 在途回合(stage 不限——running/background/dispatched 均可并入;queued 无
267
+ * promptId 自然落选)。找不到=不可并入(桌面端发起/已结清)。
268
+ */
269
+ export function selectAmendEntry(
270
+ entries: Array<Pick<import("./core/inflight-journal.js").InflightEntry, "userId" | "sessionId" | "promptId" | "text" | "at" | "msgId" | "attemptId">>,
271
+ userId: string,
272
+ sessionId: string,
273
+ ): (typeof entries)[number] | undefined {
274
+ return entries
275
+ .filter((e) => e.userId === userId && e.sessionId === sessionId && e.promptId && e.text)
276
+ .sort((a, b) => b.at - a.at)[0]
277
+ }
278
+
279
+ // ===== 会话回滚(官方 /undo 对齐批,2026-11-23 owner 令「对上opencode桌面端,开工」)=====
280
+ // 基准=opencode.ai/docs/snapshots:/undo=stage 边界→恢复文件→prompt 回盒,提交编辑后
281
+ // prompt 时才 commit;/redo=取消暂存;会话运行中拒绝 revert。QQ 侧 /undo 为一次性
282
+ // stage→commit(无暂存窗,故 /redo 无对象——如实不做,不做半成品语义)。
283
+
284
+ /** 取会话消息列表中最后一条 user 消息的 id(回滚边界;纯函数供测试)。 */
285
+ export function lastUserMessageId(msgs: Array<{ id?: string; type?: string }>): string | null {
286
+ for (let i = msgs.length - 1; i >= 0; i--) {
287
+ if (msgs[i].type === "user" && msgs[i].id) return msgs[i].id as string
288
+ }
289
+ return null
290
+ }
291
+
292
+ /** 从消息体提取可读文本(user 消息 content 可能为字符串或 text 块数组;纯函数供测试)。 */
293
+ export function messageTextOf(m: { content?: unknown }): string {
294
+ const c = m.content
295
+ if (typeof c === "string") return c
296
+ if (Array.isArray(c)) {
297
+ return c.map((p) => (typeof p === "object" && p !== null && "text" in p ? String((p as { text?: unknown }).text ?? "") : "")).join("")
298
+ }
299
+ return ""
300
+ }
301
+
246
302
  /**
247
303
  * 流活性判定(纯函数供测试)。msgs=同一次后台探知的拉取结果;
248
304
  * promptId/baseline=本回合锚点(与 turnStateOf 同口径)。
@@ -873,6 +929,9 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
873
929
  // 清槽必须两入口等价;clearIfResolved 保证桌面先决时 QQ 卡自动关闭(不双发)。
874
930
  // 多角色:本 gate 绑本角色 storageAppId(pending 落 roles/<appId>/),
875
931
  // 跨角色审批隔离=文件级+槽位 userId 级双保险,改造时不得合并。
932
+ // Y-1 cron 提醒调度器(2026-11-23):进程内单次提醒,重启即失(与 openclaw 同口径)
933
+ const cronScheduler = new ReminderScheduler()
934
+
876
935
  const perm = createPermissionGate({
877
936
  client,
878
937
  sendReply,
@@ -904,8 +963,22 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
904
963
  busyUsers,
905
964
  // 多角色:镜像开关按角色分文件(缺省 legacy 全局)
906
965
  settingsFile: storageAppId ? roleFile("settings.json") : undefined,
966
+ // A 方案(owner 2026-11-23):桌面端回合的摘要同样过 cron 钩——注册提醒+剥净标记
967
+ onDigest: (userId, digest) => {
968
+ const hit = parseCronReminder(digest, Date.now())
969
+ if (!hit) return digest
970
+ registerCron(userId, hit)
971
+ return hit.cleanedText // 剥净为空 → 镜像侧跳过投递(注册即全部语义)
972
+ },
907
973
  })
908
974
 
975
+ /** 双端共用的 cron 注册(QQ 侧与镜像侧同一调度器/上限/投递链)。 */
976
+ function registerCron(userId: string, hit: { atMs: number; reminderText: string }): boolean {
977
+ return cronScheduler.schedule(userId, hit.atMs, hit.reminderText, (uid, t) => {
978
+ void safeDeliver(ctxForUser(uid), t).catch(() => {})
979
+ })
980
+ }
981
+
909
982
  // openqq notify 外部入队通道(feature:headless 定时任务结果推送,2026-11-05 外部提案 Part1):
910
983
  // cron/CI 任意进程经 `openqq notify` 写 ~/.openqq/outbox.json(只入队),bot 进程消费投递。
911
984
  // delivery 全量复用(配额/降级/分条/24h 同文去重);TTL 过期丢弃;失败退避重试到上限。
@@ -1352,7 +1425,7 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1352
1425
  } else {
1353
1426
  // 完成无正文(被杀回合)或 L2 静默强杀 → expired + 可见交代
1354
1427
  inflight.settle(entry.msgId, undefined, "expired")
1355
- await safeDeliver(ctx, "⚠️ 检测到一个卡死的回合(长时间无进展),已自动清理;如未收到预期结果请重新发送").catch(() => {})
1428
+ await safeDeliver(ctx, NOTICE.reaperExpired()).catch(() => {})
1356
1429
  }
1357
1430
  console.log(
1358
1431
  `[reaper] ${dec.kind} user=${uid.slice(0, 8)}… lane=${shortId(sid)} msg=${shortId(entry.msgId)} age=${Math.round((now - entry.at) / 60_000)}m`,
@@ -1418,6 +1491,186 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1418
1491
  },
1419
1492
  }
1420
1493
 
1494
+ /**
1495
+ * /amend:steer 降级版「并入当前任务」(owner 2026-11-22 裁定,参考 Hermes update_prompt:y/n)。
1496
+ * 引擎无在途注入能力(openapi 139 端点实证),落地形态=打断并以「原 prompt+补充」同会话续跑
1497
+ * (模型读历史接着做,与死回合自动续作同语义)。abort 顺序复用 stopAll 证毕的
1498
+ * cancel→abort 链:先杀后台监督再 abort,杜绝「判死→自动续作」race 双跑。
1499
+ */
1500
+ async function amendCurrentTurn(userId: string, amendment: string): Promise<string> {
1501
+ const add = amendment.trim()
1502
+ if (!add) {
1503
+ return "用法:/amend <补充指令>——打断当前任务,把你的补充并入原指令一起续跑(模型从历史接着做)"
1504
+ }
1505
+ const session = sessions.getSession(userId)
1506
+ // 活动 lane=该用户名下仍 busy 的 lane(stopAll 同款口径,不依赖队列条目存在)
1507
+ const activeLane = [...busyUsers].find((k) => userIdOfLane(k) === userId)
1508
+ if (!session || !activeLane) return "当前没有进行中的任务,直接发消息即可"
1509
+ // —— /amend v3:真 steer(2026-11-23 对齐官方 TUI「忙时 Enter steers」语义)——
1510
+ // 订正:steer 不在独立端点上,藏在 prompt body 的 delivery 枚举(Session.Inbox
1511
+ // .Delivery=steer|queue)——此前「引擎无 steer」结论系关键词检索漏判(教训同
1512
+ // form 命名空间事件,已入技能纪律)。steer=补充直达在途回合:无 abort、无 token
1513
+ // 沉没、死回合残骸为零。失败(引擎旧版/竞态)回落 v2 abort+revert 链。
1514
+ try {
1515
+ await client.session.prompt({
1516
+ path: { id: session.sessionId },
1517
+ body: { text: `【补充指令】${add}`, delivery: "steer" },
1518
+ })
1519
+ console.log(`[bridge] amend steer 已送达 user=${userId.slice(0, 8)}… session=${shortId(session.sessionId)}`)
1520
+ return "✅ 已把补充送进当前任务(官方 steer 语义:模型把这条指令并入正在跑的回合,完成照常回传)"
1521
+ } catch (error) {
1522
+ console.log(`[bridge] amend steer 被拒,回落 abort+revert 链: ${toErrorMessage(error)}`)
1523
+ }
1524
+ // —— 回落链(v2,2026-11-22):abort → revert 清残骸 → 合并重发 ——
1525
+ // 原 prompt 取在途账:本用户锚定会话里已落 promptId 的活动回合(stage running/background
1526
+ // 或 dispatched——只要 state=inflight 且有 promptId 即本回合;取最新一条)
1527
+ const entry = selectAmendEntry(inflight.pending(), userId, session.sessionId)
1528
+ if (!entry) {
1529
+ return "找不到可并入的原任务(可能由桌面端发起或已被结清);请用 /cancel 后重发完整指令"
1530
+ }
1531
+ // 1) 先杀后台监督(bgWait cancel=监督循环退出,resumeDead 不可能再触发)
1532
+ bgWaits.get(session.sessionId)?.cancel()
1533
+ // 2) abort 当前回合(悬挂回合可能已自行终结,失败不阻断)
1534
+ try {
1535
+ await client.session.abort({ path: { id: session.sessionId } })
1536
+ } catch {
1537
+ /* 同 stopAll:abort 失败不阻断复位 */
1538
+ }
1539
+ // 3) 结清被并入回合的账(cancelled=用户主动中止语义,与 /cancel 同口径)
1540
+ inflight.settle(entry.msgId, entry.attemptId, "cancelled")
1541
+ // 3.5) 官方 /undo 语义对齐(snapshots 文档):abort 后会话不再 running——尝试把
1542
+ // 死回合连同原 prompt 一起 revert 出上下文(files:true=死回合改过的文件一并恢复),
1543
+ // 模型续跑时看到的是「任务从没开始」的干净历史。revert 失败(非 git 目录/旧引擎/
1544
+ // 竞态)回落 v1「读历史续跑」语义——不阻塞功能,只降级体感。
1545
+ let reverted = false
1546
+ try {
1547
+ await client.session.revertStage({ path: { id: session.sessionId }, body: { messageID: entry.promptId as string, files: true } })
1548
+ await client.session.revertCommit({ path: { id: session.sessionId } })
1549
+ reverted = true
1550
+ } catch (error) {
1551
+ try {
1552
+ await client.session.revertDiscard({ path: { id: session.sessionId } })
1553
+ } catch {
1554
+ /* 无暂存可弃(stage 即失败场景) */
1555
+ }
1556
+ console.log(`[bridge] amend revert 失败,回落读历史续跑 session=${shortId(session.sessionId)}: ${toErrorMessage(error)}`)
1557
+ }
1558
+ // 4) 合成并入消息入队:原 prompt + 补充指令,drain 在 lane 释放后续跑
1559
+ //(复用既有 FIFO/单飞/在途账全链;msgId 空=主动通道投递,同 reaper 合成 ctx 先例)
1560
+ const actx: MessageContext = { ...ctxForUser(userId), msgId: "", content: buildAmendPrompt(entry.text, add) }
1561
+ msgQueue.push(activeLane, userId, session.sessionId, actx)
1562
+ console.log(`[bridge] amend 并入 user=${userId.slice(0, 8)}… lane=${shortId(session.sessionId)} msg=${shortId(entry.msgId)}`)
1563
+ // 5) 手动释放 lane + drain(bgWait 已 cancel,监督不会复活抢 lane)
1564
+ busyUsers.delete(activeLane)
1565
+ void drainQueue(userId, session.sessionId)
1566
+ return reverted
1567
+ ? "✅ 已打断并清空该回合(含文件回滚),正带你的补充重新起跑"
1568
+ : "✅ 已打断当前任务,正把你的补充并入原指令续跑(模型从历史接着做,完成自动回复)"
1569
+ }
1570
+
1571
+ /**
1572
+ * /undo:对齐官方 TUI /undo(snapshots 文档三段语义的一次性版)——stage 到最后一条
1573
+ * user 消息边界(files:true 恢复该回合改动的文件)→ commit → 回执带被撤 prompt
1574
+ * (QQ 版「prompt 回盒」:用户改后可重发,或 /amend <补充> 带修改续跑)。
1575
+ * 运行中拒绝(官方语义:OpenCode rejects rollback while the session is running)。
1576
+ */
1577
+ async function undoLastTurn(userId: string): Promise<string> {
1578
+ const session = sessions.getSession(userId)
1579
+ if (!session) return "没有绑定的会话,无事可撤销"
1580
+ if ([...busyUsers].some((k) => userIdOfLane(k) === userId)) {
1581
+ return "当前有任务在跑——官方语义运行中不可回滚;请先等它完成,或 /cancel 后再 /undo"
1582
+ }
1583
+ let msgs: Awaited<ReturnType<typeof client.session.messages>>["data"] = []
1584
+ try {
1585
+ msgs = (await client.session.messages({ path: { id: session.sessionId }, query: { limit: 50 } })).data ?? []
1586
+ } catch (error) {
1587
+ return `读取会话失败:${toErrorMessage(error)}`
1588
+ }
1589
+ const boundary = lastUserMessageId(msgs)
1590
+ if (!boundary) return "会话里没有可撤销的用户消息"
1591
+ const removed = msgs.find((m) => m.id === boundary)
1592
+ const removedText = messageTextOf(removed ?? {}).trim()
1593
+ try {
1594
+ await client.session.revertStage({ path: { id: session.sessionId }, body: { messageID: boundary, files: true } })
1595
+ await client.session.revertCommit({ path: { id: session.sessionId } })
1596
+ } catch (error) {
1597
+ try {
1598
+ await client.session.revertDiscard({ path: { id: session.sessionId } })
1599
+ } catch {
1600
+ /* 无暂存可弃 */
1601
+ }
1602
+ return `撤销失败:${toErrorMessage(error)}(引擎拒绝或快照缺失;会话内容未改动)`
1603
+ }
1604
+ console.log(`[bridge] undo 已回滚 user=${userId.slice(0, 8)}… session=${shortId(session.sessionId)} boundary=${shortId(boundary)}`)
1605
+ const box = removedText ? `被撤回的指令:「${removedText.length > 80 ? `${removedText.slice(0, 80)}…` : removedText}」\n改好后重新发送即可,或 /amend <修改点> 带修改重跑。` : "改好后重新发送即可。"
1606
+ return `↩️ 已撤销上一回合(该回合改动的文件已一并恢复)。\n${box}`
1607
+ }
1608
+
1609
+ /**
1610
+ * 显性入队(/queue <文本>,owner 2026-11-23):steer 默认模式下把文本显式排进
1611
+ * FIFO(而非并入当前任务)。合成 ctx(msgId 空=主动通道投递,同恢复重派先例),
1612
+ * 走既有 msgQueue/drain 全链(单飞/台账/去重全继承);当前空闲则入队即执行。
1613
+ */
1614
+ async function enqueueExplicit(ctx: MessageContext, text: string): Promise<string> {
1615
+ const session = sessions.getSession(ctx.userId)
1616
+ const sid = session?.sessionId
1617
+ if (!sid) return "没有绑定的会话,请先发消息建立会话再排队"
1618
+ const lane = laneKeyOf(ctx.userId, sid)
1619
+ const actx: MessageContext = { ...ctx, msgId: "", content: text }
1620
+ const queued = msgQueue.push(lane, ctx.userId, sid, actx)
1621
+ if (!queued) return "队列已满,请等当前任务完成或 /queue clear 后重试"
1622
+ console.log(`[queue] 显性入队 user=${ctx.userId.slice(0, 8)}… qid=${queued.job.id} ahead=${queued.ahead}`)
1623
+ void drainQueue(ctx.userId, sid)
1624
+ if (queued.ahead === 0 && !busyUsers.has(lane)) {
1625
+ return `📥 已入队 #${queued.job.id},当前空闲,立即执行`
1626
+ }
1627
+ return `📥 已排队 #${queued.job.id}(第 ${queued.ahead + 1} 位),当前任务结束后自动执行`
1628
+ }
1629
+
1630
+ /**
1631
+ * 官方斜杠命令直通(owner 2026-11-23):/goal /compact /redo /btw 经引擎
1632
+ * POST /session/{id}/command 执行——与桌面端同一实现(goal 的 idle 审查器、
1633
+ * 50 轮/停滞刹车全在引擎侧,咱们零重写=严格对齐)。引擎 <2.2.1 无内置 goal
1634
+ * 时如实报错。
1635
+ */
1636
+ async function runEngineCommand(userId: string, name: string, text: string): Promise<string> {
1637
+ const session = sessions.getSession(userId)
1638
+ if (!session) return "没有绑定的会话;先在 QQ 里发一条消息建立会话"
1639
+ try {
1640
+ const res = (await client.session.command({
1641
+ path: { id: session.sessionId },
1642
+ body: { name, text },
1643
+ })) as { data?: { text?: string; message?: string }; text?: string; message?: string }
1644
+ const reply = res?.data?.text ?? res?.text ?? res?.data?.message ?? res?.message
1645
+ if (reply) return reply
1646
+ // 引擎 command 端点对多数命令不回文本——给分命令的诚实兜底(真机实证 11-23:
1647
+ // /goal 设完静默执行多轮,用户误以为没生效)
1648
+ if (name === "goal") {
1649
+ return "✅ goal 已执行(引擎无文本回执)。查状态再发 /goal;控制用 /goal pause|resume|clear。设定目标后会话自主续跑,进展会以普通回复推送到这里"
1650
+ }
1651
+ return `✅ /${name} 已执行(引擎无文本回执)`
1652
+ } catch (error) {
1653
+ const msg = toErrorMessage(error)
1654
+ // 引擎把 goal 状态(paused/done 的完成度审计)走 500 CommandExecutionError
1655
+ // 通道返回(真机实证 11-23)——非真失败:优先读 error.body 的完整 JSON
1656
+ //(日志 excerpt 有 200 字截断,长审计会切断 JSON 使正则失配),按状态报告呈现。
1657
+ if (name === "goal") {
1658
+ const full = (error as { body?: string }).body ?? msg
1659
+ const trimmed = full.trim()
1660
+ const jsonText = trimmed.startsWith("{") ? trimmed : (/\{[\s\S]*"message"[\s\S]*\}/.exec(full)?.[0] ?? "")
1661
+ if (jsonText) {
1662
+ try {
1663
+ const j = JSON.parse(jsonText) as { message?: string; command?: string }
1664
+ if (j.message) return `📋 目标状态(goal ${j.command ?? ""}):\n${j.message}`
1665
+ } catch {
1666
+ /* body 非完整 JSON → 落原失败路径 */
1667
+ }
1668
+ }
1669
+ }
1670
+ return `引擎命令执行失败(/goal 需 OpenCode ≥ 2.2.1):${msg}`
1671
+ }
1672
+ }
1673
+
1421
1674
  const commandContext: CommandContext = {
1422
1675
  config,
1423
1676
  client,
@@ -1430,6 +1683,10 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1430
1683
  ledger: ledgerApi,
1431
1684
  progress: progressApi,
1432
1685
  stopAll: stopAllForUser,
1686
+ amend: amendCurrentTurn,
1687
+ undo: undoLastTurn,
1688
+ enqueue: enqueueExplicit,
1689
+ engineCommand: runEngineCommand,
1433
1690
  }
1434
1691
 
1435
1692
  // R2 修复批次启动项(2026-10-14)
@@ -1600,6 +1857,28 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1600
1857
  }
1601
1858
 
1602
1859
  if (busyUsers.has(lane)) {
1860
+ // 忙时默认=steer(owner 2026-11-23 裁定:对齐官方 TUI「忙时 Enter steers」;
1861
+ // QQ_BUSY_DEFAULT=queue 切回客户端 FIFO 排队旧行为)——附件消息不走 steer
1862
+ //(附件需完整派发管线下载加工),自动落排队。
1863
+ if (resolveBusyMode(process.env.QQ_BUSY_DEFAULT) === "steer" && !ctx.attachments?.length) {
1864
+ try {
1865
+ const sidForSteer = anchorSid ?? sessions.getSession(ctx.userId)?.sessionId
1866
+ if (sidForSteer) {
1867
+ await client.session.prompt({
1868
+ path: { id: sidForSteer },
1869
+ body: { text: ctx.content, delivery: "steer" },
1870
+ })
1871
+ // 账侧:本条 msgId 由在途回合负责答复,steered 结清(孤儿收割不误伤)
1872
+ if (ctx.msgId) inflight.settle(ctx.msgId, undefined, "steered")
1873
+ console.log(`[bridge] 忙时 steer 并入 lane=${shortId(sidForSteer)} msg=${shortId(ctx.msgId)}`)
1874
+ await notifyUser(ctx, "🔄 已并入当前任务(官方 steer 语义,默认行为;想排队改 ~/.openqq/.env 的 QQ_BUSY_DEFAULT=queue)")
1875
+ return
1876
+ }
1877
+ } catch (error) {
1878
+ // steer 被拒(引擎竞态/旧版):落回下方排队路径,不丢消息
1879
+ console.log(`[bridge] 忙时 steer 失败改排队 msg=${shortId(ctx.msgId)}: ${toErrorMessage(error)}`)
1880
+ }
1881
+ }
1603
1882
  // Q1(学习 pi-qqbot 队列 UX):忙碌不再拒绝——FIFO 排队,回合结束自动执行
1604
1883
  // 自检补强:入队即下载附件——QQ 签名 URL 短时效,drain 时下载必过期
1605
1884
  if (ctx.attachments?.length && !ctx.preparedAttachments) {
@@ -1624,7 +1903,7 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1624
1903
  // 入队前已由 claimInflight 落账;drain 重入时回填 sessionId,不重复写账。
1625
1904
  await notifyUser(
1626
1905
  ctx,
1627
- `已排队 #${queued.job.id}(第 ${queued.ahead + 1} 位${queued.ahead > 0 ? `,前面还有 ${queued.ahead} 条` : ""}),当前任务结束后自动执行。\n发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`,
1906
+ `已排队 #${queued.job.id}(第 ${queued.ahead + 1} 位${queued.ahead > 0 ? `,前面还有 ${queued.ahead} 条` : ""}),当前任务结束后自动执行。\n发 /queue 查看队列,/cancel 可中止当前任务并清空队列;想立刻把新消息并进当前任务:/amend <补充>(打断并以原指令+补充续跑)。`,
1628
1907
  )
1629
1908
  return
1630
1909
  }
@@ -1783,7 +2062,17 @@ const sessionSubs = new Map<string, Set<string>>() // sessionID -> userIds
1783
2062
  // 超长回合可能已超被动窗口:deliver 被动失败自动降级主动,答案不丢
1784
2063
  // 直答出口统一脱敏(DEF-qqbot-20261106-2):与 history/mirror/form 同一脱敏器,
1785
2064
  // 防 AI 复述的密钥/令牌经直答气泡明文外泄。
1786
- if (extracted.text) turnDelivered = await safeDeliver(ctx, redactSecrets(extracted.text))
2065
+ // Y-1 cron 提醒(2026-11-23 学习吸收 openclaw):正文内嵌 QQBOT_PAYLOAD 标记
2066
+ // → 注册一次性提醒并剥离标记;剥净为空则以确认句回执(不留脚手架痕迹)。
2067
+ let outboundText = extracted.text
2068
+ const cronHit = parseCronReminder(extracted.text, Date.now())
2069
+ if (cronHit) {
2070
+ const okCron = registerCron(ctx.userId, cronHit)
2071
+ const when = new Date(cronHit.atMs).toLocaleString("zh-CN", { hour12: false })
2072
+ outboundText = cronHit.cleanedText ||
2073
+ (okCron ? `⏰ 好的,已设置提醒(${when}):${cronHit.reminderText}` : "⚠️ 提醒设置失败(同时在册超限),请重试")
2074
+ }
2075
+ if (outboundText.trim()) turnDelivered = await safeDeliver(ctx, redactSecrets(outboundText))
1787
2076
  }
1788
2077
  // DEF-qqbot-20261110-9(2026-11-10 回归实证):有正文但被 24h 去重拦截时
1789
2078
  // 不得记 answered——那是「台账假已答、用户侧零内容」。改记 error 并给用户交代。
package/src/cli/notify.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  import { existsSync, readFileSync } from "node:fs"
8
8
  import { createOutbox } from "../core/outbox.js"
9
9
  import { ENV_FILE, loadEnvFile } from "../config.js"
10
+ import { applyConfigOverlay } from "../core/bot-config.js"
10
11
  import { defaultOutboxPath, resolveNotifyRecipients } from "../core/notify-sink.js"
11
12
 
12
13
  export interface NotifyCliOptions {
@@ -108,7 +109,9 @@ export async function runNotifyCli(
108
109
  console.log(help)
109
110
  return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" }
110
111
  }
111
- // .env 注入:bot 进程入口已做;CLI 独立进程需自行加载(ALLOWED_USERS/凭据同源单点)
112
+ // .env 注入:bot 进程入口已做;CLI 独立进程需自行加载(ALLOWED_USERS/凭据同源单点)。
113
+ // config.json 先叠加(最低层),.env 后加载自然覆盖它——与 bot 入口同一层级序。
114
+ applyConfigOverlay()
112
115
  if (!options.env && existsSync(ENV_FILE)) loadEnvFile(ENV_FILE)
113
116
  const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "")
114
117
  .split(/[,\s]+/).filter(Boolean)
@@ -10,11 +10,10 @@
10
10
  //
11
11
  // 2026-11-09 重构:裸 healOnce 升级为 superviseOnce——优雅杀(TERM→宽限→KILL)、
12
12
  // 冷却(防互踢)、重启强度(超限 give-up 并告警,不当永动机)、监督者认领互斥。
13
- import { botWatchdogPaths, readEnvField, appendWatchdogLog, superviseOnce } from "../core/watchdog.js"
13
+ import { botWatchdogPaths, appendWatchdogLog, superviseOnce, readBotHealth, isBotDown } from "../core/watchdog.js"
14
14
  import { readAppId, startBot } from "../core/bot-control.js"
15
+ import { electSupervisor } from "../core/supervisor-election.js"
15
16
  import { runNotifyCli } from "./notify.js"
16
- import { join } from "path"
17
- import { homedir } from "os"
18
17
 
19
18
  const DEFAULT_INTERVAL_MIN = 10
20
19
 
@@ -27,7 +26,8 @@ function parseArgs(argv: string[]): { loop: boolean; intervalMin: number } {
27
26
  }
28
27
 
29
28
  function currentAppId(): string | null {
30
- return readAppId() ?? readEnvField(join(homedir(), ".openqq", ".env"), "QQ_APP_ID")
29
+ // readAppId 已含 QQ_BOTS 首角色回退(2026-11-20 应修尽修批)
30
+ return readAppId()
31
31
  }
32
32
 
33
33
  /** give-up 上报:入队 QQ 通知(bot 恢复后送达)+本进程日志;失败静默(fail-open)。 */
@@ -39,8 +39,19 @@ function alert(message: string): void {
39
39
  }
40
40
 
41
41
  async function tick(appId: string): Promise<void> {
42
+ const paths = botWatchdogPaths(appId)
43
+ // 双触发器归一(2026-11-20 owner 批):service 与 plugin 两通道租约选主。
44
+ // 破格条款(11-20 灵魂不在线复发实证):让贤仅当 bot 健康——bot 失能时无人
45
+ // 监督的空窗比双触发干扰致命(14:56-15:07 bot 死而两通道互相让贤实录)。
46
+ if (!electSupervisor("service")) {
47
+ if (!isBotDown(readBotHealth(paths, Date.now()))) {
48
+ appendWatchdogLog("[supervisor] 让贤:plugin 通道持监督租约中,本轮跳过")
49
+ return
50
+ }
51
+ appendWatchdogLog("[supervisor] 破格接管:plugin 持租约但 bot 失能——让贤条款不适用")
52
+ }
42
53
  const result = await superviseOnce({
43
- paths: botWatchdogPaths(appId),
54
+ paths,
44
55
  spawn: () => startBot(import.meta.url, (line) => console.log(line)),
45
56
  log: (line) => console.log(line),
46
57
  alert,
@@ -54,14 +65,17 @@ async function main(): Promise<void> {
54
65
  const args = parseArgs(process.argv.slice(2))
55
66
  const appId = currentAppId()
56
67
  if (!appId) {
57
- console.error("[watchdog] 未找到 QQ_APP_ID(~/.openqq/.env),无法定位实例锁")
68
+ console.error("[watchdog] 未找到任何角色凭据(~/.openqq/.env 缺 QQ_APP_ID/QQ_APP_SECRET 且 QQ_BOTS 无合法角色),无法定位实例锁")
58
69
  process.exit(1)
59
70
  }
60
71
  console.log(`[watchdog] 模式=${args.loop ? `loop/${args.intervalMin}min` : "once"}(监督矩阵:冷却2m/强度3次15m/优雅杀8s)`)
61
72
  await tick(appId)
62
73
  if (!args.loop) return
63
74
  const timer = setInterval(() => {
64
- void tick(appId).catch((error) => console.error("[watchdog] 巡检失败:", error instanceof Error ? error.message : error))
75
+ void tick(appId).catch((error) => {
76
+ appendWatchdogLog(`[watchdog] 巡检失败: ${error instanceof Error ? error.message : String(error)}`)
77
+ console.error("[watchdog] 巡检失败:", error instanceof Error ? error.message : error)
78
+ })
65
79
  }, args.intervalMin * 60_000)
66
80
  const stop = (): void => {
67
81
  clearInterval(timer)
@@ -72,6 +86,7 @@ async function main(): Promise<void> {
72
86
  }
73
87
 
74
88
  void main().catch((error) => {
89
+ appendWatchdogLog(`[watchdog] 致命错误: ${error instanceof Error ? error.message : String(error)}`)
75
90
  console.error("[watchdog] 致命错误:", error instanceof Error ? error.message : error)
76
91
  process.exit(1)
77
92
  })
package/src/commands.ts CHANGED
@@ -1,6 +1,6 @@
1
- // @input: ./config, ./qq/types, ./opencode/* (client, sessions)
1
+ // @input: ./config, ./qq/types, ./opencode/* (client, sessions)
2
2
  // @output: isCommand, handleCommand, handlePendingSelection, CommandContext, PendingSelection
3
- // @pos: 根层 - 命令系统: /new /stop /status /sessions /help /model /agent /rename
3
+ // @pos: 根层 - 命令系统: /new /cancel /status /sessions /help /models /agents /rename /undo /amend
4
4
  import type { Config } from "./config.js"
5
5
  import type { MessageContext } from "./qq/types.js"
6
6
  import type { OpencodeClient, SessionMessage } from "./opencode/client.js"
@@ -61,6 +61,14 @@ export interface CommandContext {
61
61
  progress: ProgressApi
62
62
  /** P1 防线 B:/cancel 彻底复位(清队列+abort+杀后台等待+结清在途账+drain) */
63
63
  stopAll: (userId: string) => Promise<{ cleared: number; title: string | undefined }>
64
+ /** steer 降级版:/amend <补充> 打断当前任务并以「原 prompt+补充」续跑(2026-11-22,参考 Hermes update_prompt) */
65
+ amend: (userId: string, amendment: string) => Promise<string>
66
+ /** 对齐官方 /undo:回滚上一回合并恢复文件,回执带被撤 prompt(2026-11-23,opencode.ai/docs/snapshots 为准) */
67
+ undo: (userId: string) => Promise<string>
68
+ /** 显性入队(/queue <文本>,owner 2026-11-23):steer 默认下的显式排队动词——排进 FIFO,当前任务跑完才执行 */
69
+ enqueue: (ctx: MessageContext, text: string) => Promise<string>
70
+ /** 官方斜杠命令直通(owner 2026-11-23):/goal /compact /redo /btw 走引擎内置实现,与桌面端同语义 */
71
+ engineCommand: (userId: string, name: string, text: string) => Promise<string>
64
72
  }
65
73
 
66
74
  export interface PendingSelection {
@@ -106,9 +114,20 @@ export async function handleCommand(ctx: MessageContext, cmdCtx: CommandContext)
106
114
  switch (parsed.name) {
107
115
  case "new":
108
116
  return handleNew(ctx, cmdCtx)
109
- case "stop":
110
- case "cancel": // /cancel 与 /stop 同义(用户自然习惯 + pi-qqbot 同款,UAT S3 实证缺口)
117
+ case "cancel": // 唯一中止命令(owner 2026-11-23 裁定:不收别名减负担;UAT 实证 /cancel 是用户自然习惯)
111
118
  return handleStop(ctx, cmdCtx)
119
+ case "amend": // steer 降级版:忙时插话并入当前任务(参考 Hermes update_prompt)
120
+ return cmdCtx.amend(ctx.userId, parsed.args)
121
+ case "undo": // 对齐官方 TUI /undo:回滚上一回合+恢复文件(prompt 回盒由回执承担)
122
+ return cmdCtx.undo(ctx.userId)
123
+ case "goal": // 官方引擎内置(v2.2.1+,PR#59437):目标模式直通——审查器/50轮上限在引擎侧
124
+ return cmdCtx.engineCommand(ctx.userId, "goal", parsed.args)
125
+ case "compact": // 官方引擎命令:会话压缩
126
+ return cmdCtx.engineCommand(ctx.userId, "compact", parsed.args)
127
+ case "redo": // 官方引擎命令:撤销暂存回滚的恢复
128
+ return cmdCtx.engineCommand(ctx.userId, "redo", parsed.args)
129
+ case "btw": // 官方引擎命令:侧问(不写入会话上下文)
130
+ return cmdCtx.engineCommand(ctx.userId, "btw", parsed.args)
112
131
  case "queue":
113
132
  return handleQueue(ctx, parsed.args, cmdCtx)
114
133
  case "ledger":
@@ -121,9 +140,9 @@ export async function handleCommand(ctx: MessageContext, cmdCtx: CommandContext)
121
140
  return handleSessions(ctx, cmdCtx)
122
141
  case "help":
123
142
  return buildHelpText()
124
- case "model":
143
+ case "models": // 官方 TUI 同名(owner 2026-11-23:严格对齐官方,单数别名已收编不留负担)
125
144
  return handleModel(ctx, parsed.args, cmdCtx)
126
- case "agent":
145
+ case "agents": // 官方 TUI 同名
127
146
  return handleAgent(ctx, parsed.args, cmdCtx)
128
147
  case "rename":
129
148
  return handleRename(ctx, parsed.args, cmdCtx)
@@ -226,7 +245,7 @@ async function handleStop(ctx: MessageContext, cmdCtx: CommandContext): Promise<
226
245
  }
227
246
 
228
247
  // Q1:/queue 查看与管理忙碌队列(2026-11-05:默认视图 join 台账,不再只看内存)
229
- function handleQueue(ctx: MessageContext, args: string, cmdCtx: CommandContext): string {
248
+ function handleQueue(ctx: MessageContext, args: string, cmdCtx: CommandContext): string | Promise<string> {
230
249
  const parts = args.trim().split(/\s+/).filter(Boolean)
231
250
  const sub = parts[0]?.toLowerCase() ?? ""
232
251
  if (sub === "clear") {
@@ -245,6 +264,11 @@ function handleQueue(ctx: MessageContext, args: string, cmdCtx: CommandContext):
245
264
  if (/^\d+$/.test(sub)) {
246
265
  return cmdCtx.queue.listAll(ctx.userId, Math.max(1, Number(sub)))
247
266
  }
267
+ // 显性入队动词(owner 2026-11-23):steer 默认模式下,/queue <文本>=把这条文本
268
+ // 排进 FIFO(当前任务跑完才执行),而不是默认的并入当前任务。
269
+ if (args.trim()) {
270
+ return cmdCtx.enqueue(ctx, args.trim())
271
+ }
248
272
  return cmdCtx.queue.list(ctx.userId)
249
273
  }
250
274
 
@@ -359,12 +383,12 @@ async function handleModel(ctx: MessageContext, args: string, cmdCtx: CommandCon
359
383
  return `${index + 1}. ${isCurrent ? "[当前] " : ""}${model.label}`
360
384
  })
361
385
 
362
- return ["可用模型:", ...lines, "回复序号或 /model <provider/model> 切换(60 秒内有效)"].join("\n")
386
+ return ["可用模型:", ...lines, "回复序号或 /models <provider/model> 切换(60 秒内有效)"].join("\n")
363
387
  }
364
388
 
365
389
  if (/^\d+$/.test(args)) {
366
390
  const result = await handlePendingSelection(ctx.userId, Number(args), cmdCtx)
367
- return result ?? "没有待选择的模型列表,请先发送 /model"
391
+ return result ?? "没有待选择的模型列表,请先发送 /models"
368
392
  }
369
393
 
370
394
  const model = splitModelId(args)
@@ -602,7 +626,9 @@ export function buildHelpText(): string {
602
626
  "/watch <会话ID> - 观察指定会话",
603
627
  "/watch off - 停止观察",
604
628
  "/progress - 手动进度查询(工具调用/失败统计、在途状态,本地事件源零模型调用)",
605
- "/queue - 队列与台账对账视图;/queue all [页码] 全量;/queue clear 清空;/queue drop <编号> 定点删除",
629
+ "/queue - 队列与台账对账视图;/queue all [页码] 全量;/queue clear 清空;/queue drop <编号> 定点删除;/queue <文本> 显性入队(steer 默认下排进 FIFO)",
630
+ "/goal <目标> - 官方目标模式(引擎内置 v2.2.1+);/goal 查状态;pause/resume/clear 控制",
631
+ "/compact /redo /btw - 官方引擎命令直通(压缩会话 / 恢复撤销 / 侧问)",
606
632
  "/ledger - 台账快照(在途/孤儿/最近拒绝);/ledger check 对账会话历史;/ledger settle <尾号> confirm 人工结清",
607
633
  "/cancel - 同 /stop:中止当前 AI 运行并清空忙碌队列",
608
634
  "/mirror [on|off] - 桌面问答摘要镜像开关(会话轮次完成推送问答摘要)",