@linjz/opencode-qqbot 0.3.14 → 0.3.15
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 +31 -0
- package/bin/openqq.js +21 -0
- package/dist/notify-cli.js +579 -0
- package/dist/opencode-qqbot-plugin.js +4 -1
- package/dist/openqq-bot.js +555 -105
- package/package.json +5 -4
- package/src/bridge.ts +32 -11
- package/src/cli/notify-main.ts +6 -0
- package/src/cli/notify.ts +158 -0
- package/src/config.ts +2 -2
- package/src/core/form-bridge.ts +2 -2
- package/src/core/instance-lock.ts +11 -4
- package/src/core/notify-sink.ts +96 -0
- package/src/core/permission.ts +3 -1
- package/src/plugin-entry.ts +4 -1
- package/src/qq/gateway.ts +1 -1
- package/src/qq/media.ts +5 -1
package/README.md
CHANGED
|
@@ -193,6 +193,37 @@ npm run test:e2e # 五套 e2e(需 opencode 服务在跑)
|
|
|
193
193
|
| 桌面弹窗卡住任务 | 后台等待会发带任务的停滞通告(含最近动作与无进展时长);`/stop` 可终止 |
|
|
194
194
|
| 日志见「已有实例待命」 | 单实例锁生效中——另一实例持锁(60s 自检会在锁异动时收敛双活,正常无需处理) |
|
|
195
195
|
|
|
196
|
+
## 平台注意事项
|
|
197
|
+
|
|
198
|
+
以下发现来自真实部署(Windows 11 / OpenCode v2.2.2),插件无法修复但会反复绊倒用户,集中存档:
|
|
199
|
+
|
|
200
|
+
**QQ 平台侧**
|
|
201
|
+
|
|
202
|
+
1. token 接口 `POST https://bots.qq.com/app/getAppAccessToken` 的参数是 **`clientSecret`**(旧文档写作 `appSecret`);报错 `100016 invalid appid or secret` 极具误导性——先核对字段名,别急着重置密钥。
|
|
203
|
+
2. token 与正式/沙箱无关,统一走正式域名 `bots.qq.com`;**沙箱域名 `sandbox.api.sgroup.qq.com` 没有 token 端点**(请求会返回 `11001 不支持的调用`)。
|
|
204
|
+
3. 沙箱 bot 有独立网关:`GET https://sandbox.api.sgroup.qq.com/gateway` → `wss://sandbox.api.sgroup.qq.com/websocket`;沙箱 bot 连正式网关会被 4914 拒绝。
|
|
205
|
+
|
|
206
|
+
**OpenCode 侧**
|
|
207
|
+
|
|
208
|
+
4. `opencode plugin add` 偶发无输出挂起(>3min),重试通常成功。
|
|
209
|
+
5. `opencode reload` **只增不删**:plugins 数组移除的条目在服务端内存不卸载(旧插件的定时器仍存活),彻底生效需重启服务。
|
|
210
|
+
6. 全局插件目录扫描器只认根级入口(package.json exports 指向 `./dist` 子路径会被跳过),**仅影响本地目录形态**;npm 包形态无此限制。
|
|
211
|
+
7. `opencode plugin update` 必须带 scope 全名(`@linjz/opencode-qqbot`),裸写包短名报 `Plugin is not configured`。
|
|
212
|
+
8. npm 插件缓存在 `~/.cache/opencode/npm/<pkg>@<tag>/<时间戳>/`,update 会新建时间戳目录——对「在缓存文件上打本地补丁」的用户,补丁会静默失效;请避免在缓存副本上打补丁。
|
|
213
|
+
|
|
214
|
+
## 与 OpenCode 桌面版能力对齐矩阵
|
|
215
|
+
|
|
216
|
+
QQ 桥的本质是「opencode 交互事件 → QQ 交互原语」的适配器。桌面版 TUI 能处理的每类阻塞式交互,QQ 侧应有对应物(桥接或明确降级):
|
|
217
|
+
|
|
218
|
+
| 桌面端交互类型 | QQ 侧现状 | 差距 |
|
|
219
|
+
|---|---|---|
|
|
220
|
+
| 权限审批(PermissionRequest) | ✅ 四键卡片(允许一次/总是/拒绝/忽略)+ 文字回复 + 桌面端挂起的审批同样推送(常驻监听 12s) | 无 |
|
|
221
|
+
| 单字段 Form(单选/多选/布尔/文本) | ✅ 字母按钮卡片 + 文本解析 + 30min TTL + form-journal 持久化 | 无 |
|
|
222
|
+
| **多字段 Form(Questions)** | ⚠️ 回退「请在桌面端完成」(明确降级) | 逐字段向导为候选增强(见提案,未实施) |
|
|
223
|
+
| 未来 opencode 新增交互类型 | ⚠️ 无对齐机制,只能事后逐个补 | 按矩阵验收:要么随版本桥接、要么登记为「明确降级」,不允许出现未定义状态 |
|
|
224
|
+
|
|
225
|
+
原则:未支持的类型永远给出明确文案 + 桌面端指引,不允许静默丢弃;多字段向导等增强按最小侵入接入。
|
|
226
|
+
|
|
196
227
|
## License
|
|
197
228
|
|
|
198
229
|
MIT
|
package/bin/openqq.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// 无 bun → node dist/openqq-bot.js(发布 bundle,零额外依赖)
|
|
5
5
|
// 应用者 npm i -g 后只有 node 也能跑;开发者有 bun 时始终跑源码。
|
|
6
6
|
// 注意:本文件必须保持纯 JS(无类型标注)——node 用户直接执行它。
|
|
7
|
+
// 2026-11-05 外部提案 Part1 采纳:新增 `openqq notify` 子命令分发(只入队不发送)。
|
|
7
8
|
import { spawnSync } from "node:child_process"
|
|
8
9
|
import { existsSync } from "node:fs"
|
|
9
10
|
import { fileURLToPath } from "node:url"
|
|
@@ -11,6 +12,26 @@ import { join, dirname } from "node:path"
|
|
|
11
12
|
|
|
12
13
|
const root = join(dirname(fileURLToPath(import.meta.url)), "..")
|
|
13
14
|
|
|
15
|
+
// notify 子命令分发(不改变无参数行为):CLI 只入队 ~openqq/outbox.json,
|
|
16
|
+
// 发送由 bot 进程 notify-sink 消费;CLI 不联网不取 token 不抢锁。
|
|
17
|
+
const argv = process.argv.slice(2)
|
|
18
|
+
if (argv[0] === "notify") {
|
|
19
|
+
const notifyArgs = argv.slice(1)
|
|
20
|
+
const cliDist = join(root, "dist", "notify-cli.js")
|
|
21
|
+
const cliSrc = join(root, "src", "cli", "notify.ts")
|
|
22
|
+
const bun = detectBun()
|
|
23
|
+
if (existsSync(cliDist)) {
|
|
24
|
+
const r = spawnSync("node", [cliDist, ...notifyArgs], { stdio: "inherit" })
|
|
25
|
+
process.exit(r.status ?? 1)
|
|
26
|
+
}
|
|
27
|
+
if (bun && existsSync(cliSrc)) {
|
|
28
|
+
const r = spawnSync(bun, ["run", cliSrc, ...notifyArgs], { stdio: "inherit" })
|
|
29
|
+
process.exit(r.status ?? 1)
|
|
30
|
+
}
|
|
31
|
+
console.error("[openqq] notify CLI 不存在(包安装不完整,请重装 @linjz/opencode-qqbot)")
|
|
32
|
+
process.exit(1)
|
|
33
|
+
}
|
|
34
|
+
|
|
14
35
|
// bun 探测要覆盖全形态:npm 装的 bun 在 PATH 上只有 bun.ps1(CreateProcess 起不来),
|
|
15
36
|
// 真正可执行体在 npm\bun 包内 bin\bun.exe;官方安装则直接是 bun/bun.exe。
|
|
16
37
|
function detectBun() {
|
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
// src/cli/notify.ts
|
|
2
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
|
|
3
|
+
|
|
4
|
+
// src/core/outbox.ts
|
|
5
|
+
import {
|
|
6
|
+
closeSync,
|
|
7
|
+
existsSync,
|
|
8
|
+
mkdirSync,
|
|
9
|
+
openSync,
|
|
10
|
+
readFileSync,
|
|
11
|
+
renameSync,
|
|
12
|
+
statSync,
|
|
13
|
+
unlinkSync,
|
|
14
|
+
writeFileSync
|
|
15
|
+
} from "node:fs";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { dirname, join } from "node:path";
|
|
18
|
+
import { randomUUID } from "node:crypto";
|
|
19
|
+
var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
|
|
20
|
+
var OUTBOX_SENT_RETENTION_LIMIT = 20;
|
|
21
|
+
var OUTBOX_DEFAULT_RETRY_BASE_MS = 1000;
|
|
22
|
+
var OUTBOX_DEFAULT_RETRY_MAX_MS = 60000;
|
|
23
|
+
var DEFAULT_POLL_INTERVAL_MS = 1000;
|
|
24
|
+
var DEFAULT_LEASE_MS = 30000;
|
|
25
|
+
var DEFAULT_LOCK_WAIT_MS = 5000;
|
|
26
|
+
var DEFAULT_LOCK_STALE_MS = 30000;
|
|
27
|
+
var sleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
28
|
+
function nonNegative(value, fallback, name) {
|
|
29
|
+
const resolved = value ?? fallback;
|
|
30
|
+
if (!Number.isFinite(resolved) || resolved < 0)
|
|
31
|
+
throw new Error(`${name} 必须是 >= 0 的有限数`);
|
|
32
|
+
return resolved;
|
|
33
|
+
}
|
|
34
|
+
function positive(value, fallback, name) {
|
|
35
|
+
const resolved = nonNegative(value, fallback, name);
|
|
36
|
+
if (resolved === 0)
|
|
37
|
+
throw new Error(`${name} 必须 > 0`);
|
|
38
|
+
return resolved;
|
|
39
|
+
}
|
|
40
|
+
function errorText(error) {
|
|
41
|
+
return error instanceof Error ? error.message : String(error);
|
|
42
|
+
}
|
|
43
|
+
function jsonSnapshot(value, label) {
|
|
44
|
+
const encoded = JSON.stringify(value);
|
|
45
|
+
if (encoded === undefined)
|
|
46
|
+
throw new Error(`Outbox ${label} 必须是可 JSON 序列化的值`);
|
|
47
|
+
return JSON.parse(encoded);
|
|
48
|
+
}
|
|
49
|
+
function delay(ms) {
|
|
50
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
51
|
+
}
|
|
52
|
+
function atomicWrite(filePath, document) {
|
|
53
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
54
|
+
const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
55
|
+
try {
|
|
56
|
+
writeFileSync(temporary, JSON.stringify(document, null, 2), { mode: 384 });
|
|
57
|
+
renameSync(temporary, filePath);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
try {
|
|
60
|
+
unlinkSync(temporary);
|
|
61
|
+
} catch {}
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function readDocument(filePath, now) {
|
|
66
|
+
if (!existsSync(filePath))
|
|
67
|
+
return { version: 1, entries: [] };
|
|
68
|
+
const raw = JSON.parse(readFileSync(filePath, "utf8"));
|
|
69
|
+
if (Array.isArray(raw)) {
|
|
70
|
+
return { version: 1, entries: pruneOutboxEntries(raw, now) };
|
|
71
|
+
}
|
|
72
|
+
if (typeof raw !== "object" || raw === null || raw.version !== 1 || !Array.isArray(raw.entries)) {
|
|
73
|
+
throw new Error(`Outbox 文件格式无效: ${filePath}`);
|
|
74
|
+
}
|
|
75
|
+
const entries = raw.entries;
|
|
76
|
+
return { version: 1, entries: pruneOutboxEntries(entries, now) };
|
|
77
|
+
}
|
|
78
|
+
function pruneOutboxEntries(entries, now = Date.now()) {
|
|
79
|
+
const indexed = entries.map((entry, index) => ({ entry, index }));
|
|
80
|
+
const retainedSent = new Set(indexed.filter(({ entry }) => entry.state === "sent" && now - entry.updatedAt <= OUTBOX_SENT_RETENTION_MS).sort((a, b) => b.entry.updatedAt - a.entry.updatedAt || b.index - a.index).slice(0, OUTBOX_SENT_RETENTION_LIMIT).map(({ index }) => index));
|
|
81
|
+
return indexed.filter(({ entry, index }) => entry.state !== "sent" || retainedSent.has(index)).sort((a, b) => a.entry.createdAt - b.entry.createdAt || a.index - b.index).map(({ entry }) => entry);
|
|
82
|
+
}
|
|
83
|
+
function createOutbox(options = {}) {
|
|
84
|
+
const filePath = options.filePath ?? process.env.QQ_OUTBOX_FILE ?? join(homedir(), ".openqq", "outbox.json");
|
|
85
|
+
const pollIntervalMs = nonNegative(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, "pollIntervalMs");
|
|
86
|
+
const retryBaseMs = nonNegative(options.retryBaseMs, OUTBOX_DEFAULT_RETRY_BASE_MS, "retryBaseMs");
|
|
87
|
+
const retryMaxMs = nonNegative(options.retryMaxMs, OUTBOX_DEFAULT_RETRY_MAX_MS, "retryMaxMs");
|
|
88
|
+
const leaseMs = positive(options.leaseMs, DEFAULT_LEASE_MS, "leaseMs");
|
|
89
|
+
const lockWaitMs = positive(options.lockWaitMs, DEFAULT_LOCK_WAIT_MS, "lockWaitMs");
|
|
90
|
+
const lockStaleMs = positive(options.lockStaleMs, DEFAULT_LOCK_STALE_MS, "lockStaleMs");
|
|
91
|
+
const owner = `${process.pid}:${randomUUID()}`;
|
|
92
|
+
const handlers = new Map;
|
|
93
|
+
const inFlight = new Map;
|
|
94
|
+
const automatic = new Set;
|
|
95
|
+
let timer;
|
|
96
|
+
let stopped = false;
|
|
97
|
+
let flushing;
|
|
98
|
+
function withLock(fn) {
|
|
99
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
100
|
+
const lockPath = `${filePath}.lock`;
|
|
101
|
+
const token = `${owner}:${Date.now()}:${randomUUID()}`;
|
|
102
|
+
const deadline = Date.now() + lockWaitMs;
|
|
103
|
+
for (;; ) {
|
|
104
|
+
try {
|
|
105
|
+
const fd = openSync(lockPath, "wx", 384);
|
|
106
|
+
try {
|
|
107
|
+
writeFileSync(fd, token);
|
|
108
|
+
} finally {
|
|
109
|
+
closeSync(fd);
|
|
110
|
+
}
|
|
111
|
+
break;
|
|
112
|
+
} catch (error) {
|
|
113
|
+
try {
|
|
114
|
+
if (Date.now() - statSync(lockPath).mtimeMs > lockStaleMs)
|
|
115
|
+
unlinkSync(lockPath);
|
|
116
|
+
} catch {}
|
|
117
|
+
if (Date.now() >= deadline)
|
|
118
|
+
throw new Error(`Outbox 锁等待超时: ${errorText(error)}`);
|
|
119
|
+
Atomics.wait(sleepArray, 0, 0, 10);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
return fn();
|
|
124
|
+
} finally {
|
|
125
|
+
try {
|
|
126
|
+
if (readFileSync(lockPath, "utf8") === token)
|
|
127
|
+
unlinkSync(lockPath);
|
|
128
|
+
} catch {}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function mutate(fn) {
|
|
132
|
+
return withLock(() => {
|
|
133
|
+
const document = readDocument(filePath, Date.now());
|
|
134
|
+
const result = fn(document.entries);
|
|
135
|
+
document.entries = pruneOutboxEntries(document.entries);
|
|
136
|
+
atomicWrite(filePath, document);
|
|
137
|
+
return result;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
function clone(entry) {
|
|
141
|
+
return JSON.parse(JSON.stringify(entry));
|
|
142
|
+
}
|
|
143
|
+
function clearLease(entry) {
|
|
144
|
+
delete entry.leaseOwner;
|
|
145
|
+
delete entry.leaseUntil;
|
|
146
|
+
}
|
|
147
|
+
function transitionRecovered(entry, now, maxAttempts) {
|
|
148
|
+
if (entry.state !== "sending")
|
|
149
|
+
return false;
|
|
150
|
+
const exhausted = maxAttempts !== undefined && entry.attempts >= maxAttempts;
|
|
151
|
+
entry.state = exhausted ? "failed" : "pending";
|
|
152
|
+
entry.updatedAt = now;
|
|
153
|
+
entry.nextAttemptAt = now;
|
|
154
|
+
entry.lastError = exhausted ? `${entry.lastError ? `${entry.lastError}; ` : ""}崩溃恢复后已达到 maxAttempts=${maxAttempts}` : "进程在 sending 期间退出,发送结果未知;按至少一次语义恢复";
|
|
155
|
+
clearLease(entry);
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
async function recover(recoverOptions = {}) {
|
|
159
|
+
const now = Date.now();
|
|
160
|
+
return mutate((entries) => {
|
|
161
|
+
const recovered = [];
|
|
162
|
+
const exhausted = [];
|
|
163
|
+
for (const entry of entries) {
|
|
164
|
+
if (entry.state !== "sending")
|
|
165
|
+
continue;
|
|
166
|
+
if (inFlight.has(entry.id) && entry.leaseOwner?.startsWith(`${owner}:`))
|
|
167
|
+
continue;
|
|
168
|
+
const expired = entry.leaseUntil === undefined || entry.leaseUntil <= now;
|
|
169
|
+
if (!recoverOptions.ignoreLeases && !expired)
|
|
170
|
+
continue;
|
|
171
|
+
transitionRecovered(entry, now, recoverOptions.maxAttempts);
|
|
172
|
+
const snapshot = clone(entry);
|
|
173
|
+
if (snapshot.state === "failed")
|
|
174
|
+
exhausted.push(snapshot);
|
|
175
|
+
else
|
|
176
|
+
recovered.push(snapshot);
|
|
177
|
+
}
|
|
178
|
+
return { recovered, exhausted };
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
async function dispatchInternal(id, dispatchOptions) {
|
|
182
|
+
const handlerlessSnapshot = readDocument(filePath, Date.now()).entries.find((entry) => entry.id === id);
|
|
183
|
+
if (!handlerlessSnapshot)
|
|
184
|
+
return null;
|
|
185
|
+
const handler = handlers.get(handlerlessSnapshot.kind);
|
|
186
|
+
if (!handler)
|
|
187
|
+
return clone(handlerlessSnapshot);
|
|
188
|
+
const now = Date.now();
|
|
189
|
+
const token = `${owner}:${randomUUID()}`;
|
|
190
|
+
const claimed = withLock(() => {
|
|
191
|
+
const document = readDocument(filePath, now);
|
|
192
|
+
const entry = document.entries.find((candidate) => candidate.id === id);
|
|
193
|
+
if (!entry)
|
|
194
|
+
return { entry: null };
|
|
195
|
+
if (entry.state === "sent")
|
|
196
|
+
return { entry: clone(entry) };
|
|
197
|
+
if (entry.state === "sending" && entry.leaseUntil !== undefined && entry.leaseUntil > now) {
|
|
198
|
+
return { entry: null };
|
|
199
|
+
}
|
|
200
|
+
if ((entry.state === "pending" || entry.state === "failed" || entry.state === "sending") && !dispatchOptions.force && entry.nextAttemptAt > now) {
|
|
201
|
+
return { entry: clone(entry) };
|
|
202
|
+
}
|
|
203
|
+
const maxAttempts = dispatchOptions.maxAttempts;
|
|
204
|
+
if (maxAttempts !== undefined && entry.attempts >= maxAttempts) {
|
|
205
|
+
if (entry.state !== "failed") {
|
|
206
|
+
entry.state = "failed";
|
|
207
|
+
entry.updatedAt = now;
|
|
208
|
+
clearLease(entry);
|
|
209
|
+
atomicWrite(filePath, document);
|
|
210
|
+
}
|
|
211
|
+
return { entry: clone(entry) };
|
|
212
|
+
}
|
|
213
|
+
entry.state = "sending";
|
|
214
|
+
entry.attempts += 1;
|
|
215
|
+
entry.updatedAt = now;
|
|
216
|
+
entry.leaseOwner = token;
|
|
217
|
+
entry.leaseUntil = now + leaseMs;
|
|
218
|
+
delete entry.lastError;
|
|
219
|
+
atomicWrite(filePath, document);
|
|
220
|
+
return { entry: clone(entry), token };
|
|
221
|
+
});
|
|
222
|
+
if (!claimed.entry || !("token" in claimed))
|
|
223
|
+
return claimed.entry;
|
|
224
|
+
try {
|
|
225
|
+
const receipt = await handler(clone(claimed.entry));
|
|
226
|
+
const persistedReceipt = receipt === undefined ? null : jsonSnapshot(receipt, "receipt");
|
|
227
|
+
return mutate((entries) => {
|
|
228
|
+
const current = entries.find((entry) => entry.id === id);
|
|
229
|
+
if (!current || current.leaseOwner !== token)
|
|
230
|
+
return current ? clone(current) : null;
|
|
231
|
+
const completedAt = Date.now();
|
|
232
|
+
current.state = "sent";
|
|
233
|
+
current.updatedAt = completedAt;
|
|
234
|
+
current.receipt = persistedReceipt;
|
|
235
|
+
delete current.lastError;
|
|
236
|
+
clearLease(current);
|
|
237
|
+
return clone(current);
|
|
238
|
+
});
|
|
239
|
+
} catch (error) {
|
|
240
|
+
const failed = mutate((entries) => {
|
|
241
|
+
const current = entries.find((entry) => entry.id === id);
|
|
242
|
+
if (!current || current.leaseOwner !== token)
|
|
243
|
+
return current ? clone(current) : null;
|
|
244
|
+
const failedAt = Date.now();
|
|
245
|
+
current.state = "failed";
|
|
246
|
+
current.updatedAt = failedAt;
|
|
247
|
+
current.lastError = errorText(error);
|
|
248
|
+
current.nextAttemptAt = failedAt + Math.min(retryMaxMs, retryBaseMs * 2 ** Math.max(0, current.attempts - 1));
|
|
249
|
+
clearLease(current);
|
|
250
|
+
return clone(current);
|
|
251
|
+
});
|
|
252
|
+
if (automatic.has(id))
|
|
253
|
+
return failed;
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
function dispatch(id, dispatchOptions = {}) {
|
|
258
|
+
const existing = inFlight.get(id);
|
|
259
|
+
if (existing)
|
|
260
|
+
return existing;
|
|
261
|
+
const promise = dispatchInternal(id, dispatchOptions).finally(() => {
|
|
262
|
+
if (inFlight.get(id) === promise)
|
|
263
|
+
inFlight.delete(id);
|
|
264
|
+
});
|
|
265
|
+
inFlight.set(id, promise);
|
|
266
|
+
return promise;
|
|
267
|
+
}
|
|
268
|
+
async function flush(flushOptions = {}) {
|
|
269
|
+
if (flushing)
|
|
270
|
+
return flushing;
|
|
271
|
+
const run = (async () => {
|
|
272
|
+
const results = new Map;
|
|
273
|
+
for (;; ) {
|
|
274
|
+
await recover({ maxAttempts: flushOptions.maxAttempts });
|
|
275
|
+
const entries = readDocument(filePath, Date.now()).entries;
|
|
276
|
+
const candidates = entries.filter((entry) => {
|
|
277
|
+
if (entry.state !== "pending" && entry.state !== "failed")
|
|
278
|
+
return false;
|
|
279
|
+
if (!handlers.has(entry.kind))
|
|
280
|
+
return false;
|
|
281
|
+
if (flushOptions.maxAttempts !== undefined && entry.attempts >= flushOptions.maxAttempts)
|
|
282
|
+
return false;
|
|
283
|
+
return flushOptions.force || flushOptions.wait || entry.nextAttemptAt <= Date.now();
|
|
284
|
+
});
|
|
285
|
+
const settled = await Promise.all(candidates.map(async (entry) => {
|
|
286
|
+
const result = await dispatch(entry.id, flushOptions);
|
|
287
|
+
if (result)
|
|
288
|
+
results.set(entry.id, result);
|
|
289
|
+
return result;
|
|
290
|
+
}));
|
|
291
|
+
if (!flushOptions.wait)
|
|
292
|
+
break;
|
|
293
|
+
const after = readDocument(filePath, Date.now()).entries;
|
|
294
|
+
const active = after.filter((entry) => (entry.state === "pending" || entry.state === "failed") && handlers.has(entry.kind) && (flushOptions.maxAttempts === undefined || entry.attempts < flushOptions.maxAttempts));
|
|
295
|
+
const waitingLocal = after.some((entry) => entry.state === "sending" && inFlight.has(entry.id));
|
|
296
|
+
if (active.length === 0 && !waitingLocal)
|
|
297
|
+
break;
|
|
298
|
+
if (settled.length === 0 && !waitingLocal) {
|
|
299
|
+
const next = active.reduce((minimum, entry) => Math.min(minimum, entry.nextAttemptAt), Number.POSITIVE_INFINITY);
|
|
300
|
+
if (Number.isFinite(next))
|
|
301
|
+
await delay(Math.max(1, next - Date.now()));
|
|
302
|
+
else
|
|
303
|
+
break;
|
|
304
|
+
} else {
|
|
305
|
+
await delay(1);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return [...results.values()];
|
|
309
|
+
})();
|
|
310
|
+
flushing = run;
|
|
311
|
+
try {
|
|
312
|
+
return await run;
|
|
313
|
+
} finally {
|
|
314
|
+
if (flushing === run)
|
|
315
|
+
flushing = undefined;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
async function drain() {
|
|
319
|
+
while (inFlight.size > 0) {
|
|
320
|
+
const pending = [...inFlight.values()];
|
|
321
|
+
const outcomes = await Promise.allSettled(pending);
|
|
322
|
+
const rejection = outcomes.find((outcome) => outcome.status === "rejected");
|
|
323
|
+
if (rejection)
|
|
324
|
+
throw rejection.reason;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return {
|
|
328
|
+
filePath,
|
|
329
|
+
register(kind, handler) {
|
|
330
|
+
if (!kind)
|
|
331
|
+
throw new Error("Outbox kind 不能为空");
|
|
332
|
+
handlers.set(kind, handler);
|
|
333
|
+
return () => {
|
|
334
|
+
if (handlers.get(kind) === handler)
|
|
335
|
+
handlers.delete(kind);
|
|
336
|
+
};
|
|
337
|
+
},
|
|
338
|
+
async enqueue(input) {
|
|
339
|
+
if (!input.kind)
|
|
340
|
+
throw new Error("Outbox kind 不能为空");
|
|
341
|
+
if (input.payload === undefined)
|
|
342
|
+
throw new Error("Outbox payload 必须是 JSON 值,不能为 undefined");
|
|
343
|
+
if (input.nextAttemptAt !== undefined && !Number.isFinite(input.nextAttemptAt)) {
|
|
344
|
+
throw new Error("Outbox nextAttemptAt 必须是有限时间戳");
|
|
345
|
+
}
|
|
346
|
+
const persistedCtx = jsonSnapshot(input.ctx, "ctx");
|
|
347
|
+
const persistedPayload = jsonSnapshot(input.payload, "payload");
|
|
348
|
+
const now = Date.now();
|
|
349
|
+
const id = input.id ?? randomUUID();
|
|
350
|
+
const entry = mutate((entries) => {
|
|
351
|
+
const existing = entries.find((candidate) => candidate.id === id);
|
|
352
|
+
if (existing)
|
|
353
|
+
return clone(existing);
|
|
354
|
+
const created = {
|
|
355
|
+
id,
|
|
356
|
+
kind: input.kind,
|
|
357
|
+
ctx: persistedCtx,
|
|
358
|
+
payload: persistedPayload,
|
|
359
|
+
...input.sessionId !== undefined ? { sessionId: input.sessionId } : {},
|
|
360
|
+
...input.turnId !== undefined ? { turnId: input.turnId } : {},
|
|
361
|
+
state: "pending",
|
|
362
|
+
attempts: 0,
|
|
363
|
+
createdAt: now,
|
|
364
|
+
updatedAt: now,
|
|
365
|
+
nextAttemptAt: input.nextAttemptAt ?? now
|
|
366
|
+
};
|
|
367
|
+
entries.push(created);
|
|
368
|
+
return clone(created);
|
|
369
|
+
});
|
|
370
|
+
automatic.add(id);
|
|
371
|
+
dispatch(id).finally(() => automatic.delete(id)).catch(() => {});
|
|
372
|
+
return entry;
|
|
373
|
+
},
|
|
374
|
+
dispatch,
|
|
375
|
+
recover,
|
|
376
|
+
flush,
|
|
377
|
+
async start(startOptions = {}) {
|
|
378
|
+
stopped = false;
|
|
379
|
+
if (startOptions.recover !== false)
|
|
380
|
+
await recover();
|
|
381
|
+
if (pollIntervalMs === 0 || timer)
|
|
382
|
+
return;
|
|
383
|
+
timer = setInterval(() => {
|
|
384
|
+
if (stopped)
|
|
385
|
+
return;
|
|
386
|
+
flush().catch(() => {});
|
|
387
|
+
}, pollIntervalMs);
|
|
388
|
+
timer.unref?.();
|
|
389
|
+
flush().catch(() => {});
|
|
390
|
+
},
|
|
391
|
+
stop() {
|
|
392
|
+
stopped = true;
|
|
393
|
+
if (timer)
|
|
394
|
+
clearInterval(timer);
|
|
395
|
+
timer = undefined;
|
|
396
|
+
},
|
|
397
|
+
drain,
|
|
398
|
+
async list() {
|
|
399
|
+
return readDocument(filePath, Date.now()).entries.map((entry) => clone(entry));
|
|
400
|
+
},
|
|
401
|
+
async get(id) {
|
|
402
|
+
const entry = readDocument(filePath, Date.now()).entries.find((candidate) => candidate.id === id);
|
|
403
|
+
return entry ? clone(entry) : undefined;
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// src/config.ts
|
|
409
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
410
|
+
import { join as join2 } from "path";
|
|
411
|
+
import { homedir as homedir2 } from "os";
|
|
412
|
+
var CONFIG_DIR = join2(homedir2(), ".openqq");
|
|
413
|
+
var ENV_FILE = join2(CONFIG_DIR, ".env");
|
|
414
|
+
function loadEnvFile(path) {
|
|
415
|
+
const content = readFileSync2(path, "utf-8");
|
|
416
|
+
for (const line of content.split(`
|
|
417
|
+
`)) {
|
|
418
|
+
const trimmed = line.trim();
|
|
419
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
420
|
+
continue;
|
|
421
|
+
const eqIdx = trimmed.indexOf("=");
|
|
422
|
+
if (eqIdx < 0)
|
|
423
|
+
continue;
|
|
424
|
+
const key = trimmed.slice(0, eqIdx).trim();
|
|
425
|
+
const val = trimmed.slice(eqIdx + 1).trim();
|
|
426
|
+
if (!process.env[key]) {
|
|
427
|
+
process.env[key] = val;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// src/core/notify-sink.ts
|
|
433
|
+
import { homedir as homedir3 } from "node:os";
|
|
434
|
+
import { join as join3 } from "node:path";
|
|
435
|
+
function resolveNotifyRecipients(configured, explicit) {
|
|
436
|
+
const users = [...configured];
|
|
437
|
+
if (explicit)
|
|
438
|
+
return users.includes(explicit) ? explicit : "";
|
|
439
|
+
return users.length === 1 ? users[0] : "";
|
|
440
|
+
}
|
|
441
|
+
function defaultOutboxPath() {
|
|
442
|
+
return join3(homedir3(), ".openqq", "outbox.json");
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// src/cli/notify.ts
|
|
446
|
+
var NOTIFY_DEFAULT_MAX_CHARS = 1500;
|
|
447
|
+
function parseArgs(argv) {
|
|
448
|
+
const parsed = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false };
|
|
449
|
+
for (let i = 0;i < argv.length; i++) {
|
|
450
|
+
const a = argv[i];
|
|
451
|
+
const next = argv[i + 1];
|
|
452
|
+
switch (a) {
|
|
453
|
+
case "--text":
|
|
454
|
+
parsed.text = next;
|
|
455
|
+
i++;
|
|
456
|
+
break;
|
|
457
|
+
case "--file":
|
|
458
|
+
parsed.filePath = next;
|
|
459
|
+
i++;
|
|
460
|
+
break;
|
|
461
|
+
case "--stdin":
|
|
462
|
+
parsed.stdin = true;
|
|
463
|
+
break;
|
|
464
|
+
case "--user":
|
|
465
|
+
parsed.user = next;
|
|
466
|
+
i++;
|
|
467
|
+
break;
|
|
468
|
+
case "--id":
|
|
469
|
+
parsed.id = next;
|
|
470
|
+
i++;
|
|
471
|
+
break;
|
|
472
|
+
case "--max-chars":
|
|
473
|
+
parsed.maxChars = Number(next);
|
|
474
|
+
i++;
|
|
475
|
+
break;
|
|
476
|
+
case "--ttl-hours":
|
|
477
|
+
parsed.ttlHours = Number(next);
|
|
478
|
+
i++;
|
|
479
|
+
break;
|
|
480
|
+
case "--dry-run":
|
|
481
|
+
parsed.dryRun = true;
|
|
482
|
+
break;
|
|
483
|
+
case "--json":
|
|
484
|
+
parsed.json = true;
|
|
485
|
+
break;
|
|
486
|
+
case "--help":
|
|
487
|
+
case "-h":
|
|
488
|
+
parsed.help = true;
|
|
489
|
+
i++;
|
|
490
|
+
break;
|
|
491
|
+
default:
|
|
492
|
+
throw new Error(`未知参数:${a}(用法:openqq notify --text "…" | --file <p> | --stdin)`);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
|
|
496
|
+
throw new Error("必须提供正文来源:--text / --file / --stdin 三选一");
|
|
497
|
+
}
|
|
498
|
+
if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
|
|
499
|
+
throw new Error("--max-chars 必须是 >= 0 的有限数(0=不截断)");
|
|
500
|
+
}
|
|
501
|
+
return parsed;
|
|
502
|
+
}
|
|
503
|
+
function resolveUser(envAllowed, explicit) {
|
|
504
|
+
return resolveNotifyRecipients(envAllowed, explicit);
|
|
505
|
+
}
|
|
506
|
+
function readBody(parsed) {
|
|
507
|
+
if (parsed.text !== undefined)
|
|
508
|
+
return parsed.text;
|
|
509
|
+
if (parsed.filePath !== undefined) {
|
|
510
|
+
if (parsed.filePath === "-")
|
|
511
|
+
return readFileSync3(0, "utf8");
|
|
512
|
+
if (!existsSync3(parsed.filePath))
|
|
513
|
+
throw new Error(`--file 不存在:${parsed.filePath}`);
|
|
514
|
+
return readFileSync3(parsed.filePath, "utf8");
|
|
515
|
+
}
|
|
516
|
+
if (parsed.stdin)
|
|
517
|
+
return readFileSync3(0, "utf8");
|
|
518
|
+
return "";
|
|
519
|
+
}
|
|
520
|
+
async function runNotifyCli(argv, options = {}) {
|
|
521
|
+
const now = options.now ?? Date.now();
|
|
522
|
+
const parsed = parseArgs(argv);
|
|
523
|
+
if (parsed.help) {
|
|
524
|
+
const help = [
|
|
525
|
+
'用法:openqq notify --text "…" | --file <路径> | --stdin',
|
|
526
|
+
" --user <openid> 收件人;缺省取 ALLOWED_USERS 唯一项(多用户必须显式指定)",
|
|
527
|
+
" --id <key> 幂等键(同 key 不重复投递)",
|
|
528
|
+
" --max-chars <n> 截断上限,默认 1500,0 不截断",
|
|
529
|
+
" --ttl-hours <n> 队列等待上限,默认 24(env QQ_NOTIFY_TTL_HOURS 兜底)",
|
|
530
|
+
" --dry-run / --json 不入队 / 机器可读输出"
|
|
531
|
+
].join(`
|
|
532
|
+
`);
|
|
533
|
+
console.log(help);
|
|
534
|
+
return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, reason: "help" };
|
|
535
|
+
}
|
|
536
|
+
if (!options.env && existsSync3(ENV_FILE))
|
|
537
|
+
loadEnvFile(ENV_FILE);
|
|
538
|
+
const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "").split(/[,\s]+/).filter(Boolean);
|
|
539
|
+
const user = resolveUser(allowedUsers, parsed.user);
|
|
540
|
+
if (!user) {
|
|
541
|
+
throw new Error(allowedUsers.length === 0 ? "ALLOWED_USERS 为空——fail-closed 不允许无名单入队(先在 ~/.openqq/.env 配置)" : "多用户名单必须用 --user <openid> 显式指定收件人");
|
|
542
|
+
}
|
|
543
|
+
const raw = readBody(parsed);
|
|
544
|
+
const max = parsed.maxChars;
|
|
545
|
+
const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}…` : raw;
|
|
546
|
+
const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
547
|
+
const filePath = options.filePath ?? defaultOutboxPath();
|
|
548
|
+
if (parsed.dryRun) {
|
|
549
|
+
return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true };
|
|
550
|
+
}
|
|
551
|
+
const ttlHours = parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24);
|
|
552
|
+
const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0 ? now + ttlHours * 60 * 60 * 1000 : now;
|
|
553
|
+
const outbox = createOutbox({ filePath, pollIntervalMs: 0 });
|
|
554
|
+
const entry = await outbox.enqueue({
|
|
555
|
+
...parsed.id ? { id: parsed.id } : {},
|
|
556
|
+
kind: "notify",
|
|
557
|
+
payload: { text: content },
|
|
558
|
+
ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
|
|
559
|
+
sessionId: "",
|
|
560
|
+
nextAttemptAt
|
|
561
|
+
});
|
|
562
|
+
return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false };
|
|
563
|
+
}
|
|
564
|
+
async function main(argv) {
|
|
565
|
+
try {
|
|
566
|
+
const result = await runNotifyCli(argv);
|
|
567
|
+
if (result.reason === "help")
|
|
568
|
+
return 0;
|
|
569
|
+
if (result.queued && !result.dryRun)
|
|
570
|
+
console.log(`[notify] 已入队 id=${result.id} user=${result.user} chars=${result.chars}${result.truncated ? "(已截断)" : ""}`);
|
|
571
|
+
return result.ok ? 0 : 1;
|
|
572
|
+
} catch (error) {
|
|
573
|
+
console.error(`[notify] 入队失败:${error instanceof Error ? error.message : String(error)}`);
|
|
574
|
+
return 1;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// src/cli/notify-main.ts
|
|
579
|
+
process.exitCode = await main(process.argv.slice(2));
|
|
@@ -135,7 +135,10 @@ function readDotEnvField(envPath, key) {
|
|
|
135
135
|
|
|
136
136
|
// src/plugin-entry.ts
|
|
137
137
|
var ENV_FILE = join3(homedir3(), ".openqq", ".env");
|
|
138
|
-
var CHECK_INTERVAL_MS =
|
|
138
|
+
var CHECK_INTERVAL_MS = (() => {
|
|
139
|
+
const n = Number(process.env.QQ_WATCHDOG_INTERVAL_MS ?? "300000");
|
|
140
|
+
return Number.isFinite(n) && n > 0 ? n : 300000;
|
|
141
|
+
})();
|
|
139
142
|
var PROBE_FILE = join3(homedir3(), ".openqq", "opencode-events.jsonl");
|
|
140
143
|
var PROBE_ROTATE_BYTES = 5 * 1024 * 1024;
|
|
141
144
|
function probeAppend(line) {
|