dsh-wechat-access 0.0.0-stage → 0.0.2

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +675 -0
  3. package/README.md +278 -2
  4. package/cordis.patch.yml +5 -0
  5. package/examples/config.example.json +98 -0
  6. package/index.mjs +123 -0
  7. package/lib/access.mjs +131 -0
  8. package/lib/anysearch.mjs +143 -0
  9. package/lib/capabilities.mjs +312 -0
  10. package/lib/client.js +2532 -0
  11. package/lib/config.mjs +509 -0
  12. package/lib/emotion-store.mjs +352 -0
  13. package/lib/emotion.mjs +428 -0
  14. package/lib/endocrine/LICENSE +21 -0
  15. package/lib/endocrine/README.md +39 -0
  16. package/lib/endocrine/diseases.js +791 -0
  17. package/lib/endocrine/engine.mjs +131 -0
  18. package/lib/endocrine/store.mjs +253 -0
  19. package/lib/endocrine/upstream.mjs +1230 -0
  20. package/lib/group-gate.mjs +305 -0
  21. package/lib/imagegen.mjs +360 -0
  22. package/lib/lock.mjs +204 -0
  23. package/lib/meme-classify.mjs +190 -0
  24. package/lib/memes.mjs +442 -0
  25. package/lib/memory.mjs +437 -0
  26. package/lib/normalize.mjs +230 -0
  27. package/lib/parser.mjs +602 -0
  28. package/lib/reply-settled.mjs +130 -0
  29. package/lib/runtime.mjs +3367 -0
  30. package/lib/startup.mjs +70 -0
  31. package/lib/steam-binding.mjs +144 -0
  32. package/lib/steam.mjs +334 -0
  33. package/lib/store.mjs +259 -0
  34. package/lib/thoughts.mjs +149 -0
  35. package/lib/time-context.mjs +182 -0
  36. package/lib/tools.mjs +583 -0
  37. package/lib/ui.mjs +997 -0
  38. package/lib/util.mjs +489 -0
  39. package/lib/virtual-life-generate.mjs +421 -0
  40. package/lib/virtual-life.mjs +971 -0
  41. package/lib/weather.mjs +172 -0
  42. package/lib/wechat-client.mjs +476 -0
  43. package/lib/wechat-events.mjs +269 -0
  44. package/locale/zh.json +6 -0
  45. package/package.json +77 -4
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Group-chat reply gating: decide whether a message is worth answering.
3
+ *
4
+ * The problem this solves is volume. In a busy group every message used to be a
5
+ * candidate under `group: "all"`, and `group: "mention"` swings the other way —
6
+ * she says nothing unless explicitly summoned, which reads as a dead account.
7
+ * The middle ground people actually want is "reply when it is about me, when it
8
+ * is addressed to me, or when the topic is something I care about".
9
+ *
10
+ * Three properties matter more than the scoring itself:
11
+ *
12
+ * - THE DECISION MUST BE CHEAP AND SYNCHRONOUS. It runs inside `accept()` on
13
+ * every inbound group message. A model call here would add latency to every
14
+ * line in the group and cost money for messages she then ignores. So this is
15
+ * pure string work, with an optional learned interest list.
16
+ *
17
+ * - SILENCE MUST BE THE DEFAULT. Every rule below can only ADD a reason to
18
+ * reply; with no signal at all the answer is "no". The failure mode of a
19
+ * chatty bot is far worse than the failure mode of a quiet one.
20
+ *
21
+ * - DIRECT ADDRESS ALWAYS WINS. A mention, a quote-reply to her, or her name in
22
+ * the text bypasses every threshold. Ignoring someone who called your name is
23
+ * the single most broken thing a chat bot can do.
24
+ *
25
+ * Interest scoring is deliberately transparent: named lists plus a small learned
26
+ * map, not an opaque model judgement. When she stays quiet, "why" should be
27
+ * answerable by looking at the numbers.
28
+ */
29
+
30
+ /**
31
+ * Reasons, in priority order. `direct` reasons always pass; `scored` reasons are
32
+ * compared against the threshold.
33
+ */
34
+ export const REPLY_REASONS = {
35
+ MENTION: 'mention',
36
+ QUOTE: 'quote',
37
+ NAME: 'name',
38
+ SELF_REFERENCE: 'self_reference',
39
+ QUESTION_TO_GROUP: 'question',
40
+ INTEREST: 'interest',
41
+ TOPIC: 'topic',
42
+ };
43
+
44
+ /** Phrases that mean "someone is talking about me" without an @. */
45
+ export const SELF_REFERENCE_PATTERNS = [
46
+ /你(在|在干嘛|在吗|干嘛呢|说什么|觉得|怎么|是不是|会|能)/,
47
+ /你们(在|说|聊)/,
48
+ /(bot|机器人|小助手)/i,
49
+ ];
50
+
51
+ /** Question shapes that are usually aimed at whoever will answer. */
52
+ export const GROUP_QUESTION_PATTERNS = [
53
+ /有(人|没有?人)(知道|了解|会|在)/,
54
+ /谁(知道|了解|会|在|能)/,
55
+ /(怎么|如何|为什么|为啥)(办|做|弄|搞|解决|回事)/,
56
+ /(求|需要)(推荐|帮助|解答)/,
57
+ /[??]\s*$/,
58
+ ];
59
+
60
+ /**
61
+ * Default topic interests. Kept short and generic on purpose — the user extends
62
+ * this through config, and a huge default list would make her reply to everything.
63
+ */
64
+ export const DEFAULT_INTERESTS = [
65
+ // 娱乐
66
+ '游戏', '动漫', '动画', '电影', '电视剧', '追剧', '音乐', '唱歌', '小说',
67
+ // 学习与技术
68
+ '编程', '代码', '算法', '学习', '考试', '作业', '论文', '题目',
69
+ // 生活
70
+ '吃饭', '午饭', '晚饭', '早饭', '美食', '吃什么', '好吃', '奶茶', '咖啡',
71
+ '旅游', '出去玩', '天气', '下雨', '下雪',
72
+ // 动物
73
+ '宠物', '小猫', '狗狗', '毛孩子',
74
+ // 全部用双字及以上。命中一个兴趣词就是 +3,等于必回 ——
75
+ // 阈值默认 3,所以单字词会让「这个问题怎么解」(题)、「剧烈运动」(剧)直接触发。
76
+ // 「猫」「狗」也换成了「小猫」「狗狗」:单字太容易在别的词里出现。
77
+ ];
78
+
79
+ /**
80
+ * Score one group message.
81
+ *
82
+ * Returns `{ reply, score, reason, detail }`. `reason` is the strongest single
83
+ * justification found, which is what gets logged so a surprising silence or a
84
+ * surprising reply can both be explained.
85
+ */
86
+ export function scoreGroupMessage(message, options = {}) {
87
+ const {
88
+ selfId = '',
89
+ selfNames = [],
90
+ interests = [],
91
+ threshold = 3,
92
+ // How much weight a learned/observed interest carries versus a configured one.
93
+ learnedWeight = 2,
94
+ learned = {},
95
+ replyToSelf = false,
96
+ } = options;
97
+
98
+ const text = String(message?.text ?? '').trim();
99
+ // 图片和贴纸**不加分**。
100
+ //
101
+ // 群聊闸门回答的是「这条消息像不像在跟人说话」,那只能从文字判断:
102
+ // 图片本身没有语气,刷图很常见,给图加分会让群里任何人都能靠发一张表情包把她钓出来。
103
+ //
104
+ // 图的作用不在这里 —— 而是在**已经决定要回之后**,
105
+ // 由 reply() 的 hasPictures 把图片和贴纸送进视觉上下文(见 runtime.mjs)。
106
+ // 换句话说:图不影响「回不回」,只影响「回了之后看不看得见」。
107
+
108
+ if (!text) return { reply: false, score: 0, reason: 'empty', detail: '空消息' };
109
+
110
+ // ---- direct address: unconditional -------------------------------------
111
+ if (message?.mentioned) {
112
+ return { reply: true, score: 99, reason: REPLY_REASONS.MENTION, detail: '被 @' };
113
+ }
114
+ if (replyToSelf) {
115
+ return { reply: true, score: 99, reason: REPLY_REASONS.QUOTE, detail: '引用了你的消息' };
116
+ }
117
+ // Name matching must be boundary-aware. A plain `includes` makes a QQ number
118
+ // match any message containing those digits — with a short id (or the "1" some
119
+ // tests use) every message looks like a mention of her. Digits need a
120
+ // non-digit boundary; CJK nicknames just need to not be part of a longer run.
121
+ for (const name of [String(selfId), ...selfNames].filter(Boolean)) {
122
+ const needle = String(name);
123
+ if (!needle) continue;
124
+ const isNumeric = /^\d+$/.test(needle);
125
+ const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
126
+ const pattern = isNumeric
127
+ ? new RegExp(`(^|\\D)${escaped}(\\D|$)`)
128
+ : new RegExp(escaped);
129
+ if (pattern.test(text)) {
130
+ return { reply: true, score: 95, reason: REPLY_REASONS.NAME, detail: `提到「${needle}」` };
131
+ }
132
+ }
133
+
134
+ // ---- scored signals ----------------------------------------------------
135
+ let score = 0;
136
+ let reason = '';
137
+ const notes = [];
138
+
139
+ // Talking TO someone ("你在干嘛") rather than about them.
140
+ for (const pattern of SELF_REFERENCE_PATTERNS) {
141
+ if (pattern.test(text)) {
142
+ score += 3;
143
+ reason = REPLY_REASONS.SELF_REFERENCE;
144
+ notes.push('像在对人说话');
145
+ break;
146
+ }
147
+ }
148
+
149
+ // A question nobody in particular was asked.
150
+ //
151
+ // "有没有人知道…" and "谁…" are addressed to the room and are exactly the case
152
+ // this feature exists for, so they carry the full threshold on their own. A bare
153
+ // trailing "?" is much weaker evidence (people end statements with it), so it
154
+ // only adds partial weight.
155
+ if (!reason) {
156
+ for (const pattern of GROUP_QUESTION_PATTERNS) {
157
+ if (pattern.test(text)) {
158
+ const strong = !/\[???\]?$/.test(pattern.source) || pattern.source.length > 8;
159
+ score += strong ? 3 : 2;
160
+ reason = REPLY_REASONS.QUESTION_TO_GROUP;
161
+ notes.push(strong ? '在向群里提问' : '像是提问');
162
+ break;
163
+ }
164
+ }
165
+ }
166
+
167
+ // Configured interests. A single hit is worth the full threshold on its own:
168
+ // "she replies to things she is interested in" is the feature, and making one
169
+ // keyword worth only 2/3 of a threshold would mean the common case (one topic)
170
+ // never fires. Additional hits add less each time.
171
+ const lower = text.toLowerCase();
172
+ let hits = 0;
173
+ for (const topic of interests) {
174
+ const word = String(topic ?? '').trim().toLowerCase();
175
+ if (word && lower.includes(word)) hits += 1;
176
+ }
177
+ if (hits) {
178
+ score += Math.min(6, 3 + (hits - 1));
179
+ if (!reason) reason = REPLY_REASONS.INTEREST;
180
+ notes.push(`命中兴趣 ${hits} 项`);
181
+ }
182
+
183
+ // Learned topics (from messages she actually answered) carry less weight.
184
+ let learnedHits = 0;
185
+ for (const [topic, weight] of Object.entries(learned ?? {})) {
186
+ const word = String(topic ?? '').trim().toLowerCase();
187
+ if (word && lower.includes(word)) learnedHits += Math.min(2, Number(weight) || 0);
188
+ }
189
+ if (learnedHits) {
190
+ // Learned topics are weaker evidence than configured ones: they come from
191
+ // her own past replies, which can drift. Still enough to reach the threshold
192
+ // on its own when the topic repeats.
193
+ score += Math.min(4, 2 + learnedHits);
194
+ if (!reason) reason = REPLY_REASONS.TOPIC;
195
+ notes.push(`命中历史话题 ${learnedHits}`);
196
+ }
197
+
198
+ // Length is a weak signal: a long message is more likely to deserve an answer
199
+ // than "嗯". Capped at 1 so it can never carry a decision on its own.
200
+ if ([...text].length >= 30) {
201
+ score += 1;
202
+ notes.push('内容较长');
203
+ }
204
+
205
+ const reply = score >= threshold;
206
+ return {
207
+ reply,
208
+ score,
209
+ reason: reply ? (reason || REPLY_REASONS.INTEREST) : 'below_threshold',
210
+ detail: notes.join(',') || '没有明显信号',
211
+ };
212
+ }
213
+
214
+ /**
215
+ * Track which topics actually got answered, so the gate adapts a little.
216
+ *
217
+ * Bounded and decayed: without both, the learned map converges on "everything"
218
+ * and the gate stops filtering at all.
219
+ */
220
+ export class InterestLearner {
221
+ // decay 0.75/day: a topic seen once is forgotten in about a week, one seen a
222
+ // few times survives longer. At 0.9 a single observation lingered for weeks and
223
+ // the map only ever grew.
224
+ constructor({ maxTopics = 60, decay = 0.75 } = {}) {
225
+ this.maxTopics = maxTopics;
226
+ this.decay = decay;
227
+ this.topics = new Map();
228
+ }
229
+
230
+ /** Record a topic from a message she replied to. */
231
+ observe(text, words = []) {
232
+ const lower = String(text ?? '').toLowerCase();
233
+ if (!lower) return;
234
+ for (const word of words) {
235
+ const key = String(word ?? '').trim().toLowerCase();
236
+ if (!key || !lower.includes(key)) continue;
237
+ this.topics.set(key, Math.min(6, (this.topics.get(key) ?? 0) + 1));
238
+ }
239
+ this.#trim();
240
+ }
241
+
242
+ /** Decay every topic by one step; call once per day. */
243
+ decayAll() {
244
+ for (const [key, value] of this.topics) {
245
+ const next = value * this.decay;
246
+ if (next < 0.3) this.topics.delete(key); else this.topics.set(key, next);
247
+ }
248
+ }
249
+
250
+ #trim() {
251
+ if (this.topics.size <= this.maxTopics) return;
252
+ const sorted = [...this.topics.entries()].sort((a, b) => b[1] - a[1]);
253
+ this.topics = new Map(sorted.slice(0, this.maxTopics));
254
+ }
255
+
256
+ /** Plain object for config/persistence and for scoreGroupMessage. */
257
+ toObject() {
258
+ const out = {};
259
+ for (const [key, value] of this.topics) out[key] = Math.round(value * 10) / 10;
260
+ return out;
261
+ }
262
+
263
+ load(raw) {
264
+ this.topics = new Map();
265
+ if (!raw || typeof raw !== 'object') return this;
266
+ for (const [key, value] of Object.entries(raw)) {
267
+ const n = Number(value);
268
+ if (key && Number.isFinite(n) && n > 0) this.topics.set(String(key).toLowerCase(), Math.min(6, n));
269
+ }
270
+ return this;
271
+ }
272
+ }
273
+
274
+ /**
275
+ * Cheap topic extraction: CJK bigrams plus latin words.
276
+ *
277
+ * Bigrams are crude but language-agnostic enough for Chinese without a segmenter,
278
+ * and this only feeds a heuristic, so precision is not critical.
279
+ */
280
+ // 高频虚词:切成二字组几乎每条消息都会出现,学进来等于把阈值打穿。
281
+ // 以前不过滤,她回复过一次「今天天气真好啊我们去吃饭吧」,
282
+ // 之后「我们出发」「今天开会」「真好」全都能凑到 3 分触发回复。
283
+ const STOPWORDS = new Set([
284
+ '我们', '你们', '他们', '她们', '什么', '怎么', '这个', '那个', '就是', '可以',
285
+ '今天', '明天', '昨天', '现在', '时候', '一下', '一个', '没有', '是不', '不是',
286
+ '真好', '真的', '还是', '但是', '因为', '所以', '如果', '虽然', '然后', '而且',
287
+ '知道', '觉得', '应该', '可能', '已经', '这么', '那么', '自己', '别人', '东西',
288
+ '一直', '有点', '一些', '这样', '那样', '起来', '出来', '过去', '上来', '下来',
289
+ ]);
290
+
291
+ export function extractTopicWords(text, { limit = 40 } = {}) {
292
+ const body = String(text ?? '').toLowerCase();
293
+ const out = new Set();
294
+ for (const word of body.match(/[a-z][a-z0-9_+#.-]{2,}/g) ?? []) out.add(word);
295
+ const cjk = body.match(/[\u4e00-\u9fa5]+/g) ?? [];
296
+ for (const run of cjk) {
297
+ if (run.length === 1) continue;
298
+ for (let i = 0; i + 1 < run.length; i++) {
299
+ const word = run.slice(i, i + 2);
300
+ if (STOPWORDS.has(word)) continue;
301
+ out.add(word);
302
+ }
303
+ }
304
+ return [...out].slice(0, limit);
305
+ }
@@ -0,0 +1,360 @@
1
+ /**
2
+ * 让模型「想发图时」真的能生一张图。
3
+ *
4
+ * 为什么不是直接调 dsh-connect-doubao 的函数:
5
+ * 那个插件虽然导出了 chat()/streamChat(),但它们依赖 DSH 注入的 peer 依赖
6
+ * (@earendil-works/pi-ai),在普通 Node 进程里 import 会直接 ERR_MODULE_NOT_FOUND。
7
+ * 那样等于给本插件加一个「必须同时装另一个插件、且版本匹配」的硬依赖。
8
+ *
9
+ * 所以这里走 DSH 自己的 Provider 路由:豆包插件把「豆包 生图」注册成 provider
10
+ * "doubao" 下的模型 "image-gen",我们只需要起一个短期 agent,用这个路由发一句话,
11
+ * 它就会把 Seedream 生成的图片以 Markdown 图片的形式返回。DSH 负责凭据、鉴权、
12
+ * 会话续期——我们不用碰任何 cookie。
13
+ *
14
+ * 这条路线的代价:拿不到 image_ori_raw 的无水印原图,拿到的是插件写进正文的
15
+ * Markdown 链接。取舍是「稳」优先:不需要跟着豆包插件内部实现改。
16
+ */
17
+
18
+ import { stripHostPrompt } from './util.mjs';
19
+
20
+ /** 默认路由:豆包插件注册的 provider 与生图模型别名。 */
21
+ export const DEFAULT_IMAGE_ROUTE = Object.freeze({ provider: 'doubao', model: 'image-gen' });
22
+
23
+ /** 提示词长度上限。豆包那边一次也就几百字,太长反而容易跑偏。 */
24
+ const MAX_PROMPT = 1200;
25
+ /** 单次生图最多等多久。实测 20~25 秒出图,给足余量但必须有上限。 */
26
+ const DEFAULT_TIMEOUT_MS = 120_000;
27
+
28
+ /**
29
+ * 把 Markdown 图片链接从一段文字里抠出来。
30
+ *
31
+ * 豆包生图的返回是「说明文字 + ![](url)」,而 QQ 发送需要的是图片本身,
32
+ * 所以这里只取 URL。也兼容 <img src>(个别响应会是 HTML)。
33
+ */
34
+ export function extractImageUrls(text) {
35
+ const value = String(text ?? '');
36
+ const urls = [];
37
+ const push = (raw) => {
38
+ let url = String(raw ?? '').trim();
39
+ if (!url) return;
40
+ // 去掉 Markdown 的尖括号包装:![x](<C:/a b.png>)
41
+ if (url.startsWith('<') && url.endsWith('>')) url = url.slice(1, -1).trim();
42
+ if (!url) return;
43
+ // 接受三类来源:
44
+ // 1. http(s) 远程图;
45
+ // 2. Windows 盘符路径 C:/... 或 C:\...;
46
+ // 3. file:// URL。
47
+ // 豆包 image-gen 返回的正是第 2 类——它把图直接写在本机。
48
+ // 以前这里只收 http,于是本地路径被整条扔掉,
49
+ // 判定成「模型没有返回图片」,而图其实已经在磁盘上躺着了。
50
+ const isRemote = /^https?:\/\//i.test(url);
51
+ const isWindows = /^[a-zA-Z]:[\\/]/.test(url);
52
+ const isFileUrl = /^file:\/\//i.test(url);
53
+ if (!isRemote && !isWindows && !isFileUrl) return;
54
+ // 只收图片扩展名:Markdown 里的普通文件链接不该被当成图去下载。
55
+ if (!/\.(?:png|jpe?g|webp|gif|bmp)$/i.test(url)) return;
56
+ // 保留原样(盘符路径或 file://)。
57
+ // 不要转成 file:///:runtime.imageBytes 的 isLocalPath 只认盘符和 / 开头,
58
+ // 转成 file:// 反而让它走不到本地读取分支。
59
+ if (isWindows) url = url.replace(/\\/g, '/');
60
+ if (urls.includes(url)) return;
61
+ urls.push(url);
62
+ };
63
+ // ![alt](url)
64
+ // ![alt](url) 和 ![alt](<path with spaces>):
65
+ // DSH 自己的 system prompt 就要求在路径含空格时用尖括号包起来,
66
+ // 所以两种都必须认,否则带空格的文件名会被截断成半条路径。
67
+ for (const m of value.matchAll(/!\[[^\]]*\]\(<([^>]+)>/g)) push(m[1]);
68
+ for (const m of value.matchAll(/!\[[^\]]*\]\(([^)\s]+)\)/g)) push(m[1]);
69
+ // <img src="url">
70
+ for (const m of value.matchAll(/<img[^>]+src=["']([^"']+)["']/gi)) push(m[1]);
71
+ // 裸链接兜底:只在明确是图片扩展名时收,避免把普通网页当图
72
+ for (const m of value.matchAll(/(?<![a-z])https?:\/\/[^\s)<>"']+\.(?:png|jpe?g|webp|gif)(?:\?[^\s)<>"']*)?/gi)) push(m[0]);
73
+ // 本地路径的裸形式(没写进 Markdown 时):C:/a/b.png
74
+ for (const m of value.matchAll(/(?<![a-zA-Z0-9_\-\\/])[a-zA-Z]:[\\/][^\s)<>"']*\.(?:png|jpe?g|webp|gif)(?![a-zA-Z0-9])/gi)) push(m[0]);
75
+ return urls;
76
+ }
77
+
78
+ /**
79
+ * 把用户随口一句话补成更像「画图描述」的提示词。
80
+ *
81
+ * 为什么需要:模型说「给我发张图」时往往只给几个词(「可爱的猫」)。
82
+ * 直接丢给生图模型,出来的东西随机性很大。补上画质与构图要求能明显稳定结果,
83
+ * 但**不能**改用户指定的主体、风格、颜色——那些是用户的意思。
84
+ */
85
+ export function buildImagePrompt({ prompt, style = '', aspectRatio = '' } = {}) {
86
+ const subject = String(prompt ?? '').trim().slice(0, MAX_PROMPT);
87
+ if (!subject) return '';
88
+ const parts = [subject];
89
+ const styleText = String(style ?? '').trim();
90
+ if (styleText) parts.push('风格:' + styleText.slice(0, 80));
91
+ const ratio = String(aspectRatio ?? '').trim();
92
+ if (/^\d{1,2}:\d{1,2}$/.test(ratio)) parts.push('画面比例:' + ratio);
93
+ // 「拍一张照片」是这个工具的默认语义。生成的照片带插画感是实机上最影响
94
+ // 出图的问题,所以不写风格、或风格就是写实/摄影时,把提示词往真实照片上压。
95
+ // 用户明确要别的画风(水墨/动漫/…)时不压,别把人家的画风改成照片。
96
+ const wantsPhoto = !styleText || /写实|摄影|照片|实拍|随手拍|真实|snapshot|photo|realistic/i.test(styleText);
97
+ if (wantsPhoto) {
98
+ parts.push('画面完整、构图清晰;真实照片质感:像手机随手拍的日常照片,自然光线、真实阴影和材质细节,透视和人物比例自然,轻微噪点和镜头感,不要插画、不要渲染、不要卡通、不要AI感,不要文字水印');
99
+ } else {
100
+ parts.push('画面完整、构图清晰、光线自然,不要文字水印');
101
+ }
102
+ return parts.join('。');
103
+ }
104
+
105
+ /** 从路由配置里解析出 { provider, model },缺项时回落到默认值。 */
106
+ export function resolveImageRoute(route) {
107
+ const provider = String(route?.provider ?? '').trim() || DEFAULT_IMAGE_ROUTE.provider;
108
+ const model = String(route?.model ?? '').trim() || DEFAULT_IMAGE_ROUTE.model;
109
+ return { provider, model };
110
+ }
111
+
112
+ /**
113
+ * 跑一次生图。
114
+ *
115
+ * @param {object} options
116
+ * @param {object} options.ctx DSH 上下文(要 ctx.agents)
117
+ * @param {object} options.config 插件配置里的 image 段
118
+ * @param {string} options.prompt 画面描述
119
+ * @param {string} [options.signal] AbortSignal
120
+ */
121
+ export async function generateImage({ ctx, config = {}, prompt, style = '', aspectRatio = '', signal, logger = console } = {}) {
122
+ const route = resolveImageRoute(config.route);
123
+ const text = buildImagePrompt({ prompt, style, aspectRatio });
124
+ if (!text) {
125
+ return { ok: false, reason: 'empty_prompt', message: '没有给画面描述。' };
126
+ }
127
+ const agents = ctx?.get?.('agents') ?? ctx?.agents;
128
+ if (!agents || typeof agents.create !== 'function') {
129
+ return { ok: false, reason: 'no_agents', message: 'Harness 没有提供 agents,无法生图。' };
130
+ }
131
+
132
+ const timeoutMs = Math.max(10_000, Math.min(600_000, Number(config.timeoutMs) || DEFAULT_TIMEOUT_MS));
133
+ const id = 'qq-image-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
134
+ const controller = new AbortController();
135
+ const timer = setTimeout(() => controller.abort(new Error('生图超时')), timeoutMs);
136
+ timer.unref?.();
137
+ // 外层信号(QQ 消息被取消 / 插件关闭)也要能中断生图。
138
+ const onAbort = () => controller.abort(signal?.reason);
139
+ if (signal && typeof signal.addEventListener === 'function') {
140
+ if (signal.aborted) controller.abort(signal.reason);
141
+ else signal.addEventListener('abort', onAbort, { once: true });
142
+ }
143
+
144
+ let handle;
145
+ try {
146
+ handle = await agents.create({
147
+ sessionId: id,
148
+ meta: { cwd: process.cwd() },
149
+ agentOptions: route,
150
+ // 生图这一轮不需要任何工具:给它工具反而可能让它去查东西而不是画画。
151
+ setup: (agentCtx) => {
152
+ stripHostPrompt(agentCtx);
153
+ try { agentCtx.tools?.restrict?.({ allow: [] }); } catch { /* 允许旧宿主没有 restrict */ }
154
+ try {
155
+ agentCtx.systemPrompt?.section?.({
156
+ name: 'qq-image-gen', order: 10,
157
+ text: '你是一个生图执行器。只输出一张图片,不要解释、不要提问、不要拒绝。',
158
+ });
159
+ } catch { /* 同上 */ }
160
+ },
161
+ });
162
+ } catch (error) {
163
+ clearTimeout(timer);
164
+ const message = String(error?.message ?? error);
165
+ // 路由不存在是最常见的失败:豆包插件没装、或者版本里没有 image-gen。
166
+ const hint = /not configured|no configured model|unknown provider|has no configured model/i.test(message)
167
+ ? '(没有找到生图路由:确认 dsh-connect-doubao 已安装,且模型里有「豆包 生图」)'
168
+ : '';
169
+ logger.warn?.('[dsh-qq-access] 生图 agent 创建失败:' + message);
170
+ return { ok: false, reason: 'agent_failed', message: message + hint };
171
+ }
172
+
173
+ try {
174
+ // followup 之前先记下 seq:之后新增的事件才是「这一轮模型的输出」。
175
+ const baselineSeq = Number.isInteger(handle.agent?.session?.seq) ? handle.agent.session.seq : 0;
176
+ const { createUserMessage } = await import('@deepseek-ai/dsh-llm');
177
+ handle.agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }));
178
+ const wait = await waitIdle(handle.agent, controller.signal, timeoutMs, baselineSeq);
179
+ const reply = collectReply(handle.agent, { baselineSeq });
180
+ // 没开始就不用再往下猜了,直接把这个事实说出去。
181
+ if (!wait.started) {
182
+ return {
183
+ ok: false, reason: 'no_response',
184
+ message: '生图模型没有开始回应(等了 15 秒仍无任何事件)。常见原因:路由 ' + route.provider + '/' + route.model + ' 不存在,或豆包未登录。',
185
+ route,
186
+ };
187
+ }
188
+ const urls = extractImageUrls(reply.text);
189
+ // B4:超时必须单独报。
190
+ //
191
+ // waitIdle 在超时时返回 { finished: false },但以前没人看这个字段 ——
192
+ // 于是生图卡住 120 秒被中断后,用户看到的是「模型回了话但没有图片」,
193
+ // 会去查路由和豆包登录,而真正的原因是等太久。
194
+ if (!wait.finished) {
195
+ return {
196
+ ok: false, reason: 'timeout',
197
+ message: '生图超时(' + Math.round(timeoutMs / 1000) + ' 秒)。图可能还在生成,也可能卡住了;可以把超时调大再试。',
198
+ text: reply.text.slice(0, 400),
199
+ route,
200
+ };
201
+ }
202
+ // 这里把「为什么没图」区分开:空回合、有文字没图、完全没响应,
203
+ // 三种原因的排查方向完全不同。
204
+ // 会话里一定有用户那条 prompt,所以「有没有模型输出」不能再用 seq 是否为 0 判断;
205
+ // 改成看 collectReply 有没有在我们的过滤后拿到任何内容块。
206
+ const produced = reply.rawTypes.length > 0;
207
+ if (!produced) {
208
+ return {
209
+ ok: false, reason: 'empty_turn',
210
+ message: '生图模型没有产生任何回应(会话为空)。常见原因:路由 ' + route.provider + '/' + route.model + ' 不存在,或豆包未登录。',
211
+ route,
212
+ };
213
+ }
214
+ if (!urls.length) {
215
+ // 也许图不在文本里,而是 DSH 的 image block。
216
+ // 这时图已经在 attachment 里了,不需要再下载。
217
+ if (reply.imageParts.length) {
218
+ return { ok: true, urls: [], text: reply.text, imageParts: reply.imageParts, route };
219
+ }
220
+ return {
221
+ ok: false, reason: 'no_image',
222
+ message: '模型回了话但没有图片。',
223
+ text: reply.text.slice(0, 600),
224
+ imageParts: 0,
225
+ rawTypes: reply.rawTypes.slice(0, 20),
226
+ route,
227
+ };
228
+ }
229
+ return { ok: true, urls, text: reply.text, imageParts: reply.imageParts, route };
230
+ } catch (error) {
231
+ const aborted = controller.signal.aborted;
232
+ return {
233
+ ok: false,
234
+ reason: aborted ? 'timeout' : 'failed',
235
+ message: aborted ? `生图超时(${Math.round(timeoutMs / 1000)} 秒)` : String(error?.message ?? error),
236
+ };
237
+ } finally {
238
+ clearTimeout(timer);
239
+ try { signal?.removeEventListener?.('abort', onAbort); } catch { /* ignore */ }
240
+ // 会话用完就丢:生图不需要记忆,留着只会占 maxLiveSessions。
241
+ try { Promise.resolve(handle?.dispose?.()).catch(() => {}); } catch { /* ignore */ }
242
+ }
243
+ }
244
+
245
+ /**
246
+ * 等这一轮真的跑完。
247
+ *
248
+ * 为什么不能直接 `await agent.whenIdle()`:
249
+ * agent 刚创建时本身就是 idle 的,followup() 刚发出去的那一瞬间
250
+ * whenIdle() 可能立刻 resolve——于是我们在模型还没开始流式回复时就去读
251
+ * 会话,读到空,然后在 finally 里把会话销毁掉。
252
+ *
253
+ * 表现就是:每次生图都创建了一个只有元数据的空会话,
254
+ * 图其实可能正在生成。
255
+ *
256
+ * 所以分两步:先等任何一个事件出现(说明轮次真的开始了),
257
+ * 再等 idle(说明它结束了)。两步都有硬上限。
258
+ */
259
+ async function waitIdle(agent, signal, timeoutMs, baselineSeq = 0) {
260
+ const deadline = Date.now() + timeoutMs;
261
+ const aborted = () => signal.aborted;
262
+
263
+ // 第一步:等会话里出现**模型**的事件。
264
+ //
265
+ // 基准必须是调用 followup 之前的 seq:用户那条 prompt 自己也会让 seq 加一,
266
+ // 拿 >0 当条件等于一进来就通过,这道「等它真的开始」的防线就不存在了。
267
+ // 超时向上取 15 秒——路由不存在时它不会报错,只是什么都不会发生。
268
+ const baseline = Number.isInteger(baselineSeq) && baselineSeq > 0 ? baselineSeq : 0;
269
+ const started = Date.now();
270
+ while (Date.now() - started < Math.min(15_000, timeoutMs)) {
271
+ if (aborted()) return { started: false, finished: false, cancelled: true };
272
+ const seq = Number.isInteger(agent?.session?.seq) ? agent.session.seq : 0;
273
+ if (seq > baseline) break;
274
+ await new Promise((r) => setTimeout(r, 100));
275
+ }
276
+ const seqAfterStart = Number.isInteger(agent?.session?.seq) ? agent.session.seq : 0;
277
+ if (seqAfterStart <= baseline) {
278
+ return { started: false, finished: false, cancelled: false };
279
+ }
280
+
281
+ // 第二步:等这一轮结束。
282
+ const idle = Promise.resolve().then(() => agent.whenIdle()).then(() => true).catch(() => true);
283
+ const cancelled = new Promise((resolve) => {
284
+ if (signal.aborted) return resolve(false);
285
+ signal.addEventListener('abort', () => resolve(false), { once: true });
286
+ });
287
+ const guard = new Promise((resolve) => {
288
+ const left = Math.max(0, deadline - Date.now());
289
+ const t = setTimeout(() => resolve(false), left);
290
+ t.unref?.();
291
+ });
292
+ const ok = await Promise.race([idle, cancelled, guard]);
293
+ if (!ok) {
294
+ if (signal.aborted) return { started: true, finished: false, cancelled: true };
295
+ try { agent.cancel({ kind: 'user' }); } catch { /* ignore */ }
296
+ return { started: true, finished: false, cancelled: false };
297
+ }
298
+ return { started: true, finished: true, cancelled: false };
299
+ }
300
+
301
+ /**
302
+ * 从会话事件里拼出这一轮的回复。
303
+ *
304
+ * 两件事都要做:
305
+ * 1. 拿文本——有些路由把图片以 Markdown 链接写进正文;
306
+ * 2. 拿图片块——DSH 的图片是独立的 {type:"image", attachment},
307
+ * **不会**出现在文本里。只看文本会以为模型没画图。
308
+ *
309
+ * 为什么不读 `session.events`:DSH 的 session 是 `seq` + `eventAt(i)`。
310
+ */
311
+ /**
312
+ * 从会话里取出这一轮模型的输出。
313
+ *
314
+ * 两个过滤缺一不可:
315
+ *
316
+ * 1. **只从 baselineSeq 之后取**。会话在 followup(createUserMessage(...)) 之后就已经
317
+ * 有事件了(用户那句话本身)。从 0 开始扫会把我们自己发出去的 prompt 当成模型输出。
318
+ * 2. **只要 assistant 的消息**。以前这里不过滤角色,于是 prompt 里的文本混进 texts:
319
+ * - prompt 里带图片链接时,extractImageUrls 会把「用户给的参考图」当成生图结果去发;
320
+ * - 模型完全没回(空回合)时,texts 里仍有 prompt,错误会报成「回了话但没有图」,
321
+ * 把真正的原因(路由没响应)盖掉。
322
+ *
323
+ * 其它模块(meme-classify / virtual-life-generate / 情感分析)一直都是这么过滤的,
324
+ * 只有这里漏了。
325
+ */
326
+ function collectReply(agent, { baselineSeq = 0 } = {}) {
327
+ const session = agent?.session;
328
+ const start = Number.isInteger(baselineSeq) && baselineSeq > 0 ? baselineSeq : 0;
329
+ const events = [];
330
+ try {
331
+ const end = Number.isInteger(session?.seq) ? session.seq : 0;
332
+ if (typeof session?.eventAt === 'function') {
333
+ for (let i = start; i < end; i++) {
334
+ try { const event = session.eventAt(i); if (event) events.push(event); } catch { /* ignore */ }
335
+ }
336
+ } else if (Array.isArray(session?.events)) {
337
+ events.push(...session.events.slice(start));
338
+ }
339
+ } catch { /* ignore */ }
340
+
341
+ const texts = [];
342
+ const imageParts = [];
343
+ const rawTypes = [];
344
+ for (const event of events) {
345
+ // 能确定不是 assistant 的直接跳过;宿主没给 type/role 时保持旧行为,
346
+ // 免得换了宿主版本之后这里把正常输出也滤掉。
347
+ if (event?.type && event.type !== 'assistant/message') continue;
348
+ const role = event?.data?.message?.role ?? event?.message?.role;
349
+ if (role && role !== 'assistant') continue;
350
+ const content = event?.data?.message?.content ?? event?.message?.content ?? event?.content;
351
+ if (!Array.isArray(content)) continue;
352
+ for (const part of content) {
353
+ if (!part) continue;
354
+ rawTypes.push(String(part.type));
355
+ if (part.type === 'text' && typeof part.text === 'string') texts.push(part.text);
356
+ if (part.type === 'image') imageParts.push(part);
357
+ }
358
+ }
359
+ return { text: texts.join('\n').trim(), imageParts, rawTypes };
360
+ }