@nestim/koishi-plugin-qq-group-manager 1.1.3 → 1.2.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.
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ /**
3
+ * 提示词组装(纯函数)。
4
+ *
5
+ * 设计要点(对应旧版的四个病灶):
6
+ * - 上下文严格按时间顺序,不按关键词重排,不出现"不要回复最后一条";
7
+ * - 明确「只回应当前消息」,引用与回答永远指向同一条;
8
+ * - 机器人自己的历史发言以「你」出现,前后文能接上;
9
+ * - 记忆只在检索命中时注入,并且明确允许忽略;
10
+ * - 非点名场景允许模型输出 <pass/> 放弃接话(决策与生成合一,不再两次调用)。
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.PASS_TOKEN = void 0;
14
+ exports.renderRecordLine = renderRecordLine;
15
+ exports.buildSystemPrompt = buildSystemPrompt;
16
+ exports.buildUserPrompt = buildUserPrompt;
17
+ exports.buildReplyPrompt = buildReplyPrompt;
18
+ exports.buildJudgePrompt = buildJudgePrompt;
19
+ const names_1 = require("../core/names");
20
+ const text_1 = require("../core/text");
21
+ exports.PASS_TOKEN = '<pass/>';
22
+ const RULE_LINES = [
23
+ '只输出你要发到群里的那一条消息正文。不要解释、不要旁白、不要编号、不要 Markdown、不要代码块、不要用引号把整句包起来。',
24
+ '用中文口语,像群友聊天。不要复述对方的话,不要写"作为AI"之类的自我说明。',
25
+ '只回应【当前消息】。需要称呼别人时用群昵称,不要用 QQ 号。',
26
+ '不要编造群里没发生过的事;不确定就直接说不确定。',
27
+ '不要提"记忆库""上下文""系统提示"这些词,也不要说"根据记忆"。',
28
+ '不要主动挑起旧话题;当前消息聊什么就接什么。',
29
+ ];
30
+ function timeText(ts) {
31
+ try {
32
+ return new Date(ts).toLocaleTimeString('zh-CN', {
33
+ hour: '2-digit',
34
+ minute: '2-digit',
35
+ hour12: false,
36
+ timeZone: 'Asia/Shanghai',
37
+ });
38
+ }
39
+ catch {
40
+ const d = new Date(ts);
41
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
42
+ }
43
+ }
44
+ function speaker(record, selfName) {
45
+ if (record.self)
46
+ return `${selfName}(你)`;
47
+ const role = (0, names_1.roleLabel)(record.role || 'unknown');
48
+ return role ? `${record.name}(${role})` : record.name;
49
+ }
50
+ function renderRecordLine(record, selfName) {
51
+ const time = timeText(record.at);
52
+ const quote = record.quote?.text
53
+ ? `「回复 ${record.quote.name}:${(0, text_1.truncate)(record.quote.text, 40)}」`
54
+ : '';
55
+ const body = quote ? `${quote}${record.text}` : record.text;
56
+ return `[${time}] ${speaker(record, selfName)}: ${body || '[空消息]'}`;
57
+ }
58
+ function buildSystemPrompt(input) {
59
+ const lines = [];
60
+ lines.push(`你是 QQ 群 ${input.groupId} 里的一个普通成员,自称「${input.selfName}」。`);
61
+ if (input.persona?.trim())
62
+ lines.push(input.persona.trim());
63
+ lines.push('');
64
+ lines.push('必须遵守:');
65
+ for (const rule of RULE_LINES)
66
+ lines.push(`- ${rule}`);
67
+ lines.push(`- 控制在 ${Math.max(20, input.maxReplyChars)} 个字以内,通常一两句话就够。`);
68
+ if (input.allowPass) {
69
+ lines.push(`- 如果当前消息不需要你接话(别人在互相聊、已经有人回答、纯刷屏、和你无关),只输出 ${exports.PASS_TOKEN},不要输出任何其它内容。`);
70
+ }
71
+ else {
72
+ lines.push('- 当前消息点名了你,必须回应;不要输出 <pass/>。');
73
+ }
74
+ return lines.join('\n');
75
+ }
76
+ function buildUserPrompt(input) {
77
+ const selfName = input.selfName;
78
+ const history = input.records.filter((item) => item !== input.current && item.id !== input.current.id);
79
+ const lines = [];
80
+ lines.push('【最近消息】(按时间顺序,越靠下越新;名字都是群昵称)');
81
+ if (history.length) {
82
+ for (const record of history)
83
+ lines.push(renderRecordLine(record, selfName));
84
+ }
85
+ else {
86
+ lines.push('(没有更早的消息)');
87
+ }
88
+ lines.push('');
89
+ lines.push('【当前消息】(你只需要回应这一条)');
90
+ lines.push(renderRecordLine(input.current, selfName));
91
+ if (input.mention)
92
+ lines.push('(这条消息 @ 了你或叫了你的名字)');
93
+ if (input.followup)
94
+ lines.push('(这是刚才点名话题的继续追问)');
95
+ if (input.memories.length) {
96
+ lines.push('');
97
+ lines.push('【可能相关的记忆】以下内容只在确实与当前消息相关时才可以参考;不相关就必须忽略,绝对不要硬扯。');
98
+ for (const item of input.memories) {
99
+ lines.push(`- ${item.replace(/\s+/g, ' ').trim()}`);
100
+ }
101
+ }
102
+ lines.push('');
103
+ lines.push(input.allowPass
104
+ ? `现在只输出回复正文;如果不该接话,输出 ${exports.PASS_TOKEN}。`
105
+ : '现在只输出一条回复正文。');
106
+ return lines.join('\n');
107
+ }
108
+ function buildReplyPrompt(input) {
109
+ return {
110
+ system: buildSystemPrompt(input),
111
+ user: buildUserPrompt(input),
112
+ };
113
+ }
114
+ /** 两段式模式下的判定提示词(只有显式配置 aiReplyDecision=two-stage 才会用) */
115
+ function buildJudgePrompt(input) {
116
+ const system = [
117
+ '你是群聊回复开关判定器。',
118
+ `当前群里有一个机器人,自称「${input.selfName}」。`,
119
+ '判断机器人现在是否应该接话。',
120
+ '只输出 JSON:{"reply":true|false,"score":0-100,"reason":"一句话"}。不要输出任何其它文字。',
121
+ '标准:与机器人无关、别人正在对话、纯刷屏 → reply=false;被点名、被追问、有明显互动价值 → reply=true。',
122
+ ].join('\n');
123
+ const user = buildUserPrompt({ ...input, allowPass: false }).replace(/现在只输出一条回复正文。$/, '现在只输出判定 JSON。');
124
+ return { system, user };
125
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 模型调用层:OpenAI 兼容接口 与 Gemini 原生接口。
3
+ *
4
+ * 与旧实现的区别:
5
+ * - 统一一次请求接口,支持 system/user 分开;
6
+ * - 带图片时如果服务端返回 4xx(多数是模型不支持图片),自动降级为纯文本重试一次;
7
+ * - 输出统一清洗(去代码块 / 去前后空白),不在这里做长度截断。
8
+ */
9
+ export interface ChatRequest {
10
+ system: string;
11
+ user: string;
12
+ images?: string[];
13
+ temperature?: number;
14
+ maxTokens?: number;
15
+ timeoutMs?: number;
16
+ }
17
+ export interface ChatResult {
18
+ ok: boolean;
19
+ text?: string;
20
+ error?: string;
21
+ status?: number;
22
+ /** 是否因为图片被拒而发生了降级重试 */
23
+ degradedToText?: boolean;
24
+ }
25
+ export interface ProviderConfig {
26
+ aiProvider?: string;
27
+ aiApiKey?: string;
28
+ aiBaseUrl?: string;
29
+ aiModel?: string;
30
+ aiTemperature?: number;
31
+ aiMaxOutputTokens?: number;
32
+ aiRequestTimeoutSeconds?: number;
33
+ }
34
+ export declare class ChatProvider {
35
+ private config;
36
+ private logger?;
37
+ /** 一旦确认当前模型不支持图片,后续直接跳过图片,避免每次都白跑一次 400 */
38
+ private visionUnsupported;
39
+ /** 推理模型如果在小预算下被截断,记住一个更大的下限,后续不再重复踩坑 */
40
+ private minMaxTokens;
41
+ constructor(config: ProviderConfig, logger?: any);
42
+ private get apiKey();
43
+ private get model();
44
+ private get timeoutMs();
45
+ chat(request: ChatRequest): Promise<ChatResult>;
46
+ private callOpenAi;
47
+ private callGemini;
48
+ }
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+ /**
3
+ * 模型调用层:OpenAI 兼容接口 与 Gemini 原生接口。
4
+ *
5
+ * 与旧实现的区别:
6
+ * - 统一一次请求接口,支持 system/user 分开;
7
+ * - 带图片时如果服务端返回 4xx(多数是模型不支持图片),自动降级为纯文本重试一次;
8
+ * - 输出统一清洗(去代码块 / 去前后空白),不在这里做长度截断。
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.ChatProvider = void 0;
12
+ function stripFence(text) {
13
+ return String(text || '')
14
+ .replace(/^\s*```[a-zA-Z0-9_-]*\s*\n?/, '')
15
+ .replace(/\n?\s*```\s*$/, '')
16
+ .trim();
17
+ }
18
+ class ChatProvider {
19
+ config;
20
+ logger;
21
+ /** 一旦确认当前模型不支持图片,后续直接跳过图片,避免每次都白跑一次 400 */
22
+ visionUnsupported = false;
23
+ /** 推理模型如果在小预算下被截断,记住一个更大的下限,后续不再重复踩坑 */
24
+ minMaxTokens = 0;
25
+ constructor(config, logger) {
26
+ this.config = config;
27
+ this.logger = logger;
28
+ }
29
+ get apiKey() {
30
+ return String(this.config.aiApiKey ?? '').trim();
31
+ }
32
+ get model() {
33
+ return String(this.config.aiModel ?? '').trim();
34
+ }
35
+ get timeoutMs() {
36
+ const seconds = Number(this.config.aiRequestTimeoutSeconds ?? 20);
37
+ return Math.max(5, Math.min(120, Number.isFinite(seconds) ? seconds : 20)) * 1000;
38
+ }
39
+ async chat(request) {
40
+ if (!this.apiKey)
41
+ return { ok: false, error: 'AI 未配置 apiKey' };
42
+ if (!this.model)
43
+ return { ok: false, error: 'AI 未配置 model' };
44
+ const provider = String(this.config.aiProvider ?? 'openai-compatible');
45
+ const requested = (request.images ?? []).filter((item) => /^data:image\//i.test(item) || /^https?:\/\//i.test(item));
46
+ const images = this.visionUnsupported ? [] : requested;
47
+ const result = provider === 'gemini'
48
+ ? await this.callGemini(request, images)
49
+ : await this.callOpenAi(request, images);
50
+ if (result.ok)
51
+ return { ...result, text: stripFence(result.text || '') };
52
+ // 图片被拒(常见于 deepseek 等不支持 vision 的模型)→ 记住并去掉图片重试一次
53
+ if (images.length && (result.status === 400 || result.status === 422 || /image|vision|multimodal/i.test(result.error || ''))) {
54
+ this.visionUnsupported = true;
55
+ this.logger?.warn?.(`[ai] 模型不支持图片(${result.status ?? '?'}),后续自动跳过图片: ${result.error}`);
56
+ const fallback = provider === 'gemini'
57
+ ? await this.callGemini(request, [])
58
+ : await this.callOpenAi(request, []);
59
+ if (fallback.ok)
60
+ return { ...fallback, text: stripFence(fallback.text || ''), degradedToText: true };
61
+ return fallback;
62
+ }
63
+ return result;
64
+ }
65
+ async callOpenAi(request, images, options = {}) {
66
+ const base = String(this.config.aiBaseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
67
+ const content = [{ type: 'text', text: request.user }];
68
+ for (const url of images)
69
+ content.push({ type: 'image_url', image_url: { url } });
70
+ const userContent = images.length ? content : request.user;
71
+ const maxTokens = Math.max(options.maxTokens ?? request.maxTokens ?? this.config.aiMaxOutputTokens ?? 400, this.minMaxTokens);
72
+ const controller = new AbortController();
73
+ const timer = setTimeout(() => controller.abort(), request.timeoutMs ?? this.timeoutMs);
74
+ try {
75
+ const response = await fetch(`${base}/chat/completions`, {
76
+ method: 'POST',
77
+ headers: {
78
+ Authorization: `Bearer ${this.apiKey}`,
79
+ 'Content-Type': 'application/json',
80
+ },
81
+ body: JSON.stringify({
82
+ model: this.model,
83
+ temperature: request.temperature ?? this.config.aiTemperature ?? 0.8,
84
+ max_tokens: maxTokens,
85
+ messages: [
86
+ { role: 'system', content: request.system },
87
+ { role: 'user', content: userContent },
88
+ ],
89
+ }),
90
+ signal: controller.signal,
91
+ });
92
+ const payload = await response.json().catch(() => ({}));
93
+ if (!response.ok) {
94
+ return {
95
+ ok: false,
96
+ status: response.status,
97
+ error: payload?.error?.message || response.statusText || `HTTP ${response.status}`,
98
+ };
99
+ }
100
+ const raw = payload?.choices?.[0]?.message?.content;
101
+ let text = '';
102
+ if (typeof raw === 'string') {
103
+ text = raw;
104
+ }
105
+ else if (Array.isArray(raw)) {
106
+ text = raw.map((item) => item?.text || '').join('');
107
+ }
108
+ if (!text.trim()) {
109
+ const finish = payload?.choices?.[0]?.finish_reason;
110
+ // 推理模型会把 token 先花在 reasoning 上:预算太小会正文为空、finish=length。
111
+ // 这里自动放大预算重试一次,避免"该回的不回"。
112
+ if (finish === 'length' && !options.retried) {
113
+ const bigger = Math.max(1600, maxTokens * 3);
114
+ this.logger?.warn?.(`[ai] 输出被截断(finish=length, max_tokens=${maxTokens}),用 ${bigger} 重试一次`);
115
+ const retried = await this.callOpenAi(request, images, { maxTokens: bigger, retried: true });
116
+ if (retried.ok)
117
+ this.minMaxTokens = Math.max(this.minMaxTokens, bigger);
118
+ return retried;
119
+ }
120
+ // 兼容:把 reasoning_content 里的 JSON 捞出来(主要给 two-stage 判定用)
121
+ const reasoning = String(payload?.choices?.[0]?.message?.reasoning_content || '');
122
+ const jsonLike = reasoning.match(/\{[\s\S]*\}/);
123
+ if (jsonLike)
124
+ text = jsonLike[0];
125
+ }
126
+ if (!text.trim()) {
127
+ return {
128
+ ok: false,
129
+ status: response.status,
130
+ error: `模型返回空内容(finish=${payload?.choices?.[0]?.finish_reason || 'unknown'})`,
131
+ };
132
+ }
133
+ return { ok: true, text, status: response.status };
134
+ }
135
+ catch (error) {
136
+ const aborted = error?.name === 'AbortError';
137
+ return { ok: false, error: aborted ? '请求超时' : `请求失败: ${String(error?.message || error)}` };
138
+ }
139
+ finally {
140
+ clearTimeout(timer);
141
+ }
142
+ }
143
+ async callGemini(request, images) {
144
+ const rawBase = String(this.config.aiBaseUrl || 'https://generativelanguage.googleapis.com/v1beta').replace(/\/+$/, '');
145
+ const base = /\/v\d/i.test(rawBase) ? rawBase : `${rawBase}/v1beta`;
146
+ const endpoint = `${base}/models/${encodeURIComponent(this.model)}:generateContent?key=${encodeURIComponent(this.apiKey)}`;
147
+ const parts = [{ text: request.user }];
148
+ for (const url of images) {
149
+ const match = /^data:(image\/[^;]+);base64,(.*)$/i.exec(url);
150
+ if (match)
151
+ parts.push({ inlineData: { mimeType: match[1], data: match[2] } });
152
+ }
153
+ const controller = new AbortController();
154
+ const timer = setTimeout(() => controller.abort(), request.timeoutMs ?? this.timeoutMs);
155
+ try {
156
+ const response = await fetch(endpoint, {
157
+ method: 'POST',
158
+ headers: { 'Content-Type': 'application/json' },
159
+ body: JSON.stringify({
160
+ systemInstruction: { parts: [{ text: request.system }] },
161
+ contents: [{ role: 'user', parts }],
162
+ generationConfig: {
163
+ temperature: request.temperature ?? this.config.aiTemperature ?? 0.8,
164
+ maxOutputTokens: request.maxTokens ?? this.config.aiMaxOutputTokens ?? 400,
165
+ },
166
+ }),
167
+ signal: controller.signal,
168
+ });
169
+ const payload = await response.json().catch(() => ({}));
170
+ if (!response.ok) {
171
+ return {
172
+ ok: false,
173
+ status: response.status,
174
+ error: payload?.error?.message || response.statusText || `HTTP ${response.status}`,
175
+ };
176
+ }
177
+ const text = (payload?.candidates?.[0]?.content?.parts ?? [])
178
+ .map((item) => item?.text || '')
179
+ .join('')
180
+ .trim();
181
+ if (!text)
182
+ return { ok: false, status: response.status, error: 'Gemini 返回空内容' };
183
+ return { ok: true, text, status: response.status };
184
+ }
185
+ catch (error) {
186
+ const aborted = error?.name === 'AbortError';
187
+ return { ok: false, error: aborted ? '请求超时' : `请求失败: ${String(error?.message || error)}` };
188
+ }
189
+ finally {
190
+ clearTimeout(timer);
191
+ }
192
+ }
193
+ }
194
+ exports.ChatProvider = ChatProvider;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * AI 会话状态:按群维护环形上下文、计数器、冷却与点名跟随。
3
+ *
4
+ * 与旧版的区别:
5
+ * - 机器人自己的发言也会进入上下文(self 记录),不会"说完就忘";
6
+ * - 每条记录带时间、群名片、角色、引用;
7
+ * - 计数器独立于"是否入上下文",便于触发策略单独演进。
8
+ */
9
+ import type { RenderedImage, RenderedQuote } from '../core/text';
10
+ export interface ChatRecord {
11
+ id: string;
12
+ userId: string;
13
+ name: string;
14
+ role?: string;
15
+ text: string;
16
+ images: RenderedImage[];
17
+ quote?: RenderedQuote;
18
+ /** 本条消息 @ 到的 QQ 号(不含 bot 自己) */
19
+ mentions: string[];
20
+ /** 本条消息是否 @ 了 bot */
21
+ atBot: boolean;
22
+ self: boolean;
23
+ at: number;
24
+ /** 指令类消息:进入上下文但不参与触发/计数 */
25
+ command?: boolean;
26
+ }
27
+ export interface FollowupState {
28
+ userId: string;
29
+ expiresAt: number;
30
+ turns: number;
31
+ anchorTokens: string[];
32
+ lastText: string;
33
+ }
34
+ export declare class GroupState {
35
+ records: ChatRecord[];
36
+ /** 自上次"完整考虑"(真正调用了模型)以来累计的消息数 */
37
+ counter: number;
38
+ lastReplyAt: number;
39
+ lastAttemptAt: number;
40
+ inFlight: boolean;
41
+ followup: FollowupState | null;
42
+ seen: Map<string, number>;
43
+ trim(window: number): void;
44
+ push(record: ChatRecord, window: number): void;
45
+ /** 事件去重:同一 messageId 15 秒内只处理一次 */
46
+ isDuplicate(key: string, now: number): boolean;
47
+ }
48
+ export declare class AiState {
49
+ private groups;
50
+ get(key: string): GroupState;
51
+ peek(key: string): GroupState | undefined;
52
+ clear(): void;
53
+ }
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ /**
3
+ * AI 会话状态:按群维护环形上下文、计数器、冷却与点名跟随。
4
+ *
5
+ * 与旧版的区别:
6
+ * - 机器人自己的发言也会进入上下文(self 记录),不会"说完就忘";
7
+ * - 每条记录带时间、群名片、角色、引用;
8
+ * - 计数器独立于"是否入上下文",便于触发策略单独演进。
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.AiState = exports.GroupState = void 0;
12
+ class GroupState {
13
+ records = [];
14
+ /** 自上次"完整考虑"(真正调用了模型)以来累计的消息数 */
15
+ counter = 0;
16
+ lastReplyAt = 0;
17
+ lastAttemptAt = 0;
18
+ inFlight = false;
19
+ followup = null;
20
+ seen = new Map();
21
+ trim(window) {
22
+ const max = Math.max(6, window || 24);
23
+ if (this.records.length > max)
24
+ this.records.splice(0, this.records.length - max);
25
+ }
26
+ push(record, window) {
27
+ this.records.push(record);
28
+ this.trim(window);
29
+ }
30
+ /** 事件去重:同一 messageId 15 秒内只处理一次 */
31
+ isDuplicate(key, now) {
32
+ const previous = this.seen.get(key) ?? 0;
33
+ this.seen.set(key, now);
34
+ if (this.seen.size > 512) {
35
+ const expireBefore = now - 120_000;
36
+ for (const [id, ts] of this.seen) {
37
+ if (ts < expireBefore)
38
+ this.seen.delete(id);
39
+ }
40
+ }
41
+ return previous > 0 && now - previous < 15_000;
42
+ }
43
+ }
44
+ exports.GroupState = GroupState;
45
+ class AiState {
46
+ groups = new Map();
47
+ get(key) {
48
+ let state = this.groups.get(key);
49
+ if (!state) {
50
+ state = new GroupState();
51
+ this.groups.set(key, state);
52
+ }
53
+ return state;
54
+ }
55
+ peek(key) {
56
+ return this.groups.get(key);
57
+ }
58
+ clear() {
59
+ this.groups.clear();
60
+ }
61
+ }
62
+ exports.AiState = AiState;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * 触发放行判定(纯函数,便于单测)。
3
+ *
4
+ * 三道闸门保留,但语义收紧:
5
+ * 1) 冷却:同一群两次"真正调用模型"之间至少间隔 aiMinReplyIntervalSeconds;
6
+ * 2) 阈值:hybrid/threshold 下需累计够 aiMessageThreshold 条消息;
7
+ * 3) 概率:random/hybrid 下每条消息掷一次骰。
8
+ * 点名与"点名后跟随"直接放行(不占冷却)。
9
+ */
10
+ export interface TriggerInput {
11
+ mode: 'threshold' | 'random' | 'hybrid';
12
+ counter: number;
13
+ threshold: number;
14
+ probability: number;
15
+ now: number;
16
+ lastAttemptAt: number;
17
+ minIntervalMs: number;
18
+ inFlight: boolean;
19
+ mention: boolean;
20
+ followup: boolean;
21
+ rng: () => number;
22
+ }
23
+ export interface TriggerDecision {
24
+ fire: boolean;
25
+ forced: boolean;
26
+ reason: string;
27
+ }
28
+ export declare function decideTrigger(input: TriggerInput): TriggerDecision;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /**
3
+ * 触发放行判定(纯函数,便于单测)。
4
+ *
5
+ * 三道闸门保留,但语义收紧:
6
+ * 1) 冷却:同一群两次"真正调用模型"之间至少间隔 aiMinReplyIntervalSeconds;
7
+ * 2) 阈值:hybrid/threshold 下需累计够 aiMessageThreshold 条消息;
8
+ * 3) 概率:random/hybrid 下每条消息掷一次骰。
9
+ * 点名与"点名后跟随"直接放行(不占冷却)。
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.decideTrigger = decideTrigger;
13
+ function decideTrigger(input) {
14
+ if (input.inFlight)
15
+ return { fire: false, forced: false, reason: 'in-flight' };
16
+ if (input.mention)
17
+ return { fire: true, forced: true, reason: 'direct-mention' };
18
+ if (input.followup)
19
+ return { fire: true, forced: true, reason: 'followup' };
20
+ if (input.minIntervalMs > 0 && input.now - input.lastAttemptAt < input.minIntervalMs) {
21
+ return { fire: false, forced: false, reason: 'cooldown' };
22
+ }
23
+ const needThreshold = input.mode === 'threshold' || input.mode === 'hybrid';
24
+ if (needThreshold && input.counter < Math.max(1, input.threshold)) {
25
+ return {
26
+ fire: false,
27
+ forced: false,
28
+ reason: `below-threshold(${input.counter}/${Math.max(1, input.threshold)})`,
29
+ };
30
+ }
31
+ const needRandom = input.mode === 'random' || input.mode === 'hybrid';
32
+ if (needRandom) {
33
+ const probability = Math.max(0, Math.min(1, Number(input.probability) || 0));
34
+ if (probability <= 0)
35
+ return { fire: false, forced: false, reason: 'random-disabled' };
36
+ if (input.rng() >= probability) {
37
+ return { fire: false, forced: false, reason: `random-miss(${probability})` };
38
+ }
39
+ }
40
+ return { fire: true, forced: false, reason: `trigger(${input.mode})` };
41
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * 视觉输入:把消息里的图片并发转成 data URL。
3
+ *
4
+ * 旧实现是串行的:每张图 12 秒超时、多个候选依次尝试,两张图就能拖到 60 秒,
5
+ * 等模型回答时上下文已经过期。这里改成并发 + 总预算(默认 6 秒),
6
+ * 超时/失败直接跳过,绝不阻塞回复。
7
+ */
8
+ import type { RenderedImage } from '../core/text';
9
+ export interface VisionOptions {
10
+ maxCount?: number;
11
+ budgetMs?: number;
12
+ }
13
+ export type ImageResolver = (ref: string) => Promise<string>;
14
+ export declare function pickImages(own: RenderedImage[], quoted: RenderedImage[], maxCount: number): RenderedImage[];
15
+ export declare function resolveImages(items: RenderedImage[], resolve: ImageResolver, options?: VisionOptions): Promise<string[]>;
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ /**
3
+ * 视觉输入:把消息里的图片并发转成 data URL。
4
+ *
5
+ * 旧实现是串行的:每张图 12 秒超时、多个候选依次尝试,两张图就能拖到 60 秒,
6
+ * 等模型回答时上下文已经过期。这里改成并发 + 总预算(默认 6 秒),
7
+ * 超时/失败直接跳过,绝不阻塞回复。
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.pickImages = pickImages;
11
+ exports.resolveImages = resolveImages;
12
+ function delay(ms) {
13
+ return new Promise((resolve) => setTimeout(() => resolve(''), ms));
14
+ }
15
+ async function withDeadline(task, deadline, fallback) {
16
+ const remaining = deadline - Date.now();
17
+ if (remaining <= 0)
18
+ return fallback;
19
+ return Promise.race([task, delay(remaining)]);
20
+ }
21
+ function pickImages(own, quoted, maxCount) {
22
+ const out = [];
23
+ const seen = new Set();
24
+ const push = (item) => {
25
+ const key = item.url || item.ref;
26
+ if (!key || seen.has(key))
27
+ return;
28
+ seen.add(key);
29
+ out.push(item);
30
+ };
31
+ // 当前消息优先;至少保留一张图的位置给引用消息
32
+ for (const item of own) {
33
+ if (out.length >= maxCount)
34
+ break;
35
+ push(item);
36
+ }
37
+ for (const item of quoted) {
38
+ if (out.length >= maxCount)
39
+ break;
40
+ push(item);
41
+ }
42
+ return out.slice(0, Math.max(0, maxCount));
43
+ }
44
+ async function resolveImages(items, resolve, options = {}) {
45
+ const maxCount = Math.max(0, options.maxCount ?? 2);
46
+ const budgetMs = Math.max(500, options.budgetMs ?? 6000);
47
+ if (!maxCount || !items.length)
48
+ return [];
49
+ const selected = items.slice(0, maxCount);
50
+ const deadline = Date.now() + budgetMs;
51
+ const tasks = selected.map(async (item) => {
52
+ const candidates = [item.url, item.ref].filter(Boolean);
53
+ for (const candidate of candidates) {
54
+ if (Date.now() >= deadline)
55
+ return '';
56
+ const dataUrl = await withDeadline(resolve(candidate).catch(() => ''), deadline, '');
57
+ if (dataUrl && /^data:image\//i.test(dataUrl))
58
+ return dataUrl;
59
+ }
60
+ return '';
61
+ });
62
+ const results = await Promise.all(tasks);
63
+ return results.filter((item) => !!item);
64
+ }