@linjz/opencode-qqbot 0.3.17 → 0.3.19

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/README.md CHANGED
@@ -20,11 +20,13 @@ Built for production, not just message bridging: a self-healing watchdog, an aud
20
20
  |---|---|
21
21
  | Two-way chat | QQ messages reach the OpenCode session; AI replies are pushed back to QQ (markdown rendering, long answers auto-split with table atoms intact and code-fence repair) |
22
22
  | Desktop session mirror | 📋 Digest card: the latest Q&A round of a desktop session is mirrored to QQ in real time (full text by default) |
23
- | Progress watching | `/watch` subscribes to tool-call milestones (🔧 command summary / exit code), throttled and merged |
23
+ | Status cockpit | `/status` is the single dashboard — server/session/model/agent/observation/mirror/queue/logs in one view; `/status watch on|off` and `/status mirror on|off` are the only switches (tool-call milestones 🔧 + desktop digest mirror) |
24
24
  | **Permission approval** | OpenCode permission requests arrive as 🔐 four-button cards (allow once / always allow / reject / ignore). Taps take effect silently (the tapped button shows ✓/✗ via native visited state). The card also shows exactly which rule "always allow" will save. Text replies ("允许/总是/拒绝") work too |
25
25
  | **Form prompt bridge** | OpenCode Forms (single-choice / multi-choice / boolean / text) render as 📝 QQ cards — answer by tapping buttons or replying with a letter (A/B/C). Requests and forms from desktop-side turns are pushed as well (always-on watcher, 12s poll) |
26
- | Remote commands | `/new /cancel /status /sessions /history /models /agents /rename /watch /mirror /progress /queue /ledger /send` |
27
- | Rich media | Receive images (native attachments go to the AI for vision); **receive voice** (QQ's built-in ASR transcribes to text into the prompt for free); **send images/files** (AI replies containing `QQ_SEND_FILE: <path>` or the `/send <path>` command; 20MB limit) |
26
+ | Remote commands | `/new /cancel /status /sessions /history /models /agents /rename /progress /queue /ledger /send /undo /amend /goal /compact /redo /btw` |
27
+ | Busy-time steer | New messages while a turn is running merge into the current turn (official steer semantics — the default); enqueue explicitly with `/queue <text>`; classic FIFO via `QQ_BUSY_DEFAULT=queue` |
28
+ | Goal mode | `/goal <objective>` passes through to the engine's goal mode with status-change notifications and kickoff attribution; `/goal` shows status, `pause|resume|clear` to control |
29
+ | Rich media | Receive images (native attachments go to the AI for vision); **receive voice** (QQ's built-in ASR transcribes to text into the prompt for free); **send images/files** — the AI calls the native `qq_send_file` tool (path allowlist + idempotent dedupe + precise errors; `QQ_SEND_FILE:` marker retained as fallback) or you run `/send <path>`; 20MB limit |
28
30
  | Quote context | Long-press quote a message and ask — the AI sees the quoted content (our own replies are indexed too) |
29
31
  | Long tasks never lost | 30-min foreground timeout falls back to a background wait (SSE + polling, up to 24h); a 30-min stall triggers a proactive notice with status (stalled / unknown / finished-but-lost), the latest tool action, and how long there's been no progress |
30
32
  | Duplicate-proof delivery | Two-layer dedup: cross-process atomic msgId claim + same-content in-flight fingerprint; long identical replies deduped outbound for 24h; "received" ack bubble off by default (`QQ_ACK_RECEIPT=1` to enable) |
@@ -34,6 +36,16 @@ Built for production, not just message bridging: a self-healing watchdog, an aud
34
36
  | Auditability | Every watchdog kill decision lands in a dedicated JSONL audit log (`~/.openqq/kills.log`): the rationale (health snapshot), the action (pid + TERM/KILL escalation), and the consequence (new pid + restart counter) |
35
37
  | Security | fail-closed allowlist admission (non-listed users always rejected), download-domain allowlist, secret masking in logs, push content redaction, dangerous-command approval driven by OpenCode's permission rules (four-button cards) |
36
38
 
39
+ ### What's new in v0.3.18
40
+
41
+ - **v0.3.19 hotfix** — `bin/openqq.js` TDZ (temporal dead zone) broke every `openqq` subcommand on 0.3.16-0.3.18 with a module-eval `ReferenceError`; declaration order fixed and a bin smoke suite added to the test chain. Also fixes the supervisor lease `--once` self-deferral that diluted 5-min patrols to 10-min (channel-priority + timestamp lease, pid is diagnostics only).
42
+ - **`qq_send_file` first-class tool** — the AI sends local files/images to QQ via a native tool with JSON-Schema contract and precise structured errors (allowlist roots on failure); the old `QQ_SEND_FILE:` text marker survives as a fallback. No more syntax guessing.
43
+ - **System-level channel instructions** — QQ rendering/format rules are injected as session instructions (`<context key="qq">`), not appended to your prompt text. Session history stays clean on the desktop side.
44
+ - **Status cockpit** — `/status` becomes the single dashboard and the only switch entry for observation (`watch`) and digest mirror (`mirror`); standalone `/watch` `/mirror` commands retired.
45
+ - **Honest dead-turn resumption** — a dead background turn is judged by three signals (last-activity threshold + running-tool grace window + turn-unterminated), aborted with the outcome recorded, and resumed with a targeted dedupe hint naming the in-flight tool; if the abort is unconfirmed the model must verify processes/side effects before redoing any write.
46
+ - **Busy-time steer by default** — messages arriving mid-turn merge into the running turn (official steer semantics); `/queue <text>` enqueues explicitly.
47
+ - Engineering: 69 test suites on a parallel runner, state-store hardening, `deploy/` retired, design-doc reconciliation batch. Full details in the [v0.3.18 release notes](https://github.com/linjz3376/opencode-qqbot/releases/tag/v0.3.18).
48
+
37
49
  Why QQ instead of the official mobile app: the official OpenCode Mobile (TestFlight / Google Play) is a remote for the desktop app — install required, out-of-region store accounts needed in China, and pairing through tunnels. This bot closes the loop natively in QQ: no app, no QR pairing, approval cards delivered straight to your chat.
38
50
 
39
51
  ## Quick start
@@ -142,18 +154,20 @@ launchctl load ~/Library/LaunchAgents/net.opencode-qqbot.plist
142
154
  |---|---|
143
155
  | `/new` | Start a new session |
144
156
  | `/cancel` | Abort the current generation and clear the busy queue |
145
- | `/status` | Server / session / model / agent status |
157
+ | `/status` | Cockpit: server / auth / session / model / agent / watch / mirror / queue / log; `watch` / `mirror` + `on`/`off` are the only switch entries |
146
158
  | `/sessions` | List sessions and switch by number |
147
159
  | `/history [N]` | Last N rounds (default 3, max 10; newlines / code blocks / tables preserved) |
148
160
  | `/models` | View or switch the model (session-level) |
149
161
  | `/agents` | View or switch the agent |
150
162
  | `/rename <name>` | Rename the current session (local title only) |
151
- | `/watch` / `/watch off` | Watch mode: tool-call milestones pushed live |
152
163
  | `/progress` | Manual progress query: tool/failure stats and in-flight status (local event source, zero model calls) |
153
- | `/queue` | Busy queue: view / `clear` / `drop <n>` (messages auto-queue FIFO while busy) |
164
+ | `/queue` | Busy queue: view / `clear` / `drop <n>` / `<text>` explicit enqueue (busy messages steer into the running turn by default; `QQ_BUSY_DEFAULT=queue` restores auto-queuing) |
154
165
  | `/ledger` | Ledger view: snapshot / `check` reconcile / `settle <suffix> confirm` manual settle (orphans and in-flight traceable) |
155
- | `/mirror` | Digest mirror on/off |
156
166
  | `/send <path>` | Send a file/image from an allowlisted directory to QQ |
167
+ | `/undo` | Official semantics: revert the last turn and restore files (receipt carries the reverted prompt; re-send after edits) |
168
+ | `/amend <text>` | Steer a busy turn with supplementary instructions (official steer semantics); or `/queue <text>` to explicitly enqueue |
169
+ | `/goal <objective>` | Official goal mode (engine built-in, v2.2.1+): the session drives itself until done or blocked; `/goal` for status, `pause`/`resume`/`clear` to control |
170
+ | `/compact` `/redo` `/btw` | Official engine commands: compact session / restore an undo / side question (not written into session context) |
157
171
 
158
172
  ## Environment variables (optional tuning)
159
173
 
package/README.zh-CN.md CHANGED
@@ -18,11 +18,13 @@
18
18
  |---|---|
19
19
  | 双向对话 | QQ 消息直达 opencode 会话,AI 回复推回 QQ(markdown 渲染、长文自动结构化分条:表格不拆散、代码块围栏自动修补) |
20
20
  | 桌面会话镜像 | 📋 摘要卡:桌面会话的最近一轮问答实时推送到 QQ(默认全文) |
21
- | 进度观察 | `/watch` 订阅工具调用里程碑(🔧 命令摘要/退出码),节流合并推送 |
21
+ | 驾驶舱 | `/status` 单点总控——服务器/会话/模型/Agent/观察/镜像/队列/日志一屏尽收;`/status watch on|off` 与 `/status mirror on|off` 是观察与桌面摘要镜像的唯一开关(工具里程碑 🔧 推送) |
22
22
  | **权限审批** | opencode 发起权限请求 → QQ 收 🔐 四键卡片(允许一次/总是允许/拒绝/忽略),点按钮静默生效(点击后该按钮回显 ✓/✗,其余按钮保持原样),也可文字回复"允许/总是/拒绝" |
23
23
  | **选择弹窗桥接** | opencode 的 Form(选择/多选/布尔/文本)→ QQ 📝 卡片,点按钮或回字母(A/B/C)作答;桌面端回合发起的审批/表单**同样**推送(常驻监听,12s 轮询,bot 空闲也收得到) |
24
- | 远程指令 | `/new /cancel /status /sessions /history /models /agents /rename /watch /mirror /progress /queue /ledger /send` |
25
- | 富媒体 | 收图(原生附件给 AI 看图);**收语音**(QQ 内置 ASR 免费转文字进 prompt);**发图/发文件**(AI 回复含 `QQ_SEND_FILE: <路径>` 标记或 `/send <路径>` 指令,20MB 上限) |
24
+ | 远程指令 | `/new /cancel /status /sessions /history /models /agents /rename /progress /queue /ledger /send /undo /amend /goal /compact /redo /btw` |
25
+ | 忙时 steer | 回合进行中收到新消息默认并入当前回合(官方 steer 语义);`/queue <文本>` 显式排队;`QQ_BUSY_DEFAULT=queue` 切回经典 FIFO |
26
+ | goal 模式 | `/goal <目标>` 直通引擎目标模式——状态变化通知 + kickoff 🎯 归属;`/goal` 查状态,pause/resume/clear 控制 |
27
+ | 富媒体 | 收图(原生附件给 AI 看图);**收语音**(QQ 内置 ASR 免费转文字进 prompt);**发图/发文件**——AI 调原生 `qq_send_file` 工具(路径白名单+幂等去重+精确错误,失败会告诉你可以发哪些根目录;`QQ_SEND_FILE:` 标记保留为降级通道)或 `/send <路径>`,20MB 上限 |
26
28
  | 引用上下文 | 长按引用某条消息提问,AI 能感知被引用的内容(我方回复也会入索引缓存) |
27
29
  | 长任务不丢 | 前台 30min 超时 → 后台等待(SSE + 轮询,最长 24h);停滞 30min 主动提醒(带「已停滞/状态不明/已终结未回传」状态位 + 最近工具动作 + 无进展时长) |
28
30
  | 投递幂等 | 双层去重:同 msgId 跨进程原子占位 + 同内容在途指纹(窗口=并发在途;已完成消息的重发按重发处理);同文长回复 24h 出站去重;「已收到」受理回执默认关(`QQ_ACK_RECEIPT=1` 调试召回) |
@@ -31,6 +33,16 @@
31
33
  | 自恢复 | 开机竞态退避、端口漂移自动发现与热换基、巡检告警(QQ 主动消息)、看门狗进程守护、单实例锁心跳 + 60s 周期自检(锁被他人接管/锁文件消失 → 自杀退出,杜绝多实例暗跑) |
32
34
  | 安全 | fail-closed 名单准入(名单外一律拒绝)、下载域白名单、日志密钥打码、推送内容脱敏、危险命令审批由 opencode 权限表驱动(QQ 端四键直达) |
33
35
 
36
+ ### v0.3.18 新特性
37
+
38
+ - **v0.3.19 热修**:`bin/openqq.js` 的 TDZ(暂时性死区)曾致 0.3.16-0.3.18 全部 `openqq` 子命令启动即 `ReferenceError`——声明顺序已修并补 bin 冒烟套件入测试链;同批修复监督租约 `--once` 自相让贤(5min 巡检被稀释成 10min,改 channel 优先级+时间戳租约,pid 仅诊断)。
39
+ - **`qq_send_file` 一等工具**:AI 经原生工具发本机文件/图片到 QQ——JSON Schema 契约+结构化精确错误(白名单拒绝时直接列出可用根目录);旧 `QQ_SEND_FILE:` 文本标记保留为降级。不再猜标记。
40
+ - **系统级通道指令**:QQ 渲染/格式规则以会话指令注入(`<context key="qq">`),不再拼接进 prompt 正文——桌面端会话历史零污染。
41
+ - **驾驶舱**:`/status` 升为单点总控,观察(`watch`)与桌面摘要镜像(`mirror`)的唯一开关入口;独立 `/watch` `/mirror` 命令退役。
42
+ - **死回合诚实续作**:三信号判死(末活动阈值+工具在飞豁免窗+回合未终结)→ abort 结果留痕(判据/动作/后果三段)→ 续作 prompt 点名在飞工具去重;abort 未确认时强制模型先核进程/副作用再重做写操作。
43
+ - **忙时默认 steer**:回合进行中收到消息默认并入当前回合(官方 steer 语义);`/queue <文本>` 显式排队。
44
+ - 工程面:69 套件并发测试链、state 存储加固、`deploy/` 退役、设计文档双向对账。详见 [v0.3.18 Release](https://github.com/linjz3376/opencode-qqbot/releases/tag/v0.3.18)。
45
+
34
46
  ## 快速开始
35
47
 
36
48
  ### 前置条件
@@ -73,7 +85,7 @@ QQ_SANDBOX=false
73
85
  ### 启动
74
86
 
75
87
  - **插件形态**:无需手动启动——装好插件 + 配好凭据后,插件巡检自动拉起 bot;opencode 服务重启也会自动恢复。
76
- - **独立部署形态**:`openqq` 前台运行;常驻按 OS 自选(Windows 用 `deploy/` 任务计划脚本;Linux `systemd --user`;macOS launchd 或 `nohup`)。
88
+ - **独立部署形态**:`openqq` 前台运行;常驻按 OS 自选(Windows:`openqq service install` 注册计划任务;Linux `systemd --user`;macOS launchd 或 `nohup`)。
77
89
 
78
90
  <details>
79
91
  <summary>Linux:systemd --user 单元(复制即用)</summary>
@@ -138,18 +150,20 @@ launchctl load ~/Library/LaunchAgents/net.opencode-qqbot.plist
138
150
  |---|---|
139
151
  | `/new` | 开新会话 |
140
152
  | `/cancel` | 中止当前生成并清空忙碌队列 |
141
- | `/status` | 服务器/会话/模型/Agent 状态 |
153
+ | `/status` | 驾驶舱:服务器/鉴权/会话/模型/Agent/观察/镜像/队列/日志;`watch` / `mirror` + `on`/`off` 为唯一开关入口 |
142
154
  | `/sessions` | 列出会话并可选择切换 |
143
155
  | `/history [N]` | 最近 N 轮历史(默认 3,上限 10;换行/代码块/表格完整保留) |
144
156
  | `/models` | 查看或切换模型(session 级) |
145
157
  | `/agents` | 查看或切换 Agent |
146
158
  | `/rename <名>` | 重命名当前会话(仅本地会话标题,不改服务端标题) |
147
- | `/watch` / `/watch off` | 观察模式:工具调用里程碑实时推送 |
148
159
  | `/progress` | 手动进度查询:工具调用/失败统计、当前在途状态(本地事件源,零模型调用) |
149
- | `/queue` | 忙碌队列:查看 / `clear` 清空 / `drop <编号>` 定点删除(忙碌时消息自动 FIFO 排队) |
160
+ | `/queue` | 忙碌队列:查看 / `clear` 清空 / `drop <编号>` 定点删除 / `<文本>` 显性入队(忙碌时消息默认 steer 并入当前任务,`QQ_BUSY_DEFAULT=queue` 可改回自动排队) |
150
161
  | `/ledger` | 台账视图:快照 / `check` 对账会话历史 / `settle <尾号> confirm` 人工结清(孤儿与在途可追溯) |
151
- | `/mirror` | 摘要镜像开关 |
152
162
  | `/send <路径>` | 把白名单目录内的文件/图片发到 QQ |
163
+ | `/undo` | 对齐官方:撤销上一回合,并恢复文件(回执带被撤指令,可改后重发) |
164
+ | `/amend <补充>` | 忙时插话并入当前任务(官方 steer 语义);也可 `/queue <文本>` 显式排队 |
165
+ | `/goal <目标>` | 官方目标模式(引擎内置,v2.2.1+):会话自主推进直到达成/卡住;`/goal` 查状态,`pause`/`resume`/`clear` 控制 |
166
+ | `/compact` `/redo` `/btw` | 官方引擎命令直通:压缩会话 / 恢复撤销 / 侧问(不写会话上下文) |
153
167
 
154
168
  ## 环境变量(可选调优)
155
169
 
package/bin/openqq.js CHANGED
@@ -11,6 +11,9 @@ import { fileURLToPath } from "node:url"
11
11
  import { join, dirname } from "node:path"
12
12
 
13
13
  const root = join(dirname(fileURLToPath(import.meta.url)), "..")
14
+ // argv 必须先于一切分支声明(TDZ 实证 DEF-qqbot-20261125-bin:watchdog/restart/service 分支
15
+ // 曾在本声明之前读取 argv[0],模块求值即 ReferenceError,全部子命令失效)。
16
+ const argv = process.argv.slice(2)
14
17
 
15
18
  // 2026-11-09 架构红线:看门狗/重启/自启注册都是包内 TS 产物,经本 shim 统一分发。
16
19
  // 传参不改变无参数行为。
@@ -27,7 +30,6 @@ if (argv[0] === "restart" || argv[0] === "service") {
27
30
 
28
31
  // notify 子命令分发(不改变无参数行为):CLI 只入队 ~openqq/outbox.json,
29
32
  // 发送由 bot 进程 notify-sink 消费;CLI 不联网不取 token 不抢锁。
30
- const argv = process.argv.slice(2)
31
33
  if (argv[0] === "notify") {
32
34
  const notifyArgs = argv.slice(1)
33
35
  const cliDist = join(root, "dist", "notify-cli.js")
@@ -1,9 +1,9 @@
1
1
  // @bun
2
2
  // src/plugin-entry.ts
3
3
  import { Plugin } from "@opencode/plugin";
4
- import { join as join9 } from "path";
5
- import { homedir as homedir7 } from "os";
6
- import { appendFileSync, existsSync as existsSync9, renameSync as renameSync3, statSync as statSync6 } from "fs";
4
+ import { join as join12 } from "path";
5
+ import { homedir as homedir8 } from "os";
6
+ import { appendFileSync, existsSync as existsSync11, renameSync as renameSync4, statSync as statSync7 } from "fs";
7
7
  import { fileURLToPath as fileURLToPath2 } from "url";
8
8
 
9
9
  // src/core/watchdog.ts
@@ -1233,39 +1233,256 @@ import { join as join8 } from "path";
1233
1233
  import { homedir as homedir6 } from "os";
1234
1234
  var LEASE_PATH = join8(homedir6(), ".openqq", "supervisor-lease.json");
1235
1235
  var LEASE_TTL_MS = 10 * 60000;
1236
+ var PRIORITY = { service: 2, plugin: 1 };
1236
1237
  function electSupervisor(channel, opts) {
1237
1238
  const ttlMs = opts?.ttlMs ?? LEASE_TTL_MS;
1238
1239
  const now = opts?.now ?? Date.now();
1239
1240
  const path = opts?.path ?? LEASE_PATH;
1241
+ const pid = opts?.pid ?? process.pid;
1240
1242
  try {
1241
1243
  let cur = null;
1242
1244
  try {
1243
1245
  cur = JSON.parse(readFileSync9(path, "utf-8"));
1244
1246
  } catch {}
1245
- if (cur && typeof cur.until === "number" && cur.until > now) {
1246
- const mine = cur.channel === channel && cur.pid === process.pid;
1247
- if (!mine)
1247
+ if (cur && typeof cur.until === "number" && cur.until > now && cur.channel) {
1248
+ if (cur.channel !== channel) {
1249
+ if (PRIORITY[cur.channel] > PRIORITY[channel])
1250
+ return false;
1251
+ } else if (channel === "plugin" && cur.pid !== pid) {
1248
1252
  return false;
1253
+ }
1249
1254
  }
1250
- writeFileSync5(path, JSON.stringify({ channel, pid: process.pid, until: now + ttlMs }));
1255
+ writeFileSync5(path, JSON.stringify({ channel, pid, until: now + ttlMs }));
1251
1256
  return true;
1252
1257
  } catch {
1253
1258
  return true;
1254
1259
  }
1255
1260
  }
1256
1261
 
1262
+ // src/core/send-requests.ts
1263
+ import { existsSync as existsSync9, mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync10, renameSync as renameSync3, statSync as statSync6, writeFileSync as writeFileSync6 } from "fs";
1264
+ import { join as join10 } from "path";
1265
+ import { randomUUID as randomUUID2 } from "crypto";
1266
+
1267
+ // src/core/send-media.ts
1268
+ import { resolve, extname, basename, sep, join as join9 } from "path";
1269
+ import { homedir as homedir7 } from "os";
1270
+
1271
+ // src/qq/media.ts
1272
+ var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
1273
+
1274
+ // src/qq/api.ts
1275
+ var appSandboxRegistry = new Map;
1276
+ var tokenCache = new Map;
1277
+ var tokenFetchByApp = new Map;
1278
+ var appIdByToken = new Map;
1279
+ var backgroundRefreshApps = new Set;
1280
+
1281
+ // src/core/send-media.ts
1282
+ var MAX_SEND_BYTES = 20 * 1024 * 1024;
1283
+ var SEND_DENIED_NAMES = new Set([
1284
+ ".env",
1285
+ "credentials",
1286
+ "secrets",
1287
+ "id_rsa",
1288
+ "id_dsa",
1289
+ "id_ecdsa",
1290
+ "id_ed25519",
1291
+ ".npmrc",
1292
+ ".pypirc",
1293
+ "netrc"
1294
+ ]);
1295
+ var SEND_DENIED_EXTS = new Set([".pem", ".key", ".p12", ".pfx", ".kdbx", ".htpasswd"]);
1296
+ function normalizeLocalPath(p) {
1297
+ let r = p.trim();
1298
+ if (r.startsWith("file://")) {
1299
+ r = r.slice("file://".length);
1300
+ if (/^\/[a-zA-Z]:[\\/]/.test(r))
1301
+ r = r.slice(1);
1302
+ }
1303
+ try {
1304
+ r = decodeURIComponent(r);
1305
+ } catch {}
1306
+ if (r === "~" || r.startsWith("~/") || r.startsWith("~\\")) {
1307
+ r = join9(homedir7(), r.slice(1));
1308
+ }
1309
+ return r;
1310
+ }
1311
+
1312
+ // src/core/send-requests.ts
1313
+ function sendRequestsDirFor(appId) {
1314
+ return join10(storageRoot(appId), "send-requests");
1315
+ }
1316
+ function findQQBinding(sessionId, root = storageRoot()) {
1317
+ const candidates = [{ file: join10(root, "sessions.json") }];
1318
+ const rolesDir = join10(root, "roles");
1319
+ if (existsSync9(rolesDir)) {
1320
+ for (const role of readdirSync2(rolesDir)) {
1321
+ candidates.push({ file: join10(rolesDir, role, "sessions.json"), appId: role });
1322
+ }
1323
+ }
1324
+ for (const { file, appId } of candidates) {
1325
+ try {
1326
+ const parsed = JSON.parse(readFileSync10(file, "utf-8"));
1327
+ for (const [userId, v] of Object.entries(parsed)) {
1328
+ if (v?.sessionId === sessionId)
1329
+ return appId ? { userId, appId } : { userId };
1330
+ }
1331
+ } catch {}
1332
+ }
1333
+ return null;
1334
+ }
1335
+ function dedupeKeyOf(sessionId, normalizedPath, st) {
1336
+ return `${sessionId}:${normalizedPath}:${st.mtimeMs}:${st.size}`;
1337
+ }
1338
+ function writeSendRequest(dir, req) {
1339
+ mkdirSync4(dir, { recursive: true });
1340
+ const tmp = join10(dir, `${req.id}.tmp`);
1341
+ writeFileSync6(tmp, JSON.stringify(req), "utf-8");
1342
+ renameSync3(tmp, join10(dir, `${req.id}.json`));
1343
+ return join10(dir, `${req.id}.json`);
1344
+ }
1345
+ async function awaitSendResult(dir, id, opts = {}) {
1346
+ const timeoutMs = opts.timeoutMs ?? 45000;
1347
+ const intervalMs = opts.intervalMs ?? 500;
1348
+ const file = join10(dir, `${id}.result.json`);
1349
+ const deadline = Date.now() + timeoutMs;
1350
+ for (;; ) {
1351
+ if (existsSync9(file)) {
1352
+ try {
1353
+ return JSON.parse(readFileSync10(file, "utf-8"));
1354
+ } catch {}
1355
+ }
1356
+ if (opts.signal?.aborted)
1357
+ return null;
1358
+ if (Date.now() >= deadline)
1359
+ return null;
1360
+ await new Promise((r) => setTimeout(r, intervalMs));
1361
+ }
1362
+ }
1363
+ async function executeQQSendFile(input, context) {
1364
+ const binding = findQQBinding(context.sessionID);
1365
+ if (!binding) {
1366
+ return "\u53D1\u9001\u5931\u8D25\uFF1A\u6B64 OpenCode \u4F1A\u8BDD\u672A\u7ED1\u5B9A QQ \u7528\u6237\u2014\u2014\u53EA\u6709\u4ECE QQ \u53D1\u8D77\u7684\u4F1A\u8BDD\uFF08\u6216\u5DF2 /sessions \u5207\u5165\u7ED1\u5B9A\u4F1A\u8BDD\uFF09\u624D\u80FD\u53D1\u9001\u5230 QQ\u3002";
1367
+ }
1368
+ const normalized = normalizeLocalPath(input.path);
1369
+ let st;
1370
+ try {
1371
+ const s = statSync6(normalized);
1372
+ st = { mtimeMs: s.mtimeMs, size: s.size };
1373
+ } catch {
1374
+ return `\u53D1\u9001\u5931\u8D25\uFF1A\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\u2014\u2014${normalized}\uFF08\u8BF7\u5148\u7528\u5199\u6587\u4EF6\u5DE5\u5177\u751F\u6210\u5230\u672C\u673A\u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u518D\u8C03\u7528\u672C\u5DE5\u5177\uFF09`;
1375
+ }
1376
+ const dir = sendRequestsDirFor(binding.appId);
1377
+ const req = {
1378
+ id: randomUUID2(),
1379
+ sessionId: context.sessionID,
1380
+ userId: binding.userId,
1381
+ appId: binding.appId,
1382
+ path: normalized,
1383
+ caption: input.caption,
1384
+ at: Date.now(),
1385
+ dedupeKey: dedupeKeyOf(context.sessionID, normalized, st)
1386
+ };
1387
+ writeSendRequest(dir, req);
1388
+ const result = await awaitSendResult(dir, req.id, { signal: context.signal });
1389
+ if (!result) {
1390
+ return "\u8BF7\u6C42\u5DF2\u53D7\u7406\u4F46 45s \u5185\u672A\u83B7\u56DE\u6267\u2014\u2014\u53D1\u9001\u7ED3\u679C\u672A\u77E5\uFF08bot \u53EF\u80FD\u5FD9\u6216\u79BB\u7EBF\uFF0C\u6062\u590D\u540E\u4ECD\u4F1A\u6D88\u8D39\uFF09\u3002\u8BF7\u52FF\u76F2\u76EE\u91CD\u8BD5\uFF1B\u53EF\u5148 /status \u6838\u67E5 bot \u72B6\u6001\u3002";
1391
+ }
1392
+ if (result.ok)
1393
+ return `\u5DF2\u53D1\u9001\u5230 QQ\uFF1A${result.detail ?? req.path}${result.deduped ? "\uFF08\u76F8\u540C\u6587\u4EF6\u6B64\u524D\u5DF2\u53D1\uFF0C\u672C\u6B21\u53BB\u91CD\u672A\u91CD\u590D\u53D1\u9001\uFF09" : ""}`;
1394
+ return `\u53D1\u9001\u5931\u8D25\uFF1A${result.error ?? "\u672A\u77E5\u539F\u56E0"}\u2014\u2014\u8BF7\u6309\u539F\u56E0\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF08\u82E5\u662F\u767D\u540D\u5355\u62D2\u7EDD\uFF0C\u53EF\u5148\u628A\u6587\u4EF6\u590D\u5236\u5230\u5141\u8BB8\u7684\u6839\u76EE\u5F55\u5185\u518D\u53D1\uFF09\u3002`;
1395
+ }
1396
+
1397
+ // src/core/qq-instructions.ts
1398
+ import { existsSync as existsSync10, mkdirSync as mkdirSync5, readdirSync as readdirSync3, readFileSync as readFileSync11, writeFileSync as writeFileSync7 } from "fs";
1399
+ import { dirname as dirname5, join as join11 } from "path";
1400
+ var QQ_INSTRUCTION_KEY = "qq";
1401
+ var QQ_INSTRUCTION_TEXT = [
1402
+ "\u672C\u5BF9\u8BDD\u7ECF QQ \u6E32\u67D3\uFF1A",
1403
+ "- \u8F93\u51FA\u683C\u5F0F\uFF1A\u7528\u300C1\u30012\u30013\u3001\u300D\u987F\u53F7\u6216\u300C-\u300D\u65E0\u5E8F\u5217\u8868\u4EE3\u66FF markdown \u6709\u5E8F\u5217\u8868\uFF0C\u907F\u514D\u8868\u683C\uFF1B\u4EE3\u7801\u5757\u4E0D\u53D7\u5F71\u54CD\u53EF\u6B63\u5E38\u4F7F\u7528\u3002",
1404
+ "- \u53D1\u9001\u672C\u673A\u6587\u4EF6/\u56FE\u7247\u7ED9 QQ \u7528\u6237\uFF1A\u4F18\u5148\u8C03\u7528 qq_send_file \u5DE5\u5177\uFF08\u82E5\u5DE5\u5177\u6E05\u5355\u63D0\u4F9B\uFF0C\u5931\u8D25\u4F1A\u8FD4\u56DE\u7CBE\u786E\u539F\u56E0\u53EF\u636E\u4EE5\u4FEE\u6B63\uFF09\uFF1B\u65E0\u8BE5\u5DE5\u5177\u65F6\uFF0C\u5728\u56DE\u590D\u672B\u5C3E\u72EC\u7ACB\u4E00\u884C\u5199 `QQ_SEND_FILE: <\u7EDD\u5BF9\u8DEF\u5F84>`\uFF08\u8DEF\u5F84\u987B\u5728\u53D1\u9001\u767D\u540D\u5355\u5185\uFF0C\u9ED8\u8BA4 QQ \u56FE\u7247\u7F13\u5B58\u76EE\u5F55\u4E0E bot \u5DE5\u4F5C\u76EE\u5F55\uFF09\u3002"
1405
+ ].join(`
1406
+ `);
1407
+ function qqInstructionStateFile() {
1408
+ return join11(storageRoot(), "qq-system-instructions.json");
1409
+ }
1410
+ function listQQBindings(root = storageRoot()) {
1411
+ const candidates = [{ file: join11(root, "sessions.json") }];
1412
+ const rolesDir = join11(root, "roles");
1413
+ if (existsSync10(rolesDir)) {
1414
+ for (const role of readdirSync3(rolesDir))
1415
+ candidates.push({ file: join11(rolesDir, role, "sessions.json"), appId: role });
1416
+ }
1417
+ const out = [];
1418
+ for (const { file, appId } of candidates) {
1419
+ try {
1420
+ const parsed = JSON.parse(readFileSync11(file, "utf-8"));
1421
+ for (const [userId, v] of Object.entries(parsed)) {
1422
+ if (typeof v?.sessionId === "string" && v.sessionId.startsWith("ses_")) {
1423
+ out.push(appId ? { userId, sessionId: v.sessionId, appId } : { userId, sessionId: v.sessionId });
1424
+ }
1425
+ }
1426
+ } catch {}
1427
+ }
1428
+ return out;
1429
+ }
1430
+ var hookRegistered = false;
1431
+ async function syncQQInstructions(ctx, opts = {}) {
1432
+ const bindings = opts.bindings ?? listQQBindings();
1433
+ const stateFile = opts.stateFile ?? qqInstructionStateFile();
1434
+ const writeState = (mode) => {
1435
+ mkdirSync5(dirname5(stateFile), { recursive: true });
1436
+ writeFileSync7(stateFile, JSON.stringify({ mode, at: Date.now() }), "utf-8");
1437
+ };
1438
+ try {
1439
+ const entry = ctx?.session?.instructions?.entry;
1440
+ if (entry?.put && entry?.list) {
1441
+ for (const b of bindings) {
1442
+ const existing = await entry.list({ sessionID: b.sessionId }).catch(() => []);
1443
+ const has = (existing ?? []).some((e) => e?.key === QQ_INSTRUCTION_KEY && e?.value === QQ_INSTRUCTION_TEXT);
1444
+ if (!has)
1445
+ await entry.put({ sessionID: b.sessionId, key: QQ_INSTRUCTION_KEY, value: QQ_INSTRUCTION_TEXT });
1446
+ }
1447
+ writeState("entry");
1448
+ return "entry";
1449
+ }
1450
+ if (typeof ctx?.session?.hook === "function") {
1451
+ if (!hookRegistered) {
1452
+ const cache = new Map;
1453
+ await ctx.session.hook("context", (event) => {
1454
+ const sid = event?.sessionID;
1455
+ if (!sid || !event?.system)
1456
+ return;
1457
+ let hit = cache.get(sid);
1458
+ if (!hit || Date.now() - hit.at > 60000) {
1459
+ hit = { bound: Boolean(findQQBinding(sid)), at: Date.now() };
1460
+ cache.set(sid, hit);
1461
+ }
1462
+ if (hit.bound)
1463
+ event.system.push({ type: "text", text: QQ_INSTRUCTION_TEXT });
1464
+ });
1465
+ hookRegistered = true;
1466
+ }
1467
+ writeState("hook");
1468
+ return "hook";
1469
+ }
1470
+ } catch {}
1471
+ return "none";
1472
+ }
1473
+
1257
1474
  // src/plugin-entry.ts
1258
- var ENV_FILE2 = join9(homedir7(), ".openqq", ".env");
1475
+ var ENV_FILE2 = join12(homedir8(), ".openqq", ".env");
1259
1476
  var CHECK_INTERVAL_MS = (() => {
1260
1477
  const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000");
1261
1478
  return Number.isFinite(n) && n > 0 ? n : 300000;
1262
1479
  })();
1263
- var PROBE_FILE = join9(homedir7(), ".openqq", "opencode-events.jsonl");
1480
+ var PROBE_FILE = join12(homedir8(), ".openqq", "opencode-events.jsonl");
1264
1481
  var PROBE_ROTATE_BYTES = 5 * 1024 * 1024;
1265
1482
  function probeAppend(line) {
1266
1483
  try {
1267
- if (existsSync9(PROBE_FILE) && statSync6(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
1268
- renameSync3(PROBE_FILE, PROBE_FILE + ".1");
1484
+ if (existsSync11(PROBE_FILE) && statSync7(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
1485
+ renameSync4(PROBE_FILE, PROBE_FILE + ".1");
1269
1486
  }
1270
1487
  appendFileSync(PROBE_FILE, line + `
1271
1488
  `);
@@ -1298,6 +1515,9 @@ var plugin_entry_default = Plugin.define({
1298
1515
  warnOnce("cred", "[opencode-qqbot] \u672A\u53D1\u73B0 ~/.openqq/.env \u51ED\u636E\u2014\u2014\u5148\u8FD0\u884C npx @linjz/opencode-qqbot setup \u626B\u7801\u7ED1\u5B9A\uFF08\u6216\u53C2\u8003 README \u624B\u5199 .env\uFF09\uFF0C\u5B8C\u6210\u540E\u63D2\u4EF6\u5C06\u5728\u4E0B\u6B21\u5DE1\u68C0\u81EA\u52A8\u62C9\u8D77 bot");
1299
1516
  return;
1300
1517
  }
1518
+ syncQQInstructions(_ctx).catch((error) => {
1519
+ console.warn("[opencode-qqbot] QQ \u7CFB\u7EDF\u6307\u4EE4\u540C\u6B65\u5931\u8D25\uFF08\u4E0B\u5468\u671F\u91CD\u8BD5\uFF09:", error instanceof Error ? error.message : error);
1520
+ });
1301
1521
  if (!electSupervisor("plugin"))
1302
1522
  return;
1303
1523
  superviseOnce({
@@ -1324,6 +1544,26 @@ var plugin_entry_default = Plugin.define({
1324
1544
  };
1325
1545
  ensure();
1326
1546
  const timer = setInterval(ensure, CHECK_INTERVAL_MS);
1547
+ const toolApi = _ctx.tool;
1548
+ if (toolApi?.transform) {
1549
+ toolApi.transform((editor) => {
1550
+ editor.namespace?.({ name: "qq", description: "QQ \u6D88\u606F\u901A\u9053\u5DE5\u5177\uFF08\u53D1\u9001\u5230\u5F53\u524D\u4F1A\u8BDD\u7ED1\u5B9A\u7684 QQ \u7528\u6237\uFF09" });
1551
+ editor.add({
1552
+ name: "send_file",
1553
+ description: "\u628A\u672C\u673A\u6587\u4EF6/\u56FE\u7247\u53D1\u9001\u5230\u5F53\u524D\u4F1A\u8BDD\u7ED1\u5B9A\u7684 QQ \u7528\u6237\u3002path=\u672C\u673A\u7EDD\u5BF9\u8DEF\u5F84\uFF08\u987B\u5728\u53D1\u9001\u767D\u540D\u5355\u5185\uFF0C\u9ED8\u8BA4 QQ \u56FE\u7247\u7F13\u5B58\u76EE\u5F55\u4E0E bot \u5DE5\u4F5C\u76EE\u5F55\uFF0CQQ_SEND_EXTRA_ROOTS \u53EF\u6269\uFF09\u3002\u5931\u8D25\u8FD4\u56DE\u7CBE\u786E\u539F\u56E0\uFF08\u542B\u767D\u540D\u5355\u6839\u76EE\u5F55/\u62D2\u8BC6\u7C7B\u578B\uFF09\uFF0C\u4FEE\u6B63\u540E\u53EF\u91CD\u8BD5\uFF1B\u76F8\u540C\u6587\u4EF6\u91CD\u590D\u8C03\u7528\u81EA\u52A8\u53BB\u91CD\u3002",
1554
+ input: {
1555
+ type: "object",
1556
+ properties: { path: { type: "string" }, caption: { type: "string" } },
1557
+ required: ["path"],
1558
+ additionalProperties: false
1559
+ },
1560
+ options: { namespace: "qq", codemode: true },
1561
+ execute: async (input, context) => ({ content: await executeQQSendFile(input, context) })
1562
+ });
1563
+ }).catch((error) => {
1564
+ console.warn("[opencode-qqbot] qq_send_file \u6CE8\u518C\u5931\u8D25\uFF08\u964D\u7EA7\u4E3A QQ_SEND_FILE \u6807\u8BB0\u901A\u9053\uFF09:", error);
1565
+ });
1566
+ }
1327
1567
  let probeAbort = null;
1328
1568
  if (readDotEnvField(ENV_FILE2, "QQ_EVENT_PROBE") === "true") {
1329
1569
  probeAbort = new AbortController;