@linjz/opencode-qqbot 0.3.16 → 0.3.17
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 +303 -266
- package/README.zh-CN.md +313 -0
- package/dist/notify-cli.js +64 -12
- package/dist/opencode-qqbot-plugin.js +356 -92
- package/dist/openqq-bot.js +878 -226
- package/dist/openqq-cli.js +253 -64
- package/dist/openqq-watchdog.js +373 -110
- package/package.json +2 -2
- package/src/bridge.ts +292 -3
- package/src/cli/notify.ts +4 -1
- package/src/cli/watchdog-main.ts +22 -7
- package/src/commands.ts +36 -10
- package/src/config.ts +39 -5
- package/src/core/bot-config.ts +66 -0
- package/src/core/bot-control.ts +21 -3
- package/src/core/bot-launcher.ts +4 -2
- package/src/core/cron-reminders.ts +84 -0
- package/src/core/discovery.ts +207 -169
- package/src/core/error-rescue.ts +1 -1
- package/src/core/file-log.ts +16 -7
- package/src/core/inflight-journal.ts +1 -0
- package/src/core/instance-lock.ts +32 -1
- package/src/core/log-rotate.ts +91 -0
- package/src/core/mirror.ts +7 -1
- package/src/core/notices.ts +62 -0
- package/src/core/outbound-sanitize.ts +29 -0
- package/src/core/permission.ts +7 -0
- package/src/core/queue-view.ts +1 -0
- package/src/core/send-media.ts +29 -2
- package/src/core/start-error.ts +26 -0
- package/src/core/stt.ts +55 -0
- package/src/core/supervisor-election.ts +53 -0
- package/src/core/watchdog.ts +171 -14
- package/src/index.ts +262 -250
- package/src/opencode/client.ts +32 -1
- package/src/opencode/mirror.ts +10 -3
- package/src/plugin-entry.ts +21 -2
- package/src/qq/gateway.ts +35 -0
- package/src/qq/media.ts +21 -0
- package/src/qq/sender.ts +50 -1
package/dist/openqq-bot.js
CHANGED
|
@@ -2938,9 +2938,75 @@ var require_websocket_server = __commonJS(function(exports, module) {
|
|
|
2938
2938
|
}
|
|
2939
2939
|
});
|
|
2940
2940
|
|
|
2941
|
+
// src/core/log-rotate.ts
|
|
2942
|
+
import { existsSync as existsSync6, renameSync as renameSync2, rmSync, statSync as statSync3 } from "fs";
|
|
2943
|
+
function logLimitsFromEnv(env = process.env) {
|
|
2944
|
+
return {
|
|
2945
|
+
maxBytes: num(env.QQ_LOG_MAX_MB, 20) * MB,
|
|
2946
|
+
keepBackups: Math.floor(num(env.QQ_LOG_KEEP, 4)),
|
|
2947
|
+
totalBudgetBytes: num(env.QQ_LOG_TOTAL_MB, 100) * MB
|
|
2948
|
+
};
|
|
2949
|
+
}
|
|
2950
|
+
function rotateLogIfNeeded(logPath, limits = logLimitsFromEnv()) {
|
|
2951
|
+
try {
|
|
2952
|
+
if (!existsSync6(logPath) || statSync3(logPath).size <= limits.maxBytes)
|
|
2953
|
+
return false;
|
|
2954
|
+
try {
|
|
2955
|
+
rmSync(`${logPath}.${limits.keepBackups}`, { force: true });
|
|
2956
|
+
} catch {}
|
|
2957
|
+
for (let i = limits.keepBackups - 1;i >= 1; i--) {
|
|
2958
|
+
const from = `${logPath}.${i}`;
|
|
2959
|
+
if (!existsSync6(from))
|
|
2960
|
+
continue;
|
|
2961
|
+
try {
|
|
2962
|
+
renameSync2(from, `${logPath}.${i + 1}`);
|
|
2963
|
+
} catch {}
|
|
2964
|
+
}
|
|
2965
|
+
try {
|
|
2966
|
+
renameSync2(logPath, `${logPath}.1`);
|
|
2967
|
+
} catch {
|
|
2968
|
+
return false;
|
|
2969
|
+
}
|
|
2970
|
+
return true;
|
|
2971
|
+
} catch {
|
|
2972
|
+
return false;
|
|
2973
|
+
}
|
|
2974
|
+
}
|
|
2975
|
+
function enforceLogBudget(logPath, limits = logLimitsFromEnv()) {
|
|
2976
|
+
try {
|
|
2977
|
+
const sizes = new Map;
|
|
2978
|
+
let total = 0;
|
|
2979
|
+
for (let i = 0;i <= 64; i++) {
|
|
2980
|
+
const p = i === 0 ? logPath : `${logPath}.${i}`;
|
|
2981
|
+
if (!existsSync6(p))
|
|
2982
|
+
break;
|
|
2983
|
+
const s = statSync3(p).size;
|
|
2984
|
+
sizes.set(i, s);
|
|
2985
|
+
total += s;
|
|
2986
|
+
}
|
|
2987
|
+
for (let i = limits.keepBackups;i >= 1 && total > limits.totalBudgetBytes; i--) {
|
|
2988
|
+
const s = sizes.get(i);
|
|
2989
|
+
if (s === undefined)
|
|
2990
|
+
continue;
|
|
2991
|
+
try {
|
|
2992
|
+
rmSync(`${logPath}.${i}`, { force: true });
|
|
2993
|
+
total -= s;
|
|
2994
|
+
} catch {}
|
|
2995
|
+
}
|
|
2996
|
+
} catch {}
|
|
2997
|
+
}
|
|
2998
|
+
var MB, num = (v, d) => {
|
|
2999
|
+
const n = Number(v);
|
|
3000
|
+
return Number.isFinite(n) && n > 0 ? n : d;
|
|
3001
|
+
};
|
|
3002
|
+
var init_log_rotate = __esm(() => {
|
|
3003
|
+
MB = 1024 * 1024;
|
|
3004
|
+
});
|
|
3005
|
+
|
|
2941
3006
|
// src/core/file-log.ts
|
|
2942
|
-
import { appendFileSync, existsSync as
|
|
2943
|
-
import { join as
|
|
3007
|
+
import { appendFileSync, existsSync as existsSync7, mkdirSync as mkdirSync6, statSync as statSync4 } from "fs";
|
|
3008
|
+
import { join as join8 } from "path";
|
|
3009
|
+
import { inspect as inspect2 } from "util";
|
|
2944
3010
|
function formatLocalTimestamp(d = new Date) {
|
|
2945
3011
|
const pad = (n, w = 2) => String(n).padStart(w, "0");
|
|
2946
3012
|
const offMin = -d.getTimezoneOffset();
|
|
@@ -2953,16 +3019,18 @@ function fileLogStatus() {
|
|
|
2953
3019
|
}
|
|
2954
3020
|
function installFileLog(logPath) {
|
|
2955
3021
|
try {
|
|
2956
|
-
mkdirSync6(
|
|
3022
|
+
mkdirSync6(join8(logPath, ".."), { recursive: true });
|
|
2957
3023
|
} catch {}
|
|
2958
3024
|
const state = { path: logPath, lastWriteAt: 0 };
|
|
2959
3025
|
active = state;
|
|
3026
|
+
const limits = logLimitsFromEnv();
|
|
2960
3027
|
const write = (level, args) => {
|
|
2961
3028
|
try {
|
|
2962
|
-
if (
|
|
2963
|
-
|
|
3029
|
+
if (existsSync7(logPath) && statSync4(logPath).size > limits.maxBytes) {
|
|
3030
|
+
if (rotateLogIfNeeded(logPath, limits))
|
|
3031
|
+
enforceLogBudget(logPath, limits);
|
|
2964
3032
|
}
|
|
2965
|
-
const line = args.map((a) => typeof a === "string" ? a :
|
|
3033
|
+
const line = args.map((a) => typeof a === "string" ? a : inspect2(a, { depth: 4, maxStringLength: 500, breakLength: Infinity, colors: false })).join(" ");
|
|
2966
3034
|
appendFileSync(logPath, `${formatLocalTimestamp()} [${level}] ${line}
|
|
2967
3035
|
`, { mode: 384 });
|
|
2968
3036
|
state.lastWriteAt = Date.now();
|
|
@@ -2993,16 +3061,75 @@ function installFileLog(logPath) {
|
|
|
2993
3061
|
active = null;
|
|
2994
3062
|
};
|
|
2995
3063
|
}
|
|
2996
|
-
var
|
|
3064
|
+
var active = null;
|
|
2997
3065
|
var init_file_log = __esm(() => {
|
|
2998
|
-
|
|
3066
|
+
init_log_rotate();
|
|
2999
3067
|
});
|
|
3000
3068
|
|
|
3001
3069
|
// src/config.ts
|
|
3002
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
3003
|
-
import { join } from "path";
|
|
3004
|
-
import { homedir } from "os";
|
|
3070
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
3071
|
+
import { join as join2 } from "path";
|
|
3072
|
+
import { homedir as homedir2 } from "os";
|
|
3005
3073
|
import { createInterface } from "readline";
|
|
3074
|
+
|
|
3075
|
+
// src/core/bot-config.ts
|
|
3076
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3077
|
+
import { homedir } from "node:os";
|
|
3078
|
+
import { join } from "node:path";
|
|
3079
|
+
function configJsonPath(env = process.env) {
|
|
3080
|
+
return env.QQ_CONFIG_FILE?.trim() || join(homedir(), ".openqq", "config.json");
|
|
3081
|
+
}
|
|
3082
|
+
function parseConfigJson(raw) {
|
|
3083
|
+
let parsed;
|
|
3084
|
+
try {
|
|
3085
|
+
parsed = JSON.parse(raw);
|
|
3086
|
+
} catch {
|
|
3087
|
+
console.warn("[config] config.json 不是合法 JSON,已忽略");
|
|
3088
|
+
return {};
|
|
3089
|
+
}
|
|
3090
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
3091
|
+
console.warn("[config] config.json 必须是平铺 JSON 对象,已忽略");
|
|
3092
|
+
return {};
|
|
3093
|
+
}
|
|
3094
|
+
const out = {};
|
|
3095
|
+
for (const [k, v] of Object.entries(parsed)) {
|
|
3096
|
+
if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
|
|
3097
|
+
out[k] = String(v);
|
|
3098
|
+
}
|
|
3099
|
+
}
|
|
3100
|
+
return out;
|
|
3101
|
+
}
|
|
3102
|
+
function computeOverlay(env, config) {
|
|
3103
|
+
return Object.entries(config).filter(([k]) => env[k] === undefined);
|
|
3104
|
+
}
|
|
3105
|
+
function applyConfigOverlay(env = process.env) {
|
|
3106
|
+
const path = configJsonPath(env);
|
|
3107
|
+
if (!existsSync(path))
|
|
3108
|
+
return 0;
|
|
3109
|
+
let raw;
|
|
3110
|
+
try {
|
|
3111
|
+
raw = readFileSync(path, "utf-8");
|
|
3112
|
+
} catch {
|
|
3113
|
+
return 0;
|
|
3114
|
+
}
|
|
3115
|
+
const overlay = computeOverlay(env, parseConfigJson(raw));
|
|
3116
|
+
for (const [k, v] of overlay)
|
|
3117
|
+
env[k] = v;
|
|
3118
|
+
if (overlay.length > 0) {
|
|
3119
|
+
console.log(`[config] config.json 已叠加 ${overlay.length} 项(env/.env 优先): ${path}`);
|
|
3120
|
+
}
|
|
3121
|
+
return overlay.length;
|
|
3122
|
+
}
|
|
3123
|
+
|
|
3124
|
+
// src/config.ts
|
|
3125
|
+
function hasUsableCredentials(env = process.env) {
|
|
3126
|
+
if ((env.QQ_APP_ID ?? "").trim() && (env.QQ_APP_SECRET ?? "").trim())
|
|
3127
|
+
return true;
|
|
3128
|
+
const raw = (env.QQ_BOTS ?? "").trim();
|
|
3129
|
+
if (!raw)
|
|
3130
|
+
return false;
|
|
3131
|
+
return parseRolesJson(raw).length > 0;
|
|
3132
|
+
}
|
|
3006
3133
|
function loadRoles() {
|
|
3007
3134
|
const raw = (process.env.QQ_BOTS ?? "").trim();
|
|
3008
3135
|
if (raw) {
|
|
@@ -3012,6 +3139,7 @@ function loadRoles() {
|
|
|
3012
3139
|
console.warn("[config] QQ_BOTS 配置存在但解析结果为空,回退 legacy 单角色模式");
|
|
3013
3140
|
}
|
|
3014
3141
|
const single = loadConfig();
|
|
3142
|
+
console.warn("[config] legacy 单角色配置(QQ_APP_ID/QQ_APP_SECRET)已弃用——QQ_BOTS 多角色表是唯一角色源;" + 'legacy 兜底将于 2026-12-31 移除,请迁移 .env:QQ_BOTS=[{"appId":"…","secret":"…","sandbox":false,"name":"角色名"}]');
|
|
3015
3143
|
return [{
|
|
3016
3144
|
name: single.qq.appId,
|
|
3017
3145
|
appId: single.qq.appId,
|
|
@@ -3058,8 +3186,8 @@ function parseRolesJson(raw) {
|
|
|
3058
3186
|
}
|
|
3059
3187
|
return [...seen.values()];
|
|
3060
3188
|
}
|
|
3061
|
-
var CONFIG_DIR =
|
|
3062
|
-
var ENV_FILE =
|
|
3189
|
+
var CONFIG_DIR = join2(homedir2(), ".openqq");
|
|
3190
|
+
var ENV_FILE = join2(CONFIG_DIR, ".env");
|
|
3063
3191
|
function askTwo(q1, q2) {
|
|
3064
3192
|
return new Promise((resolve, reject) => {
|
|
3065
3193
|
let done = false;
|
|
@@ -3078,17 +3206,18 @@ function askTwo(q1, q2) {
|
|
|
3078
3206
|
});
|
|
3079
3207
|
}
|
|
3080
3208
|
async function ensureConfig() {
|
|
3081
|
-
|
|
3209
|
+
applyConfigOverlay();
|
|
3210
|
+
if (hasUsableCredentials())
|
|
3082
3211
|
return;
|
|
3083
|
-
if (
|
|
3212
|
+
if (existsSync2(ENV_FILE)) {
|
|
3084
3213
|
loadEnvFile(ENV_FILE);
|
|
3085
|
-
if (
|
|
3214
|
+
if (hasUsableCredentials())
|
|
3086
3215
|
return;
|
|
3087
3216
|
}
|
|
3088
|
-
const localEnv =
|
|
3089
|
-
if (
|
|
3217
|
+
const localEnv = join2(process.cwd(), ".env");
|
|
3218
|
+
if (existsSync2(localEnv)) {
|
|
3090
3219
|
loadEnvFile(localEnv);
|
|
3091
|
-
if (
|
|
3220
|
+
if (hasUsableCredentials())
|
|
3092
3221
|
return;
|
|
3093
3222
|
}
|
|
3094
3223
|
console.log("首次运行,需要配置 QQ 机器人凭证");
|
|
@@ -3100,6 +3229,8 @@ async function ensureConfig() {
|
|
|
3100
3229
|
}
|
|
3101
3230
|
mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
|
|
3102
3231
|
const envContent = [
|
|
3232
|
+
`# 多角色(唯一角色源,推荐):QQ_BOTS=[{"appId":"…","secret":"…","sandbox":false,"name":"开发角色","allowedUsers":[]}]`,
|
|
3233
|
+
`# 以下 legacy 单角色字段已弃用,将于 2026-12-31 移除`,
|
|
3103
3234
|
`QQ_APP_ID=${appId}`,
|
|
3104
3235
|
`QQ_APP_SECRET=${appSecret}`,
|
|
3105
3236
|
`QQ_SANDBOX=false`,
|
|
@@ -3115,7 +3246,7 @@ async function ensureConfig() {
|
|
|
3115
3246
|
process.env.QQ_APP_SECRET = appSecret;
|
|
3116
3247
|
}
|
|
3117
3248
|
function loadEnvFile(path) {
|
|
3118
|
-
const content =
|
|
3249
|
+
const content = readFileSync2(path, "utf-8");
|
|
3119
3250
|
for (const line of content.split(`
|
|
3120
3251
|
`)) {
|
|
3121
3252
|
const trimmed = line.trim();
|
|
@@ -3155,21 +3286,21 @@ function loadConfig() {
|
|
|
3155
3286
|
}
|
|
3156
3287
|
|
|
3157
3288
|
// src/core/storage.ts
|
|
3158
|
-
import { homedir as
|
|
3159
|
-
import { join as
|
|
3160
|
-
var LEGACY_ROOT =
|
|
3289
|
+
import { homedir as homedir3 } from "os";
|
|
3290
|
+
import { join as join3 } from "path";
|
|
3291
|
+
var LEGACY_ROOT = join3(homedir3(), ".openqq");
|
|
3161
3292
|
function storageRoot(appId) {
|
|
3162
3293
|
const base = (process.env.QQ_DATA_DIR ?? "").trim() || LEGACY_ROOT;
|
|
3163
|
-
return appId ?
|
|
3294
|
+
return appId ? join3(base, "roles", appId) : base;
|
|
3164
3295
|
}
|
|
3165
3296
|
function storageFile(name, appId) {
|
|
3166
|
-
return
|
|
3297
|
+
return join3(storageRoot(appId), name);
|
|
3167
3298
|
}
|
|
3168
3299
|
|
|
3169
3300
|
// src/index.ts
|
|
3170
3301
|
import { mkdirSync as mkdirSync14, writeFileSync as writeFileSync15 } from "fs";
|
|
3171
|
-
import { join as
|
|
3172
|
-
import { homedir as
|
|
3302
|
+
import { join as join13 } from "path";
|
|
3303
|
+
import { homedir as homedir8 } from "os";
|
|
3173
3304
|
|
|
3174
3305
|
// src/opencode/client.ts
|
|
3175
3306
|
function turnTimeoutMinutes() {
|
|
@@ -3301,7 +3432,9 @@ function createClient(baseUrl) {
|
|
|
3301
3432
|
const txt = await res.text().catch(() => "");
|
|
3302
3433
|
const excerpt = txt.length > 200 ? `${txt.substring(0, 200)}…` : txt;
|
|
3303
3434
|
const retryAfter = res.status === 429 ? res.headers.get("retry-after") : null;
|
|
3304
|
-
|
|
3435
|
+
const err = new Error(`OpenCode API ${res.status}: ${excerpt}${retryAfter ? ` [retry-after:${retryAfter}]` : ""}`);
|
|
3436
|
+
err.body = txt;
|
|
3437
|
+
throw err;
|
|
3305
3438
|
}
|
|
3306
3439
|
if (res.status === 204)
|
|
3307
3440
|
return null;
|
|
@@ -3337,6 +3470,18 @@ function createClient(baseUrl) {
|
|
|
3337
3470
|
async abort(opts) {
|
|
3338
3471
|
return json(await req(`/session/${opts.path.id}/interrupt`, { method: "POST", body: "{}" }));
|
|
3339
3472
|
},
|
|
3473
|
+
async command(opts) {
|
|
3474
|
+
return json(await req(`/session/${opts.path.id}/command`, { method: "POST", body: JSON.stringify(opts.body) }));
|
|
3475
|
+
},
|
|
3476
|
+
async revertStage(opts) {
|
|
3477
|
+
return json(await req(`/session/${opts.path.id}/revert/stage`, { method: "POST", body: JSON.stringify(opts.body) }));
|
|
3478
|
+
},
|
|
3479
|
+
async revertCommit(opts) {
|
|
3480
|
+
return json(await req(`/session/${opts.path.id}/revert/commit`, { method: "POST", body: "{}" }));
|
|
3481
|
+
},
|
|
3482
|
+
async revertDiscard(opts) {
|
|
3483
|
+
return json(await req(`/session/${opts.path.id}/revert`, { method: "DELETE" }));
|
|
3484
|
+
},
|
|
3340
3485
|
async messages(opts) {
|
|
3341
3486
|
const query = new URLSearchParams;
|
|
3342
3487
|
if (opts.query?.limit !== undefined)
|
|
@@ -3529,9 +3674,9 @@ async function healthCheck(oc, quiet = false) {
|
|
|
3529
3674
|
// src/core/discovery.ts
|
|
3530
3675
|
import { exec } from "node:child_process";
|
|
3531
3676
|
import { promisify } from "node:util";
|
|
3532
|
-
import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
3533
|
-
import { join as
|
|
3534
|
-
import { homedir as
|
|
3677
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
3678
|
+
import { join as join4 } from "path";
|
|
3679
|
+
import { homedir as homedir4 } from "os";
|
|
3535
3680
|
var execAsync = promisify(exec);
|
|
3536
3681
|
var lastScanUnauthorized = 0;
|
|
3537
3682
|
function isOpencodeInfo(body) {
|
|
@@ -3618,18 +3763,54 @@ async function discoverOpencode(opts) {
|
|
|
3618
3763
|
console.log(`[discovery] 扫描 ${ports.length} 个监听口(${Date.now() - started}ms),无签名命中${hint}`);
|
|
3619
3764
|
return null;
|
|
3620
3765
|
}
|
|
3766
|
+
var LAST_DISCOVERED_PATH = join4(homedir4(), ".openqq", "last-discovered.json");
|
|
3767
|
+
function readLastDiscovered(path = LAST_DISCOVERED_PATH) {
|
|
3768
|
+
try {
|
|
3769
|
+
const raw = JSON.parse(readFileSync3(path, "utf-8"));
|
|
3770
|
+
if (typeof raw.baseUrl === "string" && /^https?:\/\//.test(raw.baseUrl) && Number.isInteger(raw.port)) {
|
|
3771
|
+
return raw;
|
|
3772
|
+
}
|
|
3773
|
+
} catch {}
|
|
3774
|
+
return null;
|
|
3775
|
+
}
|
|
3776
|
+
function resolveInitialBaseUrl(explicit, last) {
|
|
3777
|
+
const trimmed = explicit.trim();
|
|
3778
|
+
if (trimmed)
|
|
3779
|
+
return { url: trimmed, source: "explicit" };
|
|
3780
|
+
if (last)
|
|
3781
|
+
return { url: last.baseUrl.replace(/\/+$/, ""), source: "last-discovered" };
|
|
3782
|
+
return { url: "http://127.0.0.1:1/api", source: "placeholder" };
|
|
3783
|
+
}
|
|
3621
3784
|
function persistDiscovery(d) {
|
|
3622
3785
|
try {
|
|
3623
|
-
const dir =
|
|
3786
|
+
const dir = join4(homedir4(), ".openqq");
|
|
3624
3787
|
mkdirSync2(dir, { recursive: true });
|
|
3625
|
-
writeFileSync2(
|
|
3788
|
+
writeFileSync2(join4(dir, "last-discovered.json"), JSON.stringify({ ...d, at: new Date().toISOString() }, null, 2));
|
|
3626
3789
|
} catch (error) {
|
|
3627
3790
|
console.log(`[discovery] 发现结果落盘失败: ${error instanceof Error ? error.message : error}`);
|
|
3628
3791
|
}
|
|
3629
3792
|
}
|
|
3630
3793
|
|
|
3794
|
+
// src/core/start-error.ts
|
|
3795
|
+
import { inspect } from "util";
|
|
3796
|
+
function formatStartupError(error) {
|
|
3797
|
+
if (error instanceof Error)
|
|
3798
|
+
return error.stack ?? error.message;
|
|
3799
|
+
if (typeof error === "string")
|
|
3800
|
+
return error;
|
|
3801
|
+
return inspect(error, { depth: 6, colors: false, maxArrayLength: 50, maxStringLength: 500 });
|
|
3802
|
+
}
|
|
3803
|
+
function startupDiagnosticBundle() {
|
|
3804
|
+
return JSON.stringify({
|
|
3805
|
+
cwd: process.cwd(),
|
|
3806
|
+
execPath: process.execPath,
|
|
3807
|
+
argv: process.argv.slice(2),
|
|
3808
|
+
envKeys: Object.keys(process.env).sort()
|
|
3809
|
+
});
|
|
3810
|
+
}
|
|
3811
|
+
|
|
3631
3812
|
// src/core/linkwatch.ts
|
|
3632
|
-
import { existsSync as
|
|
3813
|
+
import { existsSync as existsSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
|
|
3633
3814
|
function incidentPath() {
|
|
3634
3815
|
return storageFile("incident.json");
|
|
3635
3816
|
}
|
|
@@ -3655,8 +3836,8 @@ function startLinkWatch(deps) {
|
|
|
3655
3836
|
let busy = false;
|
|
3656
3837
|
let loopTimer = null;
|
|
3657
3838
|
try {
|
|
3658
|
-
if (
|
|
3659
|
-
const raw = JSON.parse(
|
|
3839
|
+
if (existsSync3(file)) {
|
|
3840
|
+
const raw = JSON.parse(readFileSync4(file, "utf-8"));
|
|
3660
3841
|
if (raw?.state === "open" && typeof raw.since === "string") {
|
|
3661
3842
|
rec = raw;
|
|
3662
3843
|
alarmOpenSent = true;
|
|
@@ -4132,7 +4313,7 @@ async function sleep2(ms, signal) {
|
|
|
4132
4313
|
}
|
|
4133
4314
|
|
|
4134
4315
|
// src/opencode/sessions.ts
|
|
4135
|
-
import { existsSync as
|
|
4316
|
+
import { existsSync as existsSync4, readFileSync as readFileSync5, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
|
|
4136
4317
|
import { dirname } from "path";
|
|
4137
4318
|
var STORE_FILE = storageFile("sessions.json");
|
|
4138
4319
|
|
|
@@ -4147,9 +4328,9 @@ class SessionManager {
|
|
|
4147
4328
|
}
|
|
4148
4329
|
loadSessions() {
|
|
4149
4330
|
try {
|
|
4150
|
-
if (!
|
|
4331
|
+
if (!existsSync4(this.storeFile))
|
|
4151
4332
|
return;
|
|
4152
|
-
const raw =
|
|
4333
|
+
const raw = readFileSync5(this.storeFile, "utf8").replace(/^\uFEFF/, "");
|
|
4153
4334
|
const parsed = JSON.parse(raw);
|
|
4154
4335
|
for (const [userId, session] of Object.entries(parsed)) {
|
|
4155
4336
|
if (session?.sessionId)
|
|
@@ -4165,7 +4346,7 @@ class SessionManager {
|
|
|
4165
4346
|
saveSessions() {
|
|
4166
4347
|
try {
|
|
4167
4348
|
const dir = dirname(this.storeFile);
|
|
4168
|
-
if (!
|
|
4349
|
+
if (!existsSync4(dir))
|
|
4169
4350
|
mkdirSync3(dir, { recursive: true });
|
|
4170
4351
|
writeFileSync4(this.storeFile, JSON.stringify(Object.fromEntries(this.sessions), null, 2), "utf8");
|
|
4171
4352
|
} catch (error) {
|
|
@@ -4336,8 +4517,8 @@ var import_websocket_server = __toESM(require_websocket_server(), 1);
|
|
|
4336
4517
|
var wrapper_default = import_websocket.default;
|
|
4337
4518
|
|
|
4338
4519
|
// src/core/gateway-state.ts
|
|
4339
|
-
import { existsSync as
|
|
4340
|
-
import { join as
|
|
4520
|
+
import { existsSync as existsSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync5, mkdirSync as mkdirSync4, renameSync, unlinkSync } from "fs";
|
|
4521
|
+
import { join as join5 } from "path";
|
|
4341
4522
|
var GATEWAY_STATE_FILE = storageFile("gateway-state.json");
|
|
4342
4523
|
function gatewayStateMaxAgeMs() {
|
|
4343
4524
|
const h = Number(process.env.QQ_GATEWAY_STATE_MAX_HOURS ?? "6");
|
|
@@ -4345,9 +4526,9 @@ function gatewayStateMaxAgeMs() {
|
|
|
4345
4526
|
}
|
|
4346
4527
|
function loadGatewayState(file = GATEWAY_STATE_FILE, now = Date.now()) {
|
|
4347
4528
|
try {
|
|
4348
|
-
if (!
|
|
4529
|
+
if (!existsSync5(file))
|
|
4349
4530
|
return null;
|
|
4350
|
-
const raw = JSON.parse(
|
|
4531
|
+
const raw = JSON.parse(readFileSync6(file, "utf-8"));
|
|
4351
4532
|
if (!raw || typeof raw.session_id !== "string" || !raw.session_id)
|
|
4352
4533
|
return null;
|
|
4353
4534
|
if (typeof raw.seq !== "number" || raw.seq < 0)
|
|
@@ -4363,7 +4544,7 @@ function loadGatewayState(file = GATEWAY_STATE_FILE, now = Date.now()) {
|
|
|
4363
4544
|
}
|
|
4364
4545
|
function saveGatewayState(sessionId, seq, file = GATEWAY_STATE_FILE) {
|
|
4365
4546
|
try {
|
|
4366
|
-
mkdirSync4(
|
|
4547
|
+
mkdirSync4(join5(file, ".."), { recursive: true });
|
|
4367
4548
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
4368
4549
|
writeFileSync5(tmp, JSON.stringify({ session_id: sessionId, seq, savedAt: Date.now() }));
|
|
4369
4550
|
renameSync(tmp, file);
|
|
@@ -4393,6 +4574,7 @@ function createInitialState(stateFile) {
|
|
|
4393
4574
|
stopped: false,
|
|
4394
4575
|
connecting: false,
|
|
4395
4576
|
reconnectAttempt: 0,
|
|
4577
|
+
quickCloses: [],
|
|
4396
4578
|
reconnectTimer: null,
|
|
4397
4579
|
heartbeatTimer: null,
|
|
4398
4580
|
accessToken: null,
|
|
@@ -4449,6 +4631,12 @@ function scheduleReconnect(state, connect, customDelayMs) {
|
|
|
4449
4631
|
connect();
|
|
4450
4632
|
}, delayMs);
|
|
4451
4633
|
}
|
|
4634
|
+
function shouldEscalateReconnect(closes, now, windowMs = 60000, maxQuick = 5) {
|
|
4635
|
+
while (closes.length > 0 && now - closes[0] > windowMs)
|
|
4636
|
+
closes.shift();
|
|
4637
|
+
return closes.length >= maxQuick;
|
|
4638
|
+
}
|
|
4639
|
+
var STORM_COOLDOWN_MS = 5 * 60000;
|
|
4452
4640
|
function startHeartbeat(state, intervalMs) {
|
|
4453
4641
|
if (state.heartbeatTimer) {
|
|
4454
4642
|
clearInterval(state.heartbeatTimer);
|
|
@@ -4773,6 +4961,15 @@ async function startGateway(options) {
|
|
|
4773
4961
|
if (FATAL_CLOSE_CODES.has(code)) {
|
|
4774
4962
|
return;
|
|
4775
4963
|
}
|
|
4964
|
+
if (code !== RATE_LIMITED_CLOSE_CODE) {
|
|
4965
|
+
state.quickCloses.push(Date.now());
|
|
4966
|
+
if (shouldEscalateReconnect(state.quickCloses, Date.now())) {
|
|
4967
|
+
state.quickCloses.length = 0;
|
|
4968
|
+
console.error(`[qq-gateway] 快断连风暴(60s 内 ${5} 次以上)→ 冷却 ${STORM_COOLDOWN_MS / 60000} 分钟后重试;请排查凭据/intent/网络`);
|
|
4969
|
+
scheduleReconnect(state, connect, STORM_COOLDOWN_MS);
|
|
4970
|
+
return;
|
|
4971
|
+
}
|
|
4972
|
+
}
|
|
4776
4973
|
scheduleReconnect(state, connect);
|
|
4777
4974
|
});
|
|
4778
4975
|
ws.on("error", (error) => {
|
|
@@ -4793,14 +4990,51 @@ async function startGateway(options) {
|
|
|
4793
4990
|
}
|
|
4794
4991
|
|
|
4795
4992
|
// src/bridge.ts
|
|
4796
|
-
import { existsSync as
|
|
4797
|
-
import { join as
|
|
4798
|
-
import { homedir as
|
|
4993
|
+
import { existsSync as existsSync14, readFileSync as readFileSync16, mkdirSync as mkdirSync13, writeFileSync as writeFileSync14 } from "fs";
|
|
4994
|
+
import { join as join12 } from "path";
|
|
4995
|
+
import { homedir as homedir7 } from "os";
|
|
4799
4996
|
|
|
4800
4997
|
// src/qq/media.ts
|
|
4801
|
-
import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as
|
|
4802
|
-
import { join as
|
|
4998
|
+
import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as readFileSync7 } from "node:fs";
|
|
4999
|
+
import { join as join6 } from "node:path";
|
|
4803
5000
|
import { tmpdir } from "node:os";
|
|
5001
|
+
|
|
5002
|
+
// src/core/stt.ts
|
|
5003
|
+
function sttConfigured(env = process.env) {
|
|
5004
|
+
const baseUrl = (env.QQ_STT_BASE_URL ?? "").trim().replace(/\/+$/, "");
|
|
5005
|
+
const apiKey = (env.QQ_STT_API_KEY ?? "").trim();
|
|
5006
|
+
const model = (env.QQ_STT_MODEL ?? "whisper-1").trim();
|
|
5007
|
+
if (!baseUrl || !apiKey)
|
|
5008
|
+
return null;
|
|
5009
|
+
return { baseUrl, apiKey, model };
|
|
5010
|
+
}
|
|
5011
|
+
async function sttTranscribe(bytes, filename, cfg, fetchImpl = fetch) {
|
|
5012
|
+
const form = new FormData;
|
|
5013
|
+
form.append("model", cfg.model);
|
|
5014
|
+
form.append("file", new Blob([bytes.buffer]), filename);
|
|
5015
|
+
const ctrl = new AbortController;
|
|
5016
|
+
const timer = setTimeout(() => ctrl.abort(), 30000);
|
|
5017
|
+
let res;
|
|
5018
|
+
try {
|
|
5019
|
+
res = await fetchImpl(`${cfg.baseUrl}/audio/transcriptions`, {
|
|
5020
|
+
method: "POST",
|
|
5021
|
+
headers: { Authorization: `Bearer ${cfg.apiKey}` },
|
|
5022
|
+
body: form,
|
|
5023
|
+
signal: ctrl.signal
|
|
5024
|
+
});
|
|
5025
|
+
} finally {
|
|
5026
|
+
clearTimeout(timer);
|
|
5027
|
+
}
|
|
5028
|
+
if (!res.ok)
|
|
5029
|
+
throw new Error(`STT ${res.status}`);
|
|
5030
|
+
const j = await res.json();
|
|
5031
|
+
const text = (j.text ?? "").trim();
|
|
5032
|
+
if (!text)
|
|
5033
|
+
throw new Error("STT 空转写");
|
|
5034
|
+
return text;
|
|
5035
|
+
}
|
|
5036
|
+
|
|
5037
|
+
// src/qq/media.ts
|
|
4804
5038
|
function extForImageMime(mime) {
|
|
4805
5039
|
const m = (mime || "").toLowerCase().split(";")[0].trim();
|
|
4806
5040
|
if (m === "image/jpeg")
|
|
@@ -4824,7 +5058,7 @@ function isAllowedDownloadHost(url) {
|
|
|
4824
5058
|
}
|
|
4825
5059
|
}
|
|
4826
5060
|
function imageDir() {
|
|
4827
|
-
return
|
|
5061
|
+
return join6(tmpdir(), "opencode", "qq-images");
|
|
4828
5062
|
}
|
|
4829
5063
|
async function fetchWithTimeout(url, ms, auth) {
|
|
4830
5064
|
const ctrl = new AbortController;
|
|
@@ -4844,6 +5078,26 @@ async function downloadQQAttachment(att, getAuth) {
|
|
|
4844
5078
|
if (isVoice && att.asr_refer_text?.trim()) {
|
|
4845
5079
|
return { voice: att.asr_refer_text.trim() };
|
|
4846
5080
|
}
|
|
5081
|
+
if (isVoice && sttConfigured()) {
|
|
5082
|
+
try {
|
|
5083
|
+
if (!isAllowedDownloadHost(att.url))
|
|
5084
|
+
return { failed: "下载域不在白名单" };
|
|
5085
|
+
const name = att.filename || `voice-${Date.now()}.amr`;
|
|
5086
|
+
let res = await fetchWithTimeout(att.url, 15000);
|
|
5087
|
+
if ((res.status === 401 || res.status === 403) && getAuth) {
|
|
5088
|
+
res = await fetchWithTimeout(att.url, 15000, await getAuth());
|
|
5089
|
+
}
|
|
5090
|
+
if (!res.ok)
|
|
5091
|
+
return { failed: "语音下载失败" };
|
|
5092
|
+
const buf = new Uint8Array(await res.arrayBuffer());
|
|
5093
|
+
if (buf.byteLength > MAX_IMAGE_BYTES)
|
|
5094
|
+
return { failed: "语音超过 10MB 上限" };
|
|
5095
|
+
const text = await sttTranscribe(buf, name, sttConfigured());
|
|
5096
|
+
return { voice: text };
|
|
5097
|
+
} catch {
|
|
5098
|
+
return { failed: "语音转写失败(外部 STT 未响应或识别为空)" };
|
|
5099
|
+
}
|
|
5100
|
+
}
|
|
4847
5101
|
const ext = extForImageMime(att.content_type || "");
|
|
4848
5102
|
if (!ext)
|
|
4849
5103
|
return { unsupported: att.content_type || att.filename || "未知类型" };
|
|
@@ -4885,7 +5139,7 @@ async function downloadQQAttachment(att, getAuth) {
|
|
|
4885
5139
|
}
|
|
4886
5140
|
if (total === 0)
|
|
4887
5141
|
return { failed: "空响应" };
|
|
4888
|
-
const full =
|
|
5142
|
+
const full = join6(dir, name);
|
|
4889
5143
|
writeFileSync6(full, Buffer.concat(chunks));
|
|
4890
5144
|
return { path: full, name };
|
|
4891
5145
|
} catch (e) {
|
|
@@ -4923,7 +5177,7 @@ function tryImageDataUrl(path, maxBytes) {
|
|
|
4923
5177
|
const st = statSync(path);
|
|
4924
5178
|
if (st.size > maxBytes)
|
|
4925
5179
|
return null;
|
|
4926
|
-
const b =
|
|
5180
|
+
const b = readFileSync7(path);
|
|
4927
5181
|
return `data:image/png;base64,${b.toString("base64")}`;
|
|
4928
5182
|
} catch {
|
|
4929
5183
|
return null;
|
|
@@ -4950,7 +5204,7 @@ function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
|
|
|
4950
5204
|
const dir = imageDir();
|
|
4951
5205
|
const now = Date.now();
|
|
4952
5206
|
for (const f of readdirSync(dir)) {
|
|
4953
|
-
const full =
|
|
5207
|
+
const full = join6(dir, f);
|
|
4954
5208
|
try {
|
|
4955
5209
|
if (now - statSync(full).mtimeMs > maxAgeMs)
|
|
4956
5210
|
unlinkSync2(full);
|
|
@@ -5383,8 +5637,9 @@ function clip(value, max) {
|
|
|
5383
5637
|
}
|
|
5384
5638
|
|
|
5385
5639
|
// src/core/send-media.ts
|
|
5386
|
-
import { readFileSync as
|
|
5387
|
-
import { resolve, extname, basename, sep } from "node:path";
|
|
5640
|
+
import { readFileSync as readFileSync8, statSync as statSync2 } from "node:fs";
|
|
5641
|
+
import { resolve, extname, basename, sep, join as join7 } from "node:path";
|
|
5642
|
+
import { homedir as homedir5 } from "node:os";
|
|
5388
5643
|
var MAX_SEND_BYTES = 20 * 1024 * 1024;
|
|
5389
5644
|
function allowedSendRoots(extraEnv = process.env.QQ_SEND_EXTRA_ROOTS) {
|
|
5390
5645
|
const roots = [imageDir(), process.cwd()];
|
|
@@ -5448,8 +5703,23 @@ function extractSendFileMarkers(text) {
|
|
|
5448
5703
|
|
|
5449
5704
|
`).trim(), paths };
|
|
5450
5705
|
}
|
|
5706
|
+
function normalizeLocalPath(p) {
|
|
5707
|
+
let r = p.trim();
|
|
5708
|
+
if (r.startsWith("file://")) {
|
|
5709
|
+
r = r.slice("file://".length);
|
|
5710
|
+
if (/^\/[a-zA-Z]:[\\/]/.test(r))
|
|
5711
|
+
r = r.slice(1);
|
|
5712
|
+
}
|
|
5713
|
+
try {
|
|
5714
|
+
r = decodeURIComponent(r);
|
|
5715
|
+
} catch {}
|
|
5716
|
+
if (r === "~" || r.startsWith("~/") || r.startsWith("~\\")) {
|
|
5717
|
+
r = join7(homedir5(), r.slice(1));
|
|
5718
|
+
}
|
|
5719
|
+
return r;
|
|
5720
|
+
}
|
|
5451
5721
|
async function sendLocalFile(ctx, filePath, deps) {
|
|
5452
|
-
const trimmed = filePath
|
|
5722
|
+
const trimmed = normalizeLocalPath(filePath);
|
|
5453
5723
|
if (isDeniedSendFile(trimmed)) {
|
|
5454
5724
|
throw new Error("该文件属于密钥/凭据类,禁止外发(已拦截)");
|
|
5455
5725
|
}
|
|
@@ -5473,7 +5743,7 @@ async function sendLocalFile(ctx, filePath, deps) {
|
|
|
5473
5743
|
const name = basename(trimmed);
|
|
5474
5744
|
const uploaded = await uploadQQMedia(token, ctx, {
|
|
5475
5745
|
fileType,
|
|
5476
|
-
fileData:
|
|
5746
|
+
fileData: readFileSync8(trimmed).toString("base64"),
|
|
5477
5747
|
fileName: fileType === MediaFileType.FILE ? name : undefined
|
|
5478
5748
|
});
|
|
5479
5749
|
await sendQQMediaMessage(token, ctx, uploaded.file_info, name);
|
|
@@ -5495,9 +5765,20 @@ async function handleCommand(ctx, cmdCtx) {
|
|
|
5495
5765
|
switch (parsed.name) {
|
|
5496
5766
|
case "new":
|
|
5497
5767
|
return handleNew(ctx, cmdCtx);
|
|
5498
|
-
case "stop":
|
|
5499
5768
|
case "cancel":
|
|
5500
5769
|
return handleStop(ctx, cmdCtx);
|
|
5770
|
+
case "amend":
|
|
5771
|
+
return cmdCtx.amend(ctx.userId, parsed.args);
|
|
5772
|
+
case "undo":
|
|
5773
|
+
return cmdCtx.undo(ctx.userId);
|
|
5774
|
+
case "goal":
|
|
5775
|
+
return cmdCtx.engineCommand(ctx.userId, "goal", parsed.args);
|
|
5776
|
+
case "compact":
|
|
5777
|
+
return cmdCtx.engineCommand(ctx.userId, "compact", parsed.args);
|
|
5778
|
+
case "redo":
|
|
5779
|
+
return cmdCtx.engineCommand(ctx.userId, "redo", parsed.args);
|
|
5780
|
+
case "btw":
|
|
5781
|
+
return cmdCtx.engineCommand(ctx.userId, "btw", parsed.args);
|
|
5501
5782
|
case "queue":
|
|
5502
5783
|
return handleQueue(ctx, parsed.args, cmdCtx);
|
|
5503
5784
|
case "ledger":
|
|
@@ -5510,9 +5791,9 @@ async function handleCommand(ctx, cmdCtx) {
|
|
|
5510
5791
|
return handleSessions(ctx, cmdCtx);
|
|
5511
5792
|
case "help":
|
|
5512
5793
|
return buildHelpText();
|
|
5513
|
-
case "
|
|
5794
|
+
case "models":
|
|
5514
5795
|
return handleModel(ctx, parsed.args, cmdCtx);
|
|
5515
|
-
case "
|
|
5796
|
+
case "agents":
|
|
5516
5797
|
return handleAgent(ctx, parsed.args, cmdCtx);
|
|
5517
5798
|
case "rename":
|
|
5518
5799
|
return handleRename(ctx, parsed.args, cmdCtx);
|
|
@@ -5617,6 +5898,9 @@ function handleQueue(ctx, args, cmdCtx) {
|
|
|
5617
5898
|
if (/^\d+$/.test(sub)) {
|
|
5618
5899
|
return cmdCtx.queue.listAll(ctx.userId, Math.max(1, Number(sub)));
|
|
5619
5900
|
}
|
|
5901
|
+
if (args.trim()) {
|
|
5902
|
+
return cmdCtx.enqueue(ctx, args.trim());
|
|
5903
|
+
}
|
|
5620
5904
|
return cmdCtx.queue.list(ctx.userId);
|
|
5621
5905
|
}
|
|
5622
5906
|
async function handleLedger(ctx, args, cmdCtx) {
|
|
@@ -5706,12 +5990,12 @@ async function handleModel(ctx, args, cmdCtx) {
|
|
|
5706
5990
|
const isCurrent = current.providerId && current.modelId && `${current.providerId}/${current.modelId}` === model.id;
|
|
5707
5991
|
return `${index + 1}. ${isCurrent ? "[当前] " : ""}${model.label}`;
|
|
5708
5992
|
});
|
|
5709
|
-
return ["可用模型:", ...lines, "回复序号或 /
|
|
5993
|
+
return ["可用模型:", ...lines, "回复序号或 /models <provider/model> 切换(60 秒内有效)"].join(`
|
|
5710
5994
|
`);
|
|
5711
5995
|
}
|
|
5712
5996
|
if (/^\d+$/.test(args)) {
|
|
5713
5997
|
const result = await handlePendingSelection(ctx.userId, Number(args), cmdCtx);
|
|
5714
|
-
return result ?? "没有待选择的模型列表,请先发送 /
|
|
5998
|
+
return result ?? "没有待选择的模型列表,请先发送 /models";
|
|
5715
5999
|
}
|
|
5716
6000
|
const model = splitModelId(args);
|
|
5717
6001
|
if (!model) {
|
|
@@ -5915,7 +6199,9 @@ function buildHelpText() {
|
|
|
5915
6199
|
"/watch <会话ID> - 观察指定会话",
|
|
5916
6200
|
"/watch off - 停止观察",
|
|
5917
6201
|
"/progress - 手动进度查询(工具调用/失败统计、在途状态,本地事件源零模型调用)",
|
|
5918
|
-
"/queue - 队列与台账对账视图;/queue all [页码] 全量;/queue clear 清空;/queue drop <编号>
|
|
6202
|
+
"/queue - 队列与台账对账视图;/queue all [页码] 全量;/queue clear 清空;/queue drop <编号> 定点删除;/queue <文本> 显性入队(steer 默认下排进 FIFO)",
|
|
6203
|
+
"/goal <目标> - 官方目标模式(引擎内置 v2.2.1+);/goal 查状态;pause/resume/clear 控制",
|
|
6204
|
+
"/compact /redo /btw - 官方引擎命令直通(压缩会话 / 恢复撤销 / 侧问)",
|
|
5919
6205
|
"/ledger - 台账快照(在途/孤儿/最近拒绝);/ledger check 对账会话历史;/ledger settle <尾号> confirm 人工结清",
|
|
5920
6206
|
"/cancel - 同 /stop:中止当前 AI 运行并清空忙碌队列",
|
|
5921
6207
|
"/mirror [on|off] - 桌面问答摘要镜像开关(会话轮次完成推送问答摘要)",
|
|
@@ -5953,7 +6239,7 @@ function toErrorMessage(error) {
|
|
|
5953
6239
|
}
|
|
5954
6240
|
|
|
5955
6241
|
// src/core/mirror.ts
|
|
5956
|
-
import { existsSync as
|
|
6242
|
+
import { existsSync as existsSync8, readFileSync as readFileSync9, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "fs";
|
|
5957
6243
|
|
|
5958
6244
|
// src/opencode/mirror.ts
|
|
5959
6245
|
var USER_CLIP = 160;
|
|
@@ -5991,15 +6277,18 @@ function digestTurnKey(messages) {
|
|
|
5991
6277
|
function buildDigest(messages) {
|
|
5992
6278
|
const ordered = [...messages].reverse();
|
|
5993
6279
|
let lastUserIdx = -1;
|
|
6280
|
+
let goalDriven = false;
|
|
5994
6281
|
for (let i = ordered.length - 1;i >= 0; i--) {
|
|
5995
|
-
|
|
6282
|
+
const t = ordered[i].type;
|
|
6283
|
+
if (t === "user" || t === "synthetic") {
|
|
5996
6284
|
lastUserIdx = i;
|
|
6285
|
+
goalDriven = t === "synthetic";
|
|
5997
6286
|
break;
|
|
5998
6287
|
}
|
|
5999
6288
|
}
|
|
6000
6289
|
if (lastUserIdx < 0)
|
|
6001
6290
|
return null;
|
|
6002
|
-
const userText = (ordered[lastUserIdx].text ?? "").trim();
|
|
6291
|
+
const userText = goalDriven ? "" : (ordered[lastUserIdx].text ?? "").trim();
|
|
6003
6292
|
let answer = "";
|
|
6004
6293
|
for (let i = ordered.length - 1;i > lastUserIdx; i--) {
|
|
6005
6294
|
const m = ordered[i];
|
|
@@ -6014,7 +6303,7 @@ function buildDigest(messages) {
|
|
|
6014
6303
|
}
|
|
6015
6304
|
if (!answer)
|
|
6016
6305
|
return null;
|
|
6017
|
-
const lines = ["\uD83D\uDCCB 桌面问答摘要"];
|
|
6306
|
+
const lines = [goalDriven ? "\uD83C\uDFAF 目标续跑摘要" : "\uD83D\uDCCB 桌面问答摘要"];
|
|
6018
6307
|
if (userText)
|
|
6019
6308
|
lines.push(`\uD83E\uDDD1 ${clip2(userText, USER_CLIP)}`);
|
|
6020
6309
|
const clipLimit = answerClipLimit();
|
|
@@ -6197,8 +6486,8 @@ class MessageQueue {
|
|
|
6197
6486
|
var MIRROR_SETTINGS_FILE = storageFile("settings.json");
|
|
6198
6487
|
function loadMirrorEnabled(file = MIRROR_SETTINGS_FILE) {
|
|
6199
6488
|
try {
|
|
6200
|
-
if (
|
|
6201
|
-
const raw =
|
|
6489
|
+
if (existsSync8(file)) {
|
|
6490
|
+
const raw = readFileSync9(file, "utf-8").replace(/^\uFEFF/, "");
|
|
6202
6491
|
const parsed = JSON.parse(raw);
|
|
6203
6492
|
if (typeof parsed?.mirror === "boolean")
|
|
6204
6493
|
return parsed.mirror;
|
|
@@ -6210,9 +6499,9 @@ function saveMirrorEnabled(enabled, file = MIRROR_SETTINGS_FILE) {
|
|
|
6210
6499
|
try {
|
|
6211
6500
|
mkdirSync7(storageRoot(), { recursive: true });
|
|
6212
6501
|
let existing = {};
|
|
6213
|
-
if (
|
|
6502
|
+
if (existsSync8(file)) {
|
|
6214
6503
|
try {
|
|
6215
|
-
const raw =
|
|
6504
|
+
const raw = readFileSync9(file, "utf-8").replace(/^\uFEFF/, "");
|
|
6216
6505
|
const parsed = JSON.parse(raw);
|
|
6217
6506
|
if (parsed && typeof parsed === "object")
|
|
6218
6507
|
existing = parsed;
|
|
@@ -6312,7 +6601,11 @@ function createMirror(deps) {
|
|
|
6312
6601
|
for (const userId of owners) {
|
|
6313
6602
|
const recent = lastCtx.get(userId);
|
|
6314
6603
|
const ctx = recent ? { ...recent, anchorSessionId: sessionID } : { type: "c2c", userId, msgId: "", content: "", anchorSessionId: sessionID };
|
|
6315
|
-
|
|
6604
|
+
const cronHook = deps.onDigest;
|
|
6605
|
+
const outText = cronHook ? cronHook(userId, digest) : digest;
|
|
6606
|
+
if (!outText.trim())
|
|
6607
|
+
continue;
|
|
6608
|
+
await safeDeliver(ctx, outText);
|
|
6316
6609
|
}
|
|
6317
6610
|
console.log(`[mirror] 会话 ${sessionID} 摘要已镜像给 ${owners.length} 个用户`);
|
|
6318
6611
|
} catch (error) {
|
|
@@ -6369,14 +6662,117 @@ function rescueText(kind, rawMessage) {
|
|
|
6369
6662
|
`服务端原文:${raw}`,
|
|
6370
6663
|
"",
|
|
6371
6664
|
"恢复方式(都不用等模型在线)——",
|
|
6372
|
-
"1. 换现成模型:发 /
|
|
6665
|
+
"1. 换现成模型:发 /models 看列表,或 /models provider/id 直接切换",
|
|
6373
6666
|
"2. 更新 key:在桌面端 opencode 里更新该服务的 key 后,直接重发你的问题"
|
|
6374
6667
|
].join(`
|
|
6375
6668
|
`);
|
|
6376
6669
|
}
|
|
6377
6670
|
|
|
6671
|
+
// src/core/notices.ts
|
|
6672
|
+
function cmdInput(text, show, reference = false) {
|
|
6673
|
+
const enc = (s) => encodeURIComponent(s);
|
|
6674
|
+
const attrs = [`text="${enc(text)}"`];
|
|
6675
|
+
if (show !== undefined)
|
|
6676
|
+
attrs.push(`show="${enc(show)}"`);
|
|
6677
|
+
if (reference)
|
|
6678
|
+
attrs.push('reference="true"');
|
|
6679
|
+
return `<qqbot-cmd-input ${attrs.join(" ")} />`;
|
|
6680
|
+
}
|
|
6681
|
+
var INTERACTION_TAG = /<qqbot-(cmd-input|cmd-enter)\b[^>]*\/?>/g;
|
|
6682
|
+
function tagFallback(tag) {
|
|
6683
|
+
const show = /show="([^"]*)"/.exec(tag)?.[1];
|
|
6684
|
+
const text = /text="([^"]*)"/.exec(tag)?.[1];
|
|
6685
|
+
const pick = show ?? text;
|
|
6686
|
+
if (!pick)
|
|
6687
|
+
return "";
|
|
6688
|
+
try {
|
|
6689
|
+
return decodeURIComponent(pick);
|
|
6690
|
+
} catch {
|
|
6691
|
+
return pick;
|
|
6692
|
+
}
|
|
6693
|
+
}
|
|
6694
|
+
function stripInteractionTags(text) {
|
|
6695
|
+
return text.replace(INTERACTION_TAG, (m) => tagFallback(m));
|
|
6696
|
+
}
|
|
6697
|
+
var NOTICE = {
|
|
6698
|
+
reaperExpired: () => `⚠️ 检测到一个卡死的回合(长时间无进展),已自动清理;结果可点下面的指令开新会话重试:
|
|
6699
|
+
` + cmdInput("/new", "\uD83C\uDD95 新会话")
|
|
6700
|
+
};
|
|
6701
|
+
|
|
6702
|
+
// src/core/cron-reminders.ts
|
|
6703
|
+
function parseCronReminder(text, now) {
|
|
6704
|
+
const m = /QQBOT_PAYLOAD:\s*(\{[\s\S]*?\})/.exec(text);
|
|
6705
|
+
if (!m)
|
|
6706
|
+
return null;
|
|
6707
|
+
let payload;
|
|
6708
|
+
try {
|
|
6709
|
+
payload = JSON.parse(m[1]);
|
|
6710
|
+
} catch {
|
|
6711
|
+
return null;
|
|
6712
|
+
}
|
|
6713
|
+
if (payload?.type !== "cron_reminder")
|
|
6714
|
+
return null;
|
|
6715
|
+
const reminderText = typeof payload.text === "string" ? payload.text.trim().slice(0, 200) : "";
|
|
6716
|
+
if (!reminderText)
|
|
6717
|
+
return null;
|
|
6718
|
+
const atMs = resolveAt(payload.at, now);
|
|
6719
|
+
if (atMs === null || atMs <= now + 5000)
|
|
6720
|
+
return null;
|
|
6721
|
+
const cleanedText = text.split(`
|
|
6722
|
+
`).filter((line) => !line.includes("QQBOT_PAYLOAD:")).join(`
|
|
6723
|
+
`).replace(/\n{3,}/g, `
|
|
6724
|
+
|
|
6725
|
+
`).trim();
|
|
6726
|
+
return { atMs, reminderText, cleanedText };
|
|
6727
|
+
}
|
|
6728
|
+
function resolveAt(at, now) {
|
|
6729
|
+
if (typeof at === "number" && Number.isFinite(at)) {
|
|
6730
|
+
return at > 1000000000000 ? at : null;
|
|
6731
|
+
}
|
|
6732
|
+
if (typeof at !== "string")
|
|
6733
|
+
return null;
|
|
6734
|
+
const rel = /^in\s+(\d+)\s*([mhd])$/i.exec(at.trim());
|
|
6735
|
+
if (rel) {
|
|
6736
|
+
const n = Number(rel[1]);
|
|
6737
|
+
const unit = { m: 60000, h: 3600000, d: 86400000 }[rel[2].toLowerCase()] ?? 0;
|
|
6738
|
+
return now + n * unit;
|
|
6739
|
+
}
|
|
6740
|
+
const t = Date.parse(at);
|
|
6741
|
+
return Number.isNaN(t) ? null : t;
|
|
6742
|
+
}
|
|
6743
|
+
|
|
6744
|
+
class ReminderScheduler {
|
|
6745
|
+
maxPerUser;
|
|
6746
|
+
pending = new Map;
|
|
6747
|
+
constructor(maxPerUser = 10) {
|
|
6748
|
+
this.maxPerUser = maxPerUser;
|
|
6749
|
+
}
|
|
6750
|
+
schedule(userId, atMs, text, deliver) {
|
|
6751
|
+
if (!userId || !text.trim() || atMs <= Date.now())
|
|
6752
|
+
return false;
|
|
6753
|
+
const set = this.pending.get(userId) ?? new Set;
|
|
6754
|
+
if (set.size >= this.maxPerUser)
|
|
6755
|
+
return false;
|
|
6756
|
+
const timer = setTimeout(() => {
|
|
6757
|
+
set.delete(timer);
|
|
6758
|
+
console.log(`[cron] 提醒到点 user=${userId.slice(0, 8)}… text=${text.slice(0, 30)}`);
|
|
6759
|
+
try {
|
|
6760
|
+
deliver(userId, `⏰ 提醒:${text}`);
|
|
6761
|
+
} catch (error) {
|
|
6762
|
+
console.error("[cron] 提醒投递失败:", error);
|
|
6763
|
+
}
|
|
6764
|
+
}, atMs - Date.now());
|
|
6765
|
+
set.add(timer);
|
|
6766
|
+
this.pending.set(userId, set);
|
|
6767
|
+
return true;
|
|
6768
|
+
}
|
|
6769
|
+
size(userId) {
|
|
6770
|
+
return this.pending.get(userId)?.size ?? 0;
|
|
6771
|
+
}
|
|
6772
|
+
}
|
|
6773
|
+
|
|
6378
6774
|
// src/core/permission.ts
|
|
6379
|
-
import { existsSync as
|
|
6775
|
+
import { existsSync as existsSync9, readFileSync as readFileSync10, writeFileSync as writeFileSync8 } from "fs";
|
|
6380
6776
|
|
|
6381
6777
|
// src/core/util.ts
|
|
6382
6778
|
function truncate(value, max) {
|
|
@@ -6439,8 +6835,8 @@ function classifyApprovalReplyError(error) {
|
|
|
6439
6835
|
var PENDING_PERM_FILE = storageFile("pending-permissions.json");
|
|
6440
6836
|
function loadPendingPermMap(file = PENDING_PERM_FILE) {
|
|
6441
6837
|
try {
|
|
6442
|
-
if (
|
|
6443
|
-
const raw =
|
|
6838
|
+
if (existsSync9(file)) {
|
|
6839
|
+
const raw = readFileSync10(file, "utf-8");
|
|
6444
6840
|
const obj = JSON.parse(raw);
|
|
6445
6841
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
6446
6842
|
const out = {};
|
|
@@ -6756,6 +7152,10 @@ function formatPermissionPrompt(request, mainSessionId, origin) {
|
|
|
6756
7152
|
for (const r of resources)
|
|
6757
7153
|
lines.push(` ${truncate(r, 300)}`);
|
|
6758
7154
|
}
|
|
7155
|
+
if (request.save && request.save.length > 0) {
|
|
7156
|
+
const saves = request.save.slice(0, 3).map((s) => truncate(s, 120));
|
|
7157
|
+
lines.push(`总是允许将保存:${saves.join(";")}`);
|
|
7158
|
+
}
|
|
6759
7159
|
if (request.message)
|
|
6760
7160
|
lines.push(`说明:${truncate(request.message, 300)}`);
|
|
6761
7161
|
lines.push("");
|
|
@@ -6766,13 +7166,49 @@ function formatPermissionPrompt(request, mainSessionId, origin) {
|
|
|
6766
7166
|
}
|
|
6767
7167
|
|
|
6768
7168
|
// src/core/delivery.ts
|
|
6769
|
-
import { existsSync as
|
|
6770
|
-
import { join as
|
|
7169
|
+
import { existsSync as existsSync10, readFileSync as readFileSync11, writeFileSync as writeFileSync9, mkdirSync as mkdirSync8, renameSync as renameSync3, openSync, closeSync, unlinkSync as unlinkSync3, statSync as statSync5 } from "fs";
|
|
7170
|
+
import { join as join9 } from "path";
|
|
6771
7171
|
import { createHash } from "node:crypto";
|
|
6772
7172
|
|
|
7173
|
+
// src/core/outbound-sanitize.ts
|
|
7174
|
+
var BLOCK_PATTERNS = [
|
|
7175
|
+
/<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi,
|
|
7176
|
+
/<previous_response\b[^>]*>[\s\S]*?<\/previous_response>/gi,
|
|
7177
|
+
/`think`[\s\S]*?`\/think`/gi,
|
|
7178
|
+
/<thinking\b[^>]*>[\s\S]*?<\/thinking>/gi,
|
|
7179
|
+
/<\s*\/?\s*(?:system-reminder|previous_response)\b[^>]*\/?\s*>/gi,
|
|
7180
|
+
/<\s*\/?\s*think(?:ing)?\b[^>]*\/?\s*>/gi
|
|
7181
|
+
];
|
|
7182
|
+
function stripScaffolding(text) {
|
|
7183
|
+
let result = text;
|
|
7184
|
+
for (const re of BLOCK_PATTERNS) {
|
|
7185
|
+
result = result.replace(re, "");
|
|
7186
|
+
}
|
|
7187
|
+
return result.replace(/\n{3,}/g, `
|
|
7188
|
+
|
|
7189
|
+
`);
|
|
7190
|
+
}
|
|
7191
|
+
|
|
6773
7192
|
// src/qq/sender.ts
|
|
7193
|
+
var PUNCT_BACKSLASH = /\\(?=[!-/:-@[-`{-~])/g;
|
|
7194
|
+
var INLINE_CODE_SPLIT = /(`[^`]*`)/g;
|
|
7195
|
+
function escapeLineBackslashes(line) {
|
|
7196
|
+
return line.split(INLINE_CODE_SPLIT).map((seg, i) => i % 2 === 1 ? seg : seg.replace(PUNCT_BACKSLASH, "\\\\")).join("");
|
|
7197
|
+
}
|
|
6774
7198
|
function formatForQQMarkdown(text) {
|
|
6775
|
-
|
|
7199
|
+
const sanitized = stripScaffolding(text);
|
|
7200
|
+
const normalized = normalizeOutboundMarkdown(sanitized.trim());
|
|
7201
|
+
let inFence = false;
|
|
7202
|
+
return normalized.split(`
|
|
7203
|
+
`).map((line) => {
|
|
7204
|
+
const f = matchFence(line);
|
|
7205
|
+
if (f) {
|
|
7206
|
+
inFence = !inFence;
|
|
7207
|
+
return line;
|
|
7208
|
+
}
|
|
7209
|
+
return inFence ? line : escapeLineBackslashes(line);
|
|
7210
|
+
}).join(`
|
|
7211
|
+
`);
|
|
6776
7212
|
}
|
|
6777
7213
|
function formatForQQ(text) {
|
|
6778
7214
|
const codeBlocks = [];
|
|
@@ -6785,6 +7221,17 @@ function formatForQQ(text) {
|
|
|
6785
7221
|
for (let i = 0;i < codeBlocks.length; i++) {
|
|
6786
7222
|
processed = processed.replace(`\x00CB${i}\x00`, codeBlocks[i]);
|
|
6787
7223
|
}
|
|
7224
|
+
let inStripFence = false;
|
|
7225
|
+
processed = processed.split(`
|
|
7226
|
+
`).map((line) => {
|
|
7227
|
+
const f = matchFence(line);
|
|
7228
|
+
if (f) {
|
|
7229
|
+
inStripFence = !inStripFence;
|
|
7230
|
+
return line;
|
|
7231
|
+
}
|
|
7232
|
+
return inStripFence ? line : stripInteractionTags(line);
|
|
7233
|
+
}).join(`
|
|
7234
|
+
`);
|
|
6788
7235
|
return processed.trim();
|
|
6789
7236
|
}
|
|
6790
7237
|
function convertTables(text) {
|
|
@@ -7116,8 +7563,8 @@ function extractEmbeddedQuote(event) {
|
|
|
7116
7563
|
var DEFAULT_QUOTA_FILE = storageFile("quota.json");
|
|
7117
7564
|
function loadQuotaMap(file) {
|
|
7118
7565
|
try {
|
|
7119
|
-
if (
|
|
7120
|
-
const raw =
|
|
7566
|
+
if (existsSync10(file)) {
|
|
7567
|
+
const raw = readFileSync11(file, "utf-8");
|
|
7121
7568
|
const obj = JSON.parse(raw);
|
|
7122
7569
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
7123
7570
|
const out = {};
|
|
@@ -7194,9 +7641,9 @@ function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TT
|
|
|
7194
7641
|
function loadDeliveryAttempts() {
|
|
7195
7642
|
const out = new Map;
|
|
7196
7643
|
try {
|
|
7197
|
-
if (!
|
|
7644
|
+
if (!existsSync10(deliveryDedupeFile()))
|
|
7198
7645
|
return out;
|
|
7199
|
-
const raw = JSON.parse(
|
|
7646
|
+
const raw = JSON.parse(readFileSync11(deliveryDedupeFile(), "utf-8"));
|
|
7200
7647
|
const now = Date.now();
|
|
7201
7648
|
for (const entry of raw) {
|
|
7202
7649
|
if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
|
|
@@ -7208,7 +7655,7 @@ function loadDeliveryAttempts() {
|
|
|
7208
7655
|
}
|
|
7209
7656
|
function saveDeliveryAttempts(entries) {
|
|
7210
7657
|
const raw = [...entries.values()].filter((entry) => Date.now() - entry.at < DELIVERY_DEDUPE_TTL_MS).map((entry) => ({ key: entry.text, at: entry.at }));
|
|
7211
|
-
mkdirSync8(
|
|
7658
|
+
mkdirSync8(join9(deliveryDedupeFile(), ".."), { recursive: true });
|
|
7212
7659
|
const tmp = `${deliveryDedupeFile()}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
7213
7660
|
try {
|
|
7214
7661
|
writeFileSync9(tmp, JSON.stringify(raw, null, 2), { mode: 384 });
|
|
@@ -7224,7 +7671,7 @@ var DELIVERY_LOCK_STALE_MS = 30000;
|
|
|
7224
7671
|
var DELIVERY_LOCK_WAIT_MS = 5000;
|
|
7225
7672
|
var deliverySleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
7226
7673
|
function withDeliveryLock(fn) {
|
|
7227
|
-
mkdirSync8(
|
|
7674
|
+
mkdirSync8(join9(deliveryDedupeFile(), ".."), { recursive: true });
|
|
7228
7675
|
const lockPath = `${deliveryDedupeFile()}.lock`;
|
|
7229
7676
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
7230
7677
|
const deadline = Date.now() + DELIVERY_LOCK_WAIT_MS;
|
|
@@ -7239,7 +7686,7 @@ function withDeliveryLock(fn) {
|
|
|
7239
7686
|
break;
|
|
7240
7687
|
} catch (error) {
|
|
7241
7688
|
try {
|
|
7242
|
-
if (Date.now() -
|
|
7689
|
+
if (Date.now() - statSync5(lockPath).mtimeMs > DELIVERY_LOCK_STALE_MS)
|
|
7243
7690
|
unlinkSync3(lockPath);
|
|
7244
7691
|
} catch {}
|
|
7245
7692
|
if (Date.now() >= deadline)
|
|
@@ -7251,7 +7698,7 @@ function withDeliveryLock(fn) {
|
|
|
7251
7698
|
return fn();
|
|
7252
7699
|
} finally {
|
|
7253
7700
|
try {
|
|
7254
|
-
if (
|
|
7701
|
+
if (readFileSync11(lockPath, "utf-8") === token)
|
|
7255
7702
|
unlinkSync3(lockPath);
|
|
7256
7703
|
} catch {}
|
|
7257
7704
|
}
|
|
@@ -7494,12 +7941,12 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
|
|
|
7494
7941
|
// src/core/outbox.ts
|
|
7495
7942
|
import {
|
|
7496
7943
|
closeSync as closeSync2,
|
|
7497
|
-
existsSync as
|
|
7944
|
+
existsSync as existsSync11,
|
|
7498
7945
|
mkdirSync as mkdirSync9,
|
|
7499
7946
|
openSync as openSync2,
|
|
7500
|
-
readFileSync as
|
|
7947
|
+
readFileSync as readFileSync12,
|
|
7501
7948
|
renameSync as renameSync4,
|
|
7502
|
-
statSync as
|
|
7949
|
+
statSync as statSync6,
|
|
7503
7950
|
unlinkSync as unlinkSync4,
|
|
7504
7951
|
writeFileSync as writeFileSync10
|
|
7505
7952
|
} from "node:fs";
|
|
@@ -7552,9 +7999,9 @@ function atomicWrite(filePath, document) {
|
|
|
7552
7999
|
}
|
|
7553
8000
|
}
|
|
7554
8001
|
function readDocument(filePath, now) {
|
|
7555
|
-
if (!
|
|
8002
|
+
if (!existsSync11(filePath))
|
|
7556
8003
|
return { version: 1, entries: [] };
|
|
7557
|
-
const raw = JSON.parse(
|
|
8004
|
+
const raw = JSON.parse(readFileSync12(filePath, "utf8"));
|
|
7558
8005
|
if (Array.isArray(raw)) {
|
|
7559
8006
|
return { version: 1, entries: pruneOutboxEntries(raw, now) };
|
|
7560
8007
|
}
|
|
@@ -7600,7 +8047,7 @@ function createOutbox(options = {}) {
|
|
|
7600
8047
|
break;
|
|
7601
8048
|
} catch (error) {
|
|
7602
8049
|
try {
|
|
7603
|
-
if (Date.now() -
|
|
8050
|
+
if (Date.now() - statSync6(lockPath).mtimeMs > lockStaleMs)
|
|
7604
8051
|
unlinkSync4(lockPath);
|
|
7605
8052
|
} catch {}
|
|
7606
8053
|
if (Date.now() >= deadline)
|
|
@@ -7612,7 +8059,7 @@ function createOutbox(options = {}) {
|
|
|
7612
8059
|
return fn();
|
|
7613
8060
|
} finally {
|
|
7614
8061
|
try {
|
|
7615
|
-
if (
|
|
8062
|
+
if (readFileSync12(lockPath, "utf8") === token)
|
|
7616
8063
|
unlinkSync4(lockPath);
|
|
7617
8064
|
} catch {}
|
|
7618
8065
|
}
|
|
@@ -8005,12 +8452,12 @@ function handleApprovalInteraction(event, gate) {
|
|
|
8005
8452
|
// src/core/form-journal.ts
|
|
8006
8453
|
import {
|
|
8007
8454
|
closeSync as closeSync3,
|
|
8008
|
-
existsSync as
|
|
8455
|
+
existsSync as existsSync12,
|
|
8009
8456
|
mkdirSync as mkdirSync10,
|
|
8010
8457
|
openSync as openSync3,
|
|
8011
|
-
readFileSync as
|
|
8458
|
+
readFileSync as readFileSync13,
|
|
8012
8459
|
renameSync as renameSync5,
|
|
8013
|
-
statSync as
|
|
8460
|
+
statSync as statSync7,
|
|
8014
8461
|
unlinkSync as unlinkSync5,
|
|
8015
8462
|
writeFileSync as writeFileSync11
|
|
8016
8463
|
} from "fs";
|
|
@@ -8073,9 +8520,9 @@ function snapshot(entry) {
|
|
|
8073
8520
|
function createFormJournal(path = defaultFormJournalPath()) {
|
|
8074
8521
|
function read() {
|
|
8075
8522
|
try {
|
|
8076
|
-
if (!
|
|
8523
|
+
if (!existsSync12(path))
|
|
8077
8524
|
return [];
|
|
8078
|
-
const raw = JSON.parse(
|
|
8525
|
+
const raw = JSON.parse(readFileSync13(path, "utf-8"));
|
|
8079
8526
|
const values = Array.isArray(raw) ? raw : raw?.version === 1 && Array.isArray(raw.entries) ? raw.entries : [];
|
|
8080
8527
|
const byUser = new Map;
|
|
8081
8528
|
for (const value of values) {
|
|
@@ -8122,7 +8569,7 @@ function createFormJournal(path = defaultFormJournalPath()) {
|
|
|
8122
8569
|
break;
|
|
8123
8570
|
} catch (error) {
|
|
8124
8571
|
try {
|
|
8125
|
-
if (Date.now() -
|
|
8572
|
+
if (Date.now() - statSync7(lockPath).mtimeMs > LOCK_STALE_MS)
|
|
8126
8573
|
unlinkSync5(lockPath);
|
|
8127
8574
|
} catch {}
|
|
8128
8575
|
if (Date.now() >= deadline) {
|
|
@@ -8135,7 +8582,7 @@ function createFormJournal(path = defaultFormJournalPath()) {
|
|
|
8135
8582
|
return fn();
|
|
8136
8583
|
} finally {
|
|
8137
8584
|
try {
|
|
8138
|
-
if (
|
|
8585
|
+
if (readFileSync13(lockPath, "utf-8") === token)
|
|
8139
8586
|
unlinkSync5(lockPath);
|
|
8140
8587
|
} catch {}
|
|
8141
8588
|
}
|
|
@@ -8702,8 +9149,8 @@ function createFormBridge(deps) {
|
|
|
8702
9149
|
}
|
|
8703
9150
|
|
|
8704
9151
|
// src/core/inflight-journal.ts
|
|
8705
|
-
import { existsSync as
|
|
8706
|
-
import { join as
|
|
9152
|
+
import { existsSync as existsSync13, readFileSync as readFileSync14, writeFileSync as writeFileSync12, mkdirSync as mkdirSync11, renameSync as renameSync6, openSync as openSync4, closeSync as closeSync4, unlinkSync as unlinkSync6, statSync as statSync8 } from "fs";
|
|
9153
|
+
import { join as join10 } from "path";
|
|
8707
9154
|
|
|
8708
9155
|
// src/core/inbound-dedupe.ts
|
|
8709
9156
|
import { createHash as createHash2 } from "crypto";
|
|
@@ -8742,8 +9189,8 @@ function load(file) {
|
|
|
8742
9189
|
let entries = [];
|
|
8743
9190
|
const path = journalPath(file);
|
|
8744
9191
|
try {
|
|
8745
|
-
if (
|
|
8746
|
-
const raw = JSON.parse(
|
|
9192
|
+
if (existsSync13(path)) {
|
|
9193
|
+
const raw = JSON.parse(readFileSync14(path, "utf-8"));
|
|
8747
9194
|
if (Array.isArray(raw))
|
|
8748
9195
|
entries = raw;
|
|
8749
9196
|
}
|
|
@@ -8754,7 +9201,7 @@ function load(file) {
|
|
|
8754
9201
|
}
|
|
8755
9202
|
function save(file, entries) {
|
|
8756
9203
|
const path = journalPath(file);
|
|
8757
|
-
mkdirSync11(
|
|
9204
|
+
mkdirSync11(join10(path, ".."), { recursive: true });
|
|
8758
9205
|
const retained = pruneInflightEntries(entries);
|
|
8759
9206
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
8760
9207
|
try {
|
|
@@ -8772,7 +9219,7 @@ var JOURNAL_LOCK_WAIT_MS = 5000;
|
|
|
8772
9219
|
var sleepArray3 = new Int32Array(new SharedArrayBuffer(4));
|
|
8773
9220
|
function withJournalLock(file, fn) {
|
|
8774
9221
|
const path = journalPath(file);
|
|
8775
|
-
mkdirSync11(
|
|
9222
|
+
mkdirSync11(join10(path, ".."), { recursive: true });
|
|
8776
9223
|
const lockPath = `${path}.lock`;
|
|
8777
9224
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
8778
9225
|
const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
|
|
@@ -8787,7 +9234,7 @@ function withJournalLock(file, fn) {
|
|
|
8787
9234
|
break;
|
|
8788
9235
|
} catch (error) {
|
|
8789
9236
|
try {
|
|
8790
|
-
if (Date.now() -
|
|
9237
|
+
if (Date.now() - statSync8(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
|
|
8791
9238
|
unlinkSync6(lockPath);
|
|
8792
9239
|
} catch {}
|
|
8793
9240
|
if (Date.now() >= deadline) {
|
|
@@ -8800,7 +9247,7 @@ function withJournalLock(file, fn) {
|
|
|
8800
9247
|
return fn();
|
|
8801
9248
|
} finally {
|
|
8802
9249
|
try {
|
|
8803
|
-
if (
|
|
9250
|
+
if (readFileSync14(lockPath, "utf-8") === token)
|
|
8804
9251
|
unlinkSync6(lockPath);
|
|
8805
9252
|
} catch {}
|
|
8806
9253
|
}
|
|
@@ -9089,6 +9536,7 @@ var REASON_LABEL = {
|
|
|
9089
9536
|
dropped: "已删除",
|
|
9090
9537
|
blocked: "被阻塞",
|
|
9091
9538
|
superseded: "被新回合取代",
|
|
9539
|
+
steered: "已并入当前任务",
|
|
9092
9540
|
expired: "已过期",
|
|
9093
9541
|
redispatch: "重启重派",
|
|
9094
9542
|
manual: "人工结清"
|
|
@@ -9499,6 +9947,105 @@ function formatStatusLine(view) {
|
|
|
9499
9947
|
return `队列/台账:排队 ${view.counts.queued} · 在途 ${view.counts.inflight} · 执行中 ${view.counts.running} · 孤儿 ${view.counts.orphan} · 最近拒绝 ${view.counts.rejected}`;
|
|
9500
9948
|
}
|
|
9501
9949
|
|
|
9950
|
+
// src/core/watchdog.ts
|
|
9951
|
+
init_log_rotate();
|
|
9952
|
+
|
|
9953
|
+
// src/core/instance-lock.ts
|
|
9954
|
+
import { openSync as openSync5, readFileSync as readFileSync15, readdirSync as readdirSync2, writeFileSync as writeFileSync13, closeSync as closeSync5, unlinkSync as unlinkSync7, statSync as statSync9, utimesSync, mkdirSync as mkdirSync12 } from "fs";
|
|
9955
|
+
import { join as join11 } from "path";
|
|
9956
|
+
import { homedir as homedir6 } from "os";
|
|
9957
|
+
var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
|
|
9958
|
+
var LOCK_STALE_MS2 = 30000;
|
|
9959
|
+
var LOCK_UPDATE_MS = 1e4;
|
|
9960
|
+
var LOCK_RETRY_MS = 5000;
|
|
9961
|
+
var LOCK_SELF_CHECK_MS = 60000;
|
|
9962
|
+
function lockPathOf(appId) {
|
|
9963
|
+
return join11(homedir6(), ".openqq", `openqq-${appId}.lock`);
|
|
9964
|
+
}
|
|
9965
|
+
function touch(path) {
|
|
9966
|
+
const now = new Date;
|
|
9967
|
+
utimesSync(path, now, now);
|
|
9968
|
+
}
|
|
9969
|
+
function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
|
|
9970
|
+
const heartbeatMs = opts?.heartbeatMs ?? LOCK_UPDATE_MS;
|
|
9971
|
+
const selfCheckMs = opts?.selfCheckMs ?? LOCK_SELF_CHECK_MS;
|
|
9972
|
+
try {
|
|
9973
|
+
mkdirSync12(join11(path, ".."), { recursive: true });
|
|
9974
|
+
const fd = openSync5(path, "wx");
|
|
9975
|
+
writeFileSync13(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
|
|
9976
|
+
closeSync5(fd);
|
|
9977
|
+
} catch {
|
|
9978
|
+
try {
|
|
9979
|
+
const age = Date.now() - statSync9(path).mtimeMs;
|
|
9980
|
+
if (age <= staleMs)
|
|
9981
|
+
return null;
|
|
9982
|
+
unlinkSync7(path);
|
|
9983
|
+
const fd = openSync5(path, "wx");
|
|
9984
|
+
writeFileSync13(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
|
|
9985
|
+
closeSync5(fd);
|
|
9986
|
+
console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
|
|
9987
|
+
} catch {
|
|
9988
|
+
return null;
|
|
9989
|
+
}
|
|
9990
|
+
}
|
|
9991
|
+
const heartbeat = setInterval(() => {
|
|
9992
|
+
try {
|
|
9993
|
+
touch(path);
|
|
9994
|
+
} catch {}
|
|
9995
|
+
}, heartbeatMs);
|
|
9996
|
+
heartbeat.unref?.();
|
|
9997
|
+
const selfCheck = setInterval(() => {
|
|
9998
|
+
try {
|
|
9999
|
+
const holder = JSON.parse(readFileSync15(path, "utf-8")).pid;
|
|
10000
|
+
if (holder === process.pid)
|
|
10001
|
+
return;
|
|
10002
|
+
try {
|
|
10003
|
+
process.kill(holder, 0);
|
|
10004
|
+
const lockFresh = Date.now() - statSync9(path).mtimeMs <= LOCK_STALE_MS2;
|
|
10005
|
+
if (lockFresh) {
|
|
10006
|
+
console.error(`[instance-lock] 自检:锁已被 pid=${holder} 持有且进程存活(锁新鲜),本实例为残留 believer,自杀退出`);
|
|
10007
|
+
process.exit(1);
|
|
10008
|
+
}
|
|
10009
|
+
console.warn(`[instance-lock] 自检:holder pid=${holder} 存活但锁已陈旧(疑 PID 复用),不自杀,交由 stale 强抢接管`);
|
|
10010
|
+
} catch {}
|
|
10011
|
+
} catch {
|
|
10012
|
+
console.error("[instance-lock] 自检:锁文件已消失(被接管或强抢流程删除),本实例退出");
|
|
10013
|
+
process.exit(1);
|
|
10014
|
+
}
|
|
10015
|
+
}, selfCheckMs);
|
|
10016
|
+
selfCheck.unref?.();
|
|
10017
|
+
let released = false;
|
|
10018
|
+
return {
|
|
10019
|
+
release: () => {
|
|
10020
|
+
if (released)
|
|
10021
|
+
return;
|
|
10022
|
+
released = true;
|
|
10023
|
+
clearInterval(heartbeat);
|
|
10024
|
+
clearInterval(selfCheck);
|
|
10025
|
+
try {
|
|
10026
|
+
unlinkSync7(path);
|
|
10027
|
+
} catch {}
|
|
10028
|
+
}
|
|
10029
|
+
};
|
|
10030
|
+
}
|
|
10031
|
+
function acquireInstanceLock(appId) {
|
|
10032
|
+
return acquireInstanceLockAt(lockPathOf(appId));
|
|
10033
|
+
}
|
|
10034
|
+
function shouldLogStandby(attempt) {
|
|
10035
|
+
return attempt === 0 || attempt % 120 === 0;
|
|
10036
|
+
}
|
|
10037
|
+
async function waitInstanceLock(appId) {
|
|
10038
|
+
for (let attempt = 0;; attempt++) {
|
|
10039
|
+
const lock = acquireInstanceLock(appId);
|
|
10040
|
+
if (lock)
|
|
10041
|
+
return lock;
|
|
10042
|
+
if (shouldLogStandby(attempt)) {
|
|
10043
|
+
console.log(`[instance-lock] 已有实例在运行,本实例待命(每 ${LOCK_RETRY_MS / 1000}s 重试抢锁,日志已节流)`);
|
|
10044
|
+
}
|
|
10045
|
+
await new Promise((r) => setTimeout(r, LOCK_RETRY_MS));
|
|
10046
|
+
}
|
|
10047
|
+
}
|
|
10048
|
+
|
|
9502
10049
|
// src/core/watchdog.ts
|
|
9503
10050
|
var HEARTBEAT_STALE_MS = 5 * 60000;
|
|
9504
10051
|
function isPidAlive(pid) {
|
|
@@ -9590,6 +10137,33 @@ function resolveResumeMax(envValue) {
|
|
|
9590
10137
|
function resumeDecision(resumeCount, max) {
|
|
9591
10138
|
return max > 0 && resumeCount < max ? "resume" : "giveup";
|
|
9592
10139
|
}
|
|
10140
|
+
function resolveBusyMode(envValue) {
|
|
10141
|
+
return envValue?.trim().toLowerCase() === "queue" ? "queue" : "steer";
|
|
10142
|
+
}
|
|
10143
|
+
function buildAmendPrompt(original, amendment) {
|
|
10144
|
+
return `${original}
|
|
10145
|
+
|
|
10146
|
+
【补充指令】${amendment.trim()}`;
|
|
10147
|
+
}
|
|
10148
|
+
function selectAmendEntry(entries, userId, sessionId) {
|
|
10149
|
+
return entries.filter((e) => e.userId === userId && e.sessionId === sessionId && e.promptId && e.text).sort((a, b) => b.at - a.at)[0];
|
|
10150
|
+
}
|
|
10151
|
+
function lastUserMessageId(msgs) {
|
|
10152
|
+
for (let i = msgs.length - 1;i >= 0; i--) {
|
|
10153
|
+
if (msgs[i].type === "user" && msgs[i].id)
|
|
10154
|
+
return msgs[i].id;
|
|
10155
|
+
}
|
|
10156
|
+
return null;
|
|
10157
|
+
}
|
|
10158
|
+
function messageTextOf(m) {
|
|
10159
|
+
const c = m.content;
|
|
10160
|
+
if (typeof c === "string")
|
|
10161
|
+
return c;
|
|
10162
|
+
if (Array.isArray(c)) {
|
|
10163
|
+
return c.map((p) => typeof p === "object" && p !== null && ("text" in p) ? String(p.text ?? "") : "").join("");
|
|
10164
|
+
}
|
|
10165
|
+
return "";
|
|
10166
|
+
}
|
|
9593
10167
|
function streamLiveness(msgs, promptId, baseline, now, deadMs, toolGraceMs = BG_TOOL_GRACE_MS_DEFAULT) {
|
|
9594
10168
|
const turn = turnStateOf(msgs, promptId, baseline);
|
|
9595
10169
|
if (turn.hasIdle)
|
|
@@ -10044,6 +10618,7 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10044
10618
|
console.warn("[bridge] 通知发送失败(不阻断主流程):", toErrorMessage2(error));
|
|
10045
10619
|
}
|
|
10046
10620
|
};
|
|
10621
|
+
const cronScheduler = new ReminderScheduler;
|
|
10047
10622
|
const perm = createPermissionGate({
|
|
10048
10623
|
client,
|
|
10049
10624
|
sendReply,
|
|
@@ -10064,8 +10639,20 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10064
10639
|
safeDeliver,
|
|
10065
10640
|
bgWaits,
|
|
10066
10641
|
busyUsers,
|
|
10067
|
-
settingsFile: storageAppId ? roleFile("settings.json") : undefined
|
|
10642
|
+
settingsFile: storageAppId ? roleFile("settings.json") : undefined,
|
|
10643
|
+
onDigest: (userId, digest) => {
|
|
10644
|
+
const hit = parseCronReminder(digest, Date.now());
|
|
10645
|
+
if (!hit)
|
|
10646
|
+
return digest;
|
|
10647
|
+
registerCron(userId, hit);
|
|
10648
|
+
return hit.cleanedText;
|
|
10649
|
+
}
|
|
10068
10650
|
});
|
|
10651
|
+
function registerCron(userId, hit) {
|
|
10652
|
+
return cronScheduler.schedule(userId, hit.atMs, hit.reminderText, (uid, t) => {
|
|
10653
|
+
safeDeliver(ctxForUser(uid), t).catch(() => {});
|
|
10654
|
+
});
|
|
10655
|
+
}
|
|
10069
10656
|
createNotifySink({
|
|
10070
10657
|
config,
|
|
10071
10658
|
deliver: (ctx, text) => deliver(ctx, text),
|
|
@@ -10443,7 +11030,7 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10443
11030
|
${dec.text}`).catch(() => {});
|
|
10444
11031
|
} else {
|
|
10445
11032
|
inflight.settle(entry.msgId, undefined, "expired");
|
|
10446
|
-
await safeDeliver(ctx,
|
|
11033
|
+
await safeDeliver(ctx, NOTICE.reaperExpired()).catch(() => {});
|
|
10447
11034
|
}
|
|
10448
11035
|
console.log(`[reaper] ${dec.kind} user=${uid.slice(0, 8)}… lane=${shortId(sid)} msg=${shortId(entry.msgId)} age=${Math.round((now - entry.at) / 60000)}m`);
|
|
10449
11036
|
reaperCooldown.set(lane, now + REAPER_LANE_COOLDOWN_MS);
|
|
@@ -10502,6 +11089,136 @@ ${dec.text}`).catch(() => {});
|
|
|
10502
11089
|
`);
|
|
10503
11090
|
}
|
|
10504
11091
|
};
|
|
11092
|
+
async function amendCurrentTurn(userId, amendment) {
|
|
11093
|
+
const add = amendment.trim();
|
|
11094
|
+
if (!add) {
|
|
11095
|
+
return "用法:/amend <补充指令>——打断当前任务,把你的补充并入原指令一起续跑(模型从历史接着做)";
|
|
11096
|
+
}
|
|
11097
|
+
const session = sessions.getSession(userId);
|
|
11098
|
+
const activeLane = [...busyUsers].find((k) => userIdOfLane(k) === userId);
|
|
11099
|
+
if (!session || !activeLane)
|
|
11100
|
+
return "当前没有进行中的任务,直接发消息即可";
|
|
11101
|
+
try {
|
|
11102
|
+
await client.session.prompt({
|
|
11103
|
+
path: { id: session.sessionId },
|
|
11104
|
+
body: { text: `【补充指令】${add}`, delivery: "steer" }
|
|
11105
|
+
});
|
|
11106
|
+
console.log(`[bridge] amend steer 已送达 user=${userId.slice(0, 8)}… session=${shortId(session.sessionId)}`);
|
|
11107
|
+
return "✅ 已把补充送进当前任务(官方 steer 语义:模型把这条指令并入正在跑的回合,完成照常回传)";
|
|
11108
|
+
} catch (error) {
|
|
11109
|
+
console.log(`[bridge] amend steer 被拒,回落 abort+revert 链: ${toErrorMessage2(error)}`);
|
|
11110
|
+
}
|
|
11111
|
+
const entry = selectAmendEntry(inflight.pending(), userId, session.sessionId);
|
|
11112
|
+
if (!entry) {
|
|
11113
|
+
return "找不到可并入的原任务(可能由桌面端发起或已被结清);请用 /cancel 后重发完整指令";
|
|
11114
|
+
}
|
|
11115
|
+
bgWaits.get(session.sessionId)?.cancel();
|
|
11116
|
+
try {
|
|
11117
|
+
await client.session.abort({ path: { id: session.sessionId } });
|
|
11118
|
+
} catch {}
|
|
11119
|
+
inflight.settle(entry.msgId, entry.attemptId, "cancelled");
|
|
11120
|
+
let reverted = false;
|
|
11121
|
+
try {
|
|
11122
|
+
await client.session.revertStage({ path: { id: session.sessionId }, body: { messageID: entry.promptId, files: true } });
|
|
11123
|
+
await client.session.revertCommit({ path: { id: session.sessionId } });
|
|
11124
|
+
reverted = true;
|
|
11125
|
+
} catch (error) {
|
|
11126
|
+
try {
|
|
11127
|
+
await client.session.revertDiscard({ path: { id: session.sessionId } });
|
|
11128
|
+
} catch {}
|
|
11129
|
+
console.log(`[bridge] amend revert 失败,回落读历史续跑 session=${shortId(session.sessionId)}: ${toErrorMessage2(error)}`);
|
|
11130
|
+
}
|
|
11131
|
+
const actx = { ...ctxForUser(userId), msgId: "", content: buildAmendPrompt(entry.text, add) };
|
|
11132
|
+
msgQueue.push(activeLane, userId, session.sessionId, actx);
|
|
11133
|
+
console.log(`[bridge] amend 并入 user=${userId.slice(0, 8)}… lane=${shortId(session.sessionId)} msg=${shortId(entry.msgId)}`);
|
|
11134
|
+
busyUsers.delete(activeLane);
|
|
11135
|
+
drainQueue(userId, session.sessionId);
|
|
11136
|
+
return reverted ? "✅ 已打断并清空该回合(含文件回滚),正带你的补充重新起跑" : "✅ 已打断当前任务,正把你的补充并入原指令续跑(模型从历史接着做,完成自动回复)";
|
|
11137
|
+
}
|
|
11138
|
+
async function undoLastTurn(userId) {
|
|
11139
|
+
const session = sessions.getSession(userId);
|
|
11140
|
+
if (!session)
|
|
11141
|
+
return "没有绑定的会话,无事可撤销";
|
|
11142
|
+
if ([...busyUsers].some((k) => userIdOfLane(k) === userId)) {
|
|
11143
|
+
return "当前有任务在跑——官方语义运行中不可回滚;请先等它完成,或 /cancel 后再 /undo";
|
|
11144
|
+
}
|
|
11145
|
+
let msgs = [];
|
|
11146
|
+
try {
|
|
11147
|
+
msgs = (await client.session.messages({ path: { id: session.sessionId }, query: { limit: 50 } })).data ?? [];
|
|
11148
|
+
} catch (error) {
|
|
11149
|
+
return `读取会话失败:${toErrorMessage2(error)}`;
|
|
11150
|
+
}
|
|
11151
|
+
const boundary = lastUserMessageId(msgs);
|
|
11152
|
+
if (!boundary)
|
|
11153
|
+
return "会话里没有可撤销的用户消息";
|
|
11154
|
+
const removed = msgs.find((m) => m.id === boundary);
|
|
11155
|
+
const removedText = messageTextOf(removed ?? {}).trim();
|
|
11156
|
+
try {
|
|
11157
|
+
await client.session.revertStage({ path: { id: session.sessionId }, body: { messageID: boundary, files: true } });
|
|
11158
|
+
await client.session.revertCommit({ path: { id: session.sessionId } });
|
|
11159
|
+
} catch (error) {
|
|
11160
|
+
try {
|
|
11161
|
+
await client.session.revertDiscard({ path: { id: session.sessionId } });
|
|
11162
|
+
} catch {}
|
|
11163
|
+
return `撤销失败:${toErrorMessage2(error)}(引擎拒绝或快照缺失;会话内容未改动)`;
|
|
11164
|
+
}
|
|
11165
|
+
console.log(`[bridge] undo 已回滚 user=${userId.slice(0, 8)}… session=${shortId(session.sessionId)} boundary=${shortId(boundary)}`);
|
|
11166
|
+
const box = removedText ? `被撤回的指令:「${removedText.length > 80 ? `${removedText.slice(0, 80)}…` : removedText}」
|
|
11167
|
+
改好后重新发送即可,或 /amend <修改点> 带修改重跑。` : "改好后重新发送即可。";
|
|
11168
|
+
return `↩️ 已撤销上一回合(该回合改动的文件已一并恢复)。
|
|
11169
|
+
${box}`;
|
|
11170
|
+
}
|
|
11171
|
+
async function enqueueExplicit(ctx, text) {
|
|
11172
|
+
const session = sessions.getSession(ctx.userId);
|
|
11173
|
+
const sid = session?.sessionId;
|
|
11174
|
+
if (!sid)
|
|
11175
|
+
return "没有绑定的会话,请先发消息建立会话再排队";
|
|
11176
|
+
const lane = laneKeyOf(ctx.userId, sid);
|
|
11177
|
+
const actx = { ...ctx, msgId: "", content: text };
|
|
11178
|
+
const queued = msgQueue.push(lane, ctx.userId, sid, actx);
|
|
11179
|
+
if (!queued)
|
|
11180
|
+
return "队列已满,请等当前任务完成或 /queue clear 后重试";
|
|
11181
|
+
console.log(`[queue] 显性入队 user=${ctx.userId.slice(0, 8)}… qid=${queued.job.id} ahead=${queued.ahead}`);
|
|
11182
|
+
drainQueue(ctx.userId, sid);
|
|
11183
|
+
if (queued.ahead === 0 && !busyUsers.has(lane)) {
|
|
11184
|
+
return `\uD83D\uDCE5 已入队 #${queued.job.id},当前空闲,立即执行`;
|
|
11185
|
+
}
|
|
11186
|
+
return `\uD83D\uDCE5 已排队 #${queued.job.id}(第 ${queued.ahead + 1} 位),当前任务结束后自动执行`;
|
|
11187
|
+
}
|
|
11188
|
+
async function runEngineCommand(userId, name, text) {
|
|
11189
|
+
const session = sessions.getSession(userId);
|
|
11190
|
+
if (!session)
|
|
11191
|
+
return "没有绑定的会话;先在 QQ 里发一条消息建立会话";
|
|
11192
|
+
try {
|
|
11193
|
+
const res = await client.session.command({
|
|
11194
|
+
path: { id: session.sessionId },
|
|
11195
|
+
body: { name, text }
|
|
11196
|
+
});
|
|
11197
|
+
const reply = res?.data?.text ?? res?.text ?? res?.data?.message ?? res?.message;
|
|
11198
|
+
if (reply)
|
|
11199
|
+
return reply;
|
|
11200
|
+
if (name === "goal") {
|
|
11201
|
+
return "✅ goal 已执行(引擎无文本回执)。查状态再发 /goal;控制用 /goal pause|resume|clear。设定目标后会话自主续跑,进展会以普通回复推送到这里";
|
|
11202
|
+
}
|
|
11203
|
+
return `✅ /${name} 已执行(引擎无文本回执)`;
|
|
11204
|
+
} catch (error) {
|
|
11205
|
+
const msg = toErrorMessage2(error);
|
|
11206
|
+
if (name === "goal") {
|
|
11207
|
+
const full = error.body ?? msg;
|
|
11208
|
+
const trimmed = full.trim();
|
|
11209
|
+
const jsonText = trimmed.startsWith("{") ? trimmed : /\{[\s\S]*"message"[\s\S]*\}/.exec(full)?.[0] ?? "";
|
|
11210
|
+
if (jsonText) {
|
|
11211
|
+
try {
|
|
11212
|
+
const j = JSON.parse(jsonText);
|
|
11213
|
+
if (j.message)
|
|
11214
|
+
return `\uD83D\uDCCB 目标状态(goal ${j.command ?? ""}):
|
|
11215
|
+
${j.message}`;
|
|
11216
|
+
} catch {}
|
|
11217
|
+
}
|
|
11218
|
+
}
|
|
11219
|
+
return `引擎命令执行失败(/goal 需 OpenCode ≥ 2.2.1):${msg}`;
|
|
11220
|
+
}
|
|
11221
|
+
}
|
|
10505
11222
|
const commandContext = {
|
|
10506
11223
|
config,
|
|
10507
11224
|
client,
|
|
@@ -10513,7 +11230,11 @@ ${dec.text}`).catch(() => {});
|
|
|
10513
11230
|
queue: queueApi,
|
|
10514
11231
|
ledger: ledgerApi,
|
|
10515
11232
|
progress: progressApi,
|
|
10516
|
-
stopAll: stopAllForUser
|
|
11233
|
+
stopAll: stopAllForUser,
|
|
11234
|
+
amend: amendCurrentTurn,
|
|
11235
|
+
undo: undoLastTurn,
|
|
11236
|
+
enqueue: enqueueExplicit,
|
|
11237
|
+
engineCommand: runEngineCommand
|
|
10517
11238
|
};
|
|
10518
11239
|
if (config.allowedUsers.length === 0) {
|
|
10519
11240
|
console.warn("[security] ALLOWED_USERS 为空 → 所有消息将被拒绝(fail-closed);请在 ~/.openqq/.env 配置白名单");
|
|
@@ -10626,6 +11347,24 @@ ${dec.text}`).catch(() => {});
|
|
|
10626
11347
|
}
|
|
10627
11348
|
}
|
|
10628
11349
|
if (busyUsers.has(lane)) {
|
|
11350
|
+
if (resolveBusyMode(process.env.QQ_BUSY_DEFAULT) === "steer" && !ctx.attachments?.length) {
|
|
11351
|
+
try {
|
|
11352
|
+
const sidForSteer = anchorSid ?? sessions.getSession(ctx.userId)?.sessionId;
|
|
11353
|
+
if (sidForSteer) {
|
|
11354
|
+
await client.session.prompt({
|
|
11355
|
+
path: { id: sidForSteer },
|
|
11356
|
+
body: { text: ctx.content, delivery: "steer" }
|
|
11357
|
+
});
|
|
11358
|
+
if (ctx.msgId)
|
|
11359
|
+
inflight.settle(ctx.msgId, undefined, "steered");
|
|
11360
|
+
console.log(`[bridge] 忙时 steer 并入 lane=${shortId(sidForSteer)} msg=${shortId(ctx.msgId)}`);
|
|
11361
|
+
await notifyUser(ctx, "\uD83D\uDD04 已并入当前任务(官方 steer 语义,默认行为;想排队改 ~/.openqq/.env 的 QQ_BUSY_DEFAULT=queue)");
|
|
11362
|
+
return;
|
|
11363
|
+
}
|
|
11364
|
+
} catch (error) {
|
|
11365
|
+
console.log(`[bridge] 忙时 steer 失败改排队 msg=${shortId(ctx.msgId)}: ${toErrorMessage2(error)}`);
|
|
11366
|
+
}
|
|
11367
|
+
}
|
|
10629
11368
|
if (ctx.attachments?.length && !ctx.preparedAttachments) {
|
|
10630
11369
|
ctx.preparedAttachments = await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
|
|
10631
11370
|
}
|
|
@@ -10642,7 +11381,7 @@ ${dec.text}`).catch(() => {});
|
|
|
10642
11381
|
}
|
|
10643
11382
|
console.log(`[queue] enqueue user=${ctx.userId.slice(0, 8)}… lane=${anchorSid ? shortId(anchorSid) : "∅"} qid=${queued.job.id} msg=${shortId(ctx.msgId)} ahead=${queued.ahead} size=${msgQueue.size(lane)}/${QUEUE_MAX}`);
|
|
10644
11383
|
await notifyUser(ctx, `已排队 #${queued.job.id}(第 ${queued.ahead + 1} 位${queued.ahead > 0 ? `,前面还有 ${queued.ahead} 条` : ""}),当前任务结束后自动执行。
|
|
10645
|
-
发 /queue 查看队列,/cancel
|
|
11384
|
+
发 /queue 查看队列,/cancel 可中止当前任务并清空队列;想立刻把新消息并进当前任务:/amend <补充>(打断并以原指令+补充续跑)。`);
|
|
10646
11385
|
return;
|
|
10647
11386
|
}
|
|
10648
11387
|
activeIntents.set(lane, intentKey);
|
|
@@ -10741,8 +11480,15 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10741
11480
|
await safeDeliver(ctx, `⚠️ 发送文件失败(${p}):${error instanceof Error ? error.message : error}`);
|
|
10742
11481
|
}
|
|
10743
11482
|
}
|
|
10744
|
-
|
|
10745
|
-
|
|
11483
|
+
let outboundText = extracted.text;
|
|
11484
|
+
const cronHit = parseCronReminder(extracted.text, Date.now());
|
|
11485
|
+
if (cronHit) {
|
|
11486
|
+
const okCron = registerCron(ctx.userId, cronHit);
|
|
11487
|
+
const when = new Date(cronHit.atMs).toLocaleString("zh-CN", { hour12: false });
|
|
11488
|
+
outboundText = cronHit.cleanedText || (okCron ? `⏰ 好的,已设置提醒(${when}):${cronHit.reminderText}` : "⚠️ 提醒设置失败(同时在册超限),请重试");
|
|
11489
|
+
}
|
|
11490
|
+
if (outboundText.trim())
|
|
11491
|
+
turnDelivered = await safeDeliver(ctx, redactSecrets(outboundText));
|
|
10746
11492
|
}
|
|
10747
11493
|
if (replyText.trim() && !turnDelivered) {
|
|
10748
11494
|
if (ctx.anchorSessionId && !isBoundSession(ctx.userId, ctx.anchorSessionId)) {
|
|
@@ -11019,8 +11765,8 @@ function isAllowedUser(userId, allowedUsers) {
|
|
|
11019
11765
|
var WATCH_FILE = storageFile("watch.json");
|
|
11020
11766
|
function loadWatchedMap(file = WATCH_FILE) {
|
|
11021
11767
|
try {
|
|
11022
|
-
if (
|
|
11023
|
-
const raw =
|
|
11768
|
+
if (existsSync14(file)) {
|
|
11769
|
+
const raw = readFileSync16(file, "utf-8");
|
|
11024
11770
|
const obj = JSON.parse(raw);
|
|
11025
11771
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
11026
11772
|
const out = {};
|
|
@@ -11035,7 +11781,7 @@ function loadWatchedMap(file = WATCH_FILE) {
|
|
|
11035
11781
|
}
|
|
11036
11782
|
function saveWatchedMap(m, file = WATCH_FILE) {
|
|
11037
11783
|
try {
|
|
11038
|
-
|
|
11784
|
+
writeFileSync14(file, JSON.stringify(Object.fromEntries(m), null, 2));
|
|
11039
11785
|
} catch (error) {
|
|
11040
11786
|
console.warn("[watch] 持久化失败:", error instanceof Error ? error.message : error);
|
|
11041
11787
|
}
|
|
@@ -11043,8 +11789,8 @@ function saveWatchedMap(m, file = WATCH_FILE) {
|
|
|
11043
11789
|
var GREETED_FILE = storageFile("greeted.json");
|
|
11044
11790
|
function loadGreetedSet(file = GREETED_FILE) {
|
|
11045
11791
|
try {
|
|
11046
|
-
if (
|
|
11047
|
-
const raw =
|
|
11792
|
+
if (existsSync14(file)) {
|
|
11793
|
+
const raw = readFileSync16(file, "utf-8");
|
|
11048
11794
|
const arr = JSON.parse(raw);
|
|
11049
11795
|
if (Array.isArray(arr)) {
|
|
11050
11796
|
return new Set(arr.filter((x) => typeof x === "string"));
|
|
@@ -11055,8 +11801,8 @@ function loadGreetedSet(file = GREETED_FILE) {
|
|
|
11055
11801
|
}
|
|
11056
11802
|
function saveGreetedSet(set, file = GREETED_FILE) {
|
|
11057
11803
|
try {
|
|
11058
|
-
|
|
11059
|
-
|
|
11804
|
+
mkdirSync13(join12(homedir7(), ".openqq"), { recursive: true });
|
|
11805
|
+
writeFileSync14(file, JSON.stringify([...set]));
|
|
11060
11806
|
} catch (error) {
|
|
11061
11807
|
console.error("[bridge] 保存 greeted 失败:", error);
|
|
11062
11808
|
}
|
|
@@ -11106,102 +11852,6 @@ function toErrorMessage2(error) {
|
|
|
11106
11852
|
return error instanceof Error ? error.message : String(error);
|
|
11107
11853
|
}
|
|
11108
11854
|
|
|
11109
|
-
// src/core/instance-lock.ts
|
|
11110
|
-
import { openSync as openSync5, readFileSync as readFileSync14, writeFileSync as writeFileSync14, closeSync as closeSync5, unlinkSync as unlinkSync7, statSync as statSync8, utimesSync, mkdirSync as mkdirSync13 } from "fs";
|
|
11111
|
-
import { join as join10 } from "path";
|
|
11112
|
-
import { homedir as homedir5 } from "os";
|
|
11113
|
-
var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
|
|
11114
|
-
var LOCK_STALE_MS2 = 30000;
|
|
11115
|
-
var LOCK_UPDATE_MS = 1e4;
|
|
11116
|
-
var LOCK_RETRY_MS = 5000;
|
|
11117
|
-
var LOCK_SELF_CHECK_MS = 60000;
|
|
11118
|
-
function lockPathOf(appId) {
|
|
11119
|
-
return join10(homedir5(), ".openqq", `openqq-${appId}.lock`);
|
|
11120
|
-
}
|
|
11121
|
-
function touch(path) {
|
|
11122
|
-
const now = new Date;
|
|
11123
|
-
utimesSync(path, now, now);
|
|
11124
|
-
}
|
|
11125
|
-
function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
|
|
11126
|
-
const heartbeatMs = opts?.heartbeatMs ?? LOCK_UPDATE_MS;
|
|
11127
|
-
const selfCheckMs = opts?.selfCheckMs ?? LOCK_SELF_CHECK_MS;
|
|
11128
|
-
try {
|
|
11129
|
-
mkdirSync13(join10(path, ".."), { recursive: true });
|
|
11130
|
-
const fd = openSync5(path, "wx");
|
|
11131
|
-
writeFileSync14(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
|
|
11132
|
-
closeSync5(fd);
|
|
11133
|
-
} catch {
|
|
11134
|
-
try {
|
|
11135
|
-
const age = Date.now() - statSync8(path).mtimeMs;
|
|
11136
|
-
if (age <= staleMs)
|
|
11137
|
-
return null;
|
|
11138
|
-
unlinkSync7(path);
|
|
11139
|
-
const fd = openSync5(path, "wx");
|
|
11140
|
-
writeFileSync14(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
|
|
11141
|
-
closeSync5(fd);
|
|
11142
|
-
console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
|
|
11143
|
-
} catch {
|
|
11144
|
-
return null;
|
|
11145
|
-
}
|
|
11146
|
-
}
|
|
11147
|
-
const heartbeat = setInterval(() => {
|
|
11148
|
-
try {
|
|
11149
|
-
touch(path);
|
|
11150
|
-
} catch {}
|
|
11151
|
-
}, heartbeatMs);
|
|
11152
|
-
heartbeat.unref?.();
|
|
11153
|
-
const selfCheck = setInterval(() => {
|
|
11154
|
-
try {
|
|
11155
|
-
const holder = JSON.parse(readFileSync14(path, "utf-8")).pid;
|
|
11156
|
-
if (holder === process.pid)
|
|
11157
|
-
return;
|
|
11158
|
-
try {
|
|
11159
|
-
process.kill(holder, 0);
|
|
11160
|
-
const lockFresh = Date.now() - statSync8(path).mtimeMs <= LOCK_STALE_MS2;
|
|
11161
|
-
if (lockFresh) {
|
|
11162
|
-
console.error(`[instance-lock] 自检:锁已被 pid=${holder} 持有且进程存活(锁新鲜),本实例为残留 believer,自杀退出`);
|
|
11163
|
-
process.exit(1);
|
|
11164
|
-
}
|
|
11165
|
-
console.warn(`[instance-lock] 自检:holder pid=${holder} 存活但锁已陈旧(疑 PID 复用),不自杀,交由 stale 强抢接管`);
|
|
11166
|
-
} catch {}
|
|
11167
|
-
} catch {
|
|
11168
|
-
console.error("[instance-lock] 自检:锁文件已消失(被接管或强抢流程删除),本实例退出");
|
|
11169
|
-
process.exit(1);
|
|
11170
|
-
}
|
|
11171
|
-
}, selfCheckMs);
|
|
11172
|
-
selfCheck.unref?.();
|
|
11173
|
-
let released = false;
|
|
11174
|
-
return {
|
|
11175
|
-
release: () => {
|
|
11176
|
-
if (released)
|
|
11177
|
-
return;
|
|
11178
|
-
released = true;
|
|
11179
|
-
clearInterval(heartbeat);
|
|
11180
|
-
clearInterval(selfCheck);
|
|
11181
|
-
try {
|
|
11182
|
-
unlinkSync7(path);
|
|
11183
|
-
} catch {}
|
|
11184
|
-
}
|
|
11185
|
-
};
|
|
11186
|
-
}
|
|
11187
|
-
function acquireInstanceLock(appId) {
|
|
11188
|
-
return acquireInstanceLockAt(lockPathOf(appId));
|
|
11189
|
-
}
|
|
11190
|
-
function shouldLogStandby(attempt) {
|
|
11191
|
-
return attempt === 0 || attempt % 120 === 0;
|
|
11192
|
-
}
|
|
11193
|
-
async function waitInstanceLock(appId) {
|
|
11194
|
-
for (let attempt = 0;; attempt++) {
|
|
11195
|
-
const lock = acquireInstanceLock(appId);
|
|
11196
|
-
if (lock)
|
|
11197
|
-
return lock;
|
|
11198
|
-
if (shouldLogStandby(attempt)) {
|
|
11199
|
-
console.log(`[instance-lock] 已有实例在运行,本实例待命(每 ${LOCK_RETRY_MS / 1000}s 重试抢锁,日志已节流)`);
|
|
11200
|
-
}
|
|
11201
|
-
await new Promise((r) => setTimeout(r, LOCK_RETRY_MS));
|
|
11202
|
-
}
|
|
11203
|
-
}
|
|
11204
|
-
|
|
11205
11855
|
// src/index.ts
|
|
11206
11856
|
async function waitForOpencode(clientFactory, initialUrl) {
|
|
11207
11857
|
const deadline = Date.now() + 15 * 60 * 1000;
|
|
@@ -11250,7 +11900,7 @@ async function main() {
|
|
|
11250
11900
|
const raw = (process.env.QQ_LOG_FILE ?? "").trim();
|
|
11251
11901
|
if (!/^(0|off|false|no)$/i.test(raw)) {
|
|
11252
11902
|
await Promise.resolve().then(() => init_file_log());
|
|
11253
|
-
installFileLog(raw ||
|
|
11903
|
+
installFileLog(raw || join13(homedir8(), ".openqq", "openqq.log"));
|
|
11254
11904
|
}
|
|
11255
11905
|
}
|
|
11256
11906
|
await ensureConfig();
|
|
@@ -11279,13 +11929,14 @@ async function main() {
|
|
|
11279
11929
|
for (const r of roles)
|
|
11280
11930
|
instanceLocks.push(await waitInstanceLock(r.appId));
|
|
11281
11931
|
}
|
|
11282
|
-
|
|
11283
|
-
|
|
11932
|
+
const resolvedInitial = resolveInitialBaseUrl(baseConfig.opencode.baseUrl, baseConfig.opencode.baseUrl ? null : readLastDiscovered());
|
|
11933
|
+
if (resolvedInitial.source !== "explicit") {
|
|
11934
|
+
console.log(`[index] 未配置 OPENCODE_BASE_URL,初始地址=${resolvedInitial.source === "last-discovered" ? "上次自动发现" : "占位"} ${resolvedInitial.url}(失联时自动端口发现纠正)`);
|
|
11284
11935
|
}
|
|
11285
|
-
const heartbeatFile =
|
|
11936
|
+
const heartbeatFile = join13(homedir8(), ".openqq", "heartbeat");
|
|
11286
11937
|
const touchHeartbeat = () => {
|
|
11287
11938
|
try {
|
|
11288
|
-
mkdirSync14(
|
|
11939
|
+
mkdirSync14(join13(homedir8(), ".openqq"), { recursive: true });
|
|
11289
11940
|
writeFileSync15(heartbeatFile, String(Date.now()));
|
|
11290
11941
|
} catch (error) {
|
|
11291
11942
|
console.error("[index] 心跳写入失败:", error);
|
|
@@ -11306,7 +11957,7 @@ async function main() {
|
|
|
11306
11957
|
lagTimer.unref?.();
|
|
11307
11958
|
let client;
|
|
11308
11959
|
try {
|
|
11309
|
-
client = await waitForOpencode((u) => createClient(u),
|
|
11960
|
+
client = await waitForOpencode((u) => createClient(u), resolvedInitial.url);
|
|
11310
11961
|
} catch (error) {
|
|
11311
11962
|
clearInterval(heartbeatTimer);
|
|
11312
11963
|
clearInterval(lagTimer);
|
|
@@ -11378,7 +12029,8 @@ async function main() {
|
|
|
11378
12029
|
process.once("SIGTERM", () => shutdown("SIGTERM"));
|
|
11379
12030
|
}
|
|
11380
12031
|
main().catch((error) => {
|
|
11381
|
-
console.error("[index] 启动失败:", error);
|
|
12032
|
+
console.error("[index] 启动失败:", formatStartupError(error));
|
|
12033
|
+
console.error("[index] 启动失败诊断包:", startupDiagnosticBundle());
|
|
11382
12034
|
stopBackgroundTokenRefresh();
|
|
11383
12035
|
process.exit(1);
|
|
11384
12036
|
});
|