@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/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,15 @@ 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
+ - **`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.
42
+ - **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.
43
+ - **Status cockpit** — `/status` becomes the single dashboard and the only switch entry for observation (`watch`) and digest mirror (`mirror`); standalone `/watch` `/mirror` commands retired.
44
+ - **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.
45
+ - **Busy-time steer by default** — messages arriving mid-turn merge into the running turn (official steer semantics); `/queue <text>` enqueues explicitly.
46
+ - 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).
47
+
37
48
  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
49
 
39
50
  ## Quick start
@@ -142,18 +153,20 @@ launchctl load ~/Library/LaunchAgents/net.opencode-qqbot.plist
142
153
  |---|---|
143
154
  | `/new` | Start a new session |
144
155
  | `/cancel` | Abort the current generation and clear the busy queue |
145
- | `/status` | Server / session / model / agent status |
156
+ | `/status` | Cockpit: server / auth / session / model / agent / watch / mirror / queue / log; `watch` / `mirror` + `on`/`off` are the only switch entries |
146
157
  | `/sessions` | List sessions and switch by number |
147
158
  | `/history [N]` | Last N rounds (default 3, max 10; newlines / code blocks / tables preserved) |
148
159
  | `/models` | View or switch the model (session-level) |
149
160
  | `/agents` | View or switch the agent |
150
161
  | `/rename <name>` | Rename the current session (local title only) |
151
- | `/watch` / `/watch off` | Watch mode: tool-call milestones pushed live |
152
162
  | `/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) |
163
+ | `/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
164
  | `/ledger` | Ledger view: snapshot / `check` reconcile / `settle <suffix> confirm` manual settle (orphans and in-flight traceable) |
155
- | `/mirror` | Digest mirror on/off |
156
165
  | `/send <path>` | Send a file/image from an allowlisted directory to QQ |
166
+ | `/undo` | Official semantics: revert the last turn and restore files (receipt carries the reverted prompt; re-send after edits) |
167
+ | `/amend <text>` | Steer a busy turn with supplementary instructions (official steer semantics); or `/queue <text>` to explicitly enqueue |
168
+ | `/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 |
169
+ | `/compact` `/redo` `/btw` | Official engine commands: compact session / restore an undo / side question (not written into session context) |
157
170
 
158
171
  ## Environment variables (optional tuning)
159
172
 
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,15 @@
31
33
  | 自恢复 | 开机竞态退避、端口漂移自动发现与热换基、巡检告警(QQ 主动消息)、看门狗进程守护、单实例锁心跳 + 60s 周期自检(锁被他人接管/锁文件消失 → 自杀退出,杜绝多实例暗跑) |
32
34
  | 安全 | fail-closed 名单准入(名单外一律拒绝)、下载域白名单、日志密钥打码、推送内容脱敏、危险命令审批由 opencode 权限表驱动(QQ 端四键直达) |
33
35
 
36
+ ### v0.3.18 新特性
37
+
38
+ - **`qq_send_file` 一等工具**:AI 经原生工具发本机文件/图片到 QQ——JSON Schema 契约+结构化精确错误(白名单拒绝时直接列出可用根目录);旧 `QQ_SEND_FILE:` 文本标记保留为降级。不再猜标记。
39
+ - **系统级通道指令**:QQ 渲染/格式规则以会话指令注入(`<context key="qq">`),不再拼接进 prompt 正文——桌面端会话历史零污染。
40
+ - **驾驶舱**:`/status` 升为单点总控,观察(`watch`)与桌面摘要镜像(`mirror`)的唯一开关入口;独立 `/watch` `/mirror` 命令退役。
41
+ - **死回合诚实续作**:三信号判死(末活动阈值+工具在飞豁免窗+回合未终结)→ abort 结果留痕(判据/动作/后果三段)→ 续作 prompt 点名在飞工具去重;abort 未确认时强制模型先核进程/副作用再重做写操作。
42
+ - **忙时默认 steer**:回合进行中收到消息默认并入当前回合(官方 steer 语义);`/queue <文本>` 显式排队。
43
+ - 工程面:69 套件并发测试链、state 存储加固、`deploy/` 退役、设计文档双向对账。详见 [v0.3.18 Release](https://github.com/linjz3376/opencode-qqbot/releases/tag/v0.3.18)。
44
+
34
45
  ## 快速开始
35
46
 
36
47
  ### 前置条件
@@ -73,7 +84,7 @@ QQ_SANDBOX=false
73
84
  ### 启动
74
85
 
75
86
  - **插件形态**:无需手动启动——装好插件 + 配好凭据后,插件巡检自动拉起 bot;opencode 服务重启也会自动恢复。
76
- - **独立部署形态**:`openqq` 前台运行;常驻按 OS 自选(Windows 用 `deploy/` 任务计划脚本;Linux `systemd --user`;macOS launchd 或 `nohup`)。
87
+ - **独立部署形态**:`openqq` 前台运行;常驻按 OS 自选(Windows:`openqq service install` 注册计划任务;Linux `systemd --user`;macOS launchd 或 `nohup`)。
77
88
 
78
89
  <details>
79
90
  <summary>Linux:systemd --user 单元(复制即用)</summary>
@@ -138,18 +149,20 @@ launchctl load ~/Library/LaunchAgents/net.opencode-qqbot.plist
138
149
  |---|---|
139
150
  | `/new` | 开新会话 |
140
151
  | `/cancel` | 中止当前生成并清空忙碌队列 |
141
- | `/status` | 服务器/会话/模型/Agent 状态 |
152
+ | `/status` | 驾驶舱:服务器/鉴权/会话/模型/Agent/观察/镜像/队列/日志;`watch` / `mirror` + `on`/`off` 为唯一开关入口 |
142
153
  | `/sessions` | 列出会话并可选择切换 |
143
154
  | `/history [N]` | 最近 N 轮历史(默认 3,上限 10;换行/代码块/表格完整保留) |
144
155
  | `/models` | 查看或切换模型(session 级) |
145
156
  | `/agents` | 查看或切换 Agent |
146
157
  | `/rename <名>` | 重命名当前会话(仅本地会话标题,不改服务端标题) |
147
- | `/watch` / `/watch off` | 观察模式:工具调用里程碑实时推送 |
148
158
  | `/progress` | 手动进度查询:工具调用/失败统计、当前在途状态(本地事件源,零模型调用) |
149
- | `/queue` | 忙碌队列:查看 / `clear` 清空 / `drop <编号>` 定点删除(忙碌时消息自动 FIFO 排队) |
159
+ | `/queue` | 忙碌队列:查看 / `clear` 清空 / `drop <编号>` 定点删除 / `<文本>` 显性入队(忙碌时消息默认 steer 并入当前任务,`QQ_BUSY_DEFAULT=queue` 可改回自动排队) |
150
160
  | `/ledger` | 台账视图:快照 / `check` 对账会话历史 / `settle <尾号> confirm` 人工结清(孤儿与在途可追溯) |
151
- | `/mirror` | 摘要镜像开关 |
152
161
  | `/send <路径>` | 把白名单目录内的文件/图片发到 QQ |
162
+ | `/undo` | 对齐官方:撤销上一回合,并恢复文件(回执带被撤指令,可改后重发) |
163
+ | `/amend <补充>` | 忙时插话并入当前任务(官方 steer 语义);也可 `/queue <文本>` 显式排队 |
164
+ | `/goal <目标>` | 官方目标模式(引擎内置,v2.2.1+):会话自主推进直到达成/卡住;`/goal` 查状态,`pause`/`resume`/`clear` 控制 |
165
+ | `/compact` `/redo` `/btw` | 官方引擎命令直通:压缩会话 / 恢复撤销 / 侧问(不写会话上下文) |
153
166
 
154
167
  ## 环境变量(可选调优)
155
168
 
@@ -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
@@ -1254,18 +1254,230 @@ function electSupervisor(channel, opts) {
1254
1254
  }
1255
1255
  }
1256
1256
 
1257
+ // src/core/send-requests.ts
1258
+ import { existsSync as existsSync9, mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync10, renameSync as renameSync3, statSync as statSync6, writeFileSync as writeFileSync6 } from "fs";
1259
+ import { join as join10 } from "path";
1260
+ import { randomUUID as randomUUID2 } from "crypto";
1261
+
1262
+ // src/core/send-media.ts
1263
+ import { resolve, extname, basename, sep, join as join9 } from "path";
1264
+ import { homedir as homedir7 } from "os";
1265
+
1266
+ // src/qq/media.ts
1267
+ var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
1268
+
1269
+ // src/qq/api.ts
1270
+ var appSandboxRegistry = new Map;
1271
+ var tokenCache = new Map;
1272
+ var tokenFetchByApp = new Map;
1273
+ var appIdByToken = new Map;
1274
+ var backgroundRefreshApps = new Set;
1275
+
1276
+ // src/core/send-media.ts
1277
+ var MAX_SEND_BYTES = 20 * 1024 * 1024;
1278
+ var SEND_DENIED_NAMES = new Set([
1279
+ ".env",
1280
+ "credentials",
1281
+ "secrets",
1282
+ "id_rsa",
1283
+ "id_dsa",
1284
+ "id_ecdsa",
1285
+ "id_ed25519",
1286
+ ".npmrc",
1287
+ ".pypirc",
1288
+ "netrc"
1289
+ ]);
1290
+ var SEND_DENIED_EXTS = new Set([".pem", ".key", ".p12", ".pfx", ".kdbx", ".htpasswd"]);
1291
+ function normalizeLocalPath(p) {
1292
+ let r = p.trim();
1293
+ if (r.startsWith("file://")) {
1294
+ r = r.slice("file://".length);
1295
+ if (/^\/[a-zA-Z]:[\\/]/.test(r))
1296
+ r = r.slice(1);
1297
+ }
1298
+ try {
1299
+ r = decodeURIComponent(r);
1300
+ } catch {}
1301
+ if (r === "~" || r.startsWith("~/") || r.startsWith("~\\")) {
1302
+ r = join9(homedir7(), r.slice(1));
1303
+ }
1304
+ return r;
1305
+ }
1306
+
1307
+ // src/core/send-requests.ts
1308
+ function sendRequestsDirFor(appId) {
1309
+ return join10(storageRoot(appId), "send-requests");
1310
+ }
1311
+ function findQQBinding(sessionId, root = storageRoot()) {
1312
+ const candidates = [{ file: join10(root, "sessions.json") }];
1313
+ const rolesDir = join10(root, "roles");
1314
+ if (existsSync9(rolesDir)) {
1315
+ for (const role of readdirSync2(rolesDir)) {
1316
+ candidates.push({ file: join10(rolesDir, role, "sessions.json"), appId: role });
1317
+ }
1318
+ }
1319
+ for (const { file, appId } of candidates) {
1320
+ try {
1321
+ const parsed = JSON.parse(readFileSync10(file, "utf-8"));
1322
+ for (const [userId, v] of Object.entries(parsed)) {
1323
+ if (v?.sessionId === sessionId)
1324
+ return appId ? { userId, appId } : { userId };
1325
+ }
1326
+ } catch {}
1327
+ }
1328
+ return null;
1329
+ }
1330
+ function dedupeKeyOf(sessionId, normalizedPath, st) {
1331
+ return `${sessionId}:${normalizedPath}:${st.mtimeMs}:${st.size}`;
1332
+ }
1333
+ function writeSendRequest(dir, req) {
1334
+ mkdirSync4(dir, { recursive: true });
1335
+ const tmp = join10(dir, `${req.id}.tmp`);
1336
+ writeFileSync6(tmp, JSON.stringify(req), "utf-8");
1337
+ renameSync3(tmp, join10(dir, `${req.id}.json`));
1338
+ return join10(dir, `${req.id}.json`);
1339
+ }
1340
+ async function awaitSendResult(dir, id, opts = {}) {
1341
+ const timeoutMs = opts.timeoutMs ?? 45000;
1342
+ const intervalMs = opts.intervalMs ?? 500;
1343
+ const file = join10(dir, `${id}.result.json`);
1344
+ const deadline = Date.now() + timeoutMs;
1345
+ for (;; ) {
1346
+ if (existsSync9(file)) {
1347
+ try {
1348
+ return JSON.parse(readFileSync10(file, "utf-8"));
1349
+ } catch {}
1350
+ }
1351
+ if (opts.signal?.aborted)
1352
+ return null;
1353
+ if (Date.now() >= deadline)
1354
+ return null;
1355
+ await new Promise((r) => setTimeout(r, intervalMs));
1356
+ }
1357
+ }
1358
+ async function executeQQSendFile(input, context) {
1359
+ const binding = findQQBinding(context.sessionID);
1360
+ if (!binding) {
1361
+ 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";
1362
+ }
1363
+ const normalized = normalizeLocalPath(input.path);
1364
+ let st;
1365
+ try {
1366
+ const s = statSync6(normalized);
1367
+ st = { mtimeMs: s.mtimeMs, size: s.size };
1368
+ } catch {
1369
+ 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`;
1370
+ }
1371
+ const dir = sendRequestsDirFor(binding.appId);
1372
+ const req = {
1373
+ id: randomUUID2(),
1374
+ sessionId: context.sessionID,
1375
+ userId: binding.userId,
1376
+ appId: binding.appId,
1377
+ path: normalized,
1378
+ caption: input.caption,
1379
+ at: Date.now(),
1380
+ dedupeKey: dedupeKeyOf(context.sessionID, normalized, st)
1381
+ };
1382
+ writeSendRequest(dir, req);
1383
+ const result = await awaitSendResult(dir, req.id, { signal: context.signal });
1384
+ if (!result) {
1385
+ 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";
1386
+ }
1387
+ if (result.ok)
1388
+ 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" : ""}`;
1389
+ 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`;
1390
+ }
1391
+
1392
+ // src/core/qq-instructions.ts
1393
+ import { existsSync as existsSync10, mkdirSync as mkdirSync5, readdirSync as readdirSync3, readFileSync as readFileSync11, writeFileSync as writeFileSync7 } from "fs";
1394
+ import { dirname as dirname5, join as join11 } from "path";
1395
+ var QQ_INSTRUCTION_KEY = "qq";
1396
+ var QQ_INSTRUCTION_TEXT = [
1397
+ "\u672C\u5BF9\u8BDD\u7ECF QQ \u6E32\u67D3\uFF1A",
1398
+ "- \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",
1399
+ "- \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"
1400
+ ].join(`
1401
+ `);
1402
+ function qqInstructionStateFile() {
1403
+ return join11(storageRoot(), "qq-system-instructions.json");
1404
+ }
1405
+ function listQQBindings(root = storageRoot()) {
1406
+ const candidates = [{ file: join11(root, "sessions.json") }];
1407
+ const rolesDir = join11(root, "roles");
1408
+ if (existsSync10(rolesDir)) {
1409
+ for (const role of readdirSync3(rolesDir))
1410
+ candidates.push({ file: join11(rolesDir, role, "sessions.json"), appId: role });
1411
+ }
1412
+ const out = [];
1413
+ for (const { file, appId } of candidates) {
1414
+ try {
1415
+ const parsed = JSON.parse(readFileSync11(file, "utf-8"));
1416
+ for (const [userId, v] of Object.entries(parsed)) {
1417
+ if (typeof v?.sessionId === "string" && v.sessionId.startsWith("ses_")) {
1418
+ out.push(appId ? { userId, sessionId: v.sessionId, appId } : { userId, sessionId: v.sessionId });
1419
+ }
1420
+ }
1421
+ } catch {}
1422
+ }
1423
+ return out;
1424
+ }
1425
+ var hookRegistered = false;
1426
+ async function syncQQInstructions(ctx, opts = {}) {
1427
+ const bindings = opts.bindings ?? listQQBindings();
1428
+ const stateFile = opts.stateFile ?? qqInstructionStateFile();
1429
+ const writeState = (mode) => {
1430
+ mkdirSync5(dirname5(stateFile), { recursive: true });
1431
+ writeFileSync7(stateFile, JSON.stringify({ mode, at: Date.now() }), "utf-8");
1432
+ };
1433
+ try {
1434
+ const entry = ctx?.session?.instructions?.entry;
1435
+ if (entry?.put && entry?.list) {
1436
+ for (const b of bindings) {
1437
+ const existing = await entry.list({ sessionID: b.sessionId }).catch(() => []);
1438
+ const has = (existing ?? []).some((e) => e?.key === QQ_INSTRUCTION_KEY && e?.value === QQ_INSTRUCTION_TEXT);
1439
+ if (!has)
1440
+ await entry.put({ sessionID: b.sessionId, key: QQ_INSTRUCTION_KEY, value: QQ_INSTRUCTION_TEXT });
1441
+ }
1442
+ writeState("entry");
1443
+ return "entry";
1444
+ }
1445
+ if (typeof ctx?.session?.hook === "function") {
1446
+ if (!hookRegistered) {
1447
+ const cache = new Map;
1448
+ await ctx.session.hook("context", (event) => {
1449
+ const sid = event?.sessionID;
1450
+ if (!sid || !event?.system)
1451
+ return;
1452
+ let hit = cache.get(sid);
1453
+ if (!hit || Date.now() - hit.at > 60000) {
1454
+ hit = { bound: Boolean(findQQBinding(sid)), at: Date.now() };
1455
+ cache.set(sid, hit);
1456
+ }
1457
+ if (hit.bound)
1458
+ event.system.push({ type: "text", text: QQ_INSTRUCTION_TEXT });
1459
+ });
1460
+ hookRegistered = true;
1461
+ }
1462
+ writeState("hook");
1463
+ return "hook";
1464
+ }
1465
+ } catch {}
1466
+ return "none";
1467
+ }
1468
+
1257
1469
  // src/plugin-entry.ts
1258
- var ENV_FILE2 = join9(homedir7(), ".openqq", ".env");
1470
+ var ENV_FILE2 = join12(homedir8(), ".openqq", ".env");
1259
1471
  var CHECK_INTERVAL_MS = (() => {
1260
1472
  const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000");
1261
1473
  return Number.isFinite(n) && n > 0 ? n : 300000;
1262
1474
  })();
1263
- var PROBE_FILE = join9(homedir7(), ".openqq", "opencode-events.jsonl");
1475
+ var PROBE_FILE = join12(homedir8(), ".openqq", "opencode-events.jsonl");
1264
1476
  var PROBE_ROTATE_BYTES = 5 * 1024 * 1024;
1265
1477
  function probeAppend(line) {
1266
1478
  try {
1267
- if (existsSync9(PROBE_FILE) && statSync6(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
1268
- renameSync3(PROBE_FILE, PROBE_FILE + ".1");
1479
+ if (existsSync11(PROBE_FILE) && statSync7(PROBE_FILE).size > PROBE_ROTATE_BYTES) {
1480
+ renameSync4(PROBE_FILE, PROBE_FILE + ".1");
1269
1481
  }
1270
1482
  appendFileSync(PROBE_FILE, line + `
1271
1483
  `);
@@ -1298,6 +1510,9 @@ var plugin_entry_default = Plugin.define({
1298
1510
  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
1511
  return;
1300
1512
  }
1513
+ syncQQInstructions(_ctx).catch((error) => {
1514
+ 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);
1515
+ });
1301
1516
  if (!electSupervisor("plugin"))
1302
1517
  return;
1303
1518
  superviseOnce({
@@ -1324,6 +1539,26 @@ var plugin_entry_default = Plugin.define({
1324
1539
  };
1325
1540
  ensure();
1326
1541
  const timer = setInterval(ensure, CHECK_INTERVAL_MS);
1542
+ const toolApi = _ctx.tool;
1543
+ if (toolApi?.transform) {
1544
+ toolApi.transform((editor) => {
1545
+ 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" });
1546
+ editor.add({
1547
+ name: "send_file",
1548
+ 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",
1549
+ input: {
1550
+ type: "object",
1551
+ properties: { path: { type: "string" }, caption: { type: "string" } },
1552
+ required: ["path"],
1553
+ additionalProperties: false
1554
+ },
1555
+ options: { namespace: "qq", codemode: true },
1556
+ execute: async (input, context) => ({ content: await executeQQSendFile(input, context) })
1557
+ });
1558
+ }).catch((error) => {
1559
+ console.warn("[opencode-qqbot] qq_send_file \u6CE8\u518C\u5931\u8D25\uFF08\u964D\u7EA7\u4E3A QQ_SEND_FILE \u6807\u8BB0\u901A\u9053\uFF09:", error);
1560
+ });
1561
+ }
1327
1562
  let probeAbort = null;
1328
1563
  if (readDotEnvField(ENV_FILE2, "QQ_EVENT_PROBE") === "true") {
1329
1564
  probeAbort = new AbortController;