@linjz/opencode-qqbot 0.3.14 → 0.3.16
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 +73 -5
- package/bin/openqq.js +34 -0
- package/dist/notify-cli.js +593 -0
- package/dist/opencode-qqbot-plugin.js +938 -65
- package/dist/openqq-bot.js +3585 -717
- package/dist/openqq-cli.js +791 -0
- package/dist/openqq-watchdog.js +1063 -0
- package/package.json +9 -5
- package/src/bridge.ts +1338 -157
- package/src/cli/notify-main.ts +6 -0
- package/src/cli/notify.ts +167 -0
- package/src/cli/openqq-main.ts +95 -0
- package/src/cli/service-main.ts +302 -0
- package/src/cli/watchdog-main.ts +77 -0
- package/src/commands.ts +644 -554
- package/src/config.ts +87 -2
- package/src/core/bot-control.ts +148 -0
- package/src/core/bot-launcher.ts +106 -13
- package/src/core/card-approval.ts +20 -9
- package/src/core/delivery.ts +145 -54
- package/src/core/discovery.ts +22 -4
- package/src/core/file-log.ts +35 -3
- package/src/core/form-bridge.ts +16 -7
- package/src/core/form-journal.ts +4 -4
- package/src/core/gateway-state.ts +3 -3
- package/src/core/inflight-journal.ts +214 -36
- package/src/core/instance-lock.ts +21 -6
- package/src/core/linkwatch.ts +3 -4
- package/src/core/markdown.ts +117 -0
- package/src/core/message-queue.ts +242 -91
- package/src/core/mirror.ts +222 -182
- package/src/core/notify-sink.ts +93 -0
- package/src/core/outbox.ts +10 -9
- package/src/core/permission.ts +627 -301
- package/src/core/question-form.ts +230 -0
- package/src/core/queue-view.ts +661 -0
- package/src/core/send-media.ts +32 -0
- package/src/core/storage.ts +34 -0
- package/src/core/watchdog.ts +513 -0
- package/src/core/zombie-reaper.ts +127 -0
- package/src/index.ts +140 -52
- package/src/opencode/client.ts +206 -27
- package/src/opencode/eventstream.ts +94 -12
- package/src/opencode/history.ts +4 -2
- package/src/opencode/mirror.ts +15 -2
- package/src/opencode/sessions.ts +135 -37
- package/src/plugin-entry.ts +120 -112
- package/src/qq/api.ts +165 -61
- package/src/qq/gateway.ts +80 -17
- package/src/qq/media.ts +5 -1
- package/src/qq/sender.ts +30 -18
- package/src/qq/types.ts +7 -0
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
// src/cli/notify.ts
|
|
2
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
|
|
3
|
+
|
|
4
|
+
// src/core/storage.ts
|
|
5
|
+
import { homedir } from "os";
|
|
6
|
+
import { join } from "path";
|
|
7
|
+
var LEGACY_ROOT = join(homedir(), ".openqq");
|
|
8
|
+
function storageRoot(appId) {
|
|
9
|
+
const base = (process.env.QQ_DATA_DIR ?? "").trim() || LEGACY_ROOT;
|
|
10
|
+
return appId ? join(base, "roles", appId) : base;
|
|
11
|
+
}
|
|
12
|
+
function storageFile(name, appId) {
|
|
13
|
+
return join(storageRoot(appId), name);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// src/core/outbox.ts
|
|
17
|
+
import {
|
|
18
|
+
closeSync,
|
|
19
|
+
existsSync,
|
|
20
|
+
mkdirSync,
|
|
21
|
+
openSync,
|
|
22
|
+
readFileSync,
|
|
23
|
+
renameSync,
|
|
24
|
+
statSync,
|
|
25
|
+
unlinkSync,
|
|
26
|
+
writeFileSync
|
|
27
|
+
} from "node:fs";
|
|
28
|
+
import { dirname } from "node:path";
|
|
29
|
+
import { randomUUID } from "node:crypto";
|
|
30
|
+
var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
|
|
31
|
+
var OUTBOX_SENT_RETENTION_LIMIT = 20;
|
|
32
|
+
var OUTBOX_DEFAULT_RETRY_BASE_MS = 1000;
|
|
33
|
+
var OUTBOX_DEFAULT_RETRY_MAX_MS = 60000;
|
|
34
|
+
var DEFAULT_POLL_INTERVAL_MS = 1000;
|
|
35
|
+
var DEFAULT_LEASE_MS = 30000;
|
|
36
|
+
var DEFAULT_LOCK_WAIT_MS = 5000;
|
|
37
|
+
var DEFAULT_LOCK_STALE_MS = 30000;
|
|
38
|
+
var sleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
39
|
+
function nonNegative(value, fallback, name) {
|
|
40
|
+
const resolved = value ?? fallback;
|
|
41
|
+
if (!Number.isFinite(resolved) || resolved < 0)
|
|
42
|
+
throw new Error(`${name} 必须是 >= 0 的有限数`);
|
|
43
|
+
return resolved;
|
|
44
|
+
}
|
|
45
|
+
function positive(value, fallback, name) {
|
|
46
|
+
const resolved = nonNegative(value, fallback, name);
|
|
47
|
+
if (resolved === 0)
|
|
48
|
+
throw new Error(`${name} 必须 > 0`);
|
|
49
|
+
return resolved;
|
|
50
|
+
}
|
|
51
|
+
function errorText(error) {
|
|
52
|
+
return error instanceof Error ? error.message : String(error);
|
|
53
|
+
}
|
|
54
|
+
function jsonSnapshot(value, label) {
|
|
55
|
+
const encoded = JSON.stringify(value);
|
|
56
|
+
if (encoded === undefined)
|
|
57
|
+
throw new Error(`Outbox ${label} 必须是可 JSON 序列化的值`);
|
|
58
|
+
return JSON.parse(encoded);
|
|
59
|
+
}
|
|
60
|
+
function delay(ms) {
|
|
61
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
62
|
+
}
|
|
63
|
+
function atomicWrite(filePath, document) {
|
|
64
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
65
|
+
const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
66
|
+
try {
|
|
67
|
+
writeFileSync(temporary, JSON.stringify(document, null, 2), { mode: 384 });
|
|
68
|
+
renameSync(temporary, filePath);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
try {
|
|
71
|
+
unlinkSync(temporary);
|
|
72
|
+
} catch {}
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function readDocument(filePath, now) {
|
|
77
|
+
if (!existsSync(filePath))
|
|
78
|
+
return { version: 1, entries: [] };
|
|
79
|
+
const raw = JSON.parse(readFileSync(filePath, "utf8"));
|
|
80
|
+
if (Array.isArray(raw)) {
|
|
81
|
+
return { version: 1, entries: pruneOutboxEntries(raw, now) };
|
|
82
|
+
}
|
|
83
|
+
if (typeof raw !== "object" || raw === null || raw.version !== 1 || !Array.isArray(raw.entries)) {
|
|
84
|
+
throw new Error(`Outbox 文件格式无效: ${filePath}`);
|
|
85
|
+
}
|
|
86
|
+
const entries = raw.entries;
|
|
87
|
+
return { version: 1, entries: pruneOutboxEntries(entries, now) };
|
|
88
|
+
}
|
|
89
|
+
function pruneOutboxEntries(entries, now = Date.now()) {
|
|
90
|
+
const indexed = entries.map((entry, index) => ({ entry, index }));
|
|
91
|
+
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));
|
|
92
|
+
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);
|
|
93
|
+
}
|
|
94
|
+
function createOutbox(options = {}) {
|
|
95
|
+
const filePath = options.filePath ?? process.env.QQ_OUTBOX_FILE ?? storageFile("outbox.json");
|
|
96
|
+
const pollIntervalMs = nonNegative(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, "pollIntervalMs");
|
|
97
|
+
const retryBaseMs = nonNegative(options.retryBaseMs, OUTBOX_DEFAULT_RETRY_BASE_MS, "retryBaseMs");
|
|
98
|
+
const retryMaxMs = nonNegative(options.retryMaxMs, OUTBOX_DEFAULT_RETRY_MAX_MS, "retryMaxMs");
|
|
99
|
+
const leaseMs = positive(options.leaseMs, DEFAULT_LEASE_MS, "leaseMs");
|
|
100
|
+
const lockWaitMs = positive(options.lockWaitMs, DEFAULT_LOCK_WAIT_MS, "lockWaitMs");
|
|
101
|
+
const lockStaleMs = positive(options.lockStaleMs, DEFAULT_LOCK_STALE_MS, "lockStaleMs");
|
|
102
|
+
const owner = `${process.pid}:${randomUUID()}`;
|
|
103
|
+
const handlers = new Map;
|
|
104
|
+
const inFlight = new Map;
|
|
105
|
+
const automatic = new Set;
|
|
106
|
+
let timer;
|
|
107
|
+
let stopped = false;
|
|
108
|
+
let flushing;
|
|
109
|
+
function withLock(fn) {
|
|
110
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
111
|
+
const lockPath = `${filePath}.lock`;
|
|
112
|
+
const token = `${owner}:${Date.now()}:${randomUUID()}`;
|
|
113
|
+
const deadline = Date.now() + lockWaitMs;
|
|
114
|
+
for (;; ) {
|
|
115
|
+
try {
|
|
116
|
+
const fd = openSync(lockPath, "wx", 384);
|
|
117
|
+
try {
|
|
118
|
+
writeFileSync(fd, token);
|
|
119
|
+
} finally {
|
|
120
|
+
closeSync(fd);
|
|
121
|
+
}
|
|
122
|
+
break;
|
|
123
|
+
} catch (error) {
|
|
124
|
+
try {
|
|
125
|
+
if (Date.now() - statSync(lockPath).mtimeMs > lockStaleMs)
|
|
126
|
+
unlinkSync(lockPath);
|
|
127
|
+
} catch {}
|
|
128
|
+
if (Date.now() >= deadline)
|
|
129
|
+
throw new Error(`Outbox 锁等待超时: ${errorText(error)}`);
|
|
130
|
+
Atomics.wait(sleepArray, 0, 0, 10);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
return fn();
|
|
135
|
+
} finally {
|
|
136
|
+
try {
|
|
137
|
+
if (readFileSync(lockPath, "utf8") === token)
|
|
138
|
+
unlinkSync(lockPath);
|
|
139
|
+
} catch {}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function mutate(fn) {
|
|
143
|
+
return withLock(() => {
|
|
144
|
+
const document = readDocument(filePath, Date.now());
|
|
145
|
+
const result = fn(document.entries);
|
|
146
|
+
document.entries = pruneOutboxEntries(document.entries);
|
|
147
|
+
atomicWrite(filePath, document);
|
|
148
|
+
return result;
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
function clone(entry) {
|
|
152
|
+
return JSON.parse(JSON.stringify(entry));
|
|
153
|
+
}
|
|
154
|
+
function clearLease(entry) {
|
|
155
|
+
delete entry.leaseOwner;
|
|
156
|
+
delete entry.leaseUntil;
|
|
157
|
+
}
|
|
158
|
+
function transitionRecovered(entry, now, maxAttempts) {
|
|
159
|
+
if (entry.state !== "sending")
|
|
160
|
+
return false;
|
|
161
|
+
const exhausted = maxAttempts !== undefined && entry.attempts >= maxAttempts;
|
|
162
|
+
entry.state = exhausted ? "failed" : "pending";
|
|
163
|
+
entry.updatedAt = now;
|
|
164
|
+
entry.nextAttemptAt = now;
|
|
165
|
+
entry.lastError = exhausted ? `${entry.lastError ? `${entry.lastError}; ` : ""}崩溃恢复后已达到 maxAttempts=${maxAttempts}` : "进程在 sending 期间退出,发送结果未知;按至少一次语义恢复";
|
|
166
|
+
clearLease(entry);
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
async function recover(recoverOptions = {}) {
|
|
170
|
+
const now = Date.now();
|
|
171
|
+
return mutate((entries) => {
|
|
172
|
+
const recovered = [];
|
|
173
|
+
const exhausted = [];
|
|
174
|
+
for (const entry of entries) {
|
|
175
|
+
if (entry.state !== "sending")
|
|
176
|
+
continue;
|
|
177
|
+
if (inFlight.has(entry.id) && entry.leaseOwner?.startsWith(`${owner}:`))
|
|
178
|
+
continue;
|
|
179
|
+
const expired = entry.leaseUntil === undefined || entry.leaseUntil <= now;
|
|
180
|
+
if (!recoverOptions.ignoreLeases && !expired)
|
|
181
|
+
continue;
|
|
182
|
+
transitionRecovered(entry, now, recoverOptions.maxAttempts);
|
|
183
|
+
const snapshot = clone(entry);
|
|
184
|
+
if (snapshot.state === "failed")
|
|
185
|
+
exhausted.push(snapshot);
|
|
186
|
+
else
|
|
187
|
+
recovered.push(snapshot);
|
|
188
|
+
}
|
|
189
|
+
return { recovered, exhausted };
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
async function dispatchInternal(id, dispatchOptions) {
|
|
193
|
+
const handlerlessSnapshot = readDocument(filePath, Date.now()).entries.find((entry) => entry.id === id);
|
|
194
|
+
if (!handlerlessSnapshot)
|
|
195
|
+
return null;
|
|
196
|
+
const handler = handlers.get(handlerlessSnapshot.kind);
|
|
197
|
+
if (!handler)
|
|
198
|
+
return clone(handlerlessSnapshot);
|
|
199
|
+
const now = Date.now();
|
|
200
|
+
const token = `${owner}:${randomUUID()}`;
|
|
201
|
+
const claimed = withLock(() => {
|
|
202
|
+
const document = readDocument(filePath, now);
|
|
203
|
+
const entry = document.entries.find((candidate) => candidate.id === id);
|
|
204
|
+
if (!entry)
|
|
205
|
+
return { entry: null };
|
|
206
|
+
if (entry.state === "sent")
|
|
207
|
+
return { entry: clone(entry) };
|
|
208
|
+
if (entry.state === "sending" && entry.leaseUntil !== undefined && entry.leaseUntil > now) {
|
|
209
|
+
return { entry: null };
|
|
210
|
+
}
|
|
211
|
+
if ((entry.state === "pending" || entry.state === "failed" || entry.state === "sending") && !dispatchOptions.force && entry.nextAttemptAt > now) {
|
|
212
|
+
return { entry: clone(entry) };
|
|
213
|
+
}
|
|
214
|
+
const maxAttempts = dispatchOptions.maxAttempts;
|
|
215
|
+
if (maxAttempts !== undefined && entry.attempts >= maxAttempts) {
|
|
216
|
+
if (entry.state !== "failed") {
|
|
217
|
+
entry.state = "failed";
|
|
218
|
+
entry.updatedAt = now;
|
|
219
|
+
clearLease(entry);
|
|
220
|
+
atomicWrite(filePath, document);
|
|
221
|
+
}
|
|
222
|
+
return { entry: clone(entry) };
|
|
223
|
+
}
|
|
224
|
+
entry.state = "sending";
|
|
225
|
+
entry.attempts += 1;
|
|
226
|
+
entry.updatedAt = now;
|
|
227
|
+
entry.leaseOwner = token;
|
|
228
|
+
entry.leaseUntil = now + leaseMs;
|
|
229
|
+
delete entry.lastError;
|
|
230
|
+
atomicWrite(filePath, document);
|
|
231
|
+
return { entry: clone(entry), token };
|
|
232
|
+
});
|
|
233
|
+
if (!claimed.entry || !("token" in claimed))
|
|
234
|
+
return claimed.entry;
|
|
235
|
+
try {
|
|
236
|
+
const receipt = await handler(clone(claimed.entry));
|
|
237
|
+
const persistedReceipt = receipt === undefined ? null : jsonSnapshot(receipt, "receipt");
|
|
238
|
+
return mutate((entries) => {
|
|
239
|
+
const current = entries.find((entry) => entry.id === id);
|
|
240
|
+
if (!current || current.leaseOwner !== token)
|
|
241
|
+
return current ? clone(current) : null;
|
|
242
|
+
const completedAt = Date.now();
|
|
243
|
+
current.state = "sent";
|
|
244
|
+
current.updatedAt = completedAt;
|
|
245
|
+
current.receipt = persistedReceipt;
|
|
246
|
+
delete current.lastError;
|
|
247
|
+
clearLease(current);
|
|
248
|
+
return clone(current);
|
|
249
|
+
});
|
|
250
|
+
} catch (error) {
|
|
251
|
+
const failed = mutate((entries) => {
|
|
252
|
+
const current = entries.find((entry) => entry.id === id);
|
|
253
|
+
if (!current || current.leaseOwner !== token)
|
|
254
|
+
return current ? clone(current) : null;
|
|
255
|
+
const failedAt = Date.now();
|
|
256
|
+
current.state = "failed";
|
|
257
|
+
current.updatedAt = failedAt;
|
|
258
|
+
current.lastError = errorText(error);
|
|
259
|
+
current.nextAttemptAt = failedAt + Math.min(retryMaxMs, retryBaseMs * 2 ** Math.max(0, current.attempts - 1));
|
|
260
|
+
clearLease(current);
|
|
261
|
+
return clone(current);
|
|
262
|
+
});
|
|
263
|
+
if (automatic.has(id))
|
|
264
|
+
return failed;
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function dispatch(id, dispatchOptions = {}) {
|
|
269
|
+
const existing = inFlight.get(id);
|
|
270
|
+
if (existing)
|
|
271
|
+
return existing;
|
|
272
|
+
const promise = dispatchInternal(id, dispatchOptions).finally(() => {
|
|
273
|
+
if (inFlight.get(id) === promise)
|
|
274
|
+
inFlight.delete(id);
|
|
275
|
+
});
|
|
276
|
+
inFlight.set(id, promise);
|
|
277
|
+
return promise;
|
|
278
|
+
}
|
|
279
|
+
async function flush(flushOptions = {}) {
|
|
280
|
+
if (flushing)
|
|
281
|
+
return flushing;
|
|
282
|
+
const run = (async () => {
|
|
283
|
+
const results = new Map;
|
|
284
|
+
for (;; ) {
|
|
285
|
+
await recover({ maxAttempts: flushOptions.maxAttempts });
|
|
286
|
+
const entries = readDocument(filePath, Date.now()).entries;
|
|
287
|
+
const candidates = entries.filter((entry) => {
|
|
288
|
+
if (entry.state !== "pending" && entry.state !== "failed")
|
|
289
|
+
return false;
|
|
290
|
+
if (!handlers.has(entry.kind))
|
|
291
|
+
return false;
|
|
292
|
+
if (flushOptions.maxAttempts !== undefined && entry.attempts >= flushOptions.maxAttempts)
|
|
293
|
+
return false;
|
|
294
|
+
return flushOptions.force || flushOptions.wait || entry.nextAttemptAt <= Date.now();
|
|
295
|
+
});
|
|
296
|
+
const settled = await Promise.all(candidates.map(async (entry) => {
|
|
297
|
+
const result = await dispatch(entry.id, flushOptions);
|
|
298
|
+
if (result)
|
|
299
|
+
results.set(entry.id, result);
|
|
300
|
+
return result;
|
|
301
|
+
}));
|
|
302
|
+
if (!flushOptions.wait)
|
|
303
|
+
break;
|
|
304
|
+
const after = readDocument(filePath, Date.now()).entries;
|
|
305
|
+
const active = after.filter((entry) => (entry.state === "pending" || entry.state === "failed") && handlers.has(entry.kind) && (flushOptions.maxAttempts === undefined || entry.attempts < flushOptions.maxAttempts));
|
|
306
|
+
const waitingLocal = after.some((entry) => entry.state === "sending" && inFlight.has(entry.id));
|
|
307
|
+
if (active.length === 0 && !waitingLocal)
|
|
308
|
+
break;
|
|
309
|
+
if (settled.length === 0 && !waitingLocal) {
|
|
310
|
+
const next = active.reduce((minimum, entry) => Math.min(minimum, entry.nextAttemptAt), Number.POSITIVE_INFINITY);
|
|
311
|
+
if (Number.isFinite(next))
|
|
312
|
+
await delay(Math.max(1, next - Date.now()));
|
|
313
|
+
else
|
|
314
|
+
break;
|
|
315
|
+
} else {
|
|
316
|
+
await delay(1);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return [...results.values()];
|
|
320
|
+
})();
|
|
321
|
+
flushing = run;
|
|
322
|
+
try {
|
|
323
|
+
return await run;
|
|
324
|
+
} finally {
|
|
325
|
+
if (flushing === run)
|
|
326
|
+
flushing = undefined;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
async function drain() {
|
|
330
|
+
while (inFlight.size > 0) {
|
|
331
|
+
const pending = [...inFlight.values()];
|
|
332
|
+
const outcomes = await Promise.allSettled(pending);
|
|
333
|
+
const rejection = outcomes.find((outcome) => outcome.status === "rejected");
|
|
334
|
+
if (rejection)
|
|
335
|
+
throw rejection.reason;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return {
|
|
339
|
+
filePath,
|
|
340
|
+
register(kind, handler) {
|
|
341
|
+
if (!kind)
|
|
342
|
+
throw new Error("Outbox kind 不能为空");
|
|
343
|
+
handlers.set(kind, handler);
|
|
344
|
+
return () => {
|
|
345
|
+
if (handlers.get(kind) === handler)
|
|
346
|
+
handlers.delete(kind);
|
|
347
|
+
};
|
|
348
|
+
},
|
|
349
|
+
async enqueue(input) {
|
|
350
|
+
if (!input.kind)
|
|
351
|
+
throw new Error("Outbox kind 不能为空");
|
|
352
|
+
if (input.payload === undefined)
|
|
353
|
+
throw new Error("Outbox payload 必须是 JSON 值,不能为 undefined");
|
|
354
|
+
if (input.nextAttemptAt !== undefined && !Number.isFinite(input.nextAttemptAt)) {
|
|
355
|
+
throw new Error("Outbox nextAttemptAt 必须是有限时间戳");
|
|
356
|
+
}
|
|
357
|
+
const persistedCtx = jsonSnapshot(input.ctx, "ctx");
|
|
358
|
+
const persistedPayload = jsonSnapshot(input.payload, "payload");
|
|
359
|
+
const now = Date.now();
|
|
360
|
+
const id = input.id ?? randomUUID();
|
|
361
|
+
const entry = mutate((entries) => {
|
|
362
|
+
const existing = entries.find((candidate) => candidate.id === id);
|
|
363
|
+
if (existing)
|
|
364
|
+
return clone(existing);
|
|
365
|
+
const created = {
|
|
366
|
+
id,
|
|
367
|
+
kind: input.kind,
|
|
368
|
+
ctx: persistedCtx,
|
|
369
|
+
payload: persistedPayload,
|
|
370
|
+
...input.sessionId !== undefined ? { sessionId: input.sessionId } : {},
|
|
371
|
+
...input.turnId !== undefined ? { turnId: input.turnId } : {},
|
|
372
|
+
state: "pending",
|
|
373
|
+
attempts: 0,
|
|
374
|
+
createdAt: now,
|
|
375
|
+
updatedAt: now,
|
|
376
|
+
nextAttemptAt: input.nextAttemptAt ?? now
|
|
377
|
+
};
|
|
378
|
+
entries.push(created);
|
|
379
|
+
return clone(created);
|
|
380
|
+
});
|
|
381
|
+
automatic.add(id);
|
|
382
|
+
dispatch(id).finally(() => automatic.delete(id)).catch(() => {});
|
|
383
|
+
return entry;
|
|
384
|
+
},
|
|
385
|
+
dispatch,
|
|
386
|
+
recover,
|
|
387
|
+
flush,
|
|
388
|
+
async start(startOptions = {}) {
|
|
389
|
+
stopped = false;
|
|
390
|
+
if (startOptions.recover !== false)
|
|
391
|
+
await recover({ maxAttempts: startOptions.maxAttempts });
|
|
392
|
+
if (pollIntervalMs === 0 || timer)
|
|
393
|
+
return;
|
|
394
|
+
timer = setInterval(() => {
|
|
395
|
+
if (stopped)
|
|
396
|
+
return;
|
|
397
|
+
flush({ maxAttempts: startOptions.maxAttempts }).catch(() => {});
|
|
398
|
+
}, pollIntervalMs);
|
|
399
|
+
timer.unref?.();
|
|
400
|
+
flush({ maxAttempts: startOptions.maxAttempts }).catch(() => {});
|
|
401
|
+
},
|
|
402
|
+
stop() {
|
|
403
|
+
stopped = true;
|
|
404
|
+
if (timer)
|
|
405
|
+
clearInterval(timer);
|
|
406
|
+
timer = undefined;
|
|
407
|
+
},
|
|
408
|
+
drain,
|
|
409
|
+
async list() {
|
|
410
|
+
return readDocument(filePath, Date.now()).entries.map((entry) => clone(entry));
|
|
411
|
+
},
|
|
412
|
+
async get(id) {
|
|
413
|
+
const entry = readDocument(filePath, Date.now()).entries.find((candidate) => candidate.id === id);
|
|
414
|
+
return entry ? clone(entry) : undefined;
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// src/config.ts
|
|
420
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
421
|
+
import { join as join2 } from "path";
|
|
422
|
+
import { homedir as homedir2 } from "os";
|
|
423
|
+
var CONFIG_DIR = join2(homedir2(), ".openqq");
|
|
424
|
+
var ENV_FILE = join2(CONFIG_DIR, ".env");
|
|
425
|
+
function loadEnvFile(path) {
|
|
426
|
+
const content = readFileSync2(path, "utf-8");
|
|
427
|
+
for (const line of content.split(`
|
|
428
|
+
`)) {
|
|
429
|
+
const trimmed = line.trim();
|
|
430
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
431
|
+
continue;
|
|
432
|
+
const eqIdx = trimmed.indexOf("=");
|
|
433
|
+
if (eqIdx < 0)
|
|
434
|
+
continue;
|
|
435
|
+
const key = trimmed.slice(0, eqIdx).trim();
|
|
436
|
+
const val = trimmed.slice(eqIdx + 1).trim();
|
|
437
|
+
if (!process.env[key]) {
|
|
438
|
+
process.env[key] = val;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// src/core/notify-sink.ts
|
|
444
|
+
function resolveNotifyRecipients(configured, explicit) {
|
|
445
|
+
const users = [...configured];
|
|
446
|
+
if (explicit)
|
|
447
|
+
return users.includes(explicit) ? explicit : "";
|
|
448
|
+
return users.length === 1 ? users[0] : "";
|
|
449
|
+
}
|
|
450
|
+
function defaultOutboxPath() {
|
|
451
|
+
return storageFile("outbox.json");
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// src/cli/notify.ts
|
|
455
|
+
var NOTIFY_DEFAULT_MAX_CHARS = 1500;
|
|
456
|
+
function parseArgs(argv) {
|
|
457
|
+
const parsed = { maxChars: NOTIFY_DEFAULT_MAX_CHARS, dryRun: false, json: false, help: false };
|
|
458
|
+
for (let i = 0;i < argv.length; i++) {
|
|
459
|
+
const a = argv[i];
|
|
460
|
+
const next = argv[i + 1];
|
|
461
|
+
switch (a) {
|
|
462
|
+
case "--text":
|
|
463
|
+
parsed.text = next;
|
|
464
|
+
i++;
|
|
465
|
+
break;
|
|
466
|
+
case "--file":
|
|
467
|
+
parsed.filePath = next;
|
|
468
|
+
i++;
|
|
469
|
+
break;
|
|
470
|
+
case "--stdin":
|
|
471
|
+
parsed.stdin = true;
|
|
472
|
+
break;
|
|
473
|
+
case "--user":
|
|
474
|
+
parsed.user = next;
|
|
475
|
+
i++;
|
|
476
|
+
break;
|
|
477
|
+
case "--id":
|
|
478
|
+
parsed.id = next;
|
|
479
|
+
i++;
|
|
480
|
+
break;
|
|
481
|
+
case "--max-chars":
|
|
482
|
+
parsed.maxChars = Number(next);
|
|
483
|
+
i++;
|
|
484
|
+
break;
|
|
485
|
+
case "--ttl-hours":
|
|
486
|
+
parsed.ttlHours = Number(next);
|
|
487
|
+
i++;
|
|
488
|
+
break;
|
|
489
|
+
case "--dry-run":
|
|
490
|
+
parsed.dryRun = true;
|
|
491
|
+
break;
|
|
492
|
+
case "--json":
|
|
493
|
+
parsed.json = true;
|
|
494
|
+
break;
|
|
495
|
+
case "--help":
|
|
496
|
+
case "-h":
|
|
497
|
+
parsed.help = true;
|
|
498
|
+
i++;
|
|
499
|
+
break;
|
|
500
|
+
default:
|
|
501
|
+
throw new Error(`未知参数:${a}(用法:openqq notify --text "…" | --file <p> | --stdin)`);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (!parsed.help && !parsed.text && !parsed.filePath && !parsed.stdin) {
|
|
505
|
+
throw new Error("必须提供正文来源:--text / --file / --stdin 三选一");
|
|
506
|
+
}
|
|
507
|
+
if (!Number.isFinite(parsed.maxChars) || parsed.maxChars < 0) {
|
|
508
|
+
throw new Error("--max-chars 必须是 >= 0 的有限数(0=不截断)");
|
|
509
|
+
}
|
|
510
|
+
return parsed;
|
|
511
|
+
}
|
|
512
|
+
function resolveUser(envAllowed, explicit) {
|
|
513
|
+
return resolveNotifyRecipients(envAllowed, explicit);
|
|
514
|
+
}
|
|
515
|
+
function readBody(parsed) {
|
|
516
|
+
if (parsed.text !== undefined)
|
|
517
|
+
return parsed.text;
|
|
518
|
+
if (parsed.filePath !== undefined) {
|
|
519
|
+
if (parsed.filePath === "-")
|
|
520
|
+
return readFileSync3(0, "utf8");
|
|
521
|
+
if (!existsSync3(parsed.filePath))
|
|
522
|
+
throw new Error(`--file 不存在:${parsed.filePath}`);
|
|
523
|
+
return readFileSync3(parsed.filePath, "utf8");
|
|
524
|
+
}
|
|
525
|
+
if (parsed.stdin)
|
|
526
|
+
return readFileSync3(0, "utf8");
|
|
527
|
+
return "";
|
|
528
|
+
}
|
|
529
|
+
async function runNotifyCli(argv, options = {}) {
|
|
530
|
+
const now = options.now ?? Date.now();
|
|
531
|
+
const parsed = parseArgs(argv);
|
|
532
|
+
if (parsed.help) {
|
|
533
|
+
const help = [
|
|
534
|
+
'用法:openqq notify --text "…" | --file <路径> | --stdin',
|
|
535
|
+
" --user <openid> 收件人;缺省取 ALLOWED_USERS 唯一项(多用户必须显式指定)",
|
|
536
|
+
" --id <key> 幂等键(同 key 不重复投递)",
|
|
537
|
+
" --max-chars <n> 截断上限,默认 1500,0 不截断",
|
|
538
|
+
" --ttl-hours <n> 队列等待上限,默认 24(env QQ_NOTIFY_TTL_HOURS 兜底)",
|
|
539
|
+
" --dry-run / --json 不入队 / 机器可读输出"
|
|
540
|
+
].join(`
|
|
541
|
+
`);
|
|
542
|
+
console.log(help);
|
|
543
|
+
return { ok: true, queued: false, id: "", user: "", chars: 0, truncated: false, dryRun: true, json: parsed.json, reason: "help" };
|
|
544
|
+
}
|
|
545
|
+
if (!options.env && existsSync3(ENV_FILE))
|
|
546
|
+
loadEnvFile(ENV_FILE);
|
|
547
|
+
const allowedUsers = options.env ? [...options.env.allowedUsers] : String(process.env.ALLOWED_USERS ?? "").split(/[,\s]+/).filter(Boolean);
|
|
548
|
+
const user = resolveUser(allowedUsers, parsed.user);
|
|
549
|
+
if (!user) {
|
|
550
|
+
throw new Error(allowedUsers.length === 0 ? "ALLOWED_USERS 为空——fail-closed 不允许无名单入队(先在 ~/.openqq/.env 配置)" : parsed.user ? `收件人不在名单:${parsed.user}(ALLOWED_USERS 共 ${allowedUsers.length} 项,--user 必须精确命中;请核对 openid)` : "多用户名单必须用 --user <openid> 显式指定收件人");
|
|
551
|
+
}
|
|
552
|
+
const raw = readBody(parsed);
|
|
553
|
+
const max = parsed.maxChars;
|
|
554
|
+
const content = max === 0 ? raw : raw.length > max ? `${raw.slice(0, max)}…` : raw;
|
|
555
|
+
const id = parsed.id || `notify-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
556
|
+
const filePath = options.filePath ?? defaultOutboxPath();
|
|
557
|
+
if (parsed.dryRun) {
|
|
558
|
+
return { ok: true, queued: false, id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: true, json: parsed.json };
|
|
559
|
+
}
|
|
560
|
+
const ttlHours = parsed.ttlHours ?? Number(process.env.QQ_NOTIFY_TTL_HOURS ?? 24);
|
|
561
|
+
const nextAttemptAt = parsed.ttlHours !== undefined && Number.isFinite(ttlHours) && ttlHours > 0 ? now + ttlHours * 60 * 60 * 1000 : now;
|
|
562
|
+
const outbox = createOutbox({ filePath, pollIntervalMs: 0 });
|
|
563
|
+
const entry = await outbox.enqueue({
|
|
564
|
+
...parsed.id ? { id: parsed.id } : {},
|
|
565
|
+
kind: "notify",
|
|
566
|
+
payload: { text: content },
|
|
567
|
+
ctx: { type: "c2c", userId: user, msgId: "", content: "(openqq notify)", timestamp: String(now) },
|
|
568
|
+
sessionId: "",
|
|
569
|
+
nextAttemptAt
|
|
570
|
+
});
|
|
571
|
+
return { ok: true, queued: true, id: entry.id, user, chars: content.length, truncated: content.length !== raw.length, dryRun: false, json: parsed.json };
|
|
572
|
+
}
|
|
573
|
+
async function main(argv) {
|
|
574
|
+
try {
|
|
575
|
+
const result = await runNotifyCli(argv);
|
|
576
|
+
if (result.reason === "help")
|
|
577
|
+
return 0;
|
|
578
|
+
if (result.json) {
|
|
579
|
+
console.log(JSON.stringify(result));
|
|
580
|
+
} else if (result.queued && !result.dryRun) {
|
|
581
|
+
console.log(`[notify] 已入队 id=${result.id} user=${result.user} chars=${result.chars}${result.truncated ? "(已截断)" : ""}`);
|
|
582
|
+
} else if (result.dryRun) {
|
|
583
|
+
console.log(`[notify] dry-run:将入队 user=${result.user} chars=${result.chars}${result.truncated ? "(已截断)" : ""}`);
|
|
584
|
+
}
|
|
585
|
+
return result.ok ? 0 : 1;
|
|
586
|
+
} catch (error) {
|
|
587
|
+
console.error(`[notify] 入队失败:${error instanceof Error ? error.message : String(error)}`);
|
|
588
|
+
return 1;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// src/cli/notify-main.ts
|
|
593
|
+
process.exitCode = await main(process.argv.slice(2));
|