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/lib/tools.js CHANGED
@@ -120,7 +120,7 @@ function toolTier(bridge, exec) {
120
120
  * qq_send_file / qq_send_voice / qq_send_video(携带任意本地文件出站)、
121
121
  * qq_napcat_api、qq_group_history 仍仅管理员回合可用。
122
122
  */
123
- const SEND_TIER_TOOLS = new Set(['qq_send_text', 'qq_send_segments', 'qq_send_image']);
123
+ const SEND_TIER_TOOLS = new Set(['qq_send_text', 'qq_send_image']);
124
124
  /**
125
125
  * Register all qq_* tools on the context. Registration is effect-based: the
126
126
  * returned disposer unregisters them. Every tool's execute is wrapped with the
@@ -143,7 +143,7 @@ export function registerTools(ctx, bridge, connection, limits, log) {
143
143
  return execute(args, exec);
144
144
  }
145
145
  throw new Error(tier === 'send'
146
- ? `当前发言人为成员档位(memberTools=send):${tool.name} 不在放行清单(仅 qq_send_text / qq_send_segments / qq_send_image),其余 qq_* 工具仅管理员回合可用`
146
+ ? `当前发言人为成员档位(memberTools=send):${tool.name} 不在放行清单(仅 qq_send_text / qq_send_image),其余 qq_* 工具仅管理员回合可用`
147
147
  : '当前发言人为成员档位,无工具权限:qq_* 工具仅管理员回合可用');
148
148
  },
149
149
  };
@@ -327,69 +327,12 @@ export function registerTools(ctx, bridge, connection, limits, log) {
327
327
  const chatId = resolveChat(bridge, exec, a.chat_id);
328
328
  const replyTo = typeof a.reply_to === 'string' && a.reply_to.trim() !== '' ? a.reply_to.trim() : undefined;
329
329
  const ids = await bridge.sendToChat(chatId, text, replyTo === undefined ? {} : { replyTo });
330
+ // 双发闸(语义版,2026-11-19):把这句记账,回合末正文重复同一句就不发了。
331
+ bridge.noteToolText?.(chatId, text);
330
332
  return { sent: true, messageId: ids.length > 0 ? String(ids[ids.length - 1]) : null };
331
333
  },
332
334
  }));
333
- // T14: 插件页开关——enabled=false 时该工具不注册(模型不可见即不可用)。
334
- if (sendSegmentsConfig.enabled)
335
- register(defineTool({
336
- name: 'qq_send_segments',
337
- description: '向 QQ 会话按顺序发送多条独立的纯文本气泡(每段一条单独消息)。仅在你明确需要分条呈现时使用——不会自动分段,需自行拆好每段文字;相邻两段的发送间隔由插件配置 segments.intervalMs 控制(可用本工具的 intervalMs 参数临时覆盖)。普通回复请直接输出文本即可。',
338
- parameters: {
339
- segments: {
340
- type: 'array',
341
- items: { type: 'string' },
342
- required: true,
343
- description: '文本段列表:按顺序逐条发送为独立气泡;最多 9 段,每段 ≤500 字且不能为空',
344
- },
345
- intervalMs: {
346
- type: 'number',
347
- description: '可选:覆盖全局的相邻段发送间隔(毫秒,0–3000,超界按边界截断);省略时用插件页配置 segments.intervalMs(默认 0 = 不等待)',
348
- },
349
- chat_id: { type: 'string', description: '目标会话,格式 private:<QQ号> 或 group:<群号>;省略时默认当前会话' },
350
- },
351
- output: {
352
- schema: { type: 'json' },
353
- render: (_args, value) => {
354
- const v = value;
355
- return [{ type: 'text', text: '已发送 ' + (v.count ?? 0) + ' 条分段消息' }];
356
- },
357
- },
358
- isConcurrencySafe: () => true,
359
- execute: async (args, exec) => {
360
- const a = args;
361
- const texts = Array.isArray(a.segments) ? a.segments.filter((s) => typeof s === 'string' && s.trim() !== '') : [];
362
- if (texts.length === 0)
363
- throw new Error('qq_send_segments: segments 不能为空(需为非空文本段数组)');
364
- if (texts.length > 9)
365
- throw new Error('qq_send_segments: 一次最多 9 段');
366
- if (texts.some(t => t.length > 500))
367
- throw new Error('qq_send_segments: 每段最多 500 字');
368
- const intervalMs = typeof a.intervalMs === 'number' && Number.isFinite(a.intervalMs)
369
- ? clampSegmentsInterval(a.intervalMs)
370
- : sendSegmentsConfig.intervalMs;
371
- // #23 点 1: 分段工具绕过了 outbound 的 stripMarkdown,** 加粗 ** 这类标记
372
- // 会原样发到 QQ 里。出站正文清洗只挂在 Bridge.sendText 那条路径上,这里
373
- // 直连 sendSegments,所以要按同一套规则清洗(清洗后为空的段直接丢掉)。
374
- const cleaned = texts.map(t => stripMarkdown(t).trim()).filter(t => t !== '');
375
- if (cleaned.length === 0)
376
- throw new Error('qq_send_segments: 去掉 Markdown 后没有可发送内容');
377
- const chatId = resolveChat(bridge, exec, a.chat_id);
378
- // #25 S3: 段被清洗丢弃时输出一条可 grep 的日志(仅丢弃时输出,不刷屏)。
379
- if (log !== undefined && cleaned.length < texts.length) {
380
- log('info', 'qq_send_segments: ' + (texts.length - cleaned.length) + '/' + texts.length
381
- + ' 段 Markdown 清洗后为空,已丢弃: chat=' + chatId);
382
- }
383
- const messageIds = [];
384
- for (let i = 0; i < cleaned.length; i++) {
385
- if (i > 0)
386
- await wait(intervalMs);
387
- const id = await bridge.sendSegments(chatId, [{ type: 'text', data: { text: cleaned[i] } }]);
388
- messageIds.push(id ?? null);
389
- }
390
- return { sent: true, count: messageIds.length, messageIds };
391
- },
392
- }));
335
+ // 2026-11-19 主人要求:qq_send_segments 工具下线(分条由 outbound 自动切气泡)。
393
336
  register(defineTool({
394
337
  name: 'qq_napcat_api',
395
338
  description: '调用 NapCat 白名单内的 OneBot 扩展 API(群成员列表/信息、文件、OCR、AI 语音等)。非白名单 action 会被拒绝。',
@@ -27,6 +27,9 @@ import type { TraceStage } from './trace.js';
27
27
  * turn (the flag resets at turn/end) so a burst of queued messages never
28
28
  * spams the chat. Exported for the deterministic text wait in tests. */
29
29
  export declare const QUEUE_NOTICE_TEXT = "\u23F3 \u5F53\u524D\u4EFB\u52A1\u8FD0\u884C\u4E2D\uFF0C\u65B0\u6D88\u606F\u5DF2\u6392\u961F\uFF0C\u5C06\u5728\u5F53\u524D\u4EFB\u52A1\u7ED3\u675F\u540E\u4F9D\u6B21\u5904\u7406\u3002";
30
+ export declare const VOICE_PROB = 0.1;
31
+ export declare const STICKER_PROB = 0.39;
32
+ export declare const VOICE_HINT: string;
30
33
  /** T2-B2: how long a relayed ask_user_question batch stays interceptable —
31
34
  * after this the bridge stops treating plain replies as answers (the host's
32
35
  * continued-state question may still be answered from the Web card). */
@@ -150,6 +153,14 @@ export interface BridgeConfig {
150
153
  groupPromptFile?: string;
151
154
  /** 本地加(2026-11-18):被 @ 时带上的群聊上下文条数(0/absent = 不参考,上限 200)。 */
152
155
  groupContextLines?: number;
156
+ /** 本地加(2026-11-19):回合形式掷骰——回复转成语音条的开关与概率(默认开 / 0.1)。 */
157
+ voiceReplyEnabled?: boolean;
158
+ voiceReplyProb?: number;
159
+ /** 本地加(2026-11-19):回合形式掷骰——发表情包的开关与概率(默认开 / 0.39)。 */
160
+ stickerReplyEnabled?: boolean;
161
+ stickerReplyProb?: number;
162
+ /** 本地加(2026-11-19):表情包库目录(空 = ~/.dsh/dsh-onebot-genji/stickers)。 */
163
+ stickerRoot?: string;
153
164
  /** T4 (PR port 记忆文件):记忆文件开关(默认关,裁定口径);只对私聊生效。 */
154
165
  memoryFilesEnabled?: boolean;
155
166
  /** T4 (PR port 记忆文件):记忆文件路径列表(~/ 展开;单文件 8000 字符、
@@ -183,11 +194,15 @@ export interface BridgeConfig {
183
194
  * 服务未部署(宿主摘除 session-title 插件)时取不到 = 同步跳过,不崩。 */
184
195
  export interface SessionTitlePort {
185
196
  get(session: Session): {
197
+ title?: string;
186
198
  source?: {
187
199
  kind?: string;
188
200
  };
189
201
  } | undefined;
190
202
  refresh(session: Session): Promise<unknown>;
203
+ /** 本地补丁 2026-11-17(搬进源码):直接写标题——身份定名(昵称/群名)用,
204
+ * 宿主侧会把标题的 source 记成 user。宿主没提供时退回 refresh。 */
205
+ rename?(session: Session, title: string): unknown;
191
206
  }
192
207
  /** W1 trace/config extensions: the observability knobs ride as optional
193
208
  * members (same pattern as the W2-②③ gate keys) so the declared BridgeConfig
@@ -407,6 +422,11 @@ export declare class ChatBridge {
407
422
  /** 群聊旁观 (#58):每群旁听环形缓冲 + 冷却/每日上限记账。惰性判定,
408
423
  * 零定时器;缓冲不持久化(易失的「最近发生了什么」,重启后重新积累)。 */
409
424
  private readonly bystander;
425
+ /** 群聊上下文(2026-11-19 本地加):每群最近 N 条未 @ 我的群消息,供被叫到那回合参考。
426
+ * 不持久化(易失的「刚才在聊什么」),条数由 config.groupContextLines 控制。 */
427
+ private readonly groupContextBuf;
428
+ /** 群名缓存(本地补丁 2026-11-17):group:123 → 群名,定名时少调一次 get_group_info。 */
429
+ private readonly qqGroupTitles;
410
430
  /** W1/T5: chatId → the traceId of the chat's unsettled INJECTED round
411
431
  * (independent of the trace sink, so the dry-run guard covers the async
412
432
  * agent reply even with tracing off). Cleared by a real dispatch to the
@@ -534,6 +554,26 @@ export declare class ChatBridge {
534
554
  * - refresh 后台执行不 await 主流程;get/refresh 同步抛或拒绝都只
535
555
  * warn(标题是辅助功能,失败静默降级,不冒泡进派发主流程)。 */
536
556
  private syncSessionTitle;
557
+ noteToolText(chatId: ChatId, text: string): void;
558
+ /**
559
+ * 回合末正文是否只是把工具刚说过的话又重复一遍(意思层面)。
560
+ * @returns true 表示重复,正文应丢弃。
561
+ */
562
+ isToolTopicDuplicate(chatId: ChatId, text: string): boolean;
563
+ /** 每回合掷骰决定回合形式:语音条 / 表情包 / 纯文字(概率读配置,默认 10% / 39%)。 */
564
+ rollTurnForm(): string;
565
+ /**
566
+ * 群聊上下文(2026-11-19 本地加):把一条未 @ 我 / 没叫到唤醒词的群消息记进
567
+ * 环缓冲,被叫到那一回合按 config.groupContextLines 取最近 N 条注入。
568
+ */
569
+ recordGroupContext(chatId: ChatId, entry: {
570
+ time: number;
571
+ userId: string;
572
+ nickname: string;
573
+ text: string;
574
+ }): void;
575
+ /** 本轮要注入的群聊上下文文本(没有返回 undefined)。 */
576
+ groupContextRecent(chatId: ChatId): string | undefined;
537
577
  /**
538
578
  * 群聊旁观 (#58):把一条未通过 @ 门控的群消息喂进旁听缓冲;规则触发命中
539
579
  * 且会话空闲时开一次回顾回合(角色固定 member——旁听内容源自群消息,不可信,
@@ -1,2 +1,123 @@
1
1
  declare const window: any;
2
2
  declare const document: any;
3
+ /**
4
+ * 2026-11-19(本地加):表情包库面板用到的浏览器侧最小接口声明。
5
+ * 本 bundle 的 tsconfig lib 只有 ES2024(无 DOM),故在文件顶声明 / 类型收窄,
6
+ * 避免 strict 下引入 any 或依赖 DOM lib(宿主浏览器恒有这些全局)。
7
+ */
8
+ declare const FileReader: {
9
+ new (): {
10
+ result: unknown;
11
+ onload: (() => void) | null;
12
+ onerror: (() => void) | null;
13
+ readAsDataURL(file: unknown): void;
14
+ };
15
+ };
16
+ declare const IntersectionObserver: {
17
+ new (callback: (entries: readonly {
18
+ isIntersecting?: boolean;
19
+ target: {
20
+ getAttribute(name: string): string | null;
21
+ };
22
+ }[]) => void, options?: {
23
+ rootMargin?: string;
24
+ }): {
25
+ observe(node: unknown): void;
26
+ unobserve(node: unknown): void;
27
+ disconnect(): void;
28
+ };
29
+ };
30
+ /** 表情包条目(字段逐字对齐 host 侧 listStickers 的 items)。 */
31
+ interface StickerItemLike {
32
+ hash: string;
33
+ file: string;
34
+ approved: boolean;
35
+ dir: string;
36
+ tags: string[];
37
+ description: string;
38
+ bytes: number;
39
+ addedAt: number;
40
+ exists: boolean;
41
+ }
42
+ /** 表情包库统计(host snapshotOf 的 stats)。 */
43
+ interface StickerStatsLike {
44
+ total: number;
45
+ approved: number;
46
+ pending: number;
47
+ bytes: number;
48
+ root: string;
49
+ }
50
+ /** 单张审核 / 重新识别结果(host retagStickers 的 results 元素)。 */
51
+ interface StickerResultLike {
52
+ hash: string;
53
+ ok: boolean;
54
+ description?: string;
55
+ tags?: string[];
56
+ reason?: string;
57
+ }
58
+ /** listStickers / addSticker / approve… 的统一返回快照。 */
59
+ interface StickerSnapshotLike {
60
+ ok: boolean;
61
+ root: string;
62
+ autoCollect: boolean;
63
+ approvedDir: string;
64
+ pendingDir: string;
65
+ stats: StickerStatsLike;
66
+ items: StickerItemLike[];
67
+ error?: unknown;
68
+ results?: StickerResultLike[];
69
+ added?: {
70
+ added: boolean;
71
+ reason?: string;
72
+ item?: StickerItemLike;
73
+ };
74
+ removed?: {
75
+ hash: string;
76
+ ok: boolean;
77
+ }[];
78
+ }
79
+ /** readSticker 返回(dataUrl 走 MIME base64;超限只回 tooLarge)。 */
80
+ interface StickerImageLike {
81
+ ok: boolean;
82
+ hash: string;
83
+ dataUrl?: string;
84
+ bytes?: number;
85
+ mime?: string;
86
+ tooLarge?: boolean;
87
+ }
88
+ /** 面板用到的 remote 方法面(真身是 host remote.onebotSettings;这里只声明用到的方法)。 */
89
+ interface StickerRemoteLike {
90
+ listStickers(): unknown;
91
+ addSticker(name: string, dataUrl: string): unknown;
92
+ deleteSticker(hashes: string[]): unknown;
93
+ approveStickers(hashes: string[]): unknown;
94
+ unapproveStickers(hashes: string[]): unknown;
95
+ retagStickers(hashes: string[]): unknown;
96
+ readSticker(hash: string): unknown;
97
+ updateSticker(hash: string, patch: {
98
+ description?: string;
99
+ tags?: string[];
100
+ }): unknown;
101
+ }
102
+ /** 面板里用到的最小事件形状(change / click / keydown / 上传)。 */
103
+ interface StickerPanelEvent {
104
+ target: {
105
+ value: string;
106
+ files?: ArrayLike<unknown> | null;
107
+ };
108
+ key?: string;
109
+ /** 2026-11-19:编辑框改成多行 textarea 后,靠 Ctrl/⌘+Enter 保存。 */
110
+ ctrlKey?: boolean;
111
+ metaKey?: boolean;
112
+ preventDefault(): void;
113
+ stopPropagation(): void;
114
+ }
115
+ /** StickerPanel 的 props(ui 只需 Button 与 ImageLightbox 两个能力)。 */
116
+ interface StickerPanelProps {
117
+ remote: StickerRemoteLike;
118
+ ui: {
119
+ Button: unknown;
120
+ ImageLightbox?: unknown;
121
+ };
122
+ onNotify?: (message: string, isError?: boolean) => void;
123
+ }
@@ -137,6 +137,14 @@ export interface InboundContext {
137
137
  nickname: string;
138
138
  text: string;
139
139
  }): Promise<void>;
140
+ /** 本地加(2026-11-19):未 @ 的群消息记进「参考上下文条数」环缓冲(不触发
141
+ * 任何回合)。缺席 = 零行为,与上游等价。 */
142
+ recordGroupContext?(chatId: ChatId, entry: {
143
+ time: number;
144
+ userId: string;
145
+ nickname: string;
146
+ text: string;
147
+ }): void;
140
148
  /** T2 (P1): busy-turn policy seam — invoked for every non-command message
141
149
  * after ALL gates (dedup/policy/mention/media/rate-limit), right before the
142
150
  * turn dispatch, so queue/steer can never bypass an existing gate. Returns
@@ -210,10 +210,30 @@ export interface Config {
210
210
  deferredTimeout?: boolean | string;
211
211
  rateLimited?: boolean | string;
212
212
  };
213
- /** T14 (#6 补充): qq_send_segments 插件页开关与分段发送间隔(呼吸感)。 */
214
- segments: {
213
+ /** 回合形式掷骰(本地加 2026-11-18):语音条 / 表情包的开关与概率。 */
214
+ voiceReplyEnabled: boolean;
215
+ voiceReplyProb: number;
216
+ stickerReplyEnabled: boolean;
217
+ stickerReplyProb: number;
218
+ /** 表情包库根目录;空串 = DEFAULT_STICKER_ROOT(~/.dsh/dsh-onebot-genji/stickers)。 */
219
+ stickerRoot: string;
220
+ stickerAutoCollect: boolean;
221
+ /** 主动搭话(本地加 2026-11-19,原 startup/qq-alive.mjs 合并进插件)。 */
222
+ proactive: {
215
223
  enabled: boolean;
216
- intervalMs: number;
224
+ targetUsers: string[];
225
+ minIdleMinutes: number;
226
+ minGapMinutes: number;
227
+ maxPerDay: number;
228
+ quietFrom: number;
229
+ quietTo: number;
230
+ attemptGapMinutes: number;
231
+ burstProb: number;
232
+ followupEnabled: boolean;
233
+ followupMinSec: number;
234
+ followupMaxSec: number;
235
+ followupProb: number;
236
+ followupMaxPerDay: number;
217
237
  };
218
238
  /** Per-chat per-minute sliding-window cap for normal (non-command) messages; 0 disables. */
219
239
  rateLimitPerMinute: number;
@@ -82,6 +82,8 @@ export interface InterimContext {
82
82
  relayHostCards(chatId: ChatId, content: readonly unknown[]): void;
83
83
  /** Per-chat effective outbound mode (/mode override → global config). */
84
84
  effectiveInterim(chatId: ChatId): boolean;
85
+ /** 双发闸(语义版):回合末正文是不是把工具刚说过的话又重复一遍。 */
86
+ dropDuplicateFinal?(chatId: ChatId, text: string): boolean;
85
87
  /** Bridge log line callback. */
86
88
  log(level: 'info' | 'warn' | 'error' | 'debug', message: string): void;
87
89
  /** The only config fields the interim domain reads. */
@@ -65,6 +65,37 @@ export declare function isAsideOnly(text: string): boolean;
65
65
  * 不经过本函数)。
66
66
  */
67
67
  export declare function splitAtSegments(text: string): OutboundSegment[];
68
+ /**
69
+ * 气泡切分(2026-11-19 按 GitHub issue #6 的核心逻辑重写,主人要求):
70
+ * 1. 先按换行初步切分,一行一条——**换行是硬边界,行与行之间不合并**(主人
71
+ * 反复强调「换行了就要分成两条」);
72
+ * 2. 每行内部:长度超过 sentenceCut(35) 时按句末标点断句,短行原样保留;
73
+ * 3. 行内吸附合并:纯标点(`\p{P}\p{S}`)并进上一条;上一条不足 6 字且合计
74
+ * 不超过 24 字也并进去,避免「也是哦」「哈哈」这种碎片单独成条;
75
+ * 4. 跨行只做一件事:整行都是纯标点时并进上一条(「真的假的」+「!」);
76
+ * 5. 单轮最多 4 条,多出来的并到最后一条(防刷屏)。
77
+ * 发送侧的呼吸停顿在 sendToChat 里做(首条立即,其后 800–1500ms 随机)。
78
+ */
79
+ export declare function splitIntoBubbles(text: string, maxBubbles?: number, sentenceCut?: number): string[];
80
+ /**
81
+ * 相邻气泡之间的拟人打字停顿:800–1500ms 随机(issue #6 的生产参数)。
82
+ * 首条不等待,所以这里只被第 2 条及以后调用。
83
+ */
84
+ export declare function bubbleGapMs(random?: () => number): number;
85
+ /**
86
+ * 双发闸(语义版,2026-11-19 主人要回):判断「回合末正文」是不是把工具
87
+ * (qq_send_text / 图片配文那种)刚说过的话又重复了一遍。纯文本启发式,
88
+ * 不调模型:先归一化(去掉空白、标点、符号、emoji、括号里的颜文字),
89
+ * 再比二元组 Dice 系数。长度差超过一倍直接判不重复(一句是新内容)。
90
+ */
91
+ export declare function textTopicKey(text: string): string;
92
+ /** 二元组 Dice 系数(0–1):1 = 归一化后一模一样。 */
93
+ export declare function topicSimilarity(a: string, b: string): number;
94
+ /** 判重阈值:0.72 能把「我先去跑,几十秒」/「我去跑,几十秒」判成同一句,
95
+ * 又能放过「来了」+「来了,我这就去扒谱」这种后半句有新信息的。 */
96
+ export declare const DUPLICATE_TOPIC_THRESHOLD = 0.72;
97
+ /** 语义判重:归一化后同串直接算重复,否则二元组 Dice ≥ 阈值算重复。 */
98
+ export declare function isDuplicateTopic(a: string, b: string, threshold?: number): boolean;
68
99
  /** Options for an explicit outbound send (from tools). */
69
100
  export interface SendOptions {
70
101
  replyTo?: string;
@@ -0,0 +1,170 @@
1
+ /** 日志通道:与 lib/prompt.ts 的 ChannelLog 同形,但不 import 它(自包含)。 */
2
+ export type ProactiveLogLevel = 'info' | 'warn' | 'error' | 'debug';
3
+ export type ProactiveLog = (level: ProactiveLogLevel, message: string) => void;
4
+ /** 主动搭话的开关与门槛(设置面板 → 行为 → 私聊 那一组)。 */
5
+ export interface ProactiveSettings {
6
+ enabled: boolean;
7
+ targetUsers: string[];
8
+ minIdleMinutes: number;
9
+ minGapMinutes: number;
10
+ maxPerDay: number;
11
+ quietFrom: number;
12
+ quietTo: number;
13
+ attemptGapMinutes: number;
14
+ burstProb: number;
15
+ followupEnabled: boolean;
16
+ followupMinSec: number;
17
+ followupMaxSec: number;
18
+ followupProb: number;
19
+ followupMaxPerDay: number;
20
+ }
21
+ /** 配置默认值:Config.proactive 用 .default({}) 时不保证补齐子字段,这里垫一层,
22
+ * 免得 undefined 把阈值判断打成恒假、让主动搭话静默失效。与 lib/index.js 的
23
+ * Config.proactive 逐项对齐(不含接口地址/模型名/Key —— 2026-11-19 起走当前会话模型)。 */
24
+ export declare const PROACTIVE_DEFAULTS: ProactiveSettings;
25
+ /** 把 NapCat 的 raw_message 里那堆 CQ 码压成中文占位,不然生成时接不上话头。 */
26
+ export declare function cleanCq(text: unknown, masterQQ?: string): string;
27
+ /** 清洗模型输出:去括号旁白、去前缀引号、去句末句号、太长截断。 */
28
+ export declare function cleanText(text: unknown): string;
29
+ /** 真人会手滑:偶尔改一处常用字。概率很低,别每次都改。 */
30
+ export declare function humanize(text: string, prob?: number): string;
31
+ /** 按上一句猜一个场面标签,用来挑同场景的真实对子。 */
32
+ export declare function sceneOf(lastUserText: string): string;
33
+ /** 落盘状态(~/.dsh/alive-state.json)。字段来自文件,可能缺项或脏,读进来先垫默认。 */
34
+ export interface ProactiveState {
35
+ lastUserAt: number;
36
+ lastProactiveAt: number;
37
+ lastAttemptAt: number;
38
+ lastUserText: string;
39
+ day: string;
40
+ countToday: number;
41
+ recentProactive: string[];
42
+ lastFollowupFor: number;
43
+ followupToday: number;
44
+ }
45
+ /** 语感库(~/.dsh/style/pool.json)里的一对「主人说 → 我回」。 */
46
+ export interface ProactiveStylePair {
47
+ situation: string;
48
+ user: string;
49
+ bot: string;
50
+ }
51
+ /** 语感库文件形状:只有 pairs 有用,别的字段照旧不管。 */
52
+ export interface ProactiveStylePool {
53
+ pairs: ProactiveStylePair[];
54
+ }
55
+ /** 判定结果:通过时带余量数字,不通过时带理由(诊断日志直接用 reason)。 */
56
+ export type ProactiveDecision = {
57
+ ok: true;
58
+ reason: string;
59
+ idleMin: number;
60
+ countToday: number;
61
+ day: string;
62
+ } | {
63
+ ok: false;
64
+ reason: string;
65
+ quietFrom?: number;
66
+ quietTo?: number;
67
+ };
68
+ /** 宿主配置里这个文件用到的那几项(结构化描述,不 import index.ts 的 Config)。 */
69
+ export interface ProactiveHostConfig {
70
+ /** 主动搭话那一段(Config.proactive)。 */
71
+ proactive?: Partial<ProactiveSettings>;
72
+ /** 管理员 QQ 列表:targetUsers 留空时作为兜底目标。 */
73
+ adminUsers?: readonly string[];
74
+ /** 下面几项旧字段名在 Config 里并不存在,保留是为了不改动判定逻辑(1:1 移植)。 */
75
+ proactiveQuietFrom?: number;
76
+ proactiveQuietTo?: number;
77
+ proactiveMinIdleMinutes?: number;
78
+ proactiveMinGapMinutes?: number;
79
+ proactiveMaxPerDay?: number;
80
+ proactiveAttemptGapMinutes?: number;
81
+ }
82
+ /** 上下文尾巴(bridge.tails):只用到 read(chatId)。 */
83
+ export interface ProactiveTailsLike {
84
+ read?: (chatId: string) => unknown;
85
+ }
86
+ /** ChatBridge 里这个类用到的那两个口子。
87
+ * tails 在 ChatBridge 上是 **private** 字段:接口里一旦声明同名的公开属性,
88
+ * ChatBridge 就不再满足这个接口(私有成员两边都得私有),所以这里只收
89
+ * sendToChat,尾巴用下面的 bridgeTails() 按名字取(运行时行为不变)。 */
90
+ export interface ProactiveBridgeLike {
91
+ sendToChat: (chatId: string, text: string) => unknown;
92
+ }
93
+ /** 宿主模型调用通道(index.ts 注入;返回值当纯文本用)。 */
94
+ export type ProactiveGenerateText = (prompt: string, options: {
95
+ signal?: AbortSignal;
96
+ }) => Promise<string>;
97
+ /** 构造参数(沿用 JS 版的对象解构)。 */
98
+ export interface ProactiveTalkDeps {
99
+ /** 插件配置(proactive* 字段)。 */
100
+ config: ProactiveHostConfig;
101
+ /** ChatBridge 实例(只用 sendToChat / chats / tails)。 */
102
+ bridge: ProactiveBridgeLike;
103
+ log: ProactiveLog;
104
+ /** ~/.dsh */
105
+ dshHome: string;
106
+ /** 宿主模型调用通道(2026-11-19 起改走当前会话模型,不再自己打 HTTP)。 */
107
+ generateText?: ProactiveGenerateText;
108
+ }
109
+ export declare class ProactiveTalk {
110
+ readonly config: ProactiveHostConfig;
111
+ readonly generateText: ProactiveGenerateText | undefined;
112
+ /** 配置集中在这里(Config.proactive 那一段);adminUsers 等顶层字段仍走 this.config。 */
113
+ readonly p: ProactiveSettings;
114
+ readonly bridge: ProactiveBridgeLike;
115
+ readonly log: ProactiveLog;
116
+ readonly dshHome: string;
117
+ readonly stateFile: string;
118
+ readonly styleFile: string;
119
+ state: ProactiveState;
120
+ styleCache: ProactiveStylePool | null;
121
+ timer: ReturnType<typeof setTimeout> | null;
122
+ stopped: boolean;
123
+ nextTickAt: number;
124
+ ticking: boolean;
125
+ chatId: string;
126
+ /** 多目标(2026-11-19):配置里可以填多个搭话目标。 */
127
+ chatIds: string[];
128
+ /**
129
+ * @param deps.config 插件配置(proactive* 字段)
130
+ * @param deps.bridge ChatBridge 实例(只用 sendToChat / chats / tails)
131
+ * @param deps.log 日志通道
132
+ * @param deps.dshHome ~/.dsh
133
+ * @param deps.generateText 宿主模型调用通道(2026-11-19 起改走当前会话模型,不再自己打 HTTP)
134
+ */
135
+ constructor({ config, bridge, log, dshHome, generateText }: ProactiveTalkDeps);
136
+ emptyState(): ProactiveState;
137
+ loadState(): ProactiveState;
138
+ saveState(): void;
139
+ /** 目标私聊列表(2026-11-19 支持多个):配置的 targetUsers 优先,留空则用 adminUsers 全体。 */
140
+ resolveChatIds(): string[];
141
+ start(): void;
142
+ stop(): void;
143
+ schedule(ms: number): void;
144
+ loopOnce(): Promise<void>;
145
+ /** 入站事件打点:只认目标私聊里主人发来的消息(更新「主人最后说话时间」)。 */
146
+ noteInbound(event: unknown): void;
147
+ loadStyle(): ProactiveStylePool;
148
+ pickPairs(scene: string, want?: number): ProactiveStylePair[];
149
+ styleBlock(scene: string, want?: number): string;
150
+ /** 生成一句话。失败返回 ''(当轮不发,绝不影响插件其他部分)。 */
151
+ generate(prompt: string): Promise<string>;
152
+ /** 最近几条对话(优先用插件自己的上下文尾巴,没有就用状态里记的最后一句)。 */
153
+ recentHistory(count?: number): Promise<string[]>;
154
+ buildPrompt(idleMin: number, history: readonly string[], burst: boolean): string;
155
+ buildFollowupPrompt(sinceSec: number, history: readonly string[]): string;
156
+ /** 发给所有目标(2026-11-19:目标可以是多个,逐个发,中间隔一下)。 */
157
+ send(text: string): Promise<boolean>;
158
+ decide(): ProactiveDecision;
159
+ tick(): Promise<void>;
160
+ /** 聊完补话:45~180 秒窗口内,有想补的就补一句。 */
161
+ followupTick(): Promise<void>;
162
+ /** 诊断用:返回当前判定与状态(面板/命令排查时读)。 */
163
+ diagnose(): {
164
+ chatId: string;
165
+ chatIds: string[];
166
+ decide: ProactiveDecision;
167
+ state: ProactiveState;
168
+ styleAgeMin: number | null;
169
+ };
170
+ }
@@ -107,6 +107,8 @@ export interface ChatAgent {
107
107
  text: string;
108
108
  sentAt: number;
109
109
  }>;
110
+ /** 双发闸(2026-11-19 语义版):本回合工具用 qq_send_text 发过的文本。 */
111
+ toolSentTexts: string[];
110
112
  /** Per-interim 90s (config interimRecallMs) auto-recall timers, keyed by
111
113
  * message id; cleared when turn/end recalls the originals immediately. */
112
114
  recallTimers: Map<string, ReturnType<typeof setTimeout>>;
@@ -168,6 +170,9 @@ export interface RegistryDeps {
168
170
  log(level: 'info' | 'warn' | 'error' | 'debug', message: string): void;
169
171
  /** Bridge stop flag (guards the resume loop). */
170
172
  isStopping(): boolean;
173
+ /** 本地加(2026-11-19):恢复会话失败时的重试间隔(毫秒)覆盖;缺省用
174
+ * RESUME_RETRY_DELAYS_MS。测试传短间隔,生产不传。 */
175
+ resumeRetryDelaysMs?: readonly number[];
171
176
  /** Bridge-owned chat runtime teardown when a chat leaves the registry:
172
177
  * stop the typing indicator. Interim recall timers are cleared by the
173
178
  * registry itself (ChatAgent state), keeping the reset/heal semantics
@@ -289,6 +294,11 @@ export declare class ChatRegistry {
289
294
  /** Resume one persisted chat from its recorded session id (shared by
290
295
  * loadMapping and the B8c evicted-chat resume). */
291
296
  private resumeChat;
297
+ /** 本地加(2026-11-19):带等待的 resume。恢复失败时先等旧 agent 释放
298
+ * (热重载瞬间它可能正跑着一轮),按 RESUME_RETRY_DELAYS_MS 重试;只有全
299
+ * 都失败才把错误抛给调用方走退休流程。遇到 RESUME_RETRY_SKIP 里的错误
300
+ * (日志没了/坏了)不浪费时间去重试。 */
301
+ private resumeChatWithWait;
292
302
  private mappingPath;
293
303
  /** T3 (hole C): make a just-set /workspace override durable even when the
294
304
  * chat is not live (before its first message, or after a failed resume).