@linjz/opencode-qqbot 0.3.16 → 0.3.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +316 -266
- package/README.zh-CN.md +326 -0
- package/dist/notify-cli.js +64 -12
- package/dist/opencode-qqbot-plugin.js +591 -92
- package/dist/openqq-bot.js +1172 -303
- package/dist/openqq-cli.js +253 -64
- package/dist/openqq-watchdog.js +373 -110
- package/package.json +4 -3
- package/src/bridge.ts +448 -32
- package/src/cli/notify.ts +4 -1
- package/src/cli/watchdog-main.ts +22 -7
- package/src/commands.ts +74 -58
- 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/delivery.ts +24 -1
- 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 +13 -4
- package/src/core/notices.ts +62 -0
- package/src/core/outbound-sanitize.ts +29 -0
- package/src/core/permission.ts +16 -0
- package/src/core/qq-instructions.ts +122 -0
- package/src/core/queue-view.ts +1 -0
- package/src/core/send-media.ts +29 -2
- package/src/core/send-requests.ts +227 -0
- 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/turn-correction.ts +68 -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 +17 -4
- package/src/opencode/sessions.ts +20 -1
- package/src/plugin-entry.ts +67 -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
|
-
import { mkdirSync as
|
|
3171
|
-
import { join as
|
|
3172
|
-
import { homedir as
|
|
3301
|
+
import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync16 } from "fs";
|
|
3302
|
+
import { join as join14 } 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,13 +4328,19 @@ 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);
|
|
4335
|
+
let dropped = 0;
|
|
4154
4336
|
for (const [userId, session] of Object.entries(parsed)) {
|
|
4155
|
-
if (session?.sessionId)
|
|
4337
|
+
if (session?.sessionId && /^ses_/.test(session.sessionId))
|
|
4156
4338
|
this.sessions.set(userId, session);
|
|
4339
|
+
else
|
|
4340
|
+
dropped++;
|
|
4341
|
+
}
|
|
4342
|
+
if (dropped > 0) {
|
|
4343
|
+
console.warn(`[sessions] 加载时丢弃 ${dropped} 条非法映射(sessionId 形态不合法,不做整图回写保留)`);
|
|
4157
4344
|
}
|
|
4158
4345
|
if (this.sessions.size > 0) {
|
|
4159
4346
|
console.log(`[sessions] 已从磁盘恢复 ${this.sessions.size} 个用户会话映射`);
|
|
@@ -4165,7 +4352,7 @@ class SessionManager {
|
|
|
4165
4352
|
saveSessions() {
|
|
4166
4353
|
try {
|
|
4167
4354
|
const dir = dirname(this.storeFile);
|
|
4168
|
-
if (!
|
|
4355
|
+
if (!existsSync4(dir))
|
|
4169
4356
|
mkdirSync3(dir, { recursive: true });
|
|
4170
4357
|
writeFileSync4(this.storeFile, JSON.stringify(Object.fromEntries(this.sessions), null, 2), "utf8");
|
|
4171
4358
|
} catch (error) {
|
|
@@ -4295,6 +4482,14 @@ class SessionManager {
|
|
|
4295
4482
|
all() {
|
|
4296
4483
|
return [...this.sessions.entries()].map(([userId, s]) => ({ userId, sessionId: s.sessionId, directory: s.directory }));
|
|
4297
4484
|
}
|
|
4485
|
+
evict(userId) {
|
|
4486
|
+
const had = this.sessions.delete(userId);
|
|
4487
|
+
if (had) {
|
|
4488
|
+
this.saveSessions();
|
|
4489
|
+
console.log(`[sessions] 驱逐失效映射 userId=${userId.slice(0, 8)}…(400/404 三连判死)`);
|
|
4490
|
+
}
|
|
4491
|
+
return had;
|
|
4492
|
+
}
|
|
4298
4493
|
async setModel(userId, providerId, modelId) {
|
|
4299
4494
|
const s = this.sessions.get(userId);
|
|
4300
4495
|
if (!s)
|
|
@@ -4336,8 +4531,8 @@ var import_websocket_server = __toESM(require_websocket_server(), 1);
|
|
|
4336
4531
|
var wrapper_default = import_websocket.default;
|
|
4337
4532
|
|
|
4338
4533
|
// src/core/gateway-state.ts
|
|
4339
|
-
import { existsSync as
|
|
4340
|
-
import { join as
|
|
4534
|
+
import { existsSync as existsSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync5, mkdirSync as mkdirSync4, renameSync, unlinkSync } from "fs";
|
|
4535
|
+
import { join as join5 } from "path";
|
|
4341
4536
|
var GATEWAY_STATE_FILE = storageFile("gateway-state.json");
|
|
4342
4537
|
function gatewayStateMaxAgeMs() {
|
|
4343
4538
|
const h = Number(process.env.QQ_GATEWAY_STATE_MAX_HOURS ?? "6");
|
|
@@ -4345,9 +4540,9 @@ function gatewayStateMaxAgeMs() {
|
|
|
4345
4540
|
}
|
|
4346
4541
|
function loadGatewayState(file = GATEWAY_STATE_FILE, now = Date.now()) {
|
|
4347
4542
|
try {
|
|
4348
|
-
if (!
|
|
4543
|
+
if (!existsSync5(file))
|
|
4349
4544
|
return null;
|
|
4350
|
-
const raw = JSON.parse(
|
|
4545
|
+
const raw = JSON.parse(readFileSync6(file, "utf-8"));
|
|
4351
4546
|
if (!raw || typeof raw.session_id !== "string" || !raw.session_id)
|
|
4352
4547
|
return null;
|
|
4353
4548
|
if (typeof raw.seq !== "number" || raw.seq < 0)
|
|
@@ -4363,7 +4558,7 @@ function loadGatewayState(file = GATEWAY_STATE_FILE, now = Date.now()) {
|
|
|
4363
4558
|
}
|
|
4364
4559
|
function saveGatewayState(sessionId, seq, file = GATEWAY_STATE_FILE) {
|
|
4365
4560
|
try {
|
|
4366
|
-
mkdirSync4(
|
|
4561
|
+
mkdirSync4(join5(file, ".."), { recursive: true });
|
|
4367
4562
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
4368
4563
|
writeFileSync5(tmp, JSON.stringify({ session_id: sessionId, seq, savedAt: Date.now() }));
|
|
4369
4564
|
renameSync(tmp, file);
|
|
@@ -4393,6 +4588,7 @@ function createInitialState(stateFile) {
|
|
|
4393
4588
|
stopped: false,
|
|
4394
4589
|
connecting: false,
|
|
4395
4590
|
reconnectAttempt: 0,
|
|
4591
|
+
quickCloses: [],
|
|
4396
4592
|
reconnectTimer: null,
|
|
4397
4593
|
heartbeatTimer: null,
|
|
4398
4594
|
accessToken: null,
|
|
@@ -4449,6 +4645,12 @@ function scheduleReconnect(state, connect, customDelayMs) {
|
|
|
4449
4645
|
connect();
|
|
4450
4646
|
}, delayMs);
|
|
4451
4647
|
}
|
|
4648
|
+
function shouldEscalateReconnect(closes, now, windowMs = 60000, maxQuick = 5) {
|
|
4649
|
+
while (closes.length > 0 && now - closes[0] > windowMs)
|
|
4650
|
+
closes.shift();
|
|
4651
|
+
return closes.length >= maxQuick;
|
|
4652
|
+
}
|
|
4653
|
+
var STORM_COOLDOWN_MS = 5 * 60000;
|
|
4452
4654
|
function startHeartbeat(state, intervalMs) {
|
|
4453
4655
|
if (state.heartbeatTimer) {
|
|
4454
4656
|
clearInterval(state.heartbeatTimer);
|
|
@@ -4773,6 +4975,15 @@ async function startGateway(options) {
|
|
|
4773
4975
|
if (FATAL_CLOSE_CODES.has(code)) {
|
|
4774
4976
|
return;
|
|
4775
4977
|
}
|
|
4978
|
+
if (code !== RATE_LIMITED_CLOSE_CODE) {
|
|
4979
|
+
state.quickCloses.push(Date.now());
|
|
4980
|
+
if (shouldEscalateReconnect(state.quickCloses, Date.now())) {
|
|
4981
|
+
state.quickCloses.length = 0;
|
|
4982
|
+
console.error(`[qq-gateway] 快断连风暴(60s 内 ${5} 次以上)→ 冷却 ${STORM_COOLDOWN_MS / 60000} 分钟后重试;请排查凭据/intent/网络`);
|
|
4983
|
+
scheduleReconnect(state, connect, STORM_COOLDOWN_MS);
|
|
4984
|
+
return;
|
|
4985
|
+
}
|
|
4986
|
+
}
|
|
4776
4987
|
scheduleReconnect(state, connect);
|
|
4777
4988
|
});
|
|
4778
4989
|
ws.on("error", (error) => {
|
|
@@ -4793,14 +5004,51 @@ async function startGateway(options) {
|
|
|
4793
5004
|
}
|
|
4794
5005
|
|
|
4795
5006
|
// src/bridge.ts
|
|
4796
|
-
import { existsSync as
|
|
4797
|
-
import { join as
|
|
4798
|
-
import { homedir as
|
|
5007
|
+
import { existsSync as existsSync15, readFileSync as readFileSync17, mkdirSync as mkdirSync14, writeFileSync as writeFileSync15 } from "fs";
|
|
5008
|
+
import { join as join13 } from "path";
|
|
5009
|
+
import { homedir as homedir7 } from "os";
|
|
4799
5010
|
|
|
4800
5011
|
// src/qq/media.ts
|
|
4801
|
-
import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as
|
|
4802
|
-
import { join as
|
|
5012
|
+
import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as readFileSync7 } from "node:fs";
|
|
5013
|
+
import { join as join6 } from "node:path";
|
|
4803
5014
|
import { tmpdir } from "node:os";
|
|
5015
|
+
|
|
5016
|
+
// src/core/stt.ts
|
|
5017
|
+
function sttConfigured(env = process.env) {
|
|
5018
|
+
const baseUrl = (env.QQ_STT_BASE_URL ?? "").trim().replace(/\/+$/, "");
|
|
5019
|
+
const apiKey = (env.QQ_STT_API_KEY ?? "").trim();
|
|
5020
|
+
const model = (env.QQ_STT_MODEL ?? "whisper-1").trim();
|
|
5021
|
+
if (!baseUrl || !apiKey)
|
|
5022
|
+
return null;
|
|
5023
|
+
return { baseUrl, apiKey, model };
|
|
5024
|
+
}
|
|
5025
|
+
async function sttTranscribe(bytes, filename, cfg, fetchImpl = fetch) {
|
|
5026
|
+
const form = new FormData;
|
|
5027
|
+
form.append("model", cfg.model);
|
|
5028
|
+
form.append("file", new Blob([bytes.buffer]), filename);
|
|
5029
|
+
const ctrl = new AbortController;
|
|
5030
|
+
const timer = setTimeout(() => ctrl.abort(), 30000);
|
|
5031
|
+
let res;
|
|
5032
|
+
try {
|
|
5033
|
+
res = await fetchImpl(`${cfg.baseUrl}/audio/transcriptions`, {
|
|
5034
|
+
method: "POST",
|
|
5035
|
+
headers: { Authorization: `Bearer ${cfg.apiKey}` },
|
|
5036
|
+
body: form,
|
|
5037
|
+
signal: ctrl.signal
|
|
5038
|
+
});
|
|
5039
|
+
} finally {
|
|
5040
|
+
clearTimeout(timer);
|
|
5041
|
+
}
|
|
5042
|
+
if (!res.ok)
|
|
5043
|
+
throw new Error(`STT ${res.status}`);
|
|
5044
|
+
const j = await res.json();
|
|
5045
|
+
const text = (j.text ?? "").trim();
|
|
5046
|
+
if (!text)
|
|
5047
|
+
throw new Error("STT 空转写");
|
|
5048
|
+
return text;
|
|
5049
|
+
}
|
|
5050
|
+
|
|
5051
|
+
// src/qq/media.ts
|
|
4804
5052
|
function extForImageMime(mime) {
|
|
4805
5053
|
const m = (mime || "").toLowerCase().split(";")[0].trim();
|
|
4806
5054
|
if (m === "image/jpeg")
|
|
@@ -4824,7 +5072,7 @@ function isAllowedDownloadHost(url) {
|
|
|
4824
5072
|
}
|
|
4825
5073
|
}
|
|
4826
5074
|
function imageDir() {
|
|
4827
|
-
return
|
|
5075
|
+
return join6(tmpdir(), "opencode", "qq-images");
|
|
4828
5076
|
}
|
|
4829
5077
|
async function fetchWithTimeout(url, ms, auth) {
|
|
4830
5078
|
const ctrl = new AbortController;
|
|
@@ -4844,6 +5092,26 @@ async function downloadQQAttachment(att, getAuth) {
|
|
|
4844
5092
|
if (isVoice && att.asr_refer_text?.trim()) {
|
|
4845
5093
|
return { voice: att.asr_refer_text.trim() };
|
|
4846
5094
|
}
|
|
5095
|
+
if (isVoice && sttConfigured()) {
|
|
5096
|
+
try {
|
|
5097
|
+
if (!isAllowedDownloadHost(att.url))
|
|
5098
|
+
return { failed: "下载域不在白名单" };
|
|
5099
|
+
const name = att.filename || `voice-${Date.now()}.amr`;
|
|
5100
|
+
let res = await fetchWithTimeout(att.url, 15000);
|
|
5101
|
+
if ((res.status === 401 || res.status === 403) && getAuth) {
|
|
5102
|
+
res = await fetchWithTimeout(att.url, 15000, await getAuth());
|
|
5103
|
+
}
|
|
5104
|
+
if (!res.ok)
|
|
5105
|
+
return { failed: "语音下载失败" };
|
|
5106
|
+
const buf = new Uint8Array(await res.arrayBuffer());
|
|
5107
|
+
if (buf.byteLength > MAX_IMAGE_BYTES)
|
|
5108
|
+
return { failed: "语音超过 10MB 上限" };
|
|
5109
|
+
const text = await sttTranscribe(buf, name, sttConfigured());
|
|
5110
|
+
return { voice: text };
|
|
5111
|
+
} catch {
|
|
5112
|
+
return { failed: "语音转写失败(外部 STT 未响应或识别为空)" };
|
|
5113
|
+
}
|
|
5114
|
+
}
|
|
4847
5115
|
const ext = extForImageMime(att.content_type || "");
|
|
4848
5116
|
if (!ext)
|
|
4849
5117
|
return { unsupported: att.content_type || att.filename || "未知类型" };
|
|
@@ -4885,7 +5153,7 @@ async function downloadQQAttachment(att, getAuth) {
|
|
|
4885
5153
|
}
|
|
4886
5154
|
if (total === 0)
|
|
4887
5155
|
return { failed: "空响应" };
|
|
4888
|
-
const full =
|
|
5156
|
+
const full = join6(dir, name);
|
|
4889
5157
|
writeFileSync6(full, Buffer.concat(chunks));
|
|
4890
5158
|
return { path: full, name };
|
|
4891
5159
|
} catch (e) {
|
|
@@ -4923,7 +5191,7 @@ function tryImageDataUrl(path, maxBytes) {
|
|
|
4923
5191
|
const st = statSync(path);
|
|
4924
5192
|
if (st.size > maxBytes)
|
|
4925
5193
|
return null;
|
|
4926
|
-
const b =
|
|
5194
|
+
const b = readFileSync7(path);
|
|
4927
5195
|
return `data:image/png;base64,${b.toString("base64")}`;
|
|
4928
5196
|
} catch {
|
|
4929
5197
|
return null;
|
|
@@ -4950,7 +5218,7 @@ function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
|
|
|
4950
5218
|
const dir = imageDir();
|
|
4951
5219
|
const now = Date.now();
|
|
4952
5220
|
for (const f of readdirSync(dir)) {
|
|
4953
|
-
const full =
|
|
5221
|
+
const full = join6(dir, f);
|
|
4954
5222
|
try {
|
|
4955
5223
|
if (now - statSync(full).mtimeMs > maxAgeMs)
|
|
4956
5224
|
unlinkSync2(full);
|
|
@@ -5383,8 +5651,9 @@ function clip(value, max) {
|
|
|
5383
5651
|
}
|
|
5384
5652
|
|
|
5385
5653
|
// src/core/send-media.ts
|
|
5386
|
-
import { readFileSync as
|
|
5387
|
-
import { resolve, extname, basename, sep } from "node:path";
|
|
5654
|
+
import { readFileSync as readFileSync8, statSync as statSync2 } from "node:fs";
|
|
5655
|
+
import { resolve, extname, basename, sep, join as join7 } from "node:path";
|
|
5656
|
+
import { homedir as homedir5 } from "node:os";
|
|
5388
5657
|
var MAX_SEND_BYTES = 20 * 1024 * 1024;
|
|
5389
5658
|
function allowedSendRoots(extraEnv = process.env.QQ_SEND_EXTRA_ROOTS) {
|
|
5390
5659
|
const roots = [imageDir(), process.cwd()];
|
|
@@ -5448,8 +5717,23 @@ function extractSendFileMarkers(text) {
|
|
|
5448
5717
|
|
|
5449
5718
|
`).trim(), paths };
|
|
5450
5719
|
}
|
|
5720
|
+
function normalizeLocalPath(p) {
|
|
5721
|
+
let r = p.trim();
|
|
5722
|
+
if (r.startsWith("file://")) {
|
|
5723
|
+
r = r.slice("file://".length);
|
|
5724
|
+
if (/^\/[a-zA-Z]:[\\/]/.test(r))
|
|
5725
|
+
r = r.slice(1);
|
|
5726
|
+
}
|
|
5727
|
+
try {
|
|
5728
|
+
r = decodeURIComponent(r);
|
|
5729
|
+
} catch {}
|
|
5730
|
+
if (r === "~" || r.startsWith("~/") || r.startsWith("~\\")) {
|
|
5731
|
+
r = join7(homedir5(), r.slice(1));
|
|
5732
|
+
}
|
|
5733
|
+
return r;
|
|
5734
|
+
}
|
|
5451
5735
|
async function sendLocalFile(ctx, filePath, deps) {
|
|
5452
|
-
const trimmed = filePath
|
|
5736
|
+
const trimmed = normalizeLocalPath(filePath);
|
|
5453
5737
|
if (isDeniedSendFile(trimmed)) {
|
|
5454
5738
|
throw new Error("该文件属于密钥/凭据类,禁止外发(已拦截)");
|
|
5455
5739
|
}
|
|
@@ -5473,7 +5757,7 @@ async function sendLocalFile(ctx, filePath, deps) {
|
|
|
5473
5757
|
const name = basename(trimmed);
|
|
5474
5758
|
const uploaded = await uploadQQMedia(token, ctx, {
|
|
5475
5759
|
fileType,
|
|
5476
|
-
fileData:
|
|
5760
|
+
fileData: readFileSync8(trimmed).toString("base64"),
|
|
5477
5761
|
fileName: fileType === MediaFileType.FILE ? name : undefined
|
|
5478
5762
|
});
|
|
5479
5763
|
await sendQQMediaMessage(token, ctx, uploaded.file_info, name);
|
|
@@ -5495,9 +5779,20 @@ async function handleCommand(ctx, cmdCtx) {
|
|
|
5495
5779
|
switch (parsed.name) {
|
|
5496
5780
|
case "new":
|
|
5497
5781
|
return handleNew(ctx, cmdCtx);
|
|
5498
|
-
case "stop":
|
|
5499
5782
|
case "cancel":
|
|
5500
5783
|
return handleStop(ctx, cmdCtx);
|
|
5784
|
+
case "amend":
|
|
5785
|
+
return cmdCtx.amend(ctx.userId, parsed.args);
|
|
5786
|
+
case "undo":
|
|
5787
|
+
return cmdCtx.undo(ctx.userId);
|
|
5788
|
+
case "goal":
|
|
5789
|
+
return cmdCtx.engineCommand(ctx.userId, "goal", parsed.args);
|
|
5790
|
+
case "compact":
|
|
5791
|
+
return cmdCtx.engineCommand(ctx.userId, "compact", parsed.args);
|
|
5792
|
+
case "redo":
|
|
5793
|
+
return cmdCtx.engineCommand(ctx.userId, "redo", parsed.args);
|
|
5794
|
+
case "btw":
|
|
5795
|
+
return cmdCtx.engineCommand(ctx.userId, "btw", parsed.args);
|
|
5501
5796
|
case "queue":
|
|
5502
5797
|
return handleQueue(ctx, parsed.args, cmdCtx);
|
|
5503
5798
|
case "ledger":
|
|
@@ -5505,25 +5800,29 @@ async function handleCommand(ctx, cmdCtx) {
|
|
|
5505
5800
|
case "progress":
|
|
5506
5801
|
return cmdCtx.progress.query(ctx.userId);
|
|
5507
5802
|
case "status":
|
|
5508
|
-
return handleStatus(ctx, cmdCtx);
|
|
5803
|
+
return handleStatus(ctx, parsed.args, cmdCtx);
|
|
5804
|
+
case "watch":
|
|
5805
|
+
return "⌛ /watch 已退役:观察开关请用 /status watch on|off(盯当前绑定会话)。原 /watch <会话ID> 跨会话观察能力已随命令下线(owner 2026-11-23 裁决不保留)";
|
|
5806
|
+
case "mirror":
|
|
5807
|
+
return "⌛ /mirror 已退役:镜像开关请用 /status mirror on|off";
|
|
5509
5808
|
case "sessions":
|
|
5510
5809
|
return handleSessions(ctx, cmdCtx);
|
|
5511
5810
|
case "help":
|
|
5512
5811
|
return buildHelpText();
|
|
5513
|
-
case "
|
|
5812
|
+
case "models":
|
|
5514
5813
|
return handleModel(ctx, parsed.args, cmdCtx);
|
|
5515
|
-
case "
|
|
5814
|
+
case "agents":
|
|
5516
5815
|
return handleAgent(ctx, parsed.args, cmdCtx);
|
|
5517
5816
|
case "rename":
|
|
5518
5817
|
return handleRename(ctx, parsed.args, cmdCtx);
|
|
5519
5818
|
case "history":
|
|
5520
5819
|
return handleHistory(ctx, parsed.args, cmdCtx);
|
|
5521
5820
|
case "watch":
|
|
5522
|
-
return
|
|
5821
|
+
return "⌛ /watch 已退役:观察开关请用 /status watch on|off(盯当前绑定会话)。原 /watch <会话ID> 跨会话观察能力已随命令下线(owner 2026-11-23 裁决不保留)";
|
|
5523
5822
|
case "send":
|
|
5524
5823
|
return handleSend(ctx, parsed.args, cmdCtx);
|
|
5525
5824
|
case "mirror":
|
|
5526
|
-
return
|
|
5825
|
+
return "⌛ /mirror 已退役:镜像开关请用 /status mirror on|off";
|
|
5527
5826
|
default:
|
|
5528
5827
|
return `不支持的命令:/${parsed.name}
|
|
5529
5828
|
发送 /help 查看可用命令`;
|
|
@@ -5617,6 +5916,9 @@ function handleQueue(ctx, args, cmdCtx) {
|
|
|
5617
5916
|
if (/^\d+$/.test(sub)) {
|
|
5618
5917
|
return cmdCtx.queue.listAll(ctx.userId, Math.max(1, Number(sub)));
|
|
5619
5918
|
}
|
|
5919
|
+
if (args.trim()) {
|
|
5920
|
+
return cmdCtx.enqueue(ctx, args.trim());
|
|
5921
|
+
}
|
|
5620
5922
|
return cmdCtx.queue.list(ctx.userId);
|
|
5621
5923
|
}
|
|
5622
5924
|
async function handleLedger(ctx, args, cmdCtx) {
|
|
@@ -5648,7 +5950,22 @@ async function resolveStatusSessionTitle(sessions, client, userId) {
|
|
|
5648
5950
|
} catch {}
|
|
5649
5951
|
return { title: session.title, sessionId: session.sessionId };
|
|
5650
5952
|
}
|
|
5651
|
-
async function handleStatus(ctx, cmdCtx) {
|
|
5953
|
+
async function handleStatus(ctx, args, cmdCtx) {
|
|
5954
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
5955
|
+
if (parts.length > 0) {
|
|
5956
|
+
const target = parts[0].toLowerCase();
|
|
5957
|
+
const sw = parts[1]?.toLowerCase();
|
|
5958
|
+
if ((target === "watch" || target === "mirror") && (sw === "on" || sw === "off")) {
|
|
5959
|
+
if (target === "mirror")
|
|
5960
|
+
return cmdCtx.mirror.set(sw === "on");
|
|
5961
|
+
if (sw === "on") {
|
|
5962
|
+
const session = await cmdCtx.sessions.getOrCreate(ctx.userId);
|
|
5963
|
+
return cmdCtx.watch.start(ctx.userId, session.sessionId, ctx);
|
|
5964
|
+
}
|
|
5965
|
+
return cmdCtx.watch.stop(ctx.userId);
|
|
5966
|
+
}
|
|
5967
|
+
return "用法:/status 查看状态|/status watch on|off 观察开关|/status mirror on|off 镜像开关";
|
|
5968
|
+
}
|
|
5652
5969
|
const sessionInfo = await resolveStatusSessionTitle(cmdCtx.sessions, cmdCtx.client, ctx.userId);
|
|
5653
5970
|
const { providerId, modelId } = cmdCtx.sessions.getModel(ctx.userId);
|
|
5654
5971
|
const agentId = cmdCtx.sessions.getAgent(ctx.userId);
|
|
@@ -5667,6 +5984,8 @@ async function handleStatus(ctx, cmdCtx) {
|
|
|
5667
5984
|
`会话:${sessionInfo.sessionId ? `${sessionInfo.title ?? "未命名会话"} (${sessionInfo.sessionId})` : "未创建"}`,
|
|
5668
5985
|
`模型:${providerId && modelId ? `${providerId} / ${modelId}` : "默认"}`,
|
|
5669
5986
|
`Agent:${agentId ?? "默认"}`,
|
|
5987
|
+
cmdCtx.watch.status(ctx.userId),
|
|
5988
|
+
cmdCtx.mirror.status(),
|
|
5670
5989
|
cmdCtx.queue.summary(ctx.userId),
|
|
5671
5990
|
logLine
|
|
5672
5991
|
].join(`
|
|
@@ -5706,16 +6025,16 @@ async function handleModel(ctx, args, cmdCtx) {
|
|
|
5706
6025
|
const isCurrent = current.providerId && current.modelId && `${current.providerId}/${current.modelId}` === model.id;
|
|
5707
6026
|
return `${index + 1}. ${isCurrent ? "[当前] " : ""}${model.label}`;
|
|
5708
6027
|
});
|
|
5709
|
-
return ["可用模型:", ...lines, "回复序号或 /
|
|
6028
|
+
return ["可用模型:", ...lines, "回复序号或 /models <provider/model> 切换(60 秒内有效)"].join(`
|
|
5710
6029
|
`);
|
|
5711
6030
|
}
|
|
5712
6031
|
if (/^\d+$/.test(args)) {
|
|
5713
6032
|
const result = await handlePendingSelection(ctx.userId, Number(args), cmdCtx);
|
|
5714
|
-
return result ?? "没有待选择的模型列表,请先发送 /
|
|
6033
|
+
return result ?? "没有待选择的模型列表,请先发送 /models";
|
|
5715
6034
|
}
|
|
5716
6035
|
const model = splitModelId(args);
|
|
5717
6036
|
if (!model) {
|
|
5718
|
-
return "模型格式不对,请使用 /
|
|
6037
|
+
return "模型格式不对,请使用 /models <provider/model>";
|
|
5719
6038
|
}
|
|
5720
6039
|
let models;
|
|
5721
6040
|
try {
|
|
@@ -5742,7 +6061,7 @@ async function handleAgent(ctx, args, cmdCtx) {
|
|
|
5742
6061
|
const isCurrent = currentAgent === agent.id;
|
|
5743
6062
|
return `${index + 1}. ${isCurrent ? "[当前] " : ""}${agent.label}`;
|
|
5744
6063
|
});
|
|
5745
|
-
return ["可用 Agent:", ...lines, "回复 /
|
|
6064
|
+
return ["可用 Agent:", ...lines, "回复 /agents <name> 切换"].join(`
|
|
5746
6065
|
`);
|
|
5747
6066
|
}
|
|
5748
6067
|
const normalized = args.trim().toLowerCase();
|
|
@@ -5782,31 +6101,6 @@ async function handleHistory(ctx, args, cmdCtx) {
|
|
|
5782
6101
|
|
|
5783
6102
|
${body}`;
|
|
5784
6103
|
}
|
|
5785
|
-
async function handleWatch(ctx, args, cmdCtx) {
|
|
5786
|
-
const a = args.trim();
|
|
5787
|
-
const lower = a.toLowerCase();
|
|
5788
|
-
if (lower === "off" || lower === "stop") {
|
|
5789
|
-
return cmdCtx.watch.stop(ctx.userId);
|
|
5790
|
-
}
|
|
5791
|
-
if (!a) {
|
|
5792
|
-
const session = await cmdCtx.sessions.getOrCreate(ctx.userId);
|
|
5793
|
-
return cmdCtx.watch.start(ctx.userId, session.sessionId, ctx);
|
|
5794
|
-
}
|
|
5795
|
-
if (/^ses_/i.test(a)) {
|
|
5796
|
-
return cmdCtx.watch.start(ctx.userId, a, ctx);
|
|
5797
|
-
}
|
|
5798
|
-
return "用法:/watch 观察当前会话|/watch <会话ID> 观察指定会话|/watch off 停止观察";
|
|
5799
|
-
}
|
|
5800
|
-
function handleMirror(args, cmdCtx) {
|
|
5801
|
-
const a = args.trim().toLowerCase();
|
|
5802
|
-
if (!a)
|
|
5803
|
-
return cmdCtx.mirror.status();
|
|
5804
|
-
if (["on", "1", "开", "打开"].includes(a))
|
|
5805
|
-
return cmdCtx.mirror.set(true);
|
|
5806
|
-
if (["off", "0", "关", "关闭"].includes(a))
|
|
5807
|
-
return cmdCtx.mirror.set(false);
|
|
5808
|
-
return "用法:/mirror 查看状态|/mirror on 开启|/mirror off 关闭";
|
|
5809
|
-
}
|
|
5810
6104
|
async function ensureSession(userId, cmdCtx) {
|
|
5811
6105
|
await cmdCtx.sessions.getOrCreate(userId);
|
|
5812
6106
|
}
|
|
@@ -5900,28 +6194,25 @@ function buildHelpText() {
|
|
|
5900
6194
|
return [
|
|
5901
6195
|
"可用命令:",
|
|
5902
6196
|
"/new - 创建新会话",
|
|
5903
|
-
"/
|
|
5904
|
-
"/status -
|
|
6197
|
+
"/cancel - 中止当前生成并清空忙碌队列",
|
|
6198
|
+
"/status - 驾驶舱:服务器/会话/模型/Agent/观察/镜像/队列/日志;/status watch on|off 观察开关;/status mirror on|off 镜像开关",
|
|
5905
6199
|
"/sessions - 列出历史会话并回复序号切换",
|
|
5906
6200
|
"/help - 查看帮助",
|
|
5907
|
-
"/
|
|
5908
|
-
"/
|
|
5909
|
-
"/agent - 列出可用 Agent",
|
|
5910
|
-
"/agent <name> - 切换 Agent",
|
|
6201
|
+
"/models - 列出可用模型|/models <provider/model> 切换(session 级)",
|
|
6202
|
+
"/agents - 列出可用 Agent|/agents <name> 切换",
|
|
5911
6203
|
"/rename <name> - 重命名当前会话",
|
|
5912
6204
|
"/history [N] - 查看当前会话最近 N 轮历史(默认 3,最多 10)",
|
|
5913
6205
|
"/send <路径> - 把白名单目录内的文件/图片发到 QQ",
|
|
5914
|
-
"/watch - 观察当前会话实时过程(工具调用/完成会推送摘要)",
|
|
5915
|
-
"/watch <会话ID> - 观察指定会话",
|
|
5916
|
-
"/watch off - 停止观察",
|
|
5917
6206
|
"/progress - 手动进度查询(工具调用/失败统计、在途状态,本地事件源零模型调用)",
|
|
5918
|
-
"/queue - 队列与台账对账视图;/queue all [页码] 全量;/queue clear 清空;/queue drop <编号>
|
|
6207
|
+
"/queue - 队列与台账对账视图;/queue all [页码] 全量;/queue clear 清空;/queue drop <编号> 定点删除;/queue <文本> 显性入队(steer 默认下排进 FIFO)",
|
|
6208
|
+
"/goal <目标> - 官方目标模式(引擎内置 v2.2.1+);/goal 查状态;pause/resume/clear 控制",
|
|
6209
|
+
"/compact /redo /btw - 官方引擎命令直通(压缩会话 / 恢复撤销 / 侧问)",
|
|
5919
6210
|
"/ledger - 台账快照(在途/孤儿/最近拒绝);/ledger check 对账会话历史;/ledger settle <尾号> confirm 人工结清",
|
|
5920
|
-
"/
|
|
5921
|
-
"/
|
|
6211
|
+
"/undo - 对齐官方:撤销上一回合,并恢复文件",
|
|
6212
|
+
"/amend <补充> - 忙时插话并入当前任务(官方 steer 语义)",
|
|
5922
6213
|
"",
|
|
5923
6214
|
"权限审批(AI 请求权限时):",
|
|
5924
|
-
"
|
|
6215
|
+
"点卡片按钮(允许一次/总是允许/拒绝/忽略),或回复「允许」= 本次允许|「总是」= 总是允许|「拒绝」= 拒绝",
|
|
5925
6216
|
"(30 分钟无响应自动拒绝)"
|
|
5926
6217
|
].join(`
|
|
5927
6218
|
`);
|
|
@@ -5953,7 +6244,7 @@ function toErrorMessage(error) {
|
|
|
5953
6244
|
}
|
|
5954
6245
|
|
|
5955
6246
|
// src/core/mirror.ts
|
|
5956
|
-
import { existsSync as
|
|
6247
|
+
import { existsSync as existsSync8, readFileSync as readFileSync9, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "fs";
|
|
5957
6248
|
|
|
5958
6249
|
// src/opencode/mirror.ts
|
|
5959
6250
|
var USER_CLIP = 160;
|
|
@@ -5988,18 +6279,25 @@ function digestTurnKey(messages) {
|
|
|
5988
6279
|
}
|
|
5989
6280
|
return null;
|
|
5990
6281
|
}
|
|
5991
|
-
function buildDigest(messages) {
|
|
6282
|
+
function buildDigest(messages, goalObjective) {
|
|
5992
6283
|
const ordered = [...messages].reverse();
|
|
5993
6284
|
let lastUserIdx = -1;
|
|
6285
|
+
let goalDriven = false;
|
|
5994
6286
|
for (let i = ordered.length - 1;i >= 0; i--) {
|
|
5995
|
-
|
|
6287
|
+
const t = ordered[i].type;
|
|
6288
|
+
if (t === "user" || t === "synthetic") {
|
|
5996
6289
|
lastUserIdx = i;
|
|
6290
|
+
goalDriven = t === "synthetic";
|
|
5997
6291
|
break;
|
|
5998
6292
|
}
|
|
5999
6293
|
}
|
|
6000
6294
|
if (lastUserIdx < 0)
|
|
6001
6295
|
return null;
|
|
6002
|
-
const
|
|
6296
|
+
const boundaryMsg = ordered[lastUserIdx];
|
|
6297
|
+
const userText = goalDriven ? "" : (boundaryMsg.text ?? (boundaryMsg.content ?? []).filter((p) => p.type === "text").map((p) => p.text ?? "").join("") ?? "").trim();
|
|
6298
|
+
if (!goalDriven && goalObjective && userText && userText === goalObjective.trim()) {
|
|
6299
|
+
goalDriven = true;
|
|
6300
|
+
}
|
|
6003
6301
|
let answer = "";
|
|
6004
6302
|
for (let i = ordered.length - 1;i > lastUserIdx; i--) {
|
|
6005
6303
|
const m = ordered[i];
|
|
@@ -6014,7 +6312,7 @@ function buildDigest(messages) {
|
|
|
6014
6312
|
}
|
|
6015
6313
|
if (!answer)
|
|
6016
6314
|
return null;
|
|
6017
|
-
const lines = ["\uD83D\uDCCB 桌面问答摘要"];
|
|
6315
|
+
const lines = [goalDriven ? "\uD83C\uDFAF 目标续跑摘要" : "\uD83D\uDCCB 桌面问答摘要"];
|
|
6018
6316
|
if (userText)
|
|
6019
6317
|
lines.push(`\uD83E\uDDD1 ${clip2(userText, USER_CLIP)}`);
|
|
6020
6318
|
const clipLimit = answerClipLimit();
|
|
@@ -6197,8 +6495,8 @@ class MessageQueue {
|
|
|
6197
6495
|
var MIRROR_SETTINGS_FILE = storageFile("settings.json");
|
|
6198
6496
|
function loadMirrorEnabled(file = MIRROR_SETTINGS_FILE) {
|
|
6199
6497
|
try {
|
|
6200
|
-
if (
|
|
6201
|
-
const raw =
|
|
6498
|
+
if (existsSync8(file)) {
|
|
6499
|
+
const raw = readFileSync9(file, "utf-8").replace(/^\uFEFF/, "");
|
|
6202
6500
|
const parsed = JSON.parse(raw);
|
|
6203
6501
|
if (typeof parsed?.mirror === "boolean")
|
|
6204
6502
|
return parsed.mirror;
|
|
@@ -6210,9 +6508,9 @@ function saveMirrorEnabled(enabled, file = MIRROR_SETTINGS_FILE) {
|
|
|
6210
6508
|
try {
|
|
6211
6509
|
mkdirSync7(storageRoot(), { recursive: true });
|
|
6212
6510
|
let existing = {};
|
|
6213
|
-
if (
|
|
6511
|
+
if (existsSync8(file)) {
|
|
6214
6512
|
try {
|
|
6215
|
-
const raw =
|
|
6513
|
+
const raw = readFileSync9(file, "utf-8").replace(/^\uFEFF/, "");
|
|
6216
6514
|
const parsed = JSON.parse(raw);
|
|
6217
6515
|
if (parsed && typeof parsed === "object")
|
|
6218
6516
|
existing = parsed;
|
|
@@ -6302,7 +6600,7 @@ function createMirror(deps) {
|
|
|
6302
6600
|
mirroredTurns.set(sessionID, turnKey);
|
|
6303
6601
|
return;
|
|
6304
6602
|
}
|
|
6305
|
-
const digest = buildDigest(messages);
|
|
6603
|
+
const digest = buildDigest(messages, deps.goalObjectiveOf?.(sessionID));
|
|
6306
6604
|
if (!digest) {
|
|
6307
6605
|
console.log(`[mirror] 跳过:无可摘要内容(空轮/纯工具轮)session=${sessionID}`);
|
|
6308
6606
|
return;
|
|
@@ -6312,7 +6610,11 @@ function createMirror(deps) {
|
|
|
6312
6610
|
for (const userId of owners) {
|
|
6313
6611
|
const recent = lastCtx.get(userId);
|
|
6314
6612
|
const ctx = recent ? { ...recent, anchorSessionId: sessionID } : { type: "c2c", userId, msgId: "", content: "", anchorSessionId: sessionID };
|
|
6315
|
-
|
|
6613
|
+
const cronHook = deps.onDigest;
|
|
6614
|
+
const outText = cronHook ? cronHook(userId, digest) : digest;
|
|
6615
|
+
if (!outText.trim())
|
|
6616
|
+
continue;
|
|
6617
|
+
await safeDeliver(ctx, outText);
|
|
6316
6618
|
}
|
|
6317
6619
|
console.log(`[mirror] 会话 ${sessionID} 摘要已镜像给 ${owners.length} 个用户`);
|
|
6318
6620
|
} catch (error) {
|
|
@@ -6330,11 +6632,11 @@ function createMirror(deps) {
|
|
|
6330
6632
|
} else {
|
|
6331
6633
|
disableMirrorSubs();
|
|
6332
6634
|
}
|
|
6333
|
-
return enabled ? "✅ 摘要镜像已开启:桌面会话轮次完成后推送问答摘要" : "\uD83D\uDD07 摘要镜像已关闭(/mirror on 重新开启)";
|
|
6635
|
+
return enabled ? "✅ 摘要镜像已开启:桌面会话轮次完成后推送问答摘要" : "\uD83D\uDD07 摘要镜像已关闭(/status mirror on 重新开启)";
|
|
6334
6636
|
},
|
|
6335
6637
|
status() {
|
|
6336
6638
|
const subs = mirrorUnsubs.size;
|
|
6337
|
-
return mirrorState.enabled ? `\uD83D\uDCCB 摘要镜像:开(已挂 ${subs} 个会话订阅)` : "\uD83D\uDCCB 摘要镜像:关(/mirror on 开启)";
|
|
6639
|
+
return mirrorState.enabled ? `\uD83D\uDCCB 摘要镜像:开(已挂 ${subs} 个会话订阅)` : "\uD83D\uDCCB 摘要镜像:关(/status mirror on 开启)";
|
|
6338
6640
|
}
|
|
6339
6641
|
};
|
|
6340
6642
|
return {
|
|
@@ -6369,14 +6671,162 @@ function rescueText(kind, rawMessage) {
|
|
|
6369
6671
|
`服务端原文:${raw}`,
|
|
6370
6672
|
"",
|
|
6371
6673
|
"恢复方式(都不用等模型在线)——",
|
|
6372
|
-
"1. 换现成模型:发 /
|
|
6674
|
+
"1. 换现成模型:发 /models 看列表,或 /models provider/id 直接切换",
|
|
6373
6675
|
"2. 更新 key:在桌面端 opencode 里更新该服务的 key 后,直接重发你的问题"
|
|
6374
6676
|
].join(`
|
|
6375
6677
|
`);
|
|
6376
6678
|
}
|
|
6377
6679
|
|
|
6680
|
+
// src/core/notices.ts
|
|
6681
|
+
function cmdInput(text, show, reference = false) {
|
|
6682
|
+
const enc = (s) => encodeURIComponent(s);
|
|
6683
|
+
const attrs = [`text="${enc(text)}"`];
|
|
6684
|
+
if (show !== undefined)
|
|
6685
|
+
attrs.push(`show="${enc(show)}"`);
|
|
6686
|
+
if (reference)
|
|
6687
|
+
attrs.push('reference="true"');
|
|
6688
|
+
return `<qqbot-cmd-input ${attrs.join(" ")} />`;
|
|
6689
|
+
}
|
|
6690
|
+
var INTERACTION_TAG = /<qqbot-(cmd-input|cmd-enter)\b[^>]*\/?>/g;
|
|
6691
|
+
function tagFallback(tag) {
|
|
6692
|
+
const show = /show="([^"]*)"/.exec(tag)?.[1];
|
|
6693
|
+
const text = /text="([^"]*)"/.exec(tag)?.[1];
|
|
6694
|
+
const pick = show ?? text;
|
|
6695
|
+
if (!pick)
|
|
6696
|
+
return "";
|
|
6697
|
+
try {
|
|
6698
|
+
return decodeURIComponent(pick);
|
|
6699
|
+
} catch {
|
|
6700
|
+
return pick;
|
|
6701
|
+
}
|
|
6702
|
+
}
|
|
6703
|
+
function stripInteractionTags(text) {
|
|
6704
|
+
return text.replace(INTERACTION_TAG, (m) => tagFallback(m));
|
|
6705
|
+
}
|
|
6706
|
+
var NOTICE = {
|
|
6707
|
+
reaperExpired: () => `⚠️ 检测到一个卡死的回合(长时间无进展),已自动清理;结果可点下面的指令开新会话重试:
|
|
6708
|
+
` + cmdInput("/new", "\uD83C\uDD95 新会话")
|
|
6709
|
+
};
|
|
6710
|
+
|
|
6711
|
+
// src/core/cron-reminders.ts
|
|
6712
|
+
function parseCronReminder(text, now) {
|
|
6713
|
+
const m = /QQBOT_PAYLOAD:\s*(\{[\s\S]*?\})/.exec(text);
|
|
6714
|
+
if (!m)
|
|
6715
|
+
return null;
|
|
6716
|
+
let payload;
|
|
6717
|
+
try {
|
|
6718
|
+
payload = JSON.parse(m[1]);
|
|
6719
|
+
} catch {
|
|
6720
|
+
return null;
|
|
6721
|
+
}
|
|
6722
|
+
if (payload?.type !== "cron_reminder")
|
|
6723
|
+
return null;
|
|
6724
|
+
const reminderText = typeof payload.text === "string" ? payload.text.trim().slice(0, 200) : "";
|
|
6725
|
+
if (!reminderText)
|
|
6726
|
+
return null;
|
|
6727
|
+
const atMs = resolveAt(payload.at, now);
|
|
6728
|
+
if (atMs === null || atMs <= now + 5000)
|
|
6729
|
+
return null;
|
|
6730
|
+
const cleanedText = text.split(`
|
|
6731
|
+
`).filter((line) => !line.includes("QQBOT_PAYLOAD:")).join(`
|
|
6732
|
+
`).replace(/\n{3,}/g, `
|
|
6733
|
+
|
|
6734
|
+
`).trim();
|
|
6735
|
+
return { atMs, reminderText, cleanedText };
|
|
6736
|
+
}
|
|
6737
|
+
function resolveAt(at, now) {
|
|
6738
|
+
if (typeof at === "number" && Number.isFinite(at)) {
|
|
6739
|
+
return at > 1000000000000 ? at : null;
|
|
6740
|
+
}
|
|
6741
|
+
if (typeof at !== "string")
|
|
6742
|
+
return null;
|
|
6743
|
+
const rel = /^in\s+(\d+)\s*([mhd])$/i.exec(at.trim());
|
|
6744
|
+
if (rel) {
|
|
6745
|
+
const n = Number(rel[1]);
|
|
6746
|
+
const unit = { m: 60000, h: 3600000, d: 86400000 }[rel[2].toLowerCase()] ?? 0;
|
|
6747
|
+
return now + n * unit;
|
|
6748
|
+
}
|
|
6749
|
+
const t = Date.parse(at);
|
|
6750
|
+
return Number.isNaN(t) ? null : t;
|
|
6751
|
+
}
|
|
6752
|
+
|
|
6753
|
+
class ReminderScheduler {
|
|
6754
|
+
maxPerUser;
|
|
6755
|
+
pending = new Map;
|
|
6756
|
+
constructor(maxPerUser = 10) {
|
|
6757
|
+
this.maxPerUser = maxPerUser;
|
|
6758
|
+
}
|
|
6759
|
+
schedule(userId, atMs, text, deliver) {
|
|
6760
|
+
if (!userId || !text.trim() || atMs <= Date.now())
|
|
6761
|
+
return false;
|
|
6762
|
+
const set = this.pending.get(userId) ?? new Set;
|
|
6763
|
+
if (set.size >= this.maxPerUser)
|
|
6764
|
+
return false;
|
|
6765
|
+
const timer = setTimeout(() => {
|
|
6766
|
+
set.delete(timer);
|
|
6767
|
+
console.log(`[cron] 提醒到点 user=${userId.slice(0, 8)}… text=${text.slice(0, 30)}`);
|
|
6768
|
+
try {
|
|
6769
|
+
deliver(userId, `⏰ 提醒:${text}`);
|
|
6770
|
+
} catch (error) {
|
|
6771
|
+
console.error("[cron] 提醒投递失败:", error);
|
|
6772
|
+
}
|
|
6773
|
+
}, atMs - Date.now());
|
|
6774
|
+
set.add(timer);
|
|
6775
|
+
this.pending.set(userId, set);
|
|
6776
|
+
return true;
|
|
6777
|
+
}
|
|
6778
|
+
size(userId) {
|
|
6779
|
+
return this.pending.get(userId)?.size ?? 0;
|
|
6780
|
+
}
|
|
6781
|
+
}
|
|
6782
|
+
|
|
6783
|
+
// src/core/turn-correction.ts
|
|
6784
|
+
function buildAmendPrompt(original, amendment) {
|
|
6785
|
+
return `${original}
|
|
6786
|
+
|
|
6787
|
+
【补充指令】${amendment.trim()}`;
|
|
6788
|
+
}
|
|
6789
|
+
function selectAmendEntry(entries, userId, sessionId) {
|
|
6790
|
+
return entries.filter((e) => e.userId === userId && e.sessionId === sessionId && e.promptId && e.text).sort((a, b) => b.at - a.at)[0];
|
|
6791
|
+
}
|
|
6792
|
+
function lastUserMessageId(msgs) {
|
|
6793
|
+
for (let i = msgs.length - 1;i >= 0; i--) {
|
|
6794
|
+
if (msgs[i].type === "user" && msgs[i].id)
|
|
6795
|
+
return msgs[i].id;
|
|
6796
|
+
}
|
|
6797
|
+
return null;
|
|
6798
|
+
}
|
|
6799
|
+
function messageTextOf(m) {
|
|
6800
|
+
const c = m.content;
|
|
6801
|
+
if (typeof c === "string")
|
|
6802
|
+
return c;
|
|
6803
|
+
if (Array.isArray(c)) {
|
|
6804
|
+
return c.map((p) => typeof p === "object" && p !== null && ("text" in p) ? String(p.text ?? "") : "").join("");
|
|
6805
|
+
}
|
|
6806
|
+
return "";
|
|
6807
|
+
}
|
|
6808
|
+
function resolveBusyMode(envValue) {
|
|
6809
|
+
return envValue?.trim().toLowerCase() === "queue" ? "queue" : "steer";
|
|
6810
|
+
}
|
|
6811
|
+
function parseGoalState(raw) {
|
|
6812
|
+
const text = raw.trim();
|
|
6813
|
+
const jsonText = text.startsWith("{") ? text : "";
|
|
6814
|
+
if (!jsonText)
|
|
6815
|
+
return null;
|
|
6816
|
+
try {
|
|
6817
|
+
const j = JSON.parse(jsonText);
|
|
6818
|
+
const msg = j.message ?? "";
|
|
6819
|
+
if (!msg)
|
|
6820
|
+
return null;
|
|
6821
|
+
const head = msg.slice(0, 60);
|
|
6822
|
+
const state = /goal active|^\s*active/i.test(head) ? "active" : /paused/i.test(head) ? "paused" : /\bdone\b|complete/i.test(head) ? "done" : "unknown";
|
|
6823
|
+
return { state, message: msg };
|
|
6824
|
+
} catch {
|
|
6825
|
+
return null;
|
|
6826
|
+
}
|
|
6827
|
+
}
|
|
6378
6828
|
// src/core/permission.ts
|
|
6379
|
-
import { existsSync as
|
|
6829
|
+
import { existsSync as existsSync9, readFileSync as readFileSync10, writeFileSync as writeFileSync8 } from "fs";
|
|
6380
6830
|
|
|
6381
6831
|
// src/core/util.ts
|
|
6382
6832
|
function truncate(value, max) {
|
|
@@ -6439,8 +6889,8 @@ function classifyApprovalReplyError(error) {
|
|
|
6439
6889
|
var PENDING_PERM_FILE = storageFile("pending-permissions.json");
|
|
6440
6890
|
function loadPendingPermMap(file = PENDING_PERM_FILE) {
|
|
6441
6891
|
try {
|
|
6442
|
-
if (
|
|
6443
|
-
const raw =
|
|
6892
|
+
if (existsSync9(file)) {
|
|
6893
|
+
const raw = readFileSync10(file, "utf-8");
|
|
6444
6894
|
const obj = JSON.parse(raw);
|
|
6445
6895
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
6446
6896
|
const out = {};
|
|
@@ -6756,6 +7206,10 @@ function formatPermissionPrompt(request, mainSessionId, origin) {
|
|
|
6756
7206
|
for (const r of resources)
|
|
6757
7207
|
lines.push(` ${truncate(r, 300)}`);
|
|
6758
7208
|
}
|
|
7209
|
+
if (request.save && request.save.length > 0) {
|
|
7210
|
+
const saves = request.save.slice(0, 3).map((s) => truncate(s, 120));
|
|
7211
|
+
lines.push(`总是允许将保存:${saves.join(";")}`);
|
|
7212
|
+
}
|
|
6759
7213
|
if (request.message)
|
|
6760
7214
|
lines.push(`说明:${truncate(request.message, 300)}`);
|
|
6761
7215
|
lines.push("");
|
|
@@ -6766,13 +7220,49 @@ function formatPermissionPrompt(request, mainSessionId, origin) {
|
|
|
6766
7220
|
}
|
|
6767
7221
|
|
|
6768
7222
|
// src/core/delivery.ts
|
|
6769
|
-
import { existsSync as
|
|
6770
|
-
import { join as
|
|
7223
|
+
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";
|
|
7224
|
+
import { join as join9 } from "path";
|
|
6771
7225
|
import { createHash } from "node:crypto";
|
|
6772
7226
|
|
|
7227
|
+
// src/core/outbound-sanitize.ts
|
|
7228
|
+
var BLOCK_PATTERNS = [
|
|
7229
|
+
/<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi,
|
|
7230
|
+
/<previous_response\b[^>]*>[\s\S]*?<\/previous_response>/gi,
|
|
7231
|
+
/`think`[\s\S]*?`\/think`/gi,
|
|
7232
|
+
/<thinking\b[^>]*>[\s\S]*?<\/thinking>/gi,
|
|
7233
|
+
/<\s*\/?\s*(?:system-reminder|previous_response)\b[^>]*\/?\s*>/gi,
|
|
7234
|
+
/<\s*\/?\s*think(?:ing)?\b[^>]*\/?\s*>/gi
|
|
7235
|
+
];
|
|
7236
|
+
function stripScaffolding(text) {
|
|
7237
|
+
let result = text;
|
|
7238
|
+
for (const re of BLOCK_PATTERNS) {
|
|
7239
|
+
result = result.replace(re, "");
|
|
7240
|
+
}
|
|
7241
|
+
return result.replace(/\n{3,}/g, `
|
|
7242
|
+
|
|
7243
|
+
`);
|
|
7244
|
+
}
|
|
7245
|
+
|
|
6773
7246
|
// src/qq/sender.ts
|
|
7247
|
+
var PUNCT_BACKSLASH = /\\(?=[!-/:-@[-`{-~])/g;
|
|
7248
|
+
var INLINE_CODE_SPLIT = /(`[^`]*`)/g;
|
|
7249
|
+
function escapeLineBackslashes(line) {
|
|
7250
|
+
return line.split(INLINE_CODE_SPLIT).map((seg, i) => i % 2 === 1 ? seg : seg.replace(PUNCT_BACKSLASH, "\\\\")).join("");
|
|
7251
|
+
}
|
|
6774
7252
|
function formatForQQMarkdown(text) {
|
|
6775
|
-
|
|
7253
|
+
const sanitized = stripScaffolding(text);
|
|
7254
|
+
const normalized = normalizeOutboundMarkdown(sanitized.trim());
|
|
7255
|
+
let inFence = false;
|
|
7256
|
+
return normalized.split(`
|
|
7257
|
+
`).map((line) => {
|
|
7258
|
+
const f = matchFence(line);
|
|
7259
|
+
if (f) {
|
|
7260
|
+
inFence = !inFence;
|
|
7261
|
+
return line;
|
|
7262
|
+
}
|
|
7263
|
+
return inFence ? line : escapeLineBackslashes(line);
|
|
7264
|
+
}).join(`
|
|
7265
|
+
`);
|
|
6776
7266
|
}
|
|
6777
7267
|
function formatForQQ(text) {
|
|
6778
7268
|
const codeBlocks = [];
|
|
@@ -6785,6 +7275,17 @@ function formatForQQ(text) {
|
|
|
6785
7275
|
for (let i = 0;i < codeBlocks.length; i++) {
|
|
6786
7276
|
processed = processed.replace(`\x00CB${i}\x00`, codeBlocks[i]);
|
|
6787
7277
|
}
|
|
7278
|
+
let inStripFence = false;
|
|
7279
|
+
processed = processed.split(`
|
|
7280
|
+
`).map((line) => {
|
|
7281
|
+
const f = matchFence(line);
|
|
7282
|
+
if (f) {
|
|
7283
|
+
inStripFence = !inStripFence;
|
|
7284
|
+
return line;
|
|
7285
|
+
}
|
|
7286
|
+
return inStripFence ? line : stripInteractionTags(line);
|
|
7287
|
+
}).join(`
|
|
7288
|
+
`);
|
|
6788
7289
|
return processed.trim();
|
|
6789
7290
|
}
|
|
6790
7291
|
function convertTables(text) {
|
|
@@ -7116,8 +7617,8 @@ function extractEmbeddedQuote(event) {
|
|
|
7116
7617
|
var DEFAULT_QUOTA_FILE = storageFile("quota.json");
|
|
7117
7618
|
function loadQuotaMap(file) {
|
|
7118
7619
|
try {
|
|
7119
|
-
if (
|
|
7120
|
-
const raw =
|
|
7620
|
+
if (existsSync10(file)) {
|
|
7621
|
+
const raw = readFileSync11(file, "utf-8");
|
|
7121
7622
|
const obj = JSON.parse(raw);
|
|
7122
7623
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
7123
7624
|
const out = {};
|
|
@@ -7145,6 +7646,19 @@ var UNDELIVERED_NOTICE = `(此前有未能送达的消息)
|
|
|
7145
7646
|
var QQ_LIST_FORMAT_HINT = `
|
|
7146
7647
|
|
|
7147
7648
|
(输出格式约定:本对话经 QQ 渲染,请用「1、2、3、」顿号或「-」无序列表代替 markdown 有序列表,避免表格;代码块不受影响可正常使用。)`;
|
|
7649
|
+
var QQ_SEND_FILE_HINT = "\n\n如需把本机文件/图片发给 QQ 用户:优先调用 qq_send_file 工具(若工具清单提供,失败会返回精确原因可据以修正);无该工具时,在回复末尾独立一行写 `QQ_SEND_FILE: <绝对路径>`(路径须在发送白名单内,默认 QQ 图片缓存目录与 bot 工作目录)。";
|
|
7650
|
+
function qqPromptHints() {
|
|
7651
|
+
try {
|
|
7652
|
+
const file = join9(storageRoot(), "qq-system-instructions.json");
|
|
7653
|
+
const st = statSync5(file);
|
|
7654
|
+
if (Date.now() - st.mtimeMs < 15 * 60000) {
|
|
7655
|
+
const parsed = JSON.parse(readFileSync11(file, "utf-8"));
|
|
7656
|
+
if (parsed?.mode === "entry" || parsed?.mode === "hook")
|
|
7657
|
+
return "";
|
|
7658
|
+
}
|
|
7659
|
+
} catch {}
|
|
7660
|
+
return QQ_LIST_FORMAT_HINT + QQ_SEND_FILE_HINT;
|
|
7661
|
+
}
|
|
7148
7662
|
function qqListNormalize(text) {
|
|
7149
7663
|
const lines = text.split(`
|
|
7150
7664
|
`);
|
|
@@ -7194,9 +7708,9 @@ function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TT
|
|
|
7194
7708
|
function loadDeliveryAttempts() {
|
|
7195
7709
|
const out = new Map;
|
|
7196
7710
|
try {
|
|
7197
|
-
if (!
|
|
7711
|
+
if (!existsSync10(deliveryDedupeFile()))
|
|
7198
7712
|
return out;
|
|
7199
|
-
const raw = JSON.parse(
|
|
7713
|
+
const raw = JSON.parse(readFileSync11(deliveryDedupeFile(), "utf-8"));
|
|
7200
7714
|
const now = Date.now();
|
|
7201
7715
|
for (const entry of raw) {
|
|
7202
7716
|
if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
|
|
@@ -7208,7 +7722,7 @@ function loadDeliveryAttempts() {
|
|
|
7208
7722
|
}
|
|
7209
7723
|
function saveDeliveryAttempts(entries) {
|
|
7210
7724
|
const raw = [...entries.values()].filter((entry) => Date.now() - entry.at < DELIVERY_DEDUPE_TTL_MS).map((entry) => ({ key: entry.text, at: entry.at }));
|
|
7211
|
-
mkdirSync8(
|
|
7725
|
+
mkdirSync8(join9(deliveryDedupeFile(), ".."), { recursive: true });
|
|
7212
7726
|
const tmp = `${deliveryDedupeFile()}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
7213
7727
|
try {
|
|
7214
7728
|
writeFileSync9(tmp, JSON.stringify(raw, null, 2), { mode: 384 });
|
|
@@ -7224,7 +7738,7 @@ var DELIVERY_LOCK_STALE_MS = 30000;
|
|
|
7224
7738
|
var DELIVERY_LOCK_WAIT_MS = 5000;
|
|
7225
7739
|
var deliverySleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
7226
7740
|
function withDeliveryLock(fn) {
|
|
7227
|
-
mkdirSync8(
|
|
7741
|
+
mkdirSync8(join9(deliveryDedupeFile(), ".."), { recursive: true });
|
|
7228
7742
|
const lockPath = `${deliveryDedupeFile()}.lock`;
|
|
7229
7743
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
7230
7744
|
const deadline = Date.now() + DELIVERY_LOCK_WAIT_MS;
|
|
@@ -7239,7 +7753,7 @@ function withDeliveryLock(fn) {
|
|
|
7239
7753
|
break;
|
|
7240
7754
|
} catch (error) {
|
|
7241
7755
|
try {
|
|
7242
|
-
if (Date.now() -
|
|
7756
|
+
if (Date.now() - statSync5(lockPath).mtimeMs > DELIVERY_LOCK_STALE_MS)
|
|
7243
7757
|
unlinkSync3(lockPath);
|
|
7244
7758
|
} catch {}
|
|
7245
7759
|
if (Date.now() >= deadline)
|
|
@@ -7251,7 +7765,7 @@ function withDeliveryLock(fn) {
|
|
|
7251
7765
|
return fn();
|
|
7252
7766
|
} finally {
|
|
7253
7767
|
try {
|
|
7254
|
-
if (
|
|
7768
|
+
if (readFileSync11(lockPath, "utf-8") === token)
|
|
7255
7769
|
unlinkSync3(lockPath);
|
|
7256
7770
|
} catch {}
|
|
7257
7771
|
}
|
|
@@ -7494,12 +8008,12 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
|
|
|
7494
8008
|
// src/core/outbox.ts
|
|
7495
8009
|
import {
|
|
7496
8010
|
closeSync as closeSync2,
|
|
7497
|
-
existsSync as
|
|
8011
|
+
existsSync as existsSync11,
|
|
7498
8012
|
mkdirSync as mkdirSync9,
|
|
7499
8013
|
openSync as openSync2,
|
|
7500
|
-
readFileSync as
|
|
8014
|
+
readFileSync as readFileSync12,
|
|
7501
8015
|
renameSync as renameSync4,
|
|
7502
|
-
statSync as
|
|
8016
|
+
statSync as statSync6,
|
|
7503
8017
|
unlinkSync as unlinkSync4,
|
|
7504
8018
|
writeFileSync as writeFileSync10
|
|
7505
8019
|
} from "node:fs";
|
|
@@ -7552,9 +8066,9 @@ function atomicWrite(filePath, document) {
|
|
|
7552
8066
|
}
|
|
7553
8067
|
}
|
|
7554
8068
|
function readDocument(filePath, now) {
|
|
7555
|
-
if (!
|
|
8069
|
+
if (!existsSync11(filePath))
|
|
7556
8070
|
return { version: 1, entries: [] };
|
|
7557
|
-
const raw = JSON.parse(
|
|
8071
|
+
const raw = JSON.parse(readFileSync12(filePath, "utf8"));
|
|
7558
8072
|
if (Array.isArray(raw)) {
|
|
7559
8073
|
return { version: 1, entries: pruneOutboxEntries(raw, now) };
|
|
7560
8074
|
}
|
|
@@ -7600,7 +8114,7 @@ function createOutbox(options = {}) {
|
|
|
7600
8114
|
break;
|
|
7601
8115
|
} catch (error) {
|
|
7602
8116
|
try {
|
|
7603
|
-
if (Date.now() -
|
|
8117
|
+
if (Date.now() - statSync6(lockPath).mtimeMs > lockStaleMs)
|
|
7604
8118
|
unlinkSync4(lockPath);
|
|
7605
8119
|
} catch {}
|
|
7606
8120
|
if (Date.now() >= deadline)
|
|
@@ -7612,7 +8126,7 @@ function createOutbox(options = {}) {
|
|
|
7612
8126
|
return fn();
|
|
7613
8127
|
} finally {
|
|
7614
8128
|
try {
|
|
7615
|
-
if (
|
|
8129
|
+
if (readFileSync12(lockPath, "utf8") === token)
|
|
7616
8130
|
unlinkSync4(lockPath);
|
|
7617
8131
|
} catch {}
|
|
7618
8132
|
}
|
|
@@ -8005,12 +8519,12 @@ function handleApprovalInteraction(event, gate) {
|
|
|
8005
8519
|
// src/core/form-journal.ts
|
|
8006
8520
|
import {
|
|
8007
8521
|
closeSync as closeSync3,
|
|
8008
|
-
existsSync as
|
|
8522
|
+
existsSync as existsSync12,
|
|
8009
8523
|
mkdirSync as mkdirSync10,
|
|
8010
8524
|
openSync as openSync3,
|
|
8011
|
-
readFileSync as
|
|
8525
|
+
readFileSync as readFileSync13,
|
|
8012
8526
|
renameSync as renameSync5,
|
|
8013
|
-
statSync as
|
|
8527
|
+
statSync as statSync7,
|
|
8014
8528
|
unlinkSync as unlinkSync5,
|
|
8015
8529
|
writeFileSync as writeFileSync11
|
|
8016
8530
|
} from "fs";
|
|
@@ -8073,9 +8587,9 @@ function snapshot(entry) {
|
|
|
8073
8587
|
function createFormJournal(path = defaultFormJournalPath()) {
|
|
8074
8588
|
function read() {
|
|
8075
8589
|
try {
|
|
8076
|
-
if (!
|
|
8590
|
+
if (!existsSync12(path))
|
|
8077
8591
|
return [];
|
|
8078
|
-
const raw = JSON.parse(
|
|
8592
|
+
const raw = JSON.parse(readFileSync13(path, "utf-8"));
|
|
8079
8593
|
const values = Array.isArray(raw) ? raw : raw?.version === 1 && Array.isArray(raw.entries) ? raw.entries : [];
|
|
8080
8594
|
const byUser = new Map;
|
|
8081
8595
|
for (const value of values) {
|
|
@@ -8122,7 +8636,7 @@ function createFormJournal(path = defaultFormJournalPath()) {
|
|
|
8122
8636
|
break;
|
|
8123
8637
|
} catch (error) {
|
|
8124
8638
|
try {
|
|
8125
|
-
if (Date.now() -
|
|
8639
|
+
if (Date.now() - statSync7(lockPath).mtimeMs > LOCK_STALE_MS)
|
|
8126
8640
|
unlinkSync5(lockPath);
|
|
8127
8641
|
} catch {}
|
|
8128
8642
|
if (Date.now() >= deadline) {
|
|
@@ -8135,7 +8649,7 @@ function createFormJournal(path = defaultFormJournalPath()) {
|
|
|
8135
8649
|
return fn();
|
|
8136
8650
|
} finally {
|
|
8137
8651
|
try {
|
|
8138
|
-
if (
|
|
8652
|
+
if (readFileSync13(lockPath, "utf-8") === token)
|
|
8139
8653
|
unlinkSync5(lockPath);
|
|
8140
8654
|
} catch {}
|
|
8141
8655
|
}
|
|
@@ -8702,8 +9216,8 @@ function createFormBridge(deps) {
|
|
|
8702
9216
|
}
|
|
8703
9217
|
|
|
8704
9218
|
// src/core/inflight-journal.ts
|
|
8705
|
-
import { existsSync as
|
|
8706
|
-
import { join as
|
|
9219
|
+
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";
|
|
9220
|
+
import { join as join10 } from "path";
|
|
8707
9221
|
|
|
8708
9222
|
// src/core/inbound-dedupe.ts
|
|
8709
9223
|
import { createHash as createHash2 } from "crypto";
|
|
@@ -8742,8 +9256,8 @@ function load(file) {
|
|
|
8742
9256
|
let entries = [];
|
|
8743
9257
|
const path = journalPath(file);
|
|
8744
9258
|
try {
|
|
8745
|
-
if (
|
|
8746
|
-
const raw = JSON.parse(
|
|
9259
|
+
if (existsSync13(path)) {
|
|
9260
|
+
const raw = JSON.parse(readFileSync14(path, "utf-8"));
|
|
8747
9261
|
if (Array.isArray(raw))
|
|
8748
9262
|
entries = raw;
|
|
8749
9263
|
}
|
|
@@ -8754,7 +9268,7 @@ function load(file) {
|
|
|
8754
9268
|
}
|
|
8755
9269
|
function save(file, entries) {
|
|
8756
9270
|
const path = journalPath(file);
|
|
8757
|
-
mkdirSync11(
|
|
9271
|
+
mkdirSync11(join10(path, ".."), { recursive: true });
|
|
8758
9272
|
const retained = pruneInflightEntries(entries);
|
|
8759
9273
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
8760
9274
|
try {
|
|
@@ -8772,7 +9286,7 @@ var JOURNAL_LOCK_WAIT_MS = 5000;
|
|
|
8772
9286
|
var sleepArray3 = new Int32Array(new SharedArrayBuffer(4));
|
|
8773
9287
|
function withJournalLock(file, fn) {
|
|
8774
9288
|
const path = journalPath(file);
|
|
8775
|
-
mkdirSync11(
|
|
9289
|
+
mkdirSync11(join10(path, ".."), { recursive: true });
|
|
8776
9290
|
const lockPath = `${path}.lock`;
|
|
8777
9291
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
8778
9292
|
const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
|
|
@@ -8787,7 +9301,7 @@ function withJournalLock(file, fn) {
|
|
|
8787
9301
|
break;
|
|
8788
9302
|
} catch (error) {
|
|
8789
9303
|
try {
|
|
8790
|
-
if (Date.now() -
|
|
9304
|
+
if (Date.now() - statSync8(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
|
|
8791
9305
|
unlinkSync6(lockPath);
|
|
8792
9306
|
} catch {}
|
|
8793
9307
|
if (Date.now() >= deadline) {
|
|
@@ -8800,7 +9314,7 @@ function withJournalLock(file, fn) {
|
|
|
8800
9314
|
return fn();
|
|
8801
9315
|
} finally {
|
|
8802
9316
|
try {
|
|
8803
|
-
if (
|
|
9317
|
+
if (readFileSync14(lockPath, "utf-8") === token)
|
|
8804
9318
|
unlinkSync6(lockPath);
|
|
8805
9319
|
} catch {}
|
|
8806
9320
|
}
|
|
@@ -9089,6 +9603,7 @@ var REASON_LABEL = {
|
|
|
9089
9603
|
dropped: "已删除",
|
|
9090
9604
|
blocked: "被阻塞",
|
|
9091
9605
|
superseded: "被新回合取代",
|
|
9606
|
+
steered: "已并入当前任务",
|
|
9092
9607
|
expired: "已过期",
|
|
9093
9608
|
redispatch: "重启重派",
|
|
9094
9609
|
manual: "人工结清"
|
|
@@ -9499,6 +10014,105 @@ function formatStatusLine(view) {
|
|
|
9499
10014
|
return `队列/台账:排队 ${view.counts.queued} · 在途 ${view.counts.inflight} · 执行中 ${view.counts.running} · 孤儿 ${view.counts.orphan} · 最近拒绝 ${view.counts.rejected}`;
|
|
9500
10015
|
}
|
|
9501
10016
|
|
|
10017
|
+
// src/core/watchdog.ts
|
|
10018
|
+
init_log_rotate();
|
|
10019
|
+
|
|
10020
|
+
// src/core/instance-lock.ts
|
|
10021
|
+
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";
|
|
10022
|
+
import { join as join11 } from "path";
|
|
10023
|
+
import { homedir as homedir6 } from "os";
|
|
10024
|
+
var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
|
|
10025
|
+
var LOCK_STALE_MS2 = 30000;
|
|
10026
|
+
var LOCK_UPDATE_MS = 1e4;
|
|
10027
|
+
var LOCK_RETRY_MS = 5000;
|
|
10028
|
+
var LOCK_SELF_CHECK_MS = 60000;
|
|
10029
|
+
function lockPathOf(appId) {
|
|
10030
|
+
return join11(homedir6(), ".openqq", `openqq-${appId}.lock`);
|
|
10031
|
+
}
|
|
10032
|
+
function touch(path) {
|
|
10033
|
+
const now = new Date;
|
|
10034
|
+
utimesSync(path, now, now);
|
|
10035
|
+
}
|
|
10036
|
+
function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
|
|
10037
|
+
const heartbeatMs = opts?.heartbeatMs ?? LOCK_UPDATE_MS;
|
|
10038
|
+
const selfCheckMs = opts?.selfCheckMs ?? LOCK_SELF_CHECK_MS;
|
|
10039
|
+
try {
|
|
10040
|
+
mkdirSync12(join11(path, ".."), { recursive: true });
|
|
10041
|
+
const fd = openSync5(path, "wx");
|
|
10042
|
+
writeFileSync13(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
|
|
10043
|
+
closeSync5(fd);
|
|
10044
|
+
} catch {
|
|
10045
|
+
try {
|
|
10046
|
+
const age = Date.now() - statSync9(path).mtimeMs;
|
|
10047
|
+
if (age <= staleMs)
|
|
10048
|
+
return null;
|
|
10049
|
+
unlinkSync7(path);
|
|
10050
|
+
const fd = openSync5(path, "wx");
|
|
10051
|
+
writeFileSync13(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
|
|
10052
|
+
closeSync5(fd);
|
|
10053
|
+
console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
|
|
10054
|
+
} catch {
|
|
10055
|
+
return null;
|
|
10056
|
+
}
|
|
10057
|
+
}
|
|
10058
|
+
const heartbeat = setInterval(() => {
|
|
10059
|
+
try {
|
|
10060
|
+
touch(path);
|
|
10061
|
+
} catch {}
|
|
10062
|
+
}, heartbeatMs);
|
|
10063
|
+
heartbeat.unref?.();
|
|
10064
|
+
const selfCheck = setInterval(() => {
|
|
10065
|
+
try {
|
|
10066
|
+
const holder = JSON.parse(readFileSync15(path, "utf-8")).pid;
|
|
10067
|
+
if (holder === process.pid)
|
|
10068
|
+
return;
|
|
10069
|
+
try {
|
|
10070
|
+
process.kill(holder, 0);
|
|
10071
|
+
const lockFresh = Date.now() - statSync9(path).mtimeMs <= LOCK_STALE_MS2;
|
|
10072
|
+
if (lockFresh) {
|
|
10073
|
+
console.error(`[instance-lock] 自检:锁已被 pid=${holder} 持有且进程存活(锁新鲜),本实例为残留 believer,自杀退出`);
|
|
10074
|
+
process.exit(1);
|
|
10075
|
+
}
|
|
10076
|
+
console.warn(`[instance-lock] 自检:holder pid=${holder} 存活但锁已陈旧(疑 PID 复用),不自杀,交由 stale 强抢接管`);
|
|
10077
|
+
} catch {}
|
|
10078
|
+
} catch {
|
|
10079
|
+
console.error("[instance-lock] 自检:锁文件已消失(被接管或强抢流程删除),本实例退出");
|
|
10080
|
+
process.exit(1);
|
|
10081
|
+
}
|
|
10082
|
+
}, selfCheckMs);
|
|
10083
|
+
selfCheck.unref?.();
|
|
10084
|
+
let released = false;
|
|
10085
|
+
return {
|
|
10086
|
+
release: () => {
|
|
10087
|
+
if (released)
|
|
10088
|
+
return;
|
|
10089
|
+
released = true;
|
|
10090
|
+
clearInterval(heartbeat);
|
|
10091
|
+
clearInterval(selfCheck);
|
|
10092
|
+
try {
|
|
10093
|
+
unlinkSync7(path);
|
|
10094
|
+
} catch {}
|
|
10095
|
+
}
|
|
10096
|
+
};
|
|
10097
|
+
}
|
|
10098
|
+
function acquireInstanceLock(appId) {
|
|
10099
|
+
return acquireInstanceLockAt(lockPathOf(appId));
|
|
10100
|
+
}
|
|
10101
|
+
function shouldLogStandby(attempt) {
|
|
10102
|
+
return attempt === 0 || attempt % 120 === 0;
|
|
10103
|
+
}
|
|
10104
|
+
async function waitInstanceLock(appId) {
|
|
10105
|
+
for (let attempt = 0;; attempt++) {
|
|
10106
|
+
const lock = acquireInstanceLock(appId);
|
|
10107
|
+
if (lock)
|
|
10108
|
+
return lock;
|
|
10109
|
+
if (shouldLogStandby(attempt)) {
|
|
10110
|
+
console.log(`[instance-lock] 已有实例在运行,本实例待命(每 ${LOCK_RETRY_MS / 1000}s 重试抢锁,日志已节流)`);
|
|
10111
|
+
}
|
|
10112
|
+
await new Promise((r) => setTimeout(r, LOCK_RETRY_MS));
|
|
10113
|
+
}
|
|
10114
|
+
}
|
|
10115
|
+
|
|
9502
10116
|
// src/core/watchdog.ts
|
|
9503
10117
|
var HEARTBEAT_STALE_MS = 5 * 60000;
|
|
9504
10118
|
function isPidAlive(pid) {
|
|
@@ -9519,6 +10133,78 @@ var DEFAULT_SUPERVISOR_POLICY = {
|
|
|
9519
10133
|
claimTtlMs: 90000
|
|
9520
10134
|
};
|
|
9521
10135
|
|
|
10136
|
+
// src/core/send-requests.ts
|
|
10137
|
+
import { existsSync as existsSync14, mkdirSync as mkdirSync13, readdirSync as readdirSync3, readFileSync as readFileSync16, renameSync as renameSync7, statSync as statSync10, writeFileSync as writeFileSync14 } from "node:fs";
|
|
10138
|
+
import { join as join12 } from "node:path";
|
|
10139
|
+
function sendRequestsDirFor(appId) {
|
|
10140
|
+
return join12(storageRoot(appId), "send-requests");
|
|
10141
|
+
}
|
|
10142
|
+
function startSendRequestConsumer(opts) {
|
|
10143
|
+
const dir = opts.dir ?? sendRequestsDirFor(opts.appId);
|
|
10144
|
+
const intervalMs = opts.intervalMs ?? 1500;
|
|
10145
|
+
const log = opts.log ?? (() => {});
|
|
10146
|
+
const seen = new Map;
|
|
10147
|
+
mkdirSync13(dir, { recursive: true });
|
|
10148
|
+
for (const f of readdirSync3(dir)) {
|
|
10149
|
+
if (!f.endsWith(".result.json"))
|
|
10150
|
+
continue;
|
|
10151
|
+
const full = join12(dir, f);
|
|
10152
|
+
try {
|
|
10153
|
+
const result = JSON.parse(readFileSync16(full, "utf-8"));
|
|
10154
|
+
const key = result.dedupeKey;
|
|
10155
|
+
if (key)
|
|
10156
|
+
seen.set(key, result);
|
|
10157
|
+
if (Date.now() - statSync10(full).mtimeMs > 24 * 60 * 60000)
|
|
10158
|
+
renameSync7(full, full + ".old");
|
|
10159
|
+
} catch {}
|
|
10160
|
+
}
|
|
10161
|
+
const sendFile = opts.sendFile ?? ((ctx, path) => sendLocalFile(ctx, path, { getToken: opts.getToken }));
|
|
10162
|
+
async function consumeOne(file) {
|
|
10163
|
+
const full = join12(dir, file);
|
|
10164
|
+
let req;
|
|
10165
|
+
try {
|
|
10166
|
+
req = JSON.parse(readFileSync16(full, "utf-8"));
|
|
10167
|
+
} catch {
|
|
10168
|
+
renameSync7(full, full + ".bad.json");
|
|
10169
|
+
log(`[send-requests] 坏请求已隔离: ${file}`);
|
|
10170
|
+
return;
|
|
10171
|
+
}
|
|
10172
|
+
const prior = seen.get(req.dedupeKey);
|
|
10173
|
+
const base = { id: req.id, ok: true, at: Date.now() };
|
|
10174
|
+
let result;
|
|
10175
|
+
if (prior) {
|
|
10176
|
+
result = { ...base, ok: prior.ok, detail: prior.detail, error: prior.error, deduped: true };
|
|
10177
|
+
} else {
|
|
10178
|
+
try {
|
|
10179
|
+
const ctx = opts.ctxForUser(req.userId);
|
|
10180
|
+
const detail = await sendFile(ctx, normalizeLocalPath(req.path));
|
|
10181
|
+
result = { ...base, ok: true, detail };
|
|
10182
|
+
} catch (error) {
|
|
10183
|
+
result = { ...base, ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
10184
|
+
}
|
|
10185
|
+
seen.set(req.dedupeKey, { ...result, dedupeKey: req.dedupeKey });
|
|
10186
|
+
}
|
|
10187
|
+
const payload = JSON.stringify({ ...result, dedupeKey: req.dedupeKey });
|
|
10188
|
+
writeFileSync14(join12(dir, `${req.id}.result.tmp`), payload, "utf-8");
|
|
10189
|
+
renameSync7(join12(dir, `${req.id}.result.tmp`), join12(dir, `${req.id}.result.json`));
|
|
10190
|
+
renameSync7(full, full + ".done");
|
|
10191
|
+
log(`[send-requests] ${result.ok ? "已发送" : "发送失败"}${result.deduped ? "(去重)" : ""} user=${req.userId.slice(0, 8)}… path=${req.path}`);
|
|
10192
|
+
}
|
|
10193
|
+
const timer = setInterval(() => {
|
|
10194
|
+
let files;
|
|
10195
|
+
try {
|
|
10196
|
+
files = readdirSync3(dir).filter((f) => f.endsWith(".json") && !f.endsWith(".result.json") && !f.endsWith(".bad.json") && !f.endsWith(".done"));
|
|
10197
|
+
} catch {
|
|
10198
|
+
return;
|
|
10199
|
+
}
|
|
10200
|
+
for (const f of files) {
|
|
10201
|
+
consumeOne(f).catch((error) => log(`[send-requests] 消费失败 ${f}: ${error instanceof Error ? error.message : error}`));
|
|
10202
|
+
}
|
|
10203
|
+
}, intervalMs);
|
|
10204
|
+
timer.unref?.();
|
|
10205
|
+
return () => clearInterval(timer);
|
|
10206
|
+
}
|
|
10207
|
+
|
|
9522
10208
|
// src/bridge.ts
|
|
9523
10209
|
var QUEUE_MAX = 20;
|
|
9524
10210
|
var QUEUE_RECEIPTS_ENABLED = /^(1|true|on)$/i.test(process.env.QQ_QUEUE_RECEIPTS ?? "");
|
|
@@ -9562,12 +10248,12 @@ function heartbeatDecision(lastHeartbeatAt, now, intervalMs = BG_HEARTBEAT_MS) {
|
|
|
9562
10248
|
}
|
|
9563
10249
|
function heartbeatText(execMin, idleMin, lastAction) {
|
|
9564
10250
|
const action = lastAction ? `,刚才在处理【${lastAction}】` : "";
|
|
9565
|
-
const stale = idleMin >= 30 ? `。⚠️ 注意:已 ${idleMin} 分钟没有任何动静,疑似卡住——可发 /
|
|
10251
|
+
const stale = idleMin >= 30 ? `。⚠️ 注意:已 ${idleMin} 分钟没有任何动静,疑似卡住——可发 /cancel 中止后重发` : "";
|
|
9566
10252
|
return `⏳ 你的任务还在后台执行:已用时 ${execMin} 分钟${action}${stale}。完成后我会自动把结果发给你。`;
|
|
9567
10253
|
}
|
|
9568
10254
|
var MISSING_IDLE_GRACE_MS = 10 * 60000;
|
|
9569
|
-
function missingIdleDone(turn, lastProgressAt, now, graceMs = MISSING_IDLE_GRACE_MS) {
|
|
9570
|
-
return !turn.hasIdle && Boolean(turn.text) && now - lastProgressAt >= graceMs;
|
|
10255
|
+
function missingIdleDone(turn, lastProgressAt, now, graceMs = MISSING_IDLE_GRACE_MS, hasRunningTool = false) {
|
|
10256
|
+
return !turn.hasIdle && !hasRunningTool && Boolean(turn.text) && now - lastProgressAt >= graceMs;
|
|
9571
10257
|
}
|
|
9572
10258
|
var BG_STREAM_DEAD_MS_DEFAULT = 15 * 60000;
|
|
9573
10259
|
var BG_TOOL_GRACE_MS_DEFAULT = 60 * 60000;
|
|
@@ -9581,6 +10267,16 @@ function resolveToolGraceMs(envValue) {
|
|
|
9581
10267
|
const raw = Number(envValue);
|
|
9582
10268
|
return Number.isFinite(raw) && raw >= 300000 && raw <= 14400000 ? Math.floor(raw) : BG_TOOL_GRACE_MS_DEFAULT;
|
|
9583
10269
|
}
|
|
10270
|
+
function deadToolResumeHint(runningTools, abortConfirmed = true) {
|
|
10271
|
+
if (runningTools.length === 0)
|
|
10272
|
+
return "";
|
|
10273
|
+
const base = `
|
|
10274
|
+
|
|
10275
|
+
【断点续作提示】上一轮在执行工具 ${runningTools.join("、")} 时中断,该工具执行结果未知(可能已生效)。重做任何写操作前,请先用只读手段核实副作用是否已发生(如查 git log、文件内容),避免重复执行。`;
|
|
10276
|
+
if (abortConfirmed)
|
|
10277
|
+
return base;
|
|
10278
|
+
return base + "另:上一轮中止未获确认,相关进程可能仍在运行——请先核实相关进程与副作用状态,再决定是否重做写操作。";
|
|
10279
|
+
}
|
|
9584
10280
|
function resolveResumeMax(envValue) {
|
|
9585
10281
|
if (envValue === undefined || envValue.trim() === "")
|
|
9586
10282
|
return 3;
|
|
@@ -9590,10 +10286,10 @@ function resolveResumeMax(envValue) {
|
|
|
9590
10286
|
function resumeDecision(resumeCount, max) {
|
|
9591
10287
|
return max > 0 && resumeCount < max ? "resume" : "giveup";
|
|
9592
10288
|
}
|
|
9593
|
-
function
|
|
10289
|
+
function streamLivenessDetail(msgs, promptId, baseline, now, deadMs, toolGraceMs = BG_TOOL_GRACE_MS_DEFAULT) {
|
|
9594
10290
|
const turn = turnStateOf(msgs, promptId, baseline);
|
|
9595
10291
|
if (turn.hasIdle)
|
|
9596
|
-
return "alive";
|
|
10292
|
+
return { state: "alive", runningTools: [] };
|
|
9597
10293
|
const ordered = [...msgs].sort((a, b) => (a.time?.created ?? 0) - (b.time?.created ?? 0));
|
|
9598
10294
|
let startIdx = 0;
|
|
9599
10295
|
if (turn.anchored) {
|
|
@@ -9617,7 +10313,7 @@ function streamLiveness(msgs, promptId, baseline, now, deadMs, toolGraceMs = BG_
|
|
|
9617
10313
|
}
|
|
9618
10314
|
let latestActivity = 0;
|
|
9619
10315
|
let anyUncompleted = false;
|
|
9620
|
-
|
|
10316
|
+
const runningTools = new Set;
|
|
9621
10317
|
for (let i = startIdx;i < ordered.length; i++) {
|
|
9622
10318
|
const m = ordered[i];
|
|
9623
10319
|
if (m.type !== "assistant")
|
|
@@ -9631,16 +10327,19 @@ function streamLiveness(msgs, promptId, baseline, now, deadMs, toolGraceMs = BG_
|
|
|
9631
10327
|
anyUncompleted = true;
|
|
9632
10328
|
for (const p of [...m.parts ?? [], ...m.content ?? []]) {
|
|
9633
10329
|
if ((p.type === "tool" || p.type === undefined) && p.state?.status === "running")
|
|
9634
|
-
|
|
10330
|
+
runningTools.add(p.tool ?? "unknown");
|
|
9635
10331
|
}
|
|
9636
10332
|
}
|
|
9637
10333
|
if (latestActivity === 0)
|
|
9638
|
-
return "none";
|
|
10334
|
+
return { state: "none", runningTools: [] };
|
|
9639
10335
|
if (!anyUncompleted)
|
|
9640
|
-
return "alive";
|
|
9641
|
-
if (
|
|
9642
|
-
return "alive";
|
|
9643
|
-
|
|
10336
|
+
return { state: "alive", runningTools: [...runningTools] };
|
|
10337
|
+
if (runningTools.size > 0 && now - latestActivity < toolGraceMs)
|
|
10338
|
+
return { state: "alive", runningTools: [...runningTools] };
|
|
10339
|
+
if (now - latestActivity >= deadMs) {
|
|
10340
|
+
return { state: runningTools.size > 0 ? "dead-tool" : "dead", runningTools: [...runningTools] };
|
|
10341
|
+
}
|
|
10342
|
+
return { state: "alive", runningTools: [...runningTools] };
|
|
9644
10343
|
}
|
|
9645
10344
|
function assistantTextOf(m) {
|
|
9646
10345
|
return (m.content ?? []).filter((p) => p.type === "text" && p.text?.trim()).map((p) => p.text ?? "").join(`
|
|
@@ -9880,18 +10579,19 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
9880
10579
|
await safeDeliver(ctx, `⚠️ 后台任务底层执行多次失去响应(已自动续作 ${resumeCount} 次仍失败),停止自动跟进;队列已放行。如仍需要该结果请重新发送`).catch(() => {});
|
|
9881
10580
|
console.log(`[bridge] 后台回合流活性丧失:续作${resumeCount}次仍死,expired 结清 session=${sessionId} msg=${shortId(trackId)}`);
|
|
9882
10581
|
}
|
|
9883
|
-
async function resumeDead() {
|
|
10582
|
+
async function resumeDead(hint = "", abortConfirmed = true) {
|
|
9884
10583
|
if (cancelled || finished)
|
|
9885
10584
|
return;
|
|
9886
10585
|
resumeCount += 1;
|
|
9887
10586
|
console.log(`[bridge] 后台死回合自动续作 #${resumeCount}/${MAX_RESUME} session=${sessionId} msg=${shortId(trackId)}`);
|
|
9888
|
-
|
|
10587
|
+
const notice = abortConfirmed ? `⚠️ 后台任务底层执行失去响应,已中止旧回合并续作(第 ${resumeCount}/${MAX_RESUME} 次);继续后台跟踪,完成自动回传` : `⚠️ 后台任务底层执行失去响应,已请求中止旧回合(未获已停止确认,旧进程可能仍在运行)并续作(第 ${resumeCount}/${MAX_RESUME} 次);继续后台跟踪,完成自动回传`;
|
|
10588
|
+
await safeDeliver(ctx, notice).catch(() => {});
|
|
9889
10589
|
try {
|
|
9890
10590
|
const prepared = ctx.preparedAttachments ?? await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
|
|
9891
10591
|
const { text: promptBody, files } = augmentPromptWithAttachments(ctx.content, prepared);
|
|
9892
10592
|
const promptText = (ctx.quoteText ? `> 引用上文:${ctx.quoteText}
|
|
9893
10593
|
|
|
9894
|
-
${promptBody}` : promptBody) +
|
|
10594
|
+
${promptBody}` : promptBody) + qqPromptHints() + hint;
|
|
9895
10595
|
client.promptAndWait(sessionId, promptText, {
|
|
9896
10596
|
files: files.length ? files : undefined,
|
|
9897
10597
|
directory: anchorDirectory,
|
|
@@ -9965,13 +10665,13 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
9965
10665
|
console.log(`[bridge] 后台任务进度心跳 session=${sessionId} execMin=${hbExecMin} idleMin=${hbIdleMin}`);
|
|
9966
10666
|
safeDeliver(ctx, heartbeatText(hbExecMin, hbIdleMin, hbAction)).catch(() => {});
|
|
9967
10667
|
}
|
|
9968
|
-
const
|
|
9969
|
-
|
|
9970
|
-
|
|
9971
|
-
|
|
9972
|
-
});
|
|
10668
|
+
const probe = streamLivenessDetail(msgs, promptId, baseline, now, STREAM_DEAD_MS, TOOL_GRACE_MS);
|
|
10669
|
+
const live = probe.state;
|
|
10670
|
+
if (live === "dead" || live === "dead-tool") {
|
|
10671
|
+
const abortConfirmed = await client.session.abort({ path: { id: sessionId } }).then(() => true).catch(() => false);
|
|
10672
|
+
console.log(`[bridge] 判死处置 session=${sessionId} live=${live} abortConfirmed=${abortConfirmed} resumeCount=${resumeCount}`);
|
|
9973
10673
|
if (resumeDecision(resumeCount, MAX_RESUME) === "resume") {
|
|
9974
|
-
await resumeDead();
|
|
10674
|
+
await resumeDead(live === "dead-tool" ? deadToolResumeHint(probe.runningTools, abortConfirmed) : "", abortConfirmed);
|
|
9975
10675
|
} else {
|
|
9976
10676
|
await finishDead();
|
|
9977
10677
|
}
|
|
@@ -9979,7 +10679,7 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
9979
10679
|
}
|
|
9980
10680
|
if (turn.superseded) {
|
|
9981
10681
|
await finish("superseded");
|
|
9982
|
-
} else if (turn.hasIdle || missingIdleDone(turn, lastProgressAt, now)) {
|
|
10682
|
+
} else if (turn.hasIdle || missingIdleDone(turn, lastProgressAt, now, MISSING_IDLE_GRACE_MS, probe.runningTools.length > 0)) {
|
|
9983
10683
|
await finish("done");
|
|
9984
10684
|
}
|
|
9985
10685
|
} catch (error) {
|
|
@@ -10013,7 +10713,7 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10013
10713
|
saveWatchedMap(activeWatches, storageAppId ? roleFile("watch.json") : undefined);
|
|
10014
10714
|
return [
|
|
10015
10715
|
`\uD83D\uDC41 已开启观察:${sessionID}`,
|
|
10016
|
-
"该会话的工具调用/执行完成会实时推送摘要,/watch off 停止。",
|
|
10716
|
+
"该会话的工具调用/执行完成会实时推送摘要,/status watch off 停止。",
|
|
10017
10717
|
"(≥2 秒节流合并;QQ 主动消息有日配额,被动窗口内不受限)"
|
|
10018
10718
|
].join(`
|
|
10019
10719
|
`);
|
|
@@ -10044,6 +10744,45 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10044
10744
|
console.warn("[bridge] 通知发送失败(不阻断主流程):", toErrorMessage2(error));
|
|
10045
10745
|
}
|
|
10046
10746
|
};
|
|
10747
|
+
const cronScheduler = new ReminderScheduler;
|
|
10748
|
+
const goalStates = new Map;
|
|
10749
|
+
const goalKickoffs = new Map;
|
|
10750
|
+
const GOAL_WATCH_INTERVAL_MS = 5 * 60000;
|
|
10751
|
+
const GOAL_NOTIFY_DEDUP_MS = 30 * 60000;
|
|
10752
|
+
let lastGoalWatchAt = 0;
|
|
10753
|
+
async function goalWatchTick() {
|
|
10754
|
+
if (Date.now() - lastGoalWatchAt < GOAL_WATCH_INTERVAL_MS)
|
|
10755
|
+
return;
|
|
10756
|
+
lastGoalWatchAt = Date.now();
|
|
10757
|
+
for (const s of sessions.all()) {
|
|
10758
|
+
const prev = goalStates.get(s.sessionId);
|
|
10759
|
+
if (!prev)
|
|
10760
|
+
continue;
|
|
10761
|
+
try {
|
|
10762
|
+
let raw = null;
|
|
10763
|
+
try {
|
|
10764
|
+
const res = await client.session.command({ path: { id: s.sessionId }, body: { name: "goal", text: "" } });
|
|
10765
|
+
raw = JSON.stringify(res);
|
|
10766
|
+
} catch (error) {
|
|
10767
|
+
raw = error.body ?? null;
|
|
10768
|
+
}
|
|
10769
|
+
const parsed = raw ? parseGoalState(raw) : null;
|
|
10770
|
+
if (!parsed)
|
|
10771
|
+
continue;
|
|
10772
|
+
const transitionToTerminal = (parsed.state === "paused" || parsed.state === "done") && prev.state === "active" && (!prev.notified || Date.now() - prev.at > GOAL_NOTIFY_DEDUP_MS);
|
|
10773
|
+
if (parsed.state === "active") {
|
|
10774
|
+
goalStates.set(s.sessionId, { state: "active", at: Date.now(), notified: false });
|
|
10775
|
+
} else if (transitionToTerminal) {
|
|
10776
|
+
goalStates.set(s.sessionId, { state: parsed.state, at: Date.now(), notified: true });
|
|
10777
|
+
const head = parsed.state === "done" ? "✅ 目标已达成" : "\uD83C\uDFAF 目标已暂停";
|
|
10778
|
+
safeDeliver(ctxForUser(s.userId), `${head}(${s.sessionId})
|
|
10779
|
+
${parsed.message.slice(0, 400)}
|
|
10780
|
+
——发 /goal 看详情;resume 继续 / clear 放弃`).catch(() => {});
|
|
10781
|
+
console.log(`[goal-watch] 状态转变通知 user=${s.userId.slice(0, 8)}… state=${parsed.state}`);
|
|
10782
|
+
}
|
|
10783
|
+
} catch {}
|
|
10784
|
+
}
|
|
10785
|
+
}
|
|
10047
10786
|
const perm = createPermissionGate({
|
|
10048
10787
|
client,
|
|
10049
10788
|
sendReply,
|
|
@@ -10064,8 +10803,30 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10064
10803
|
safeDeliver,
|
|
10065
10804
|
bgWaits,
|
|
10066
10805
|
busyUsers,
|
|
10067
|
-
settingsFile: storageAppId ? roleFile("settings.json") : undefined
|
|
10806
|
+
settingsFile: storageAppId ? roleFile("settings.json") : undefined,
|
|
10807
|
+
onDigest: (userId, digest) => {
|
|
10808
|
+
const hit = parseCronReminder(digest, Date.now());
|
|
10809
|
+
if (!hit)
|
|
10810
|
+
return digest;
|
|
10811
|
+
registerCron(userId, hit);
|
|
10812
|
+
return hit.cleanedText;
|
|
10813
|
+
},
|
|
10814
|
+
goalObjectiveOf: (sessionID) => {
|
|
10815
|
+
const k = goalKickoffs.get(sessionID);
|
|
10816
|
+
if (!k)
|
|
10817
|
+
return;
|
|
10818
|
+
if (Date.now() - k.at > 30 * 60000) {
|
|
10819
|
+
goalKickoffs.delete(sessionID);
|
|
10820
|
+
return;
|
|
10821
|
+
}
|
|
10822
|
+
return k.text;
|
|
10823
|
+
}
|
|
10068
10824
|
});
|
|
10825
|
+
function registerCron(userId, hit) {
|
|
10826
|
+
return cronScheduler.schedule(userId, hit.atMs, hit.reminderText, (uid, t) => {
|
|
10827
|
+
safeDeliver(ctxForUser(uid), t).catch(() => {});
|
|
10828
|
+
});
|
|
10829
|
+
}
|
|
10069
10830
|
createNotifySink({
|
|
10070
10831
|
config,
|
|
10071
10832
|
deliver: (ctx, text) => deliver(ctx, text),
|
|
@@ -10097,6 +10858,27 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10097
10858
|
const n = Number(process.env.QQ_INTERACTION_WATCH_SECONDS ?? "12");
|
|
10098
10859
|
return Number.isFinite(n) && n >= 0 ? Math.floor(n * 1000) : 12000;
|
|
10099
10860
|
})();
|
|
10861
|
+
const pollFails = new Map;
|
|
10862
|
+
const httpStatusOf = (error) => {
|
|
10863
|
+
const m = error instanceof Error ? error.message : String(error);
|
|
10864
|
+
const hit = /API\s+(\d{3})/.exec(m);
|
|
10865
|
+
return hit ? Number(hit[1]) : undefined;
|
|
10866
|
+
};
|
|
10867
|
+
const notePollResult = (userId, sessionId, ok, status) => {
|
|
10868
|
+
const key = `${userId}|${sessionId}`;
|
|
10869
|
+
if (ok) {
|
|
10870
|
+
pollFails.delete(key);
|
|
10871
|
+
return;
|
|
10872
|
+
}
|
|
10873
|
+
if (status !== 400 && status !== 404)
|
|
10874
|
+
return;
|
|
10875
|
+
const n = (pollFails.get(key) ?? 0) + 1;
|
|
10876
|
+
pollFails.set(key, n);
|
|
10877
|
+
if (n >= 3) {
|
|
10878
|
+
pollFails.delete(key);
|
|
10879
|
+
sessions.evict(userId);
|
|
10880
|
+
}
|
|
10881
|
+
};
|
|
10100
10882
|
function usersOfSession(sessionID) {
|
|
10101
10883
|
return sessions.all().filter((e) => e.sessionId === sessionID).map((e) => e.userId);
|
|
10102
10884
|
}
|
|
@@ -10105,9 +10887,14 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10105
10887
|
}
|
|
10106
10888
|
async function interactionTick() {
|
|
10107
10889
|
try {
|
|
10890
|
+
goalWatchTick().catch(() => {});
|
|
10108
10891
|
{
|
|
10109
10892
|
const seen = new Map;
|
|
10110
|
-
const lists = await Promise.all(sessions.all().map((entry) => client.permission.forSession(entry.sessionId).
|
|
10893
|
+
const lists = await Promise.all(sessions.all().map((entry) => client.permission.forSession(entry.sessionId).then((res) => {
|
|
10894
|
+
notePollResult(entry.userId, entry.sessionId, true);
|
|
10895
|
+
return res;
|
|
10896
|
+
}, (error) => {
|
|
10897
|
+
notePollResult(entry.userId, entry.sessionId, false, httpStatusOf(error));
|
|
10111
10898
|
return;
|
|
10112
10899
|
})));
|
|
10113
10900
|
for (const res of lists) {
|
|
@@ -10130,7 +10917,11 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10130
10917
|
}
|
|
10131
10918
|
{
|
|
10132
10919
|
for (const entry of sessions.all()) {
|
|
10133
|
-
const forms = (await client.form.list({ sessionID: entry.sessionId }).
|
|
10920
|
+
const forms = (await client.form.list({ sessionID: entry.sessionId }).then((res) => {
|
|
10921
|
+
notePollResult(entry.userId, entry.sessionId, true);
|
|
10922
|
+
return res;
|
|
10923
|
+
}, (error) => {
|
|
10924
|
+
notePollResult(entry.userId, entry.sessionId, false, httpStatusOf(error));
|
|
10134
10925
|
return;
|
|
10135
10926
|
}))?.data ?? [];
|
|
10136
10927
|
for (const form of forms) {
|
|
@@ -10374,6 +11165,12 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10374
11165
|
}
|
|
10375
11166
|
}, ORPHAN_SCAN_MS);
|
|
10376
11167
|
}
|
|
11168
|
+
startSendRequestConsumer({
|
|
11169
|
+
appId: config.qq.appId,
|
|
11170
|
+
ctxForUser,
|
|
11171
|
+
getToken: () => getAccessToken(config.qq.appId, config.qq.clientSecret),
|
|
11172
|
+
log: (line) => console.log(line)
|
|
11173
|
+
});
|
|
10377
11174
|
const REAPER_SCAN_MS = (() => {
|
|
10378
11175
|
const n = Number(process.env.QQ_REAPER_SCAN_SECONDS ?? "60");
|
|
10379
11176
|
return Number.isFinite(n) && n > 0 ? Math.floor(n * 1000) : 0;
|
|
@@ -10443,7 +11240,7 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10443
11240
|
${dec.text}`).catch(() => {});
|
|
10444
11241
|
} else {
|
|
10445
11242
|
inflight.settle(entry.msgId, undefined, "expired");
|
|
10446
|
-
await safeDeliver(ctx,
|
|
11243
|
+
await safeDeliver(ctx, NOTICE.reaperExpired()).catch(() => {});
|
|
10447
11244
|
}
|
|
10448
11245
|
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
11246
|
reaperCooldown.set(lane, now + REAPER_LANE_COOLDOWN_MS);
|
|
@@ -10502,6 +11299,143 @@ ${dec.text}`).catch(() => {});
|
|
|
10502
11299
|
`);
|
|
10503
11300
|
}
|
|
10504
11301
|
};
|
|
11302
|
+
async function amendCurrentTurn(userId, amendment) {
|
|
11303
|
+
const add = amendment.trim();
|
|
11304
|
+
if (!add) {
|
|
11305
|
+
return "用法:/amend <补充指令>——打断当前任务,把你的补充并入原指令一起续跑(模型从历史接着做)";
|
|
11306
|
+
}
|
|
11307
|
+
const session = sessions.getSession(userId);
|
|
11308
|
+
const activeLane = [...busyUsers].find((k) => userIdOfLane(k) === userId);
|
|
11309
|
+
if (!session || !activeLane)
|
|
11310
|
+
return "当前没有进行中的任务,直接发消息即可";
|
|
11311
|
+
try {
|
|
11312
|
+
await client.session.prompt({
|
|
11313
|
+
path: { id: session.sessionId },
|
|
11314
|
+
body: { text: `【补充指令】${add}`, delivery: "steer" }
|
|
11315
|
+
});
|
|
11316
|
+
console.log(`[bridge] amend steer 已送达 user=${userId.slice(0, 8)}… session=${shortId(session.sessionId)}`);
|
|
11317
|
+
return "✅ 已把补充送进当前任务(官方 steer 语义:模型把这条指令并入正在跑的回合,完成照常回传)";
|
|
11318
|
+
} catch (error) {
|
|
11319
|
+
console.log(`[bridge] amend steer 被拒,回落 abort+revert 链: ${toErrorMessage2(error)}`);
|
|
11320
|
+
}
|
|
11321
|
+
const entry = selectAmendEntry(inflight.pending(), userId, session.sessionId);
|
|
11322
|
+
if (!entry) {
|
|
11323
|
+
return "找不到可并入的原任务(可能由桌面端发起或已被结清);请用 /cancel 后重发完整指令";
|
|
11324
|
+
}
|
|
11325
|
+
bgWaits.get(session.sessionId)?.cancel();
|
|
11326
|
+
try {
|
|
11327
|
+
await client.session.abort({ path: { id: session.sessionId } });
|
|
11328
|
+
} catch {}
|
|
11329
|
+
inflight.settle(entry.msgId, entry.attemptId, "cancelled");
|
|
11330
|
+
let reverted = false;
|
|
11331
|
+
try {
|
|
11332
|
+
await client.session.revertStage({ path: { id: session.sessionId }, body: { messageID: entry.promptId, files: true } });
|
|
11333
|
+
await client.session.revertCommit({ path: { id: session.sessionId } });
|
|
11334
|
+
reverted = true;
|
|
11335
|
+
} catch (error) {
|
|
11336
|
+
try {
|
|
11337
|
+
await client.session.revertDiscard({ path: { id: session.sessionId } });
|
|
11338
|
+
} catch {}
|
|
11339
|
+
console.log(`[bridge] amend revert 失败,回落读历史续跑 session=${shortId(session.sessionId)}: ${toErrorMessage2(error)}`);
|
|
11340
|
+
}
|
|
11341
|
+
const actx = { ...ctxForUser(userId), msgId: "", content: buildAmendPrompt(entry.text, add) };
|
|
11342
|
+
msgQueue.push(activeLane, userId, session.sessionId, actx);
|
|
11343
|
+
console.log(`[bridge] amend 并入 user=${userId.slice(0, 8)}… lane=${shortId(session.sessionId)} msg=${shortId(entry.msgId)}`);
|
|
11344
|
+
busyUsers.delete(activeLane);
|
|
11345
|
+
drainQueue(userId, session.sessionId);
|
|
11346
|
+
return reverted ? "✅ 已打断并清空该回合(含文件回滚),正带你的补充重新起跑" : "✅ 已打断当前任务,正把你的补充并入原指令续跑(模型从历史接着做,完成自动回复)";
|
|
11347
|
+
}
|
|
11348
|
+
async function undoLastTurn(userId) {
|
|
11349
|
+
const session = sessions.getSession(userId);
|
|
11350
|
+
if (!session)
|
|
11351
|
+
return "没有绑定的会话,无事可撤销";
|
|
11352
|
+
if ([...busyUsers].some((k) => userIdOfLane(k) === userId)) {
|
|
11353
|
+
return "当前有任务在跑——官方语义运行中不可回滚;请先等它完成,或 /cancel 后再 /undo";
|
|
11354
|
+
}
|
|
11355
|
+
let msgs = [];
|
|
11356
|
+
try {
|
|
11357
|
+
msgs = (await client.session.messages({ path: { id: session.sessionId }, query: { limit: 50 } })).data ?? [];
|
|
11358
|
+
} catch (error) {
|
|
11359
|
+
return `读取会话失败:${toErrorMessage2(error)}`;
|
|
11360
|
+
}
|
|
11361
|
+
const boundary = lastUserMessageId(msgs);
|
|
11362
|
+
if (!boundary)
|
|
11363
|
+
return "会话里没有可撤销的用户消息";
|
|
11364
|
+
const removed = msgs.find((m) => m.id === boundary);
|
|
11365
|
+
const removedText = messageTextOf(removed ?? {}).trim();
|
|
11366
|
+
try {
|
|
11367
|
+
await client.session.revertStage({ path: { id: session.sessionId }, body: { messageID: boundary, files: true } });
|
|
11368
|
+
await client.session.revertCommit({ path: { id: session.sessionId } });
|
|
11369
|
+
} catch (error) {
|
|
11370
|
+
try {
|
|
11371
|
+
await client.session.revertDiscard({ path: { id: session.sessionId } });
|
|
11372
|
+
} catch {}
|
|
11373
|
+
return `撤销失败:${toErrorMessage2(error)}(引擎拒绝或快照缺失;会话内容未改动)`;
|
|
11374
|
+
}
|
|
11375
|
+
console.log(`[bridge] undo 已回滚 user=${userId.slice(0, 8)}… session=${shortId(session.sessionId)} boundary=${shortId(boundary)}`);
|
|
11376
|
+
const box = removedText ? `被撤回的指令:「${removedText.length > 80 ? `${removedText.slice(0, 80)}…` : removedText}」
|
|
11377
|
+
改好后重新发送即可,或 /amend <修改点> 带修改重跑。` : "改好后重新发送即可。";
|
|
11378
|
+
return `↩️ 已撤销上一回合(该回合改动的文件已一并恢复)。
|
|
11379
|
+
${box}`;
|
|
11380
|
+
}
|
|
11381
|
+
async function enqueueExplicit(ctx, text) {
|
|
11382
|
+
const session = sessions.getSession(ctx.userId);
|
|
11383
|
+
const sid = session?.sessionId;
|
|
11384
|
+
if (!sid)
|
|
11385
|
+
return "没有绑定的会话,请先发消息建立会话再排队";
|
|
11386
|
+
const lane = laneKeyOf(ctx.userId, sid);
|
|
11387
|
+
const actx = { ...ctx, msgId: "", content: text };
|
|
11388
|
+
const queued = msgQueue.push(lane, ctx.userId, sid, actx);
|
|
11389
|
+
if (!queued)
|
|
11390
|
+
return "队列已满,请等当前任务完成或 /queue clear 后重试";
|
|
11391
|
+
console.log(`[queue] 显性入队 user=${ctx.userId.slice(0, 8)}… qid=${queued.job.id} ahead=${queued.ahead}`);
|
|
11392
|
+
drainQueue(ctx.userId, sid);
|
|
11393
|
+
if (queued.ahead === 0 && !busyUsers.has(lane)) {
|
|
11394
|
+
return `\uD83D\uDCE5 已入队 #${queued.job.id},当前空闲,立即执行`;
|
|
11395
|
+
}
|
|
11396
|
+
return `\uD83D\uDCE5 已排队 #${queued.job.id}(第 ${queued.ahead + 1} 位),当前任务结束后自动执行`;
|
|
11397
|
+
}
|
|
11398
|
+
async function runEngineCommand(userId, name, text) {
|
|
11399
|
+
const session = sessions.getSession(userId);
|
|
11400
|
+
if (!session)
|
|
11401
|
+
return "没有绑定的会话;先在 QQ 里发一条消息建立会话";
|
|
11402
|
+
try {
|
|
11403
|
+
const res = await client.session.command({
|
|
11404
|
+
path: { id: session.sessionId },
|
|
11405
|
+
body: { name, text }
|
|
11406
|
+
});
|
|
11407
|
+
const reply = res?.data?.text ?? res?.text ?? res?.data?.message ?? res?.message;
|
|
11408
|
+
if (reply)
|
|
11409
|
+
return reply;
|
|
11410
|
+
if (name === "goal") {
|
|
11411
|
+
const t = text.trim();
|
|
11412
|
+
if (/^clear/i.test(t)) {
|
|
11413
|
+
goalKickoffs.delete(session.sessionId);
|
|
11414
|
+
goalStates.delete(session.sessionId);
|
|
11415
|
+
} else if (t && !/^(pause|resume|status)?$/i.test(t)) {
|
|
11416
|
+
goalKickoffs.set(session.sessionId, { text: t, at: Date.now() });
|
|
11417
|
+
goalStates.set(session.sessionId, { state: "active", at: Date.now(), notified: false });
|
|
11418
|
+
} else if (/^resume/i.test(t)) {
|
|
11419
|
+
goalStates.set(session.sessionId, { state: "active", at: Date.now(), notified: false });
|
|
11420
|
+
}
|
|
11421
|
+
return "✅ goal 已执行(引擎无文本回执)。查状态再发 /goal;控制用 /goal pause|resume|clear。设定目标后会话自主续跑,进展会以普通回复推送到这里";
|
|
11422
|
+
}
|
|
11423
|
+
return `✅ /${name} 已执行(引擎无文本回执)`;
|
|
11424
|
+
} catch (error) {
|
|
11425
|
+
const msg = toErrorMessage2(error);
|
|
11426
|
+
if (name === "goal") {
|
|
11427
|
+
const full = error.body ?? msg;
|
|
11428
|
+
const parsed = parseGoalState(full);
|
|
11429
|
+
if (parsed) {
|
|
11430
|
+
if (parsed.state === "active")
|
|
11431
|
+
goalStates.set(session.sessionId, { state: "active", at: Date.now(), notified: false });
|
|
11432
|
+
return `\uD83D\uDCCB 目标状态(goal):
|
|
11433
|
+
${parsed.message}`;
|
|
11434
|
+
}
|
|
11435
|
+
}
|
|
11436
|
+
return `引擎命令执行失败(/goal 需 OpenCode ≥ 2.2.1):${msg}`;
|
|
11437
|
+
}
|
|
11438
|
+
}
|
|
10505
11439
|
const commandContext = {
|
|
10506
11440
|
config,
|
|
10507
11441
|
client,
|
|
@@ -10513,7 +11447,11 @@ ${dec.text}`).catch(() => {});
|
|
|
10513
11447
|
queue: queueApi,
|
|
10514
11448
|
ledger: ledgerApi,
|
|
10515
11449
|
progress: progressApi,
|
|
10516
|
-
stopAll: stopAllForUser
|
|
11450
|
+
stopAll: stopAllForUser,
|
|
11451
|
+
amend: amendCurrentTurn,
|
|
11452
|
+
undo: undoLastTurn,
|
|
11453
|
+
enqueue: enqueueExplicit,
|
|
11454
|
+
engineCommand: runEngineCommand
|
|
10517
11455
|
};
|
|
10518
11456
|
if (config.allowedUsers.length === 0) {
|
|
10519
11457
|
console.warn("[security] ALLOWED_USERS 为空 → 所有消息将被拒绝(fail-closed);请在 ~/.openqq/.env 配置白名单");
|
|
@@ -10626,6 +11564,24 @@ ${dec.text}`).catch(() => {});
|
|
|
10626
11564
|
}
|
|
10627
11565
|
}
|
|
10628
11566
|
if (busyUsers.has(lane)) {
|
|
11567
|
+
if (resolveBusyMode(process.env.QQ_BUSY_DEFAULT) === "steer" && !ctx.attachments?.length) {
|
|
11568
|
+
try {
|
|
11569
|
+
const sidForSteer = anchorSid ?? sessions.getSession(ctx.userId)?.sessionId;
|
|
11570
|
+
if (sidForSteer) {
|
|
11571
|
+
await client.session.prompt({
|
|
11572
|
+
path: { id: sidForSteer },
|
|
11573
|
+
body: { text: ctx.content, delivery: "steer" }
|
|
11574
|
+
});
|
|
11575
|
+
if (ctx.msgId)
|
|
11576
|
+
inflight.settle(ctx.msgId, undefined, "steered");
|
|
11577
|
+
console.log(`[bridge] 忙时 steer 并入 lane=${shortId(sidForSteer)} msg=${shortId(ctx.msgId)}`);
|
|
11578
|
+
await notifyUser(ctx, "\uD83D\uDD04 已并入当前任务(官方 steer 语义,默认行为;想排队改 ~/.openqq/.env 的 QQ_BUSY_DEFAULT=queue)");
|
|
11579
|
+
return;
|
|
11580
|
+
}
|
|
11581
|
+
} catch (error) {
|
|
11582
|
+
console.log(`[bridge] 忙时 steer 失败改排队 msg=${shortId(ctx.msgId)}: ${toErrorMessage2(error)}`);
|
|
11583
|
+
}
|
|
11584
|
+
}
|
|
10629
11585
|
if (ctx.attachments?.length && !ctx.preparedAttachments) {
|
|
10630
11586
|
ctx.preparedAttachments = await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
|
|
10631
11587
|
}
|
|
@@ -10642,7 +11598,7 @@ ${dec.text}`).catch(() => {});
|
|
|
10642
11598
|
}
|
|
10643
11599
|
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
11600
|
await notifyUser(ctx, `已排队 #${queued.job.id}(第 ${queued.ahead + 1} 位${queued.ahead > 0 ? `,前面还有 ${queued.ahead} 条` : ""}),当前任务结束后自动执行。
|
|
10645
|
-
发 /queue 查看队列,/cancel
|
|
11601
|
+
发 /queue 查看队列,/cancel 可中止当前任务并清空队列;想立刻把新消息并进当前任务:/amend <补充>(打断并以原指令+补充续跑)。`);
|
|
10646
11602
|
return;
|
|
10647
11603
|
}
|
|
10648
11604
|
activeIntents.set(lane, intentKey);
|
|
@@ -10686,7 +11642,7 @@ ${dec.text}`).catch(() => {});
|
|
|
10686
11642
|
const { text: promptBody, files } = augmentPromptWithAttachments(content, prepared);
|
|
10687
11643
|
const promptText = (ctx.quoteText ? `> 引用上文:${ctx.quoteText}
|
|
10688
11644
|
|
|
10689
|
-
${promptBody}` : promptBody) +
|
|
11645
|
+
${promptBody}` : promptBody) + qqPromptHints();
|
|
10690
11646
|
trackId = ctx.msgId || `redispatch-${sessionId}-${turnStart}`;
|
|
10691
11647
|
inflight.record({ msgId: trackId, userId: ctx.userId, sessionId, text: content.slice(0, 300), at: Date.now() });
|
|
10692
11648
|
inflight.markStage(trackId, "dispatched", { sessionId });
|
|
@@ -10741,8 +11697,15 @@ ${promptBody}` : promptBody) + QQ_LIST_FORMAT_HINT;
|
|
|
10741
11697
|
await safeDeliver(ctx, `⚠️ 发送文件失败(${p}):${error instanceof Error ? error.message : error}`);
|
|
10742
11698
|
}
|
|
10743
11699
|
}
|
|
10744
|
-
|
|
10745
|
-
|
|
11700
|
+
let outboundText = extracted.text;
|
|
11701
|
+
const cronHit = parseCronReminder(extracted.text, Date.now());
|
|
11702
|
+
if (cronHit) {
|
|
11703
|
+
const okCron = registerCron(ctx.userId, cronHit);
|
|
11704
|
+
const when = new Date(cronHit.atMs).toLocaleString("zh-CN", { hour12: false });
|
|
11705
|
+
outboundText = cronHit.cleanedText || (okCron ? `⏰ 好的,已设置提醒(${when}):${cronHit.reminderText}` : "⚠️ 提醒设置失败(同时在册超限),请重试");
|
|
11706
|
+
}
|
|
11707
|
+
if (outboundText.trim())
|
|
11708
|
+
turnDelivered = await safeDeliver(ctx, redactSecrets(outboundText));
|
|
10746
11709
|
}
|
|
10747
11710
|
if (replyText.trim() && !turnDelivered) {
|
|
10748
11711
|
if (ctx.anchorSessionId && !isBoundSession(ctx.userId, ctx.anchorSessionId)) {
|
|
@@ -10781,7 +11744,7 @@ ${rescuedText}`).catch(() => {});
|
|
|
10781
11744
|
} else if (isSessionBusyError(error)) {
|
|
10782
11745
|
console.error(`[bridge] 会话被占用(active prompt)sid=${shortId(sessionId)}: ${toErrorMessage2(error)}`);
|
|
10783
11746
|
await safeDeliver(ctx, `⏳ 该会话正有回合在执行(可能是桌面端在跑,或上一轮尚未结束),本轮未重复发起。
|
|
10784
|
-
发 /
|
|
11747
|
+
发 /cancel 可中止当前回合后重试。`);
|
|
10785
11748
|
inflight.settle(trackId, undefined, "error");
|
|
10786
11749
|
} else {
|
|
10787
11750
|
const errText = toErrorMessage2(error);
|
|
@@ -11019,8 +11982,8 @@ function isAllowedUser(userId, allowedUsers) {
|
|
|
11019
11982
|
var WATCH_FILE = storageFile("watch.json");
|
|
11020
11983
|
function loadWatchedMap(file = WATCH_FILE) {
|
|
11021
11984
|
try {
|
|
11022
|
-
if (
|
|
11023
|
-
const raw =
|
|
11985
|
+
if (existsSync15(file)) {
|
|
11986
|
+
const raw = readFileSync17(file, "utf-8");
|
|
11024
11987
|
const obj = JSON.parse(raw);
|
|
11025
11988
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
11026
11989
|
const out = {};
|
|
@@ -11035,7 +11998,7 @@ function loadWatchedMap(file = WATCH_FILE) {
|
|
|
11035
11998
|
}
|
|
11036
11999
|
function saveWatchedMap(m, file = WATCH_FILE) {
|
|
11037
12000
|
try {
|
|
11038
|
-
|
|
12001
|
+
writeFileSync15(file, JSON.stringify(Object.fromEntries(m), null, 2));
|
|
11039
12002
|
} catch (error) {
|
|
11040
12003
|
console.warn("[watch] 持久化失败:", error instanceof Error ? error.message : error);
|
|
11041
12004
|
}
|
|
@@ -11043,8 +12006,8 @@ function saveWatchedMap(m, file = WATCH_FILE) {
|
|
|
11043
12006
|
var GREETED_FILE = storageFile("greeted.json");
|
|
11044
12007
|
function loadGreetedSet(file = GREETED_FILE) {
|
|
11045
12008
|
try {
|
|
11046
|
-
if (
|
|
11047
|
-
const raw =
|
|
12009
|
+
if (existsSync15(file)) {
|
|
12010
|
+
const raw = readFileSync17(file, "utf-8");
|
|
11048
12011
|
const arr = JSON.parse(raw);
|
|
11049
12012
|
if (Array.isArray(arr)) {
|
|
11050
12013
|
return new Set(arr.filter((x) => typeof x === "string"));
|
|
@@ -11055,8 +12018,8 @@ function loadGreetedSet(file = GREETED_FILE) {
|
|
|
11055
12018
|
}
|
|
11056
12019
|
function saveGreetedSet(set, file = GREETED_FILE) {
|
|
11057
12020
|
try {
|
|
11058
|
-
|
|
11059
|
-
|
|
12021
|
+
mkdirSync14(join13(homedir7(), ".openqq"), { recursive: true });
|
|
12022
|
+
writeFileSync15(file, JSON.stringify([...set]));
|
|
11060
12023
|
} catch (error) {
|
|
11061
12024
|
console.error("[bridge] 保存 greeted 失败:", error);
|
|
11062
12025
|
}
|
|
@@ -11106,102 +12069,6 @@ function toErrorMessage2(error) {
|
|
|
11106
12069
|
return error instanceof Error ? error.message : String(error);
|
|
11107
12070
|
}
|
|
11108
12071
|
|
|
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
12072
|
// src/index.ts
|
|
11206
12073
|
async function waitForOpencode(clientFactory, initialUrl) {
|
|
11207
12074
|
const deadline = Date.now() + 15 * 60 * 1000;
|
|
@@ -11250,7 +12117,7 @@ async function main() {
|
|
|
11250
12117
|
const raw = (process.env.QQ_LOG_FILE ?? "").trim();
|
|
11251
12118
|
if (!/^(0|off|false|no)$/i.test(raw)) {
|
|
11252
12119
|
await Promise.resolve().then(() => init_file_log());
|
|
11253
|
-
installFileLog(raw ||
|
|
12120
|
+
installFileLog(raw || join14(homedir8(), ".openqq", "openqq.log"));
|
|
11254
12121
|
}
|
|
11255
12122
|
}
|
|
11256
12123
|
await ensureConfig();
|
|
@@ -11279,14 +12146,15 @@ async function main() {
|
|
|
11279
12146
|
for (const r of roles)
|
|
11280
12147
|
instanceLocks.push(await waitInstanceLock(r.appId));
|
|
11281
12148
|
}
|
|
11282
|
-
|
|
11283
|
-
|
|
12149
|
+
const resolvedInitial = resolveInitialBaseUrl(baseConfig.opencode.baseUrl, baseConfig.opencode.baseUrl ? null : readLastDiscovered());
|
|
12150
|
+
if (resolvedInitial.source !== "explicit") {
|
|
12151
|
+
console.log(`[index] 未配置 OPENCODE_BASE_URL,初始地址=${resolvedInitial.source === "last-discovered" ? "上次自动发现" : "占位"} ${resolvedInitial.url}(失联时自动端口发现纠正)`);
|
|
11284
12152
|
}
|
|
11285
|
-
const heartbeatFile =
|
|
12153
|
+
const heartbeatFile = join14(homedir8(), ".openqq", "heartbeat");
|
|
11286
12154
|
const touchHeartbeat = () => {
|
|
11287
12155
|
try {
|
|
11288
|
-
|
|
11289
|
-
|
|
12156
|
+
mkdirSync15(join14(homedir8(), ".openqq"), { recursive: true });
|
|
12157
|
+
writeFileSync16(heartbeatFile, String(Date.now()));
|
|
11290
12158
|
} catch (error) {
|
|
11291
12159
|
console.error("[index] 心跳写入失败:", error);
|
|
11292
12160
|
}
|
|
@@ -11306,7 +12174,7 @@ async function main() {
|
|
|
11306
12174
|
lagTimer.unref?.();
|
|
11307
12175
|
let client;
|
|
11308
12176
|
try {
|
|
11309
|
-
client = await waitForOpencode((u) => createClient(u),
|
|
12177
|
+
client = await waitForOpencode((u) => createClient(u), resolvedInitial.url);
|
|
11310
12178
|
} catch (error) {
|
|
11311
12179
|
clearInterval(heartbeatTimer);
|
|
11312
12180
|
clearInterval(lagTimer);
|
|
@@ -11378,7 +12246,8 @@ async function main() {
|
|
|
11378
12246
|
process.once("SIGTERM", () => shutdown("SIGTERM"));
|
|
11379
12247
|
}
|
|
11380
12248
|
main().catch((error) => {
|
|
11381
|
-
console.error("[index] 启动失败:", error);
|
|
12249
|
+
console.error("[index] 启动失败:", formatStartupError(error));
|
|
12250
|
+
console.error("[index] 启动失败诊断包:", startupDiagnosticBundle());
|
|
11382
12251
|
stopBackgroundTokenRefresh();
|
|
11383
12252
|
process.exit(1);
|
|
11384
12253
|
});
|