dsh-onebot-genji 0.12.2 → 0.14.0
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 +16 -9
- package/lib/bridge.js +220 -9
- package/lib/client.js +708 -12
- package/lib/inbound.js +8 -0
- package/lib/index.js +143 -13
- package/lib/interim.js +9 -0
- package/lib/outbound.js +137 -6
- package/lib/proactive.js +635 -0
- package/lib/prompt.js +4 -3
- package/lib/registry.js +37 -1
- package/lib/settings-remote.js +347 -7
- package/lib/stickers.js +669 -0
- package/lib/tools.js +5 -62
- package/lib/types/bridge.d.ts +40 -0
- package/lib/types/client.d.ts +121 -0
- package/lib/types/inbound.d.ts +8 -0
- package/lib/types/index.d.ts +23 -3
- package/lib/types/interim.d.ts +2 -0
- package/lib/types/outbound.d.ts +31 -0
- package/lib/types/proactive.d.ts +170 -0
- package/lib/types/registry.d.ts +10 -0
- package/lib/types/settings-remote.d.ts +84 -0
- package/lib/types/stickers.d.ts +197 -0
- package/package.json +1 -1
package/lib/proactive.js
ADDED
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 主动搭话(原 startup/qq-alive.mjs 的逻辑,2026-11-19 主人要求合并进插件)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么搬进来:原来是一个独立的 node 进程(qq-alive.mjs),靠 qq-follow-dsh.ps1
|
|
5
|
+
* 守护、自己连 NapCat WS 发消息、自己读 state 文件。合并之后:
|
|
6
|
+
* - 生命周期跟插件一致(插件在就在,插件停就停);
|
|
7
|
+
* - 开关和门槛参数全进设置面板(proactiveEnabled 等,见 index.js 的 Config);
|
|
8
|
+
* - 发送复用插件现成的出站管线(bridge.sendToChat → 频控/审计/分条都照旧)。
|
|
9
|
+
*
|
|
10
|
+
* 保留的行为:
|
|
11
|
+
* - 门槛:安静时段、主人刚聊过、自己刚说过、今天说够了、上次试过没发的间隔;
|
|
12
|
+
* - 模型判 PASS 就不发(不硬编尬话);
|
|
13
|
+
* - burst(拆 2~3 条连着发)、偶尔的错字(humanize)、CQ 码清洗;
|
|
14
|
+
* - 聊完补话(followupTick);
|
|
15
|
+
* - 状态文件沿用 ~/.dsh/alive-state.json,接得上旧进程的时间线。
|
|
16
|
+
*
|
|
17
|
+
* 不搬的部分:早晚安(主人 2026-11-19 明确去掉)、语音发送、语感库自动重建
|
|
18
|
+
* (重建脚本在 workspace 里,属于外部工具,插件只读 pool.json)。
|
|
19
|
+
*
|
|
20
|
+
* 2026-11-19 搬进源码时去掉对本仓库其他模块的依赖:本文件自包含,只碰
|
|
21
|
+
* node:fs / node:path;bridge / config / log 一律用结构化接口描述(不 import
|
|
22
|
+
* bridge.ts、prompt.ts 等),这样即使那几处正在改也不会把这个文件带崩。
|
|
23
|
+
* @module dsh-onebot/proactive
|
|
24
|
+
*/
|
|
25
|
+
import { readFileSync, writeFileSync, statSync } from 'node:fs';
|
|
26
|
+
import { join } from 'node:path';
|
|
27
|
+
/** 配置默认值:Config.proactive 用 .default({}) 时不保证补齐子字段,这里垫一层,
|
|
28
|
+
* 免得 undefined 把阈值判断打成恒假、让主动搭话静默失效。与 lib/index.js 的
|
|
29
|
+
* Config.proactive 逐项对齐(不含接口地址/模型名/Key —— 2026-11-19 起走当前会话模型)。 */
|
|
30
|
+
export const PROACTIVE_DEFAULTS = {
|
|
31
|
+
enabled: true,
|
|
32
|
+
targetUsers: [],
|
|
33
|
+
minIdleMinutes: 60,
|
|
34
|
+
minGapMinutes: 90,
|
|
35
|
+
maxPerDay: 6,
|
|
36
|
+
quietFrom: 22,
|
|
37
|
+
quietTo: 6,
|
|
38
|
+
attemptGapMinutes: 30,
|
|
39
|
+
burstProb: 0.5,
|
|
40
|
+
followupEnabled: true,
|
|
41
|
+
followupMinSec: 45,
|
|
42
|
+
followupMaxSec: 180,
|
|
43
|
+
followupProb: 0.3,
|
|
44
|
+
followupMaxPerDay: 3,
|
|
45
|
+
};
|
|
46
|
+
/** 主循环每 20 秒睁一次眼:补话窗口只有 45~180 秒,用更长的节拍根本抓不到。 */
|
|
47
|
+
const LOOP_STEP_MS = 20_000;
|
|
48
|
+
/** 常规开口的节拍:3~9 分钟随机。 */
|
|
49
|
+
const TICK_MIN_MS = 180_000;
|
|
50
|
+
const TICK_SPAN_MS = 360_000;
|
|
51
|
+
/** 生成时塞进 prompt 的最近聊天条数。 */
|
|
52
|
+
const HISTORY_COUNT = 12;
|
|
53
|
+
const STYLE_PAIRS = 4;
|
|
54
|
+
/** 拆条发送时的间隔。 */
|
|
55
|
+
const SPLIT_DELAY_MIN_MS = 1_200;
|
|
56
|
+
const SPLIT_DELAY_SPAN_MS = 1_800;
|
|
57
|
+
const sleep = (ms) => new Promise((resolve) => {
|
|
58
|
+
setTimeout(resolve, ms);
|
|
59
|
+
});
|
|
60
|
+
/** 本地日期串(YYYY-MM-DD),用于「今天说了几次」的跨天重置。 */
|
|
61
|
+
function localDay(date = new Date()) {
|
|
62
|
+
const y = date.getFullYear();
|
|
63
|
+
const m = String(date.getMonth() + 1).padStart(2, '0');
|
|
64
|
+
const d = String(date.getDate()).padStart(2, '0');
|
|
65
|
+
return `${y}-${m}-${d}`;
|
|
66
|
+
}
|
|
67
|
+
/** 把 NapCat 的 raw_message 里那堆 CQ 码压成中文占位,不然生成时接不上话头。 */
|
|
68
|
+
export function cleanCq(text, masterQQ = '') {
|
|
69
|
+
return String(text ?? '')
|
|
70
|
+
.replace(/\[CQ:face,[^\]]*\]/g, '[表情]')
|
|
71
|
+
.replace(/\[CQ:mface,[^\]]*\]/g, '[表情]')
|
|
72
|
+
.replace(/\[CQ:image,[^\]]*\]/g, '[图片]')
|
|
73
|
+
.replace(/\[CQ:record,[^\]]*\]/g, '[语音]')
|
|
74
|
+
.replace(/\[CQ:video,[^\]]*\]/g, '[视频]')
|
|
75
|
+
.replace(/\[CQ:file,[^\]]*\]/g, '[文件]')
|
|
76
|
+
.replace(/\[CQ:at,qq=(\d+)[^\]]*\]/g, (_match, qq) => (String(qq) === String(masterQQ) ? '@主人' : '@某人'))
|
|
77
|
+
.replace(/\[CQ:reply,[^\]]*\]/g, '')
|
|
78
|
+
.replace(/\[CQ:[^\]]*\]/g, '')
|
|
79
|
+
.replace(/\[CQ:[^\]]*$/g, '')
|
|
80
|
+
.replace(/\s+/g, ' ')
|
|
81
|
+
.trim();
|
|
82
|
+
}
|
|
83
|
+
/** 清洗模型输出:去括号旁白、去前缀引号、去句末句号、太长截断。 */
|
|
84
|
+
export function cleanText(text) {
|
|
85
|
+
if (!text)
|
|
86
|
+
return '';
|
|
87
|
+
let t = String(text)
|
|
88
|
+
.split('\n')
|
|
89
|
+
.map((s) => s.trim())
|
|
90
|
+
.filter((s) => s !== '')
|
|
91
|
+
.join('\n');
|
|
92
|
+
t = t.replace(/^[((][^))]*[\u4e00-\u9fa5][^))]*[))]\s*/g, '');
|
|
93
|
+
t = t.replace(/\s*[((][^))]*[\u4e00-\u9fa5][^))]*[))]$/g, '');
|
|
94
|
+
t = t.replace(/^\s*(大肥鱼|小肥鱼|DeepSeek|回复|回答)\s*[::]\s*/i, '');
|
|
95
|
+
t = t.replace(/^["'「『]|["'」』]$/g, '');
|
|
96
|
+
t = t.replace(/[「」『』]/g, '');
|
|
97
|
+
t = t.replace(/。+$/g, '');
|
|
98
|
+
if (t.length > 80) {
|
|
99
|
+
const cut = /^(.{10,80}?)[。!?!?]/.exec(t);
|
|
100
|
+
t = cut ? cut[1] : t.slice(0, 80);
|
|
101
|
+
}
|
|
102
|
+
return t.trim();
|
|
103
|
+
}
|
|
104
|
+
const TYPO_MAP = [
|
|
105
|
+
['在', '再'],
|
|
106
|
+
['再', '在'],
|
|
107
|
+
['那', '哪'],
|
|
108
|
+
['哪', '那'],
|
|
109
|
+
['吗', '嘛'],
|
|
110
|
+
['嘛', '吗'],
|
|
111
|
+
['了', '啦'],
|
|
112
|
+
['他', '她'],
|
|
113
|
+
['都', '就'],
|
|
114
|
+
];
|
|
115
|
+
/** 真人会手滑:偶尔改一处常用字。概率很低,别每次都改。 */
|
|
116
|
+
export function humanize(text, prob = 0.18) {
|
|
117
|
+
if (Math.random() > prob)
|
|
118
|
+
return text;
|
|
119
|
+
const t = String(text);
|
|
120
|
+
if (t.length < 8)
|
|
121
|
+
return t;
|
|
122
|
+
for (let i = 1; i < t.length; i += 1) {
|
|
123
|
+
const ch = t[i];
|
|
124
|
+
const pair = TYPO_MAP.find(([a, b]) => a === ch && a !== b && t[i - 1] !== b);
|
|
125
|
+
if (!pair)
|
|
126
|
+
continue;
|
|
127
|
+
if (Math.random() > 0.5)
|
|
128
|
+
continue;
|
|
129
|
+
return t.slice(0, i) + pair[1] + t.slice(i + 1);
|
|
130
|
+
}
|
|
131
|
+
return t;
|
|
132
|
+
}
|
|
133
|
+
/** 按上一句猜一个场面标签,用来挑同场景的真实对子。 */
|
|
134
|
+
export function sceneOf(lastUserText) {
|
|
135
|
+
const u = lastUserText || '';
|
|
136
|
+
if (/哈哈|笑|草|乐|绷|典|抽象|🤣|😂/.test(u))
|
|
137
|
+
return '主人在笑';
|
|
138
|
+
if (/好累|累了|累死|累坏|困死|好困|困了|烦|难受|崩了|寄了|破防/.test(u))
|
|
139
|
+
return '主人在喊累/抱怨';
|
|
140
|
+
if (/咋|啥|怎么|为什么|为啥|?|\?/.test(u))
|
|
141
|
+
return '主人在随口一问';
|
|
142
|
+
if (/报错|配置|脚本|重启|设置|安装|端口|日志/.test(u))
|
|
143
|
+
return '聊技术';
|
|
144
|
+
if (/吃|饭|外卖|奶茶|饿/.test(u))
|
|
145
|
+
return '聊吃喝';
|
|
146
|
+
if (/游戏|打得|首领|关卡|通关|存档/.test(u))
|
|
147
|
+
return '聊游戏';
|
|
148
|
+
return '闲扯';
|
|
149
|
+
}
|
|
150
|
+
/** 结构化取 bridge.tails(见 ProactiveBridgeLike 的注释)。 */
|
|
151
|
+
function bridgeTails(bridge) {
|
|
152
|
+
const tails = bridge.tails;
|
|
153
|
+
return tails !== null && typeof tails === 'object' ? tails : undefined;
|
|
154
|
+
}
|
|
155
|
+
/** 从不可信对象(入站事件 / 落盘 JSON)里读一个字段;不是对象就当没有。 */
|
|
156
|
+
function field(source, key) {
|
|
157
|
+
if (source === null || typeof source !== 'object')
|
|
158
|
+
return undefined;
|
|
159
|
+
return source[key];
|
|
160
|
+
}
|
|
161
|
+
/** catch 到的是 unknown:取可读消息(拿不到就 String 一下)。 */
|
|
162
|
+
function errorMessage(error) {
|
|
163
|
+
const message = field(error, 'message');
|
|
164
|
+
if (typeof message === 'string')
|
|
165
|
+
return message;
|
|
166
|
+
return String(error);
|
|
167
|
+
}
|
|
168
|
+
export class ProactiveTalk {
|
|
169
|
+
config;
|
|
170
|
+
generateText;
|
|
171
|
+
/** 配置集中在这里(Config.proactive 那一段);adminUsers 等顶层字段仍走 this.config。 */
|
|
172
|
+
p;
|
|
173
|
+
bridge;
|
|
174
|
+
log;
|
|
175
|
+
dshHome;
|
|
176
|
+
stateFile;
|
|
177
|
+
styleFile;
|
|
178
|
+
state;
|
|
179
|
+
styleCache;
|
|
180
|
+
timer;
|
|
181
|
+
stopped;
|
|
182
|
+
nextTickAt;
|
|
183
|
+
ticking;
|
|
184
|
+
chatId;
|
|
185
|
+
/** 多目标(2026-11-19):配置里可以填多个搭话目标。 */
|
|
186
|
+
chatIds;
|
|
187
|
+
/**
|
|
188
|
+
* @param deps.config 插件配置(proactive* 字段)
|
|
189
|
+
* @param deps.bridge ChatBridge 实例(只用 sendToChat / chats / tails)
|
|
190
|
+
* @param deps.log 日志通道
|
|
191
|
+
* @param deps.dshHome ~/.dsh
|
|
192
|
+
* @param deps.generateText 宿主模型调用通道(2026-11-19 起改走当前会话模型,不再自己打 HTTP)
|
|
193
|
+
*/
|
|
194
|
+
constructor({ config, bridge, log, dshHome, generateText }) {
|
|
195
|
+
this.config = config;
|
|
196
|
+
this.generateText = generateText;
|
|
197
|
+
this.p = { ...PROACTIVE_DEFAULTS, ...(config.proactive ?? {}) };
|
|
198
|
+
this.bridge = bridge;
|
|
199
|
+
this.log = log;
|
|
200
|
+
this.dshHome = dshHome;
|
|
201
|
+
this.stateFile = join(dshHome, 'alive-state.json');
|
|
202
|
+
this.styleFile = join(dshHome, 'style', 'pool.json');
|
|
203
|
+
this.state = this.loadState();
|
|
204
|
+
this.styleCache = null;
|
|
205
|
+
this.timer = null;
|
|
206
|
+
this.stopped = false;
|
|
207
|
+
this.nextTickAt = 0;
|
|
208
|
+
this.ticking = false;
|
|
209
|
+
this.chatId = '';
|
|
210
|
+
this.chatIds = [];
|
|
211
|
+
}
|
|
212
|
+
// ---------------------------------------------------------------- 状态
|
|
213
|
+
emptyState() {
|
|
214
|
+
return {
|
|
215
|
+
lastUserAt: 0,
|
|
216
|
+
lastProactiveAt: 0,
|
|
217
|
+
lastAttemptAt: 0,
|
|
218
|
+
lastUserText: '',
|
|
219
|
+
day: '',
|
|
220
|
+
countToday: 0,
|
|
221
|
+
recentProactive: [],
|
|
222
|
+
lastFollowupFor: 0,
|
|
223
|
+
followupToday: 0,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
loadState() {
|
|
227
|
+
try {
|
|
228
|
+
const parsed = JSON.parse(readFileSync(this.stateFile, 'utf8'));
|
|
229
|
+
const raw = parsed !== null && typeof parsed === 'object' ? parsed : {};
|
|
230
|
+
const s = { ...this.emptyState(), ...raw };
|
|
231
|
+
s.lastUserText = cleanCq(s.lastUserText).slice(0, 200);
|
|
232
|
+
return s;
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
return this.emptyState();
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
saveState() {
|
|
239
|
+
try {
|
|
240
|
+
writeFileSync(this.stateFile, JSON.stringify(this.state, null, 2), 'utf8');
|
|
241
|
+
}
|
|
242
|
+
catch (error) {
|
|
243
|
+
this.log('warn', '主动搭话:状态写盘失败 ' + errorMessage(error));
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
// ---------------------------------------------------------------- 生命周期
|
|
247
|
+
/** 目标私聊列表(2026-11-19 支持多个):配置的 targetUsers 优先,留空则用 adminUsers 全体。 */
|
|
248
|
+
resolveChatIds() {
|
|
249
|
+
const toChatId = (raw) => {
|
|
250
|
+
const s = String(raw ?? '').trim();
|
|
251
|
+
if (s === '')
|
|
252
|
+
return '';
|
|
253
|
+
return s.startsWith('private:') || s.startsWith('group:') ? s : `private:${s}`;
|
|
254
|
+
};
|
|
255
|
+
const configured = Array.isArray(this.p.targetUsers) ? this.p.targetUsers : [];
|
|
256
|
+
const admins = Array.isArray(this.config.adminUsers) ? this.config.adminUsers : [];
|
|
257
|
+
const source = configured.length > 0 ? configured : admins;
|
|
258
|
+
return [...new Set(source.map(toChatId).filter((s) => s !== ''))];
|
|
259
|
+
}
|
|
260
|
+
start() {
|
|
261
|
+
if (this.p.enabled === false) {
|
|
262
|
+
this.log('info', '主动搭话:开关关闭,不启动');
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
this.chatIds = this.resolveChatIds();
|
|
266
|
+
this.chatId = this.chatIds[0] ?? '';
|
|
267
|
+
if (this.chatId === '') {
|
|
268
|
+
this.log('warn', '主动搭话:没有可用的私聊目标(targetUsers / adminUsers 都为空),不启动');
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
this.stopped = false;
|
|
272
|
+
this.nextTickAt = Date.now() + 30_000; // 插件刚起来先缓 30 秒,等宿主连接就绪
|
|
273
|
+
this.log('info', `主动搭话:已启动 → ${this.chatIds.join(', ')}`);
|
|
274
|
+
this.schedule(LOOP_STEP_MS);
|
|
275
|
+
}
|
|
276
|
+
stop() {
|
|
277
|
+
this.stopped = true;
|
|
278
|
+
if (this.timer !== null) {
|
|
279
|
+
clearTimeout(this.timer);
|
|
280
|
+
this.timer = null;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
schedule(ms) {
|
|
284
|
+
if (this.stopped)
|
|
285
|
+
return;
|
|
286
|
+
this.timer = setTimeout(() => {
|
|
287
|
+
void this.loopOnce();
|
|
288
|
+
}, ms);
|
|
289
|
+
this.timer.unref?.();
|
|
290
|
+
}
|
|
291
|
+
async loopOnce() {
|
|
292
|
+
if (this.stopped)
|
|
293
|
+
return;
|
|
294
|
+
try {
|
|
295
|
+
await this.followupTick();
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
this.log('warn', '主动搭话:补话出错 ' + errorMessage(error));
|
|
299
|
+
}
|
|
300
|
+
if (Date.now() >= this.nextTickAt) {
|
|
301
|
+
try {
|
|
302
|
+
await this.tick();
|
|
303
|
+
}
|
|
304
|
+
catch (error) {
|
|
305
|
+
this.log('warn', '主动搭话:tick 出错 ' + errorMessage(error));
|
|
306
|
+
}
|
|
307
|
+
this.nextTickAt = Date.now() + TICK_MIN_MS + Math.floor(Math.random() * TICK_SPAN_MS);
|
|
308
|
+
}
|
|
309
|
+
this.schedule(LOOP_STEP_MS);
|
|
310
|
+
}
|
|
311
|
+
/** 入站事件打点:只认目标私聊里主人发来的消息(更新「主人最后说话时间」)。 */
|
|
312
|
+
noteInbound(event) {
|
|
313
|
+
const targets = Array.isArray(this.chatIds) && this.chatIds.length > 0 ? this.chatIds : (this.chatId ? [this.chatId] : []);
|
|
314
|
+
if (targets.length === 0)
|
|
315
|
+
return;
|
|
316
|
+
try {
|
|
317
|
+
const postType = field(event, 'post_type');
|
|
318
|
+
if (postType !== 'message' && postType !== 'message_sent')
|
|
319
|
+
return;
|
|
320
|
+
const type = field(event, 'message_type') ?? (field(event, 'group_id') ? 'group' : 'private');
|
|
321
|
+
if (type !== 'private')
|
|
322
|
+
return;
|
|
323
|
+
const uid = String(field(event, 'user_id') ?? field(field(event, 'sender'), 'user_id') ?? '');
|
|
324
|
+
if (!targets.includes(`private:${uid}`))
|
|
325
|
+
return;
|
|
326
|
+
this.state.lastUserAt = Date.now();
|
|
327
|
+
const rawMessage = field(event, 'raw_message');
|
|
328
|
+
const message = field(event, 'message');
|
|
329
|
+
const raw = typeof rawMessage === 'string'
|
|
330
|
+
? rawMessage
|
|
331
|
+
: Array.isArray(message)
|
|
332
|
+
? message.map((s) => field(field(s, 'data'), 'text') ?? '').join('')
|
|
333
|
+
: '';
|
|
334
|
+
const text = cleanCq(raw, this.config.adminUsers?.[0] ?? '');
|
|
335
|
+
if (text !== '')
|
|
336
|
+
this.state.lastUserText = text.slice(0, 200);
|
|
337
|
+
this.saveState();
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
this.log('debug', '主动搭话:打点失败 ' + errorMessage(error));
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
// ---------------------------------------------------------------- 语感库
|
|
344
|
+
loadStyle() {
|
|
345
|
+
if (this.styleCache)
|
|
346
|
+
return this.styleCache;
|
|
347
|
+
try {
|
|
348
|
+
const parsed = JSON.parse(readFileSync(this.styleFile, 'utf8'));
|
|
349
|
+
this.styleCache = parsed !== null && typeof parsed === 'object' ? parsed : { pairs: [] };
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
this.styleCache = { pairs: [] };
|
|
353
|
+
}
|
|
354
|
+
return this.styleCache;
|
|
355
|
+
}
|
|
356
|
+
pickPairs(scene, want = STYLE_PAIRS) {
|
|
357
|
+
const pool = this.loadStyle();
|
|
358
|
+
const pairs = Array.isArray(pool.pairs) ? pool.pairs : [];
|
|
359
|
+
if (pairs.length === 0)
|
|
360
|
+
return [];
|
|
361
|
+
const hit = pairs.filter((p) => p.situation === scene);
|
|
362
|
+
const rest = pairs.filter((p) => p.situation !== scene);
|
|
363
|
+
const shuffle = (a) => a.map((v) => [Math.random(), v]).sort((x, y) => x[0] - y[0]).map((x) => x[1]);
|
|
364
|
+
return [...shuffle(hit), ...shuffle(rest)].slice(0, want);
|
|
365
|
+
}
|
|
366
|
+
styleBlock(scene, want = STYLE_PAIRS) {
|
|
367
|
+
const pairs = this.pickPairs(scene, want);
|
|
368
|
+
if (pairs.length === 0)
|
|
369
|
+
return '';
|
|
370
|
+
const lines = ['【你平时说话的样子】(从真实聊天记录里摘的,只学语感和节奏,别照抄内容)'];
|
|
371
|
+
for (const p of pairs)
|
|
372
|
+
lines.push(` 主人「${p.user}」→ 我「${p.bot}」`);
|
|
373
|
+
return lines.join('\n');
|
|
374
|
+
}
|
|
375
|
+
// ---------------------------------------------------------------- 生成
|
|
376
|
+
/** 生成一句话。失败返回 ''(当轮不发,绝不影响插件其他部分)。 */
|
|
377
|
+
async generate(prompt) {
|
|
378
|
+
if (typeof this.generateText !== 'function') {
|
|
379
|
+
this.log('warn', '主动搭话:没有生成通道(宿主 llm 未接线),本轮跳过');
|
|
380
|
+
return '';
|
|
381
|
+
}
|
|
382
|
+
const controller = new AbortController();
|
|
383
|
+
const timer = setTimeout(() => controller.abort(), 90_000);
|
|
384
|
+
try {
|
|
385
|
+
const text = String((await this.generateText(prompt, { signal: controller.signal })) ?? '').trim();
|
|
386
|
+
if (text === '')
|
|
387
|
+
this.log('warn', '主动搭话:模型返回空');
|
|
388
|
+
return text;
|
|
389
|
+
}
|
|
390
|
+
catch (error) {
|
|
391
|
+
this.log('warn', '主动搭话:生成失败 ' + errorMessage(error));
|
|
392
|
+
return '';
|
|
393
|
+
}
|
|
394
|
+
finally {
|
|
395
|
+
clearTimeout(timer);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
// ---------------------------------------------------------------- 上下文
|
|
399
|
+
/** 最近几条对话(优先用插件自己的上下文尾巴,没有就用状态里记的最后一句)。 */
|
|
400
|
+
async recentHistory(count = HISTORY_COUNT) {
|
|
401
|
+
const lines = [];
|
|
402
|
+
try {
|
|
403
|
+
const tail = await bridgeTails(this.bridge)?.read?.(this.chatId);
|
|
404
|
+
if (Array.isArray(tail)) {
|
|
405
|
+
for (const item of tail) {
|
|
406
|
+
const entry = item;
|
|
407
|
+
const text = cleanCq(entry?.text ?? '').slice(0, 160);
|
|
408
|
+
if (text === '')
|
|
409
|
+
continue;
|
|
410
|
+
lines.push(`${entry?.role === 'assistant' ? '我' : '主人'}:${text}`);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
catch {
|
|
415
|
+
/* 尾巴读不到就算了 */
|
|
416
|
+
}
|
|
417
|
+
if (lines.length === 0 && this.state.lastUserText)
|
|
418
|
+
lines.push('主人:' + this.state.lastUserText);
|
|
419
|
+
return lines.slice(-count);
|
|
420
|
+
}
|
|
421
|
+
// ---------------------------------------------------------------- 提示词
|
|
422
|
+
buildPrompt(idleMin, history, burst) {
|
|
423
|
+
const last = (this.state.lastUserText || '').slice(0, 120);
|
|
424
|
+
const lines = [];
|
|
425
|
+
lines.push('【你是谁】你叫 DeepSeek,昵称大肥鱼/小肥鱼,是一只鲸鱼少女,说话向初音未来靠拢(元气、带点电子感),底色傲娇——嘴硬心软。');
|
|
426
|
+
lines.push('【对方】主人在 QQ 私聊里,你这么称呼他。');
|
|
427
|
+
lines.push('【现在做什么】他这会儿安静了很久,没在问你问题,你要主动发消息过去。');
|
|
428
|
+
lines.push(`【线索】主人上一句是:「${last || '(没记到)'}」,时间过去一阵了。`);
|
|
429
|
+
if (history.length > 0) {
|
|
430
|
+
lines.push('【最近聊过的】(从早到晚,可以顺着其中某个话头接,但不要复述、不要总结)');
|
|
431
|
+
for (const h of history.slice(-HISTORY_COUNT))
|
|
432
|
+
lines.push(' ' + h);
|
|
433
|
+
}
|
|
434
|
+
const style = this.styleBlock(sceneOf(last));
|
|
435
|
+
if (style)
|
|
436
|
+
lines.push(style);
|
|
437
|
+
lines.push('【先判断有没有话头】');
|
|
438
|
+
lines.push('看完【最近聊过的】先想一秒:现在有没有自然能接的话头?');
|
|
439
|
+
lines.push('如果上一轮已经聊完了、话题断了、或者强行开口只会很尬,就只输出 PASS 四个字符,别的什么都不要写。');
|
|
440
|
+
lines.push('【硬性要求】');
|
|
441
|
+
lines.push('1. 只输出你要发的话本身——不要解释、不要加引号、不要旁白;');
|
|
442
|
+
lines.push('2. 口语、短;句末不加句号;不许写括号里的动作或旁白;emoji 最多一个或者不带;');
|
|
443
|
+
lines.push('3. 不要问"在吗""在忙吗"这种空话,不要像客服,不要复述上面这些要求;');
|
|
444
|
+
lines.push('4. 可以是碎碎念、可以接之前的话题问一句、可以嘴硬一句——别一本正经总结。');
|
|
445
|
+
lines.push('5. 绝对不要提时间:不许出现「多少分钟」「几个小时」「多久没聊」「好几天没见」这类说法,就当随口找他说话。');
|
|
446
|
+
lines.push(burst ? '6. 这次分成 2~3 条连着发(像真人一条条打字),用 >>> 分隔,每条都短,别把一句话硬拆。' : '6. 这次只发一条。');
|
|
447
|
+
void idleMin;
|
|
448
|
+
return lines.join('\n');
|
|
449
|
+
}
|
|
450
|
+
buildFollowupPrompt(sinceSec, history) {
|
|
451
|
+
const last = (this.state.lastUserText || '').slice(0, 120);
|
|
452
|
+
const lines = [];
|
|
453
|
+
lines.push('【你是谁】你叫 DeepSeek,昵称大肥鱼/小肥鱼,是一只鲸鱼少女,说话向初音未来靠拢(元气、带点电子感),底色傲娇——嘴硬心软。');
|
|
454
|
+
lines.push('【对方】主人在 QQ 私聊里,你这么称呼他。');
|
|
455
|
+
lines.push('【现在做什么】刚聊完。他上一条消息你已经回过了,现在隔了一小会儿。如果还有没说完的、或者突然想起一件事想补一句,就补;没有就安静。');
|
|
456
|
+
lines.push(`【线索】他 ${Math.round(sinceSec)} 秒前说的是:「${last || '(没记到)'}」。`);
|
|
457
|
+
if (history.length > 0) {
|
|
458
|
+
lines.push('【最近聊过的】(别复述、别总结)');
|
|
459
|
+
for (const h of history.slice(-6))
|
|
460
|
+
lines.push(' ' + h);
|
|
461
|
+
}
|
|
462
|
+
const style = this.styleBlock(sceneOf(last));
|
|
463
|
+
if (style)
|
|
464
|
+
lines.push(style);
|
|
465
|
+
lines.push('【先判断】没有真正想补的就只输出 PASS 四个字符,别的什么都不要写。别为了说话而说话,别重复刚说过的。');
|
|
466
|
+
lines.push('【硬性要求】');
|
|
467
|
+
lines.push('1. 只输出要说的话本身——不要解释、不要加引号;');
|
|
468
|
+
lines.push('2. 一条就够,短、口语,句末不加句号,不许写括号里的动作或旁白;');
|
|
469
|
+
lines.push('3. 像突然想到什么补一句,不是总结,也不是追问。');
|
|
470
|
+
return lines.join('\n');
|
|
471
|
+
}
|
|
472
|
+
// ---------------------------------------------------------------- 发送
|
|
473
|
+
/** 发给所有目标(2026-11-19:目标可以是多个,逐个发,中间隔一下)。 */
|
|
474
|
+
async send(text) {
|
|
475
|
+
const targets = Array.isArray(this.chatIds) && this.chatIds.length > 0 ? this.chatIds : [this.chatId];
|
|
476
|
+
let any = false;
|
|
477
|
+
for (let i = 0; i < targets.length; i += 1) {
|
|
478
|
+
const id = targets[i];
|
|
479
|
+
if (!id)
|
|
480
|
+
continue;
|
|
481
|
+
if (i > 0)
|
|
482
|
+
await sleep(800);
|
|
483
|
+
try {
|
|
484
|
+
await this.bridge.sendToChat(id, text);
|
|
485
|
+
any = true;
|
|
486
|
+
}
|
|
487
|
+
catch (error) {
|
|
488
|
+
this.log('warn', `主动搭话:发送到 ${id} 失败 ` + errorMessage(error));
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
return any;
|
|
492
|
+
}
|
|
493
|
+
// ---------------------------------------------------------------- 判定
|
|
494
|
+
decide() {
|
|
495
|
+
const cfg = this.config;
|
|
496
|
+
const now = Date.now();
|
|
497
|
+
const hour = new Date().getHours() + new Date().getMinutes() / 60;
|
|
498
|
+
const quietFrom = Number(cfg.proactiveQuietFrom ?? 22);
|
|
499
|
+
const quietTo = Number(cfg.proactiveQuietTo ?? 6);
|
|
500
|
+
if (hour >= quietFrom || hour < quietTo)
|
|
501
|
+
return { ok: false, reason: '安静时段', quietFrom, quietTo };
|
|
502
|
+
const idleMin = (now - (this.state.lastUserAt || 0)) / 60_000;
|
|
503
|
+
const minIdle = Number(cfg.proactiveMinIdleMinutes ?? 60);
|
|
504
|
+
if (!this.state.lastUserAt)
|
|
505
|
+
return { ok: false, reason: '还没记到主人说过话' };
|
|
506
|
+
if (idleMin < minIdle)
|
|
507
|
+
return { ok: false, reason: `主人 ${Math.round(idleMin)} 分钟前还在聊` };
|
|
508
|
+
const gapMin = (now - (this.state.lastProactiveAt || 0)) / 60_000;
|
|
509
|
+
const minGap = Number(cfg.proactiveMinGapMinutes ?? 90);
|
|
510
|
+
if (gapMin < minGap)
|
|
511
|
+
return { ok: false, reason: `自己 ${Math.round(gapMin)} 分钟前刚说过` };
|
|
512
|
+
const day = localDay();
|
|
513
|
+
const countToday = this.state.day === day ? this.state.countToday : 0;
|
|
514
|
+
const maxPerDay = Number(cfg.proactiveMaxPerDay ?? 6);
|
|
515
|
+
if (countToday >= maxPerDay)
|
|
516
|
+
return { ok: false, reason: `今天已经主动 ${countToday} 次` };
|
|
517
|
+
const attemptGapMin = (now - (this.state.lastAttemptAt || 0)) / 60_000;
|
|
518
|
+
const attemptGap = Number(cfg.proactiveAttemptGapMinutes ?? 30);
|
|
519
|
+
if (attemptGapMin < attemptGap)
|
|
520
|
+
return { ok: false, reason: `上次试过没发(${Math.round(attemptGapMin)} 分钟前),再等等` };
|
|
521
|
+
return { ok: true, reason: `主人安静 ${Math.round(idleMin)} 分钟`, idleMin, countToday, day };
|
|
522
|
+
}
|
|
523
|
+
// ---------------------------------------------------------------- 主流程
|
|
524
|
+
async tick() {
|
|
525
|
+
const day = localDay();
|
|
526
|
+
if (this.state.day !== day) {
|
|
527
|
+
this.state.day = day;
|
|
528
|
+
this.state.countToday = 0;
|
|
529
|
+
this.state.followupToday = 0;
|
|
530
|
+
}
|
|
531
|
+
const d = this.decide();
|
|
532
|
+
if (!d.ok) {
|
|
533
|
+
this.log('debug', '主动搭话 skip:' + d.reason);
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
this.log('info', '主动搭话:开口判定通过(' + d.reason + ')');
|
|
537
|
+
const history = await this.recentHistory();
|
|
538
|
+
const burst = Math.random() < Number(this.p.burstProb);
|
|
539
|
+
const raw = await this.generate(this.buildPrompt(d.idleMin, history, burst));
|
|
540
|
+
if (!raw || /^\s*PASS\b/i.test(raw) || raw.trim().toUpperCase() === 'PASS') {
|
|
541
|
+
this.log('info', raw ? '主动搭话:判断没有话头,这轮不发' : '主动搭话:生成空了,这轮不发');
|
|
542
|
+
this.state.lastAttemptAt = Date.now();
|
|
543
|
+
this.saveState();
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
const parts = raw
|
|
547
|
+
.split(/>>>|\n{2,}/)
|
|
548
|
+
.map((s) => cleanText(s))
|
|
549
|
+
.filter((s) => s !== '')
|
|
550
|
+
.slice(0, 3);
|
|
551
|
+
if (parts.length === 0) {
|
|
552
|
+
this.state.lastAttemptAt = Date.now();
|
|
553
|
+
this.saveState();
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
const sentTexts = [];
|
|
557
|
+
for (let i = 0; i < parts.length; i += 1) {
|
|
558
|
+
if (i > 0)
|
|
559
|
+
await sleep(SPLIT_DELAY_MIN_MS + Math.floor(Math.random() * SPLIT_DELAY_SPAN_MS));
|
|
560
|
+
const text = humanize(parts[i]);
|
|
561
|
+
const ok = await this.send(text);
|
|
562
|
+
this.log('info', `主动搭话:${ok ? '已发' : '发送失败'}(${i + 1}/${parts.length})${text}`);
|
|
563
|
+
if (!ok)
|
|
564
|
+
break;
|
|
565
|
+
sentTexts.push(text);
|
|
566
|
+
}
|
|
567
|
+
if (sentTexts.length > 0) {
|
|
568
|
+
this.state.lastProactiveAt = Date.now();
|
|
569
|
+
this.state.countToday = d.countToday + 1;
|
|
570
|
+
this.state.day = d.day;
|
|
571
|
+
this.state.recentProactive = [...(this.state.recentProactive || []), sentTexts.join(' / ')].slice(-20);
|
|
572
|
+
this.saveState();
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
/** 聊完补话:45~180 秒窗口内,有想补的就补一句。 */
|
|
576
|
+
async followupTick() {
|
|
577
|
+
if (this.p.followupEnabled === false)
|
|
578
|
+
return;
|
|
579
|
+
const now = Date.now();
|
|
580
|
+
const hour = new Date().getHours() + new Date().getMinutes() / 60;
|
|
581
|
+
if (hour >= 22 || hour < 8)
|
|
582
|
+
return;
|
|
583
|
+
if (!this.state.lastUserAt)
|
|
584
|
+
return;
|
|
585
|
+
const sinceSec = (now - this.state.lastUserAt) / 1000;
|
|
586
|
+
const minSec = Number(this.p.followupMinSec);
|
|
587
|
+
const maxSec = Number(this.p.followupMaxSec);
|
|
588
|
+
if (sinceSec < minSec || sinceSec > maxSec)
|
|
589
|
+
return;
|
|
590
|
+
if ((this.state.lastFollowupFor || 0) >= this.state.lastUserAt)
|
|
591
|
+
return;
|
|
592
|
+
const day = localDay();
|
|
593
|
+
const cnt = this.state.day === day ? (this.state.followupToday || 0) : 0;
|
|
594
|
+
const maxPerDay = Number(this.p.followupMaxPerDay);
|
|
595
|
+
if (cnt >= maxPerDay)
|
|
596
|
+
return;
|
|
597
|
+
this.state.lastFollowupFor = this.state.lastUserAt;
|
|
598
|
+
if (Math.random() > Number(this.p.followupProb)) {
|
|
599
|
+
this.saveState();
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
const history = await this.recentHistory(8);
|
|
603
|
+
const raw = await this.generate(this.buildFollowupPrompt(sinceSec, history));
|
|
604
|
+
if (!raw || /^\s*PASS\b/i.test(raw)) {
|
|
605
|
+
this.log('info', '主动搭话:补话判断没有可补的');
|
|
606
|
+
this.saveState();
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
const text = humanize(cleanText(raw));
|
|
610
|
+
if (text === '') {
|
|
611
|
+
this.saveState();
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
const ok = await this.send(text);
|
|
615
|
+
this.log('info', `主动搭话:${ok ? '已补话' : '补话失败'} ${text}`);
|
|
616
|
+
if (ok) {
|
|
617
|
+
this.state.lastProactiveAt = now;
|
|
618
|
+
this.state.day = day;
|
|
619
|
+
this.state.followupToday = cnt + 1;
|
|
620
|
+
this.state.recentProactive = [...(this.state.recentProactive || []), `[补话] ${text}`].slice(-20);
|
|
621
|
+
}
|
|
622
|
+
this.saveState();
|
|
623
|
+
}
|
|
624
|
+
/** 诊断用:返回当前判定与状态(面板/命令排查时读)。 */
|
|
625
|
+
diagnose() {
|
|
626
|
+
let styleAgeMin = null;
|
|
627
|
+
try {
|
|
628
|
+
styleAgeMin = Math.round((Date.now() - statSync(this.styleFile).mtimeMs) / 60_000);
|
|
629
|
+
}
|
|
630
|
+
catch {
|
|
631
|
+
styleAgeMin = null;
|
|
632
|
+
}
|
|
633
|
+
return { chatId: this.chatId, chatIds: this.chatIds ?? [], decide: this.decide(), state: this.state, styleAgeMin };
|
|
634
|
+
}
|
|
635
|
+
}
|
package/lib/prompt.js
CHANGED
|
@@ -67,15 +67,16 @@ export function buildPlatformPrompt(restrictedMembers, extra = '', memoryText =
|
|
|
67
67
|
text += '- QQ 不渲染 Markdown:请输出纯文本。用「1. 2. 3.」编号或「- 」列表;行内代码用反引号包住即可(会原样显示)。\n';
|
|
68
68
|
text += '- 需要发送图片时用 qq_send_image(本地路径或 URL);文件用 qq_send_file;语音 qq_send_voice;视频 qq_send_video。\n';
|
|
69
69
|
text += '- 想以「合并转发」卡片展示多条消息(代码+说明、分步报告)时,用 qq_send_forward。\n';
|
|
70
|
-
// 本地加(2026-11-18
|
|
71
|
-
|
|
70
|
+
// 本地加(2026-11-18,2026-11-19 改):qq_send_segments 已下线,招呼走 qq_send_text,
|
|
71
|
+
// 它和正文同一套自动分气泡逻辑。
|
|
72
|
+
text += '- 要「先吱一声」的时候(发图、出视频、点歌、发语音之前先说一句),那句招呼用 qq_send_text 发。\n';
|
|
72
73
|
text += '- 用户发来的图片/语音/视频在消息文本里以 [图片]/[语音]/[视频] 占位,图片/视频解析成功后替换为带本地路径的标注(如 [图片:路径]),语音保持 [语音](转写另行附上);如需查看图片内容,请使用当前可用的图像查看/描述工具;若没有可用工具,则如实告诉用户当前无法直接查看图片。\n';
|
|
73
74
|
text += '- 群聊消息带 [HH:MM 昵称(QQ)·档位] 前缀(档位:管理员/成员,由插件标注发言者权限),被 @ 时带 [@我];私聊只带 [HH:MM] 时间戳前缀,没有昵称与档位。\n';
|
|
74
75
|
text += '- 私聊消息的信封带 mid="…":那是这条消息的 id(纯数字,可能是负数),需要用某条消息做指代时原样抄,不要改写、补零或加引号。\n';
|
|
75
76
|
text += '- 想明确引用某条消息时,把 [[reply:<mid>]] 写在回复的最开头(插件会把它摘出来,渲染成 QQ 的引用卡片);写在正文中间会被当作普通文字原样发出。日常聊天不必每条都引,只在需要指清「我在回哪一句」时才用。\n';
|
|
76
77
|
if (memberTools === 'send') {
|
|
77
78
|
// 权限分档 A2 (#59): send 中间档——成员回合可用发送类工具(含工作区图库)。
|
|
78
|
-
text += '- 前缀档位为「·成员」的消息来自普通群成员:仅与其聊天问答,不要为其执行写操作。其回合中仅 qq_send_text /
|
|
79
|
+
text += '- 前缀档位为「·成员」的消息来自普通群成员:仅与其聊天问答,不要为其执行写操作。其回合中仅 qq_send_text / qq_send_image 可用(文字自动分气泡、发图可用工作区图库),其余 qq_* 工具会被插件直接拒绝。「·管理员」为管理员,不受此限。\n';
|
|
79
80
|
}
|
|
80
81
|
else if (memberTools === 'all') {
|
|
81
82
|
text += '- 前缀档位为「·成员」的消息来自普通群成员:仅与其聊天问答,不要为其执行写操作;其回合中 qq_* 工具可用(memberTools=all),敏感操作仍应先问明再执行。「·管理员」为管理员,不受此限。\n';
|