@linjz/opencode-qqbot 0.3.17 → 0.3.18

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/src/commands.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // @input: ./config, ./qq/types, ./opencode/* (client, sessions)
2
2
  // @output: isCommand, handleCommand, handlePendingSelection, CommandContext, PendingSelection
3
- // @pos: 根层 - 命令系统: /new /cancel /status /sessions /help /models /agents /rename /undo /amend
3
+ // @pos: 根层 - 命令系统: /new /cancel /status /sessions /help /models /agents /rename /history /send /progress /queue /ledger /goal /compact /redo /btw /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"
@@ -135,7 +135,11 @@ export async function handleCommand(ctx: MessageContext, cmdCtx: CommandContext)
135
135
  case "progress":
136
136
  return cmdCtx.progress.query(ctx.userId)
137
137
  case "status":
138
- return handleStatus(ctx, cmdCtx)
138
+ return handleStatus(ctx, parsed.args, cmdCtx)
139
+ case "watch": // 已退役(owner 2026-11-23 定案):开关迁入 /status 驾驶舱
140
+ return "⌛ /watch 已退役:观察开关请用 /status watch on|off(盯当前绑定会话)。原 /watch <会话ID> 跨会话观察能力已随命令下线(owner 2026-11-23 裁决不保留)"
141
+ case "mirror": // 已退役:迁入 /status 驾驶舱
142
+ return "⌛ /mirror 已退役:镜像开关请用 /status mirror on|off"
139
143
  case "sessions":
140
144
  return handleSessions(ctx, cmdCtx)
141
145
  case "help":
@@ -148,12 +152,12 @@ export async function handleCommand(ctx: MessageContext, cmdCtx: CommandContext)
148
152
  return handleRename(ctx, parsed.args, cmdCtx)
149
153
  case "history":
150
154
  return handleHistory(ctx, parsed.args, cmdCtx)
151
- case "watch":
152
- return handleWatch(ctx, parsed.args, cmdCtx)
155
+ case "watch": // 已退役(owner 2026-11-23 定案):开关迁入 /status 驾驶舱
156
+ return "⌛ /watch 已退役:观察开关请用 /status watch on|off(盯当前绑定会话)。原 /watch <会话ID> 跨会话观察能力已随命令下线(owner 2026-11-23 裁决不保留)"
153
157
  case "send":
154
158
  return handleSend(ctx, parsed.args, cmdCtx)
155
- case "mirror":
156
- return handleMirror(parsed.args, cmdCtx)
159
+ case "mirror": // 已退役:迁入 /status 驾驶舱
160
+ return "⌛ /mirror 已退役:镜像开关请用 /status mirror on|off"
157
161
  default:
158
162
  return `不支持的命令:/${parsed.name}\n发送 /help 查看可用命令`
159
163
  }
@@ -315,7 +319,24 @@ export async function resolveStatusSessionTitle(
315
319
  return { title: session.title, sessionId: session.sessionId }
316
320
  }
317
321
 
318
- async function handleStatus(ctx: MessageContext, cmdCtx: CommandContext): Promise<string> {
322
+ async function handleStatus(ctx: MessageContext, args: string, cmdCtx: CommandContext): Promise<string> {
323
+ // 驾驶舱开关(owner 2026-11-23 定案):/status watch|mirror on|off = 观察/镜像唯一开关
324
+ // 入口(/watch /mirror 命令已退役);裸 /status 保持纯读。
325
+ const parts = args.trim().split(/\s+/).filter(Boolean)
326
+ if (parts.length > 0) {
327
+ const target = parts[0].toLowerCase()
328
+ const sw = parts[1]?.toLowerCase()
329
+ if ((target === "watch" || target === "mirror") && (sw === "on" || sw === "off")) {
330
+ if (target === "mirror") return cmdCtx.mirror.set(sw === "on")
331
+ if (sw === "on") {
332
+ const session = await cmdCtx.sessions.getOrCreate(ctx.userId)
333
+ return cmdCtx.watch.start(ctx.userId, session.sessionId, ctx)
334
+ }
335
+ return cmdCtx.watch.stop(ctx.userId)
336
+ }
337
+ return "用法:/status 查看状态|/status watch on|off 观察开关|/status mirror on|off 镜像开关"
338
+ }
339
+
319
340
  const sessionInfo = await resolveStatusSessionTitle(cmdCtx.sessions, cmdCtx.client, ctx.userId)
320
341
  const { providerId, modelId } = cmdCtx.sessions.getModel(ctx.userId)
321
342
  const agentId = cmdCtx.sessions.getAgent(ctx.userId)
@@ -338,6 +359,8 @@ async function handleStatus(ctx: MessageContext, cmdCtx: CommandContext): Promis
338
359
  `会话:${sessionInfo.sessionId ? `${sessionInfo.title ?? "未命名会话"} (${sessionInfo.sessionId})` : "未创建"}`,
339
360
  `模型:${providerId && modelId ? `${providerId} / ${modelId}` : "默认"}`,
340
361
  `Agent:${agentId ?? "默认"}`,
362
+ cmdCtx.watch.status(ctx.userId),
363
+ cmdCtx.mirror.status(),
341
364
  cmdCtx.queue.summary(ctx.userId),
342
365
  logLine,
343
366
  ].join("\n")
@@ -393,7 +416,7 @@ async function handleModel(ctx: MessageContext, args: string, cmdCtx: CommandCon
393
416
 
394
417
  const model = splitModelId(args)
395
418
  if (!model) {
396
- return "模型格式不对,请使用 /model <provider/model>"
419
+ return "模型格式不对,请使用 /models <provider/model>"
397
420
  }
398
421
 
399
422
  // DEF-qqbot-20261111-01:存在性校验——此前仅校格式直写映射,假模型也回「已切换成功」误导用户
@@ -426,7 +449,7 @@ async function handleAgent(ctx: MessageContext, args: string, cmdCtx: CommandCon
426
449
  return `${index + 1}. ${isCurrent ? "[当前] " : ""}${agent.label}`
427
450
  })
428
451
 
429
- return ["可用 Agent:", ...lines, "回复 /agent <name> 切换"].join("\n")
452
+ return ["可用 Agent:", ...lines, "回复 /agents <name> 切换"].join("\n")
430
453
  }
431
454
 
432
455
  const normalized = args.trim().toLowerCase()
@@ -471,34 +494,6 @@ async function handleHistory(ctx: MessageContext, args: string, cmdCtx: CommandC
471
494
  return `📜 ${session.title ?? session.sessionId} · 最近 ${n} 轮\n\n${body}`
472
495
  }
473
496
 
474
- async function handleWatch(ctx: MessageContext, args: string, cmdCtx: CommandContext): Promise<string> {
475
- const a = args.trim()
476
- const lower = a.toLowerCase()
477
-
478
- if (lower === "off" || lower === "stop") {
479
- return cmdCtx.watch.stop(ctx.userId)
480
- }
481
-
482
- if (!a) {
483
- const session = await cmdCtx.sessions.getOrCreate(ctx.userId)
484
- return cmdCtx.watch.start(ctx.userId, session.sessionId, ctx)
485
- }
486
-
487
- if (/^ses_/i.test(a)) {
488
- return cmdCtx.watch.start(ctx.userId, a, ctx)
489
- }
490
-
491
- return "用法:/watch 观察当前会话|/watch <会话ID> 观察指定会话|/watch off 停止观察"
492
- }
493
-
494
- function handleMirror(args: string, cmdCtx: CommandContext): string {
495
- const a = args.trim().toLowerCase()
496
- if (!a) return cmdCtx.mirror.status()
497
- if (["on", "1", "开", "打开"].includes(a)) return cmdCtx.mirror.set(true)
498
- if (["off", "0", "关", "关闭"].includes(a)) return cmdCtx.mirror.set(false)
499
- return "用法:/mirror 查看状态|/mirror on 开启|/mirror off 关闭"
500
- }
501
-
502
497
  async function ensureSession(userId: string, cmdCtx: CommandContext): Promise<void> {
503
498
  await cmdCtx.sessions.getOrCreate(userId)
504
499
  }
@@ -611,30 +606,25 @@ export function buildHelpText(): string {
611
606
  return [
612
607
  "可用命令:",
613
608
  "/new - 创建新会话",
614
- "/stop - 停止当前 AI 运行",
615
- "/status - 查看服务器和当前会话状态",
609
+ "/cancel - 中止当前生成并清空忙碌队列",
610
+ "/status - 驾驶舱:服务器/会话/模型/Agent/观察/镜像/队列/日志;/status watch on|off 观察开关;/status mirror on|off 镜像开关",
616
611
  "/sessions - 列出历史会话并回复序号切换",
617
612
  "/help - 查看帮助",
618
- "/model - 列出可用模型",
619
- "/model <provider/model> - 切换模型",
620
- "/agent - 列出可用 Agent",
621
- "/agent <name> - 切换 Agent",
613
+ "/models - 列出可用模型|/models <provider/model> 切换(session 级)",
614
+ "/agents - 列出可用 Agent|/agents <name> 切换",
622
615
  "/rename <name> - 重命名当前会话",
623
616
  "/history [N] - 查看当前会话最近 N 轮历史(默认 3,最多 10)",
624
617
  "/send <路径> - 把白名单目录内的文件/图片发到 QQ",
625
- "/watch - 观察当前会话实时过程(工具调用/完成会推送摘要)",
626
- "/watch <会话ID> - 观察指定会话",
627
- "/watch off - 停止观察",
628
618
  "/progress - 手动进度查询(工具调用/失败统计、在途状态,本地事件源零模型调用)",
629
619
  "/queue - 队列与台账对账视图;/queue all [页码] 全量;/queue clear 清空;/queue drop <编号> 定点删除;/queue <文本> 显性入队(steer 默认下排进 FIFO)",
630
620
  "/goal <目标> - 官方目标模式(引擎内置 v2.2.1+);/goal 查状态;pause/resume/clear 控制",
631
621
  "/compact /redo /btw - 官方引擎命令直通(压缩会话 / 恢复撤销 / 侧问)",
632
622
  "/ledger - 台账快照(在途/孤儿/最近拒绝);/ledger check 对账会话历史;/ledger settle <尾号> confirm 人工结清",
633
- "/cancel - 同 /stop:中止当前 AI 运行并清空忙碌队列",
634
- "/mirror [on|off] - 桌面问答摘要镜像开关(会话轮次完成推送问答摘要)",
623
+ "/undo - 对齐官方:撤销上一回合,并恢复文件",
624
+ "/amend <补充> - 忙时插话并入当前任务(官方 steer 语义)",
635
625
  "",
636
626
  "权限审批(AI 请求权限时):",
637
- "回复「允许」= 本次允许|「总是」= 总是允许|「拒绝」= 拒绝",
627
+ "点卡片按钮(允许一次/总是允许/拒绝/忽略),或回复「允许」= 本次允许|「总是」= 总是允许|「拒绝」= 拒绝",
638
628
  "(30 分钟无响应自动拒绝)",
639
629
  ].join("\n")
640
630
  }
@@ -2,7 +2,7 @@
2
2
  // @output: createDelivery
3
3
  // @pos: 根层/core - 投递域(O7c 2026-10-15 自 bridge.ts 拆出:统一投递
4
4
  // 被动→主动降级、日配额记账与落盘、观察推送节流队列、主动/被动通道发送)
5
- import { storageFile } from "./storage.js"
5
+ import { storageFile, storageRoot } from "./storage.js"
6
6
  import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, unlinkSync, statSync } from "fs"
7
7
  import { join } from "path"
8
8
  import { createHash } from "node:crypto"
@@ -77,6 +77,29 @@ export const UNDELIVERED_NOTICE = "(此前有未能送达的消息)\n"
77
77
  export const QQ_LIST_FORMAT_HINT =
78
78
  "\n\n(输出格式约定:本对话经 QQ 渲染,请用「1、2、3、」顿号或「-」无序列表代替 markdown 有序列表,避免表格;代码块不受影响可正常使用。)"
79
79
 
80
+ /** AI 出站发文件指引(2026-11-23 工具化批):一等工具优先,魔法标记降级——语法必须随 prompt 注入,
81
+ * 此前标记从未告知模型,新会话只能猜(「发文件总要试好几次」根因)。 */
82
+ export const QQ_SEND_FILE_HINT =
83
+ "\n\n如需把本机文件/图片发给 QQ 用户:优先调用 qq_send_file 工具(若工具清单提供,失败会返回精确原因可据以修正);无该工具时,在回复末尾独立一行写 `QQ_SEND_FILE: <绝对路径>`(路径须在发送白名单内,默认 QQ 图片缓存目录与 bot 工作目录)。"
84
+
85
+ /** prompt 注入与系统级注入的切换闸(owner 2026-11-24 批准):
86
+ * 插件已成功走系统层(entry/hook 模式,状态文件 15min 内新鲜)时,prompt 正文不再携带
87
+ * 格式与发文件约定——治「输出格式约定以用户消息气泡入史」的显性注入污染;
88
+ * 状态文件缺失/陈旧/模式未知=系统层不可用,回退 prompt 注入(现状,永不裸奔)。 */
89
+ export function qqPromptHints(): string {
90
+ try {
91
+ const file = join(storageRoot(), "qq-system-instructions.json")
92
+ const st = statSync(file)
93
+ if (Date.now() - st.mtimeMs < 15 * 60_000) {
94
+ const parsed = JSON.parse(readFileSync(file, "utf-8")) as { mode?: string }
95
+ if (parsed?.mode === "entry" || parsed?.mode === "hook") return ""
96
+ }
97
+ } catch {
98
+ // 无状态文件/坏 JSON=回退 prompt 注入
99
+ }
100
+ return QQ_LIST_FORMAT_HINT + QQ_SEND_FILE_HINT
101
+ }
102
+
80
103
  export function qqListNormalize(text: string): string {
81
104
  const lines = text.split("\n")
82
105
  let fence: { ch: string; len: number } | null = null
@@ -63,6 +63,9 @@ export interface MirrorDeps {
63
63
  /** A 方案(2026-11-23):摘要投递前过 cron 标记钩——注册提醒并返回剥净正文。
64
64
  * 桌面端发起的回合也会输出 QQBOT_PAYLOAD,不经此钩会原样泄漏到 QQ。 */
65
65
  onDigest?: (userId: string, digest: string) => string
66
+ /** kickoff 归属 bot 侧标记(2026-11-23):goal 设定时的目标原文——buildDigest
67
+ * 对「边界 user 文本==目标原文」的回合标 🎯(引擎不给 kickoff 打标的近似识别)。 */
68
+ goalObjectiveOf?: (sessionID: string) => string | undefined
66
69
  }
67
70
 
68
71
  export interface Mirror {
@@ -167,7 +170,7 @@ export function createMirror(deps: MirrorDeps): Mirror {
167
170
  if (turnKey) mirroredTurns.set(sessionID, turnKey)
168
171
  return
169
172
  }
170
- const digest = buildDigest(messages)
173
+ const digest = buildDigest(messages, deps.goalObjectiveOf?.(sessionID))
171
174
  if (!digest) {
172
175
  console.log(`[mirror] 跳过:无可摘要内容(空轮/纯工具轮)session=${sessionID}`)
173
176
  return
@@ -205,13 +208,13 @@ export function createMirror(deps: MirrorDeps): Mirror {
205
208
  }
206
209
  return enabled
207
210
  ? "✅ 摘要镜像已开启:桌面会话轮次完成后推送问答摘要"
208
- : "🔇 摘要镜像已关闭(/mirror on 重新开启)"
211
+ : "🔇 摘要镜像已关闭(/status mirror on 重新开启)"
209
212
  },
210
213
  status() {
211
214
  const subs = mirrorUnsubs.size
212
215
  return mirrorState.enabled
213
216
  ? `📋 摘要镜像:开(已挂 ${subs} 个会话订阅)`
214
- : "📋 摘要镜像:关(/mirror on 开启)"
217
+ : "📋 摘要镜像:关(/status mirror on 开启)"
215
218
  },
216
219
  }
217
220
 
@@ -622,6 +622,15 @@ export function formatPermissionPrompt(
622
622
  // W 项(2026-11-22 宿主侧学习):官方文档 permissions 页——always 保存工具提案的
623
623
  // pattern(shell=命令前缀等)。卡片上明示「总是允许」将保存什么,owner 点之前知道
624
624
  // 豁免范围(request.save 即引擎提案的保存规则,仅 always 决策时生效)。
625
+ // ── 截断语义与判据口径(owner 2026-11-25 批注,勿删)──
626
+ // truncate(s,120) 的契约=保留前 120 字符**再追加省略号「…」**——被截断时用户可见
627
+ // 长度=121,不是 120(core/util.ts truncate 全库同此语义:max=保留位数,省略号在预算外)。
628
+ // UAT 任务书 AC-PRM-002 的判据=「每条 ≤120 字符(省略号计入)」→ 121 越界 1 字符,
629
+ // 已登记 DEF-qqbot-20261124-03(代码缺陷 off-by-one,P3);主理人 11-24 裁定「判据
630
+ // 直接失败、AC 终态 ❌、本轮不改码」;11-25 复核认为该硬阈值本身存争议(观感级
631
+ // 1 字符,QQ 平台层 121 不触任何组件限制,功能零影响),故保留现状。
632
+ // 若日后裁定修码:本行改 truncate(s, 119) 即可(可见长度回到 120);或走判据修订
633
+ // (任务书口径改 ≤121)——两条路都只需动一处,且须同步本注释与 DEF 条目状态。
625
634
  if (request.save && request.save.length > 0) {
626
635
  const saves = request.save.slice(0, 3).map((s) => truncate(s, 120))
627
636
  lines.push(`总是允许将保存:${saves.join(";")}`)
@@ -0,0 +1,122 @@
1
+ // @input: fs/path + ./storage (storageRoot) + ./send-requests (findQQBinding)
2
+ // @output: QQ_INSTRUCTION_KEY, QQ_INSTRUCTION_TEXT, listQQBindings, qqInstructionStateFile, syncQQInstructions
3
+ // @pos: core - QQ 会话系统级指令注入(owner 2026-11-24 批准):治显性注入污染
4
+ //
5
+ // 病灶:QQ_LIST_FORMAT_HINT/QQ_SEND_FILE_HINT 拼在 user prompt 正文——格式约定以用户消息
6
+ // 气泡进入会话历史(桌面端可见),污染阅读且占用 user 语义位。
7
+ // 方案(官方 plugins/server 文档取证):优先 session.instructions.entry(keyed 指令条目,
8
+ // key="qq" 即通道标签,<context key="qq"> 块注入系统指令,每回合生效且不入历史);
9
+ // 旧引擎无 entry API 时降级 session.hook("context")(event.system.push 逐发注入);
10
+ // 两者皆无→不写状态文件,bridge 继续 prompt 正文注入(现状兜底)。
11
+ // 三态经 ~/.openqq/qq-system-instructions.json 状态文件告知 bridge(见 delivery.qqPromptHints)。
12
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"
13
+ import { dirname, join } from "node:path"
14
+ import { storageRoot } from "./storage.js"
15
+ import { findQQBinding } from "./send-requests.js"
16
+
17
+ export const QQ_INSTRUCTION_KEY = "qq"
18
+
19
+ /** 系统层指令正文(与 delivery.ts 两个 HINT 同语义,迁出 user 消息体)。 */
20
+ export const QQ_INSTRUCTION_TEXT = [
21
+ "本对话经 QQ 渲染:",
22
+ "- 输出格式:用「1、2、3、」顿号或「-」无序列表代替 markdown 有序列表,避免表格;代码块不受影响可正常使用。",
23
+ "- 发送本机文件/图片给 QQ 用户:优先调用 qq_send_file 工具(若工具清单提供,失败会返回精确原因可据以修正);无该工具时,在回复末尾独立一行写 `QQ_SEND_FILE: <绝对路径>`(路径须在发送白名单内,默认 QQ 图片缓存目录与 bot 工作目录)。",
24
+ ].join("\n")
25
+
26
+ export interface QQBinding {
27
+ userId: string
28
+ sessionId: string
29
+ appId?: string
30
+ }
31
+
32
+ export function qqInstructionStateFile(): string {
33
+ return join(storageRoot(), "qq-system-instructions.json")
34
+ }
35
+
36
+ /** 全量绑定枚举(插件巡检用):legacy + roles/* 的 sessions.json 全部有效映射。 */
37
+ export function listQQBindings(root = storageRoot()): QQBinding[] {
38
+ const candidates: Array<{ file: string; appId?: string }> = [{ file: join(root, "sessions.json") }]
39
+ const rolesDir = join(root, "roles")
40
+ if (existsSync(rolesDir)) {
41
+ for (const role of readdirSync(rolesDir)) candidates.push({ file: join(rolesDir, role, "sessions.json"), appId: role })
42
+ }
43
+ const out: QQBinding[] = []
44
+ for (const { file, appId } of candidates) {
45
+ try {
46
+ const parsed = JSON.parse(readFileSync(file, "utf-8")) as Record<string, { sessionId?: string }>
47
+ for (const [userId, v] of Object.entries(parsed)) {
48
+ if (typeof v?.sessionId === "string" && v.sessionId.startsWith("ses_")) {
49
+ out.push(appId ? { userId, sessionId: v.sessionId, appId } : { userId, sessionId: v.sessionId })
50
+ }
51
+ }
52
+ } catch {
53
+ // 单文件缺失/坏 JSON 不阻断其余角色
54
+ }
55
+ }
56
+ return out
57
+ }
58
+
59
+ interface EntryApi {
60
+ list?: (input: { sessionID: string }) => Promise<Array<{ key?: string; value?: string }>>
61
+ put?: (input: { sessionID: string; key: string; value: string }) => Promise<unknown>
62
+ }
63
+ interface CtxLike {
64
+ session?: {
65
+ instructions?: { entry?: EntryApi }
66
+ hook?: (name: string, fn: (event: { sessionID?: string; system?: Array<{ type: string; text: string }> }) => void) => Promise<unknown>
67
+ }
68
+ }
69
+
70
+ // hook 模式防重复注册(插件 hourly reload 重跑 setup 是常态,模块级标记跨 ensure 周期)
71
+ let hookRegistered = false
72
+
73
+ /**
74
+ * 同步 QQ 系统指令(插件 ensure 每周期调用,幂等):
75
+ * entry 模式逐绑定补齐条目;hook 模式注册一次后仅刷新状态文件。
76
+ * 返回模式并落状态文件(bridge 以 15min 新鲜度判定是否停用 prompt 注入)。
77
+ * 任何失败不抛出——宿主引导器永不被阻断。
78
+ */
79
+ export async function syncQQInstructions(
80
+ ctx: CtxLike | undefined,
81
+ opts: { bindings?: QQBinding[]; stateFile?: string } = {},
82
+ ): Promise<"entry" | "hook" | "none"> {
83
+ const bindings = opts.bindings ?? listQQBindings()
84
+ const stateFile = opts.stateFile ?? qqInstructionStateFile()
85
+ const writeState = (mode: "entry" | "hook"): void => {
86
+ mkdirSync(dirname(stateFile), { recursive: true })
87
+ writeFileSync(stateFile, JSON.stringify({ mode, at: Date.now() }), "utf-8")
88
+ }
89
+ try {
90
+ const entry = ctx?.session?.instructions?.entry
91
+ if (entry?.put && entry?.list) {
92
+ for (const b of bindings) {
93
+ const existing = await entry.list({ sessionID: b.sessionId }).catch(() => [])
94
+ const has = (existing ?? []).some((e) => e?.key === QQ_INSTRUCTION_KEY && e?.value === QQ_INSTRUCTION_TEXT)
95
+ if (!has) await entry.put({ sessionID: b.sessionId, key: QQ_INSTRUCTION_KEY, value: QQ_INSTRUCTION_TEXT })
96
+ }
97
+ writeState("entry")
98
+ return "entry"
99
+ }
100
+ if (typeof ctx?.session?.hook === "function") {
101
+ if (!hookRegistered) {
102
+ const cache = new Map<string, { bound: boolean; at: number }>()
103
+ await ctx.session.hook("context", (event) => {
104
+ const sid = event?.sessionID
105
+ if (!sid || !event?.system) return
106
+ let hit = cache.get(sid)
107
+ if (!hit || Date.now() - hit.at > 60_000) {
108
+ hit = { bound: Boolean(findQQBinding(sid)), at: Date.now() }
109
+ cache.set(sid, hit)
110
+ }
111
+ if (hit.bound) event.system.push({ type: "text", text: QQ_INSTRUCTION_TEXT })
112
+ })
113
+ hookRegistered = true
114
+ }
115
+ writeState("hook")
116
+ return "hook"
117
+ }
118
+ } catch {
119
+ // 同步失败不落状态——bridge 继续 prompt 注入兜底
120
+ }
121
+ return "none"
122
+ }
@@ -0,0 +1,227 @@
1
+ // @input: fs/path/crypto + ./storage (storageRoot) + ./send-media (sendLocalFile/normalizeLocalPath)
2
+ // @output: SendFileRequest, SendFileResult, sendRequestsDirFor, findQQBinding, dedupeKeyOf,
3
+ // writeSendRequest, awaitSendResult, startSendRequestConsumer
4
+ // @pos: core - AI→QQ 出站发送的文件队列协议(qq_send_file 工具化,owner 2026-11-23 批准)
5
+ //
6
+ // 背景:AI 出站发文件原先只有「QQ_SEND_FILE: <路径>」魔法标记,且语法从未注入 prompt——
7
+ // 模型只能猜标记/猜路径,反复尝试才成功。工具化后:插件侧(引擎宿主)注册 qq_send_file
8
+ // 一等工具,经本文件队列把请求交给 bot 进程消费——插件与 bot 是两个进程,文件队列与
9
+ // outbox 离线通知同构,满足状态落盘红线,不新增端口与攻击面。
10
+ // 权威安全校验(白名单/拒识名单/20MB 上限)只在 bot 侧 sendLocalFile 内执行——
11
+ // 插件宿主与 bot 的 process.cwd() 不同,白名单绝不在插件侧预判。
12
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
13
+ import { join } from "node:path"
14
+ import { randomUUID } from "node:crypto"
15
+ import { storageRoot } from "./storage.js"
16
+ import { normalizeLocalPath, sendLocalFile } from "./send-media.js"
17
+ import type { MessageContext } from "../qq/types.js"
18
+
19
+ export interface SendFileRequest {
20
+ id: string
21
+ sessionId: string
22
+ userId: string
23
+ /** 多角色时目标角色;legacy 单角色为空 */
24
+ appId?: string
25
+ path: string
26
+ caption?: string
27
+ at: number
28
+ /** 幂等键:sessionId+规范化路径+mtime+size——同文件同内容重试不重复发 */
29
+ dedupeKey: string
30
+ }
31
+
32
+ export interface SendFileResult {
33
+ id: string
34
+ ok: boolean
35
+ detail?: string
36
+ error?: string
37
+ deduped?: boolean
38
+ at: number
39
+ }
40
+
41
+ export function sendRequestsDirFor(appId?: string): string {
42
+ return join(storageRoot(appId), "send-requests")
43
+ }
44
+
45
+ /** 会话→QQ 绑定查找(插件侧用):扫 legacy sessions.json 与 roles/*\/sessions.json。
46
+ * 映射形状 { [userId]: { sessionId } }(sessions.ts);找不到=null(未绑定会话不得发送)。 */
47
+ export function findQQBinding(sessionId: string, root = storageRoot()): { userId: string; appId?: string } | null {
48
+ const candidates: Array<{ file: string; appId?: string }> = [{ file: join(root, "sessions.json") }]
49
+ const rolesDir = join(root, "roles")
50
+ if (existsSync(rolesDir)) {
51
+ for (const role of readdirSync(rolesDir)) {
52
+ candidates.push({ file: join(rolesDir, role, "sessions.json"), appId: role })
53
+ }
54
+ }
55
+ for (const { file, appId } of candidates) {
56
+ try {
57
+ const parsed = JSON.parse(readFileSync(file, "utf-8")) as Record<string, { sessionId?: string }>
58
+ for (const [userId, v] of Object.entries(parsed)) {
59
+ if (v?.sessionId === sessionId) return appId ? { userId, appId } : { userId }
60
+ }
61
+ } catch {
62
+ // 单文件缺失/坏 JSON 不阻断其余角色查找
63
+ }
64
+ }
65
+ return null
66
+ }
67
+
68
+ export function dedupeKeyOf(sessionId: string, normalizedPath: string, st: { mtimeMs: number; size: number }): string {
69
+ return `${sessionId}:${normalizedPath}:${st.mtimeMs}:${st.size}`
70
+ }
71
+
72
+ export function writeSendRequest(dir: string, req: SendFileRequest): string {
73
+ mkdirSync(dir, { recursive: true })
74
+ const tmp = join(dir, `${req.id}.tmp`)
75
+ writeFileSync(tmp, JSON.stringify(req), "utf-8")
76
+ renameSync(tmp, join(dir, `${req.id}.json`))
77
+ return join(dir, `${req.id}.json`)
78
+ }
79
+
80
+ /** 插件侧等回执:轮询 <id>.result.json;超时/取消返回 null(结果未知如实上报,不编造)。 */
81
+ export async function awaitSendResult(
82
+ dir: string,
83
+ id: string,
84
+ opts: { timeoutMs?: number; intervalMs?: number; signal?: AbortSignal } = {},
85
+ ): Promise<SendFileResult | null> {
86
+ const timeoutMs = opts.timeoutMs ?? 45_000
87
+ const intervalMs = opts.intervalMs ?? 500
88
+ const file = join(dir, `${id}.result.json`)
89
+ const deadline = Date.now() + timeoutMs
90
+ for (;;) {
91
+ if (existsSync(file)) {
92
+ try {
93
+ return JSON.parse(readFileSync(file, "utf-8")) as SendFileResult
94
+ } catch {
95
+ // 结果文件写半截(原子 rename 前不应发生)——下一轮再读
96
+ }
97
+ }
98
+ if (opts.signal?.aborted) return null
99
+ if (Date.now() >= deadline) return null
100
+ await new Promise((r) => setTimeout(r, intervalMs))
101
+ }
102
+ }
103
+
104
+ export interface SendRequestConsumerOptions {
105
+ /** 消费目录(按角色隔离);缺省 sendRequestsDirFor(appId) */
106
+ dir?: string
107
+ appId?: string
108
+ ctxForUser: (userId: string) => MessageContext
109
+ getToken: () => Promise<string>
110
+ /** 测试注入:替换真实发送(默认 sendLocalFile 全量安全链) */
111
+ sendFile?: (ctx: MessageContext, path: string) => Promise<string>
112
+ intervalMs?: number
113
+ log?: (line: string) => void
114
+ }
115
+
116
+ /**
117
+ * bot 侧消费器:轮询请求目录 → 逐条发送 → 结果回写。
118
+ * 幂等:启动时从既有 result 文件重建去重账(重启不洗白);同 dedupeKey 直接回旧结果不重发。
119
+ * 坏请求改名 .bad.json 防毒丸卡队列;返回停止函数。
120
+ */
121
+ export function startSendRequestConsumer(opts: SendRequestConsumerOptions): () => void {
122
+ const dir = opts.dir ?? sendRequestsDirFor(opts.appId)
123
+ const intervalMs = opts.intervalMs ?? 1500
124
+ const log = opts.log ?? (() => {})
125
+ const seen = new Map<string, SendFileResult>()
126
+ mkdirSync(dir, { recursive: true })
127
+ // 启动重建去重账 + 清理 24h 前结果文件(先读后删,重启不重复发)
128
+ for (const f of readdirSync(dir)) {
129
+ if (!f.endsWith(".result.json")) continue
130
+ const full = join(dir, f)
131
+ try {
132
+ const result = JSON.parse(readFileSync(full, "utf-8")) as SendFileResult & { dedupeKey?: string }
133
+ const key = (result as { dedupeKey?: string }).dedupeKey
134
+ if (key) seen.set(key, result)
135
+ if (Date.now() - statSync(full).mtimeMs > 24 * 60 * 60_000) renameSync(full, full + ".old")
136
+ } catch {
137
+ // 单文件损坏忽略
138
+ }
139
+ }
140
+ const sendFile =
141
+ opts.sendFile ?? ((ctx: MessageContext, path: string) => sendLocalFile(ctx, path, { getToken: opts.getToken }))
142
+
143
+ async function consumeOne(file: string): Promise<void> {
144
+ const full = join(dir, file)
145
+ let req: SendFileRequest
146
+ try {
147
+ req = JSON.parse(readFileSync(full, "utf-8")) as SendFileRequest
148
+ } catch {
149
+ renameSync(full, full + ".bad.json")
150
+ log(`[send-requests] 坏请求已隔离: ${file}`)
151
+ return
152
+ }
153
+ const prior = seen.get(req.dedupeKey)
154
+ const base: SendFileResult = { id: req.id, ok: true, at: Date.now() }
155
+ let result: SendFileResult
156
+ if (prior) {
157
+ result = { ...base, ok: prior.ok, detail: prior.detail, error: prior.error, deduped: true }
158
+ } else {
159
+ try {
160
+ const ctx = opts.ctxForUser(req.userId)
161
+ const detail = await sendFile(ctx, normalizeLocalPath(req.path))
162
+ result = { ...base, ok: true, detail }
163
+ } catch (error) {
164
+ result = { ...base, ok: false, error: error instanceof Error ? error.message : String(error) }
165
+ }
166
+ seen.set(req.dedupeKey, { ...result, dedupeKey: req.dedupeKey } as SendFileResult)
167
+ }
168
+ // 结果文件带上 dedupeKey 供重启后重建账;原子写
169
+ const payload = JSON.stringify({ ...result, dedupeKey: req.dedupeKey })
170
+ writeFileSync(join(dir, `${req.id}.result.tmp`), payload, "utf-8")
171
+ renameSync(join(dir, `${req.id}.result.tmp`), join(dir, `${req.id}.result.json`))
172
+ // 请求本体归档(防重复消费;保留 24h 由启动清理归并)
173
+ renameSync(full, full + ".done")
174
+ log(`[send-requests] ${result.ok ? "已发送" : "发送失败"}${result.deduped ? "(去重)" : ""} user=${req.userId.slice(0, 8)}… path=${req.path}`)
175
+ }
176
+
177
+ const timer = setInterval(() => {
178
+ let files: string[]
179
+ try {
180
+ files = readdirSync(dir).filter((f) => f.endsWith(".json") && !f.endsWith(".result.json") && !f.endsWith(".bad.json") && !f.endsWith(".done"))
181
+ } catch {
182
+ return
183
+ }
184
+ for (const f of files) {
185
+ void consumeOne(f).catch((error) => log(`[send-requests] 消费失败 ${f}: ${error instanceof Error ? error.message : error}`))
186
+ }
187
+ }, intervalMs)
188
+ timer.unref?.()
189
+ return () => clearInterval(timer)
190
+ }
191
+
192
+ /** 插件侧工具执行体(plugin-entry 调用):绑定查找 → 落请求 → 等回执 → 结构化文案。 */
193
+ export async function executeQQSendFile(
194
+ input: { path: string; caption?: string },
195
+ context: { sessionID: string; signal?: AbortSignal },
196
+ ): Promise<string> {
197
+ const binding = findQQBinding(context.sessionID)
198
+ if (!binding) {
199
+ return "发送失败:此 OpenCode 会话未绑定 QQ 用户——只有从 QQ 发起的会话(或已 /sessions 切入绑定会话)才能发送到 QQ。"
200
+ }
201
+ const normalized = normalizeLocalPath(input.path)
202
+ let st: { mtimeMs: number; size: number }
203
+ try {
204
+ const s = statSync(normalized)
205
+ st = { mtimeMs: s.mtimeMs, size: s.size }
206
+ } catch {
207
+ return `发送失败:文件不存在或不可读——${normalized}(请先用写文件工具生成到本机绝对路径,再调用本工具)`
208
+ }
209
+ const dir = sendRequestsDirFor(binding.appId)
210
+ const req: SendFileRequest = {
211
+ id: randomUUID(),
212
+ sessionId: context.sessionID,
213
+ userId: binding.userId,
214
+ appId: binding.appId,
215
+ path: normalized,
216
+ caption: input.caption,
217
+ at: Date.now(),
218
+ dedupeKey: dedupeKeyOf(context.sessionID, normalized, st),
219
+ }
220
+ writeSendRequest(dir, req)
221
+ const result = await awaitSendResult(dir, req.id, { signal: context.signal })
222
+ if (!result) {
223
+ return "请求已受理但 45s 内未获回执——发送结果未知(bot 可能忙或离线,恢复后仍会消费)。请勿盲目重试;可先 /status 核查 bot 状态。"
224
+ }
225
+ if (result.ok) return `已发送到 QQ:${result.detail ?? req.path}${result.deduped ? "(相同文件此前已发,本次去重未重复发送)" : ""}`
226
+ return `发送失败:${result.error ?? "未知原因"}——请按原因修正后重试(若是白名单拒绝,可先把文件复制到允许的根目录内再发)。`
227
+ }