pygmalion 0.1.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/src/inbound.js ADDED
@@ -0,0 +1,759 @@
1
+ /**
2
+ * Inbound pipeline (QQ → DSH agent): normalize the gateway event, dedupe,
3
+ * enforce the allowlist, strip @mentions, resolve quoted messages via the
4
+ * ref index, process attachments (images → ImageBlock via the attachment
5
+ * service, voice → ASR text / STT, files → download under the session cwd),
6
+ * assemble the model-facing text, intercept slash commands, keep the typing
7
+ * indicator alive, and deliver to the per-conversation DSH agent.
8
+ */
9
+ import { mkdir, writeFile } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { targetKey } from './threads.js';
12
+ import { listLifeScripts, listRunningLifeScripts } from './agent-life.js';
13
+ import { isRoleDirectorSession } from './persona.js';
14
+ import { sessionFileFor } from './active-session.js';
15
+ import { refreshRawRecordFromSession, charLabelOf } from './memory-write.js';
16
+ export const SESSION_PREFIX = 'qq:v2';
17
+ /** LRU caps for inbound dedup. */
18
+ const DEDUP_MAX = 2_000;
19
+ /** Voice/file download budget. */
20
+ const DOWNLOAD_MAX_BYTES = 100 * 1024 * 1024;
21
+ const DOWNLOAD_TIMEOUT_MS = 120_000;
22
+ /** Media formats the attachment service accepts as ImageBlocks. */
23
+ const IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
24
+ function asRecord(value) {
25
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
26
+ ? value
27
+ : undefined;
28
+ }
29
+ /** Normalize one gateway op-0 payload into an IncomingMessage. */
30
+ export function normalizeMessage(payload, eventType) {
31
+ const data = asRecord(payload);
32
+ if (data === undefined || typeof data.id !== 'string')
33
+ return undefined;
34
+ const author = asRecord(data.author);
35
+ // ref_msg_idx / msg_idx ride inside message_scene.ext as "k=v" strings.
36
+ let msgIdx;
37
+ let refMsgIdx;
38
+ const scene = asRecord(data.message_scene);
39
+ if (Array.isArray(scene?.ext)) {
40
+ for (const entry of scene.ext) {
41
+ if (typeof entry !== 'string')
42
+ continue;
43
+ const eq = entry.indexOf('=');
44
+ if (eq < 0)
45
+ continue;
46
+ const key = entry.slice(0, eq).trim();
47
+ const value = entry.slice(eq + 1).trim();
48
+ if (value.length === 0)
49
+ continue;
50
+ if (key === 'msg_idx')
51
+ msgIdx = value;
52
+ else if (key === 'ref_msg_idx')
53
+ refMsgIdx = value;
54
+ }
55
+ }
56
+ // msg_type 103 carries the quoted element index in msg_elements[0].msg_idx.
57
+ const elements = Array.isArray(data.msg_elements)
58
+ ? data.msg_elements.map(asRecord).filter((el) => el !== undefined)
59
+ : [];
60
+ if (data.message_type === 103 && elements[0]?.msg_idx !== undefined && typeof elements[0].msg_idx === 'string') {
61
+ refMsgIdx = elements[0].msg_idx;
62
+ }
63
+ const attachments = (Array.isArray(data.attachments) ? data.attachments : [])
64
+ .map(asRecord)
65
+ .filter((att) => att !== undefined)
66
+ .map((att) => ({
67
+ content_type: typeof att.content_type === 'string' ? att.content_type : 'application/octet-stream',
68
+ url: typeof att.url === 'string' ? (att.url.startsWith('//') ? `https:${att.url}` : att.url) : '',
69
+ filename: typeof att.filename === 'string' ? att.filename : undefined,
70
+ voice_wav_url: typeof att.voice_wav_url === 'string' && att.voice_wav_url.startsWith('//')
71
+ ? `https:${att.voice_wav_url}`
72
+ : typeof att.voice_wav_url === 'string' ? att.voice_wav_url : undefined,
73
+ asr_refer_text: typeof att.asr_refer_text === 'string' ? att.asr_refer_text : undefined,
74
+ }));
75
+ const mentions = (Array.isArray(data.mentions) ? data.mentions : [])
76
+ .map(asRecord)
77
+ .filter((m) => m !== undefined)
78
+ .map((m) => ({
79
+ id: typeof m.id === 'string' ? m.id : undefined,
80
+ user_openid: typeof m.user_openid === 'string' ? m.user_openid : undefined,
81
+ member_openid: typeof m.member_openid === 'string' ? m.member_openid : undefined,
82
+ nickname: typeof m.nickname === 'string' ? m.nickname : undefined,
83
+ username: typeof m.username === 'string' ? m.username : undefined,
84
+ is_you: m.is_you === true,
85
+ }));
86
+ if (eventType === 'C2C_MESSAGE_CREATE' && author !== undefined && typeof author.user_openid === 'string') {
87
+ return {
88
+ id: data.id,
89
+ kind: 'c2c',
90
+ content: typeof data.content === 'string' ? data.content : '',
91
+ senderId: author.user_openid,
92
+ senderName: undefined,
93
+ timestamp: typeof data.timestamp === 'string' ? data.timestamp : '',
94
+ msgIdx,
95
+ refMsgIdx,
96
+ msgType: typeof data.message_type === 'number' ? data.message_type : undefined,
97
+ attachments,
98
+ msgElements: elements.map((el) => ({
99
+ msg_idx: typeof el.msg_idx === 'string' ? el.msg_idx : undefined,
100
+ content: typeof el.content === 'string' ? el.content : undefined,
101
+ attachments: [],
102
+ })),
103
+ mentions,
104
+ reply: { kind: 'c2c', userId: author.user_openid },
105
+ };
106
+ }
107
+ if (eventType === 'GROUP_AT_MESSAGE_CREATE' && author !== undefined && typeof author.member_openid === 'string' && typeof data.group_openid === 'string') {
108
+ return {
109
+ id: data.id,
110
+ kind: 'group',
111
+ content: typeof data.content === 'string' ? data.content : '',
112
+ senderId: author.member_openid,
113
+ senderName: typeof author.username === 'string' ? author.username : undefined,
114
+ timestamp: typeof data.timestamp === 'string' ? data.timestamp : '',
115
+ msgIdx,
116
+ refMsgIdx,
117
+ msgType: typeof data.message_type === 'number' ? data.message_type : undefined,
118
+ attachments,
119
+ msgElements: elements.map((el) => ({
120
+ msg_idx: typeof el.msg_idx === 'string' ? el.msg_idx : undefined,
121
+ content: typeof el.content === 'string' ? el.content : undefined,
122
+ attachments: [],
123
+ })),
124
+ mentions,
125
+ reply: { kind: 'group', groupId: data.group_openid },
126
+ };
127
+ }
128
+ if ((eventType === 'AT_MESSAGE_CREATE' || eventType === 'DIRECT_MESSAGE_CREATE') && author !== undefined && typeof author.id === 'string') {
129
+ const channelId = typeof data.channel_id === 'string' ? data.channel_id : undefined;
130
+ if (channelId === undefined)
131
+ return undefined;
132
+ return {
133
+ id: data.id,
134
+ kind: 'channel',
135
+ content: typeof data.content === 'string' ? data.content : '',
136
+ senderId: author.id,
137
+ senderName: typeof author.username === 'string' ? author.username : undefined,
138
+ timestamp: typeof data.timestamp === 'string' ? data.timestamp : '',
139
+ msgIdx,
140
+ refMsgIdx,
141
+ msgType: undefined,
142
+ attachments,
143
+ msgElements: [],
144
+ mentions,
145
+ reply: { kind: 'channel', channelId },
146
+ };
147
+ }
148
+ return undefined;
149
+ }
150
+ /**
151
+ * Base session id for a conversation target (no thread suffix).
152
+ * 正式版多 bot:session id 带 botId 段 `qq:v2:<botId>:c2c:<userId>`,
153
+ * 使不同机器人的会话/代理/出站事件完全隔离(修多 bot 数据串)。
154
+ */
155
+ export function baseSessionId(target, botId) {
156
+ const scope = target.kind === 'c2c' ? `c2c:${target.userId}`
157
+ : target.kind === 'group' ? `group:${target.groupId}`
158
+ : `channel:${target.channelId}`;
159
+ return botId ? `${SESSION_PREFIX}:${botId}:${scope}` : `${SESSION_PREFIX}:${scope}`;
160
+ }
161
+ /** Session id used by the DSH agent for a given target+thread. */
162
+ export function effectiveSessionId(target, thread, botId) {
163
+ return thread === 0 ? baseSessionId(target, botId) : `${baseSessionId(target, botId)}#n${thread}`;
164
+ }
165
+ /** Compatibility shim: returns the base id (thread 0) for the inbound message. */
166
+ export function sessionIdFor(message, botId) {
167
+ return baseSessionId(message.reply, botId);
168
+ }
169
+ /** Replace <@openid> with @nickname and drop self-mentions. */
170
+ export function stripMentions(text, mentions) {
171
+ let cleaned = text;
172
+ for (const mention of mentions) {
173
+ const openid = mention.member_openid ?? mention.id ?? mention.user_openid;
174
+ if (openid === undefined || openid.length === 0)
175
+ continue;
176
+ if (mention.is_you) {
177
+ cleaned = cleaned.replace(new RegExp(`<@!?${openid}>`, 'g'), '');
178
+ }
179
+ else {
180
+ const display = mention.nickname ?? mention.username;
181
+ if (display !== undefined) {
182
+ cleaned = cleaned.replace(new RegExp(`<@!?${openid}>`, 'g'), `@${display}`);
183
+ }
184
+ }
185
+ }
186
+ return cleaned.trim();
187
+ }
188
+ /** Allowlist gate: '*' or an empty list admits everyone. */
189
+ export function isAllowed(list, id) {
190
+ if (list === undefined || list.length === 0 || list.includes('*'))
191
+ return true;
192
+ return list.includes(id);
193
+ }
194
+ /** Build the model-facing text: quoted message first, then the new content. */
195
+ export function assembleText(cleanedText, quote, extras) {
196
+ const parts = [];
197
+ if (quote !== undefined && quote.content.trim().length > 0) {
198
+ const who = quote.senderName !== undefined && quote.senderName.length > 0 ? `${quote.senderName}: ` : '';
199
+ parts.push(`[引用消息开始]\n${who}${quote.content.trim()}\n[引用消息结束]`);
200
+ }
201
+ parts.push(cleanedText);
202
+ for (const extra of extras) {
203
+ if (extra.trim().length > 0)
204
+ parts.push(extra.trim());
205
+ }
206
+ return parts.join('\n').trim();
207
+ }
208
+
209
+ /** 时间线上下文(仅模型侧):当前时间 / 本条消息时间 / 距上一条用户消息间隔。(含日期,供记忆归档正确分日期) */
210
+ export function buildTimeline(now, msgTime, prevAt) {
211
+ const pad = (n) => String(n).padStart(2, '0');
212
+ const WEEK = '日一二三四五六';
213
+ const hm = (d) => `${d.getMonth() + 1}-${d.getDate()} ${WEEK[d.getDay()]} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
214
+ const parts = [`现在是 ${hm(now)}`];
215
+ if (msgTime instanceof Date)
216
+ parts.push(`本条消息时间 ${hm(msgTime)}`);
217
+ if (msgTime instanceof Date && typeof prevAt === 'number' && Number.isFinite(prevAt)) {
218
+ const gapMin = Math.round((msgTime.getTime() - prevAt) / 60_000);
219
+ if (gapMin > 0) {
220
+ const gapText = gapMin >= 60
221
+ ? `${Math.floor(gapMin / 60)}小时${gapMin % 60 ? `${gapMin % 60}分` : ''}`
222
+ : `${gapMin}分钟`;
223
+ parts.push(`距上一条用户消息约 ${gapText}`);
224
+ }
225
+ }
226
+ return `[时间线] ${parts.join(';')}`;
227
+ }
228
+ /** Describe attachments for the model when binary transfer is unavailable. */
229
+ function describeAttachments(attachments, voiceText) {
230
+ const parts = [];
231
+ if (voiceText !== undefined && voiceText.length > 0)
232
+ parts.push(`[语音] ${voiceText}`);
233
+ for (const att of attachments) {
234
+ const type = att.content_type.toLowerCase();
235
+ if (type.startsWith('audio/'))
236
+ continue; // covered by voiceText
237
+ if (type.startsWith('image/'))
238
+ parts.push(`[图片${att.filename !== undefined ? `: ${att.filename}` : ''}]`);
239
+ else if (type.startsWith('video/'))
240
+ parts.push(`[视频${att.filename !== undefined ? `: ${att.filename}` : ''}]`);
241
+ else
242
+ parts.push(`[文件${att.filename !== undefined ? `: ${att.filename}` : ''}]`);
243
+ }
244
+ return parts.join('\n');
245
+ }
246
+ async function downloadTo(url, dir, filename) {
247
+ if (!url.startsWith('https://'))
248
+ return undefined;
249
+ try {
250
+ await mkdir(dir, { recursive: true });
251
+ const response = await fetch(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
252
+ if (!response.ok)
253
+ return undefined;
254
+ const buffer = Buffer.from(await response.arrayBuffer());
255
+ if (buffer.byteLength > DOWNLOAD_MAX_BYTES)
256
+ return undefined;
257
+ const safeName = (filename ?? `qq-${Date.now()}`).replace(/[/\\:*?"<>|]/g, '_');
258
+ const path = join(dir, safeName);
259
+ await writeFile(path, buffer);
260
+ return path;
261
+ }
262
+ catch {
263
+ return undefined;
264
+ }
265
+ }
266
+ /** OpenAI-compatible speech-to-text transcription (skipped without an apiKey). */
267
+ async function transcribe(stt, wavPath) {
268
+ if (stt.apiKey === undefined || stt.apiKey.length === 0)
269
+ return undefined;
270
+ const { readFile } = await import('node:fs/promises');
271
+ const form = new FormData();
272
+ form.append('file', new Blob([await readFile(wavPath)]), 'audio.wav');
273
+ form.append('model', stt.model);
274
+ const base = stt.baseUrl.replace(/\/+$/, '');
275
+ const response = await fetch(`${base}/audio/transcriptions`, {
276
+ method: 'POST',
277
+ headers: { Authorization: `Bearer ${stt.apiKey}` },
278
+ body: form,
279
+ signal: AbortSignal.timeout(60_000),
280
+ });
281
+ if (!response.ok)
282
+ return undefined;
283
+ const data = asRecord(await response.json());
284
+ return typeof data?.text === 'string' ? data.text : undefined;
285
+ }
286
+ /** The inbound pipeline. */
287
+ export class InboundPipeline {
288
+ deps;
289
+ seen = new Set();
290
+ seenOrder = [];
291
+ agentCreation = new Map();
292
+ /** Per-session C2C typing indicator timers; cleared on turn end / disposal. */
293
+ typingTimers = new Map();
294
+ /** Per-session last user-activity timestamp (for Pygmalion collision detection). */
295
+ lastActivity = new Map();
296
+ /** 每进程每导演会话只补记一次 agent-preset/selected(避免反复 append)。 */
297
+ directorPresetRecorded = new Set();
298
+ /** Attached after construction so the handlers can close over outbound. */
299
+ onSlashCommand;
300
+ setupAgent;
301
+ /** 已存在 agent 时补登记会话上下文(standing 导演工具按 sessionId 查 sessionDeps)。 */
302
+ registerSessionContext;
303
+ constructor(deps) {
304
+ this.deps = deps;
305
+ }
306
+ /**
307
+ * Attach the slash-command and per-agent setup callbacks after the
308
+ * pipeline itself is wired. Used by the composition root so the handlers
309
+ * can close over the outbound pipeline (which depends on inbound being
310
+ * constructed first).
311
+ */
312
+ attachHooks(hooks) {
313
+ if (hooks.onSlashCommand !== undefined)
314
+ this.onSlashCommand = hooks.onSlashCommand;
315
+ if (hooks.setupAgent !== undefined)
316
+ this.setupAgent = hooks.setupAgent;
317
+ if (hooks.registerSessionContext !== undefined)
318
+ this.registerSessionContext = hooks.registerSessionContext;
319
+ }
320
+ /**
321
+ * 用户消息送达后延迟刷新日期层原始记录:从活跃会话 session log 提取当日原文合并写入。
322
+ * 延迟 ~3s 等 dsh 把本条落盘到 session.jsonl.zstd;仅 c2c 拥有者会话(群聊不记)。
323
+ */
324
+ scheduleRawRefresh(sessionId) {
325
+ const { persona, roleId, log } = this.deps;
326
+ if (!persona?.roleWorkspace || !roleId || !sessionId)
327
+ return;
328
+ const workspace = persona.roleWorkspace(roleId);
329
+ const file = sessionFileFor({ sessionId, workspace });
330
+ setTimeout(() => {
331
+ void (async () => {
332
+ try {
333
+ const charLabel = await charLabelOf(persona, roleId);
334
+ await refreshRawRecordFromSession({ workspace, sessionFile: file, charLabel, log });
335
+ }
336
+ catch (error) {
337
+ log?.warn?.('pygmalion: 刷新原始记录失败: %o', error);
338
+ }
339
+ })();
340
+ }, 3000);
341
+ }
342
+ /** Entry point for every normalized gateway message. */
343
+ async handle(message) {
344
+ if (this.dedupe(message.id))
345
+ return;
346
+ const allowed = message.kind === 'group'
347
+ ? isAllowed(this.deps.config.groupAllowFrom, message.reply.kind === 'group' ? message.reply.groupId : '')
348
+ : isAllowed(this.deps.config.allowFrom, message.senderId);
349
+ if (!allowed) {
350
+ if (this.deps.config.debug)
351
+ this.deps.log.debug?.('dropped message from non-allowlisted sender %s', message.senderId);
352
+ return;
353
+ }
354
+ // openid 绑定校验(修 D5):c2c 消息按本 bot 服务的角色绑定/校验拥有者。
355
+ // 未绑定 → 首聊自动绑定为角色拥有者;已绑定同 openid → 放行;已绑定不同 → 拒绝。
356
+ // 群/频道消息无单拥有者概念,跳过绑定校验(仍受 groupAllowFrom 白名单约束)。
357
+ if (message.kind === 'c2c' && this.deps.roleId && this.deps.persona?.bindRoleOpenid !== undefined) {
358
+ const bind = await this.deps.persona.bindRoleOpenid(this.deps.roleId, message.senderId, this.deps.botAppId);
359
+ if (bind.status === 'mismatch') {
360
+ this.deps.log.warn('QQ inbound: openid %s rejected for role %s (bound to %s)', message.senderId, this.deps.roleId, bind.role?.binding?.openid);
361
+ return;
362
+ }
363
+ if (bind.status === 'bound') {
364
+ this.deps.log.info('QQ inbound: openid %s first-chat bound to role %s', message.senderId, this.deps.roleId);
365
+ }
366
+ else if (bind.status === 'no-role') {
367
+ this.deps.log.warn('QQ inbound: bot serves role %s which does not exist; dropping c2c %s', this.deps.roleId, message.senderId);
368
+ return;
369
+ }
370
+ }
371
+ // Resolve the effective DSH session id for this target's current thread
372
+ // (the /new slash command bumps the thread counter so the next inbound
373
+ // message lands in a fresh session). The base id is unchanged for
374
+ // thread 0, so existing sessions keep their ids.
375
+ const thread = this.deps.threads.current(targetKey(message.reply));
376
+ const sessionId = effectiveSessionId(message.reply, thread, this.deps.botId);
377
+ this.deps.log.info('QQ inbound: id=%s kind=%s sender=%s thread=%d sessionId=%s', message.id, message.kind, message.senderId, thread, sessionId);
378
+ // Slash commands are checked before any routing bookkeeping so /new
379
+ // doesn't disturb the previous thread's anchor and /help /ping /me
380
+ // don't start a typing indicator for a one-line canned reply.
381
+ const cleaned = stripMentions(message.content, message.mentions);
382
+ if (this.deps.config.slashCommands !== false && cleaned.startsWith('/')) {
383
+ const reply = async (replyText) => {
384
+ await this.deps.api.sendText(message.reply, replyText, message.id).catch((error) => {
385
+ this.deps.log.error('slash-command reply failed: %o', error);
386
+ });
387
+ };
388
+ const handled = await this.onSlashCommand?.(sessionId, message, cleaned, reply) ?? false;
389
+ if (handled)
390
+ return;
391
+ }
392
+ // Routing bookkeeping before anything async: the outbound pipeline and
393
+ // any non-slash replies both depend on the anchor being present.
394
+ this.deps.routes.anchor(sessionId, message.reply, message.id);
395
+ // 时间线(模型侧):当前时间 / 本条消息时间戳 / 距上一条用户消息的间隔。
396
+ // 仅注入模型上下文,用于导演做合理互动,不会发送给用户。
397
+ const msgTs = typeof message.timestamp === 'string' ? Date.parse(message.timestamp) : Number.NaN;
398
+ const msgTime = Number.isNaN(msgTs) ? Date.now() : msgTs;
399
+ const prevUserAt = this.userActivityAt(sessionId);
400
+ this.markUserActivity(sessionId, msgTime);
401
+ this.startTyping(sessionId, message.reply, message.id);
402
+ // Record this message for future quote resolution.
403
+ if (message.msgIdx !== undefined) {
404
+ this.deps.refIndex.set(message.msgIdx, {
405
+ messageId: message.id,
406
+ senderId: message.senderId,
407
+ senderName: message.senderName,
408
+ content: message.content.slice(0, 500),
409
+ scope: message.kind,
410
+ });
411
+ }
412
+ // Resolve the quoted message: ref index first, msg_elements fallback.
413
+ let quote;
414
+ if (message.refMsgIdx !== undefined) {
415
+ const entry = this.deps.refIndex.get(message.refMsgIdx);
416
+ if (entry !== undefined) {
417
+ quote = { senderName: entry.senderName, content: entry.content };
418
+ }
419
+ else {
420
+ const element = message.msgElements[0];
421
+ if (element?.content !== undefined && element.content.length > 0) {
422
+ quote = { content: element.content };
423
+ }
424
+ }
425
+ }
426
+ // Attachments: images become ImageBlocks; voice becomes text; the rest
427
+ // download under the session cwd so the agent's file tools can read them.
428
+ const imageBlocks = [];
429
+ const extras = [];
430
+ let voiceText;
431
+ // 附件落盘目录 = 本 bot 服务的角色工作区(与 dsh 会话 cwd 一致,保证文件工具可读)。
432
+ const cwd = (this.deps.roleId && this.deps.persona?.roleWorkspace)
433
+ ? this.deps.persona.roleWorkspace(this.deps.roleId)
434
+ : process.cwd();
435
+ const mediaDir = join(cwd, '.qq-media');
436
+ for (const att of message.attachments) {
437
+ const type = att.content_type.toLowerCase();
438
+ try {
439
+ if (type.startsWith('image/') && IMAGE_MEDIA_TYPES.has(type) && this.deps.attachments !== undefined) {
440
+ const response = await fetch(att.url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
441
+ if (response.ok) {
442
+ const bytes = new Uint8Array(await response.arrayBuffer());
443
+ const name = att.filename ?? 'qq-image';
444
+ const ref = await this.deps.attachments.saveImage({
445
+ data: bytes,
446
+ mediaType: type,
447
+ name,
448
+ });
449
+ imageBlocks.push({ type: 'image', attachment: ref });
450
+ continue;
451
+ }
452
+ }
453
+ if (type.startsWith('audio/')) {
454
+ voiceText = att.asr_refer_text;
455
+ if ((voiceText === undefined || voiceText.length === 0) && this.deps.config.stt !== undefined) {
456
+ const wavUrl = att.voice_wav_url ?? att.url;
457
+ const local = await downloadTo(wavUrl, mediaDir, att.filename);
458
+ if (local !== undefined) {
459
+ voiceText = (await transcribe(this.deps.config.stt, local)) ?? undefined;
460
+ }
461
+ }
462
+ continue;
463
+ }
464
+ if (this.deps.config.mediaDownload !== false && att.url.length > 0) {
465
+ const local = await downloadTo(att.url, mediaDir, att.filename);
466
+ if (local !== undefined)
467
+ extras.push(`[已下载附件: ${local}]`);
468
+ else
469
+ extras.push(`[附件下载失败${att.filename !== undefined ? `: ${att.filename}` : ''}]`);
470
+ }
471
+ }
472
+ catch (error) {
473
+ this.deps.log.warn('attachment processing failed: %o', error);
474
+ }
475
+ }
476
+ const described = describeAttachments(message.attachments, voiceText);
477
+ if (described.length > 0)
478
+ extras.unshift(described);
479
+ // 时间线前置(模型侧,不发送给用户)
480
+ const timeline = buildTimeline(new Date(), Number.isNaN(msgTs) ? undefined : new Date(msgTs), prevUserAt);
481
+ if (timeline) extras.unshift(timeline);
482
+ // 新会话首条消息:向导演注入「生活脚本状态」提示(非零意识)。
483
+ // 「非零」= 至少一个脚本在跑(running 表非空,文件存在不算);无脚本 → 提示收尾时新建并 life_run。
484
+ if (prevUserAt === undefined && this.deps.roleId && this.deps.persona?.roleWorkspace) {
485
+ try {
486
+ if (await isRoleDirectorSession(this.deps.roleId, sessionId)) {
487
+ const ws = this.deps.persona.roleWorkspace(this.deps.roleId);
488
+ const running = await listRunningLifeScripts(ws);
489
+ const scripts = await listLifeScripts(ws);
490
+ extras.unshift(running.length
491
+ ? `[生活脚本] 有脚本在跑(${running.map((r) => r.scriptName).join('、')}),非零已满足。`
492
+ : scripts.length
493
+ ? `[生活脚本] life/ 下有脚本(${scripts.join('、')})但当前都没有在跑——想保留主动关心 ta 的可能,可用 life_run 重启一个。`
494
+ : '[生活脚本] life/ 当前没有任何脚本在跑(不满足「非零」)。若想保留主动关心 ta 的可能,可新建一个你的脚本(新文件,勿覆盖已有文件)并用 life_run 运行。');
495
+ }
496
+ } catch (e) { this.deps.log.warn('life script hint failed: %o', e); }
497
+ }
498
+ const text = assembleText(cleaned, quote, extras);
499
+ if (text.length === 0 && imageBlocks.length === 0) {
500
+ this.stopTyping(sessionId);
501
+ return;
502
+ }
503
+ const agent = await this.ensureAgent(sessionId);
504
+ if (!agent) {
505
+ this.deps.log.error('QQ inbound: ensureAgent returned no agent for %s', sessionId);
506
+ this.stopTyping(sessionId);
507
+ return;
508
+ }
509
+ this.deps.log.info('QQ inbound: agent.send %s (target session=%s)', message.id, sessionId);
510
+ agent.send({
511
+ id: message.id,
512
+ role: 'user',
513
+ content: [
514
+ ...(text.length > 0 ? [{ type: 'text', text }] : []),
515
+ ...imageBlocks,
516
+ ],
517
+ source: { kind: 'user', id: message.senderId, name: message.senderName ?? message.senderId },
518
+ }, 'next-turn', true);
519
+ // 日期层记忆:消息送达后延迟从活跃会话 session log 提取写原始记录(仅 c2c 拥有者会话)。
520
+ if (message.kind === 'c2c')
521
+ this.scheduleRawRefresh(sessionId);
522
+ }
523
+ dedupe(messageId) {
524
+ if (this.seen.has(messageId))
525
+ return true;
526
+ this.seen.add(messageId);
527
+ this.seenOrder.push(messageId);
528
+ if (this.seenOrder.length > DEDUP_MAX) {
529
+ const oldest = this.seenOrder.shift();
530
+ if (oldest !== undefined)
531
+ this.seen.delete(oldest);
532
+ }
533
+ return false;
534
+ }
535
+ startTyping(sessionId, target, msgId) {
536
+ if (this.deps.config.typing !== true || target.kind !== 'c2c')
537
+ return;
538
+ this.stopTyping(sessionId);
539
+ const send = () => { void this.deps.api.sendTyping(target, msgId); };
540
+ send();
541
+ this.typingTimers.set(sessionId, setInterval(send, 50_000));
542
+ }
543
+ stopTyping(sessionId) {
544
+ const timer = this.typingTimers.get(sessionId);
545
+ if (timer !== undefined) {
546
+ clearInterval(timer);
547
+ this.typingTimers.delete(sessionId);
548
+ }
549
+ }
550
+ /**
551
+ * Create or resume the DSH agent bound to the QQ session id. Also the entry
552
+ * point for the HTTP push API's `record: true` path and Pygmalion's wakeup,
553
+ * which need the same setup (preset mount, workspace attach, approval
554
+ * answerer) as an inbound conversation.
555
+ *
556
+ * With `deps.persona` present, per-user runtime is resolved (provider/model
557
+ * from the user's config/binding, workspace = <data>/users/<openid>/workspace)
558
+ * so every user runs on their own model and memory space.
559
+ */
560
+ async ensureAgent(sessionId) {
561
+ const existing = this.deps.agents.get(sessionId);
562
+ if (existing !== undefined) {
563
+ // 已存在 agent(可能是 dsh 核心路径冷恢复/重组合创建的):若缺
564
+ // pygmalion-director preset 记录,补记 selected 事件,让下一次冷恢复挂对
565
+ // composition;同时补登记会话上下文——standing 导演工具执行时按 sessionId
566
+ // 查 sessionDeps,而核心创建/重组合的 agent 没跑 pygmalion setup。
567
+ void this.recordDirectorPreset(sessionId, existing);
568
+ this.registerSessionContext?.(sessionId);
569
+ return existing;
570
+ }
571
+ let creation = this.agentCreation.get(sessionId);
572
+ if (creation === undefined) {
573
+ this.deps.log.info('QQ ensureAgent: creating agent for %s', sessionId);
574
+ creation = (async () => {
575
+ // 角色运行时:provider/model/cwd 从本 bot 服务的角色配置解析
576
+ //(正式版 Config 无顶层 provider/model/cwd)。
577
+ let provider;
578
+ let model;
579
+ let cwd = process.cwd();
580
+ let isDirector = false;
581
+ if (this.deps.roleId) {
582
+ const role = await this.deps.persona?.loadRole?.(this.deps.roleId);
583
+ if (role) {
584
+ await this.deps.persona?.syncRoleMemory?.(role);
585
+ provider = role.model.provider;
586
+ model = role.model.model;
587
+ cwd = role.workspace;
588
+ // 导演 = c2c 且 openid 已绑定本角色且角色有人设;群/频道走标准模式。
589
+ const openid = this.deps.persona?.openidFromSessionId?.(sessionId);
590
+ isDirector = openid !== undefined && openid === role.binding.openid && Boolean(role.persona);
591
+ this.deps.log.info('QQ ensureAgent: role %s for %s -> director=%s provider=%s model=%s cwd=%s', this.deps.roleId, sessionId, isDirector, provider, model, cwd);
592
+ }
593
+ else {
594
+ this.deps.log.warn('QQ ensureAgent: role %s missing, session %s falls back to default runtime', this.deps.roleId, sessionId);
595
+ }
596
+ }
597
+ // No per-user runtime: keep the original behavior of honoring a
598
+ // persisted session cwd before the configured default.
599
+ if (this.deps.roleId === undefined && this.deps.sessionPersistence !== undefined) {
600
+ try {
601
+ const inspected = await this.deps.sessionPersistence.inspect(sessionId);
602
+ if (typeof inspected.meta.cwd === 'string' && inspected.meta.cwd.length > 0)
603
+ cwd = inspected.meta.cwd;
604
+ }
605
+ catch {
606
+ // No persisted session: fall through with the configured cwd.
607
+ }
608
+ }
609
+ const setup = this.setupAgent !== undefined
610
+ ? async (agentCtx) => {
611
+ await this.setupAgent?.(agentCtx, sessionId);
612
+ }
613
+ : undefined;
614
+ // 导演(Pygmalion)会话:已持久化的会话(重启前聊过)用 resume——resume 会重跑
615
+ // setup 注册最新工具(含此插件刚注册的 life_run 等),并还原历史上下文;
616
+ // 全新会话(无持久化记录)才 create。不能对已有持久化日志的 id 直接 create:
617
+ // dsh 判为 id collision,且该错误在 create 返回后异步抛出,绕开这里的 try/catch。
618
+ if (isDirector) {
619
+ const persisted = this.deps.sessionPersistence !== undefined
620
+ ? await this.deps.sessionPersistence.inspect(sessionId).then(() => true).catch(() => false)
621
+ : false;
622
+ // meta.agentPreset 写进 session header:冷重启后任何恢复路径(含 dsh
623
+ // 核心 api-proxy)经 resolveSessionPreset 都会挂 pygmalion-director,
624
+ // 否则挂 standard 默认 composition → director_send 等工具缺失。
625
+ const createOpts = { sessionId, agentOptions: { provider, model }, meta: { cwd, agentPreset: 'pygmalion-director' } };
626
+ const resumeOpts = { resumeSessionId: sessionId, agentOptions: { provider, model } };
627
+ try {
628
+ const agent = persisted
629
+ ? (await this.deps.agents.resume({ ...resumeOpts, ...(setup !== undefined ? { setup } : {}) })).agent
630
+ : (await this.deps.agents.create({ ...createOpts, ...(setup !== undefined ? { setup } : {}) })).agent;
631
+ await this.recordDirectorPreset(sessionId, agent);
632
+ this.deps.log.info('QQ ensureAgent: director %s %s (tools registered)', persisted ? 'resumed' : 'created', agent.id);
633
+ return agent;
634
+ }
635
+ catch (error) {
636
+ this.deps.log.error('QQ ensureAgent: director %s for %s failed, swap fallback: %o', persisted ? 'resume' : 'create', sessionId, error);
637
+ try {
638
+ const agent = persisted
639
+ ? (await this.deps.agents.create({ ...createOpts, ...(setup !== undefined ? { setup } : {}) })).agent
640
+ : (await this.deps.agents.resume({ ...resumeOpts, ...(setup !== undefined ? { setup } : {}) })).agent;
641
+ await this.recordDirectorPreset(sessionId, agent);
642
+ return agent;
643
+ }
644
+ catch (swapError) {
645
+ this.deps.log.error('QQ director session %s could not be created/resumed: %o', sessionId, swapError);
646
+ throw swapError;
647
+ }
648
+ }
649
+ }
650
+ try {
651
+ return (await this.deps.agents.resume({
652
+ resumeSessionId: sessionId,
653
+ agentOptions: { provider, model },
654
+ ...(setup !== undefined ? { setup } : {}),
655
+ })).agent;
656
+ }
657
+ catch (error) {
658
+ if (this.deps.config.debug)
659
+ this.deps.log.debug?.('resume %s failed, creating fresh: %o', sessionId, error);
660
+ }
661
+ try {
662
+ const agent = (await this.deps.agents.create({
663
+ sessionId,
664
+ agentOptions: { provider, model },
665
+ meta: { cwd },
666
+ ...(setup !== undefined ? { setup } : {}),
667
+ })).agent;
668
+ this.deps.log.info('QQ ensureAgent: created %s', agent.id);
669
+ return agent;
670
+ }
671
+ catch (error) {
672
+ this.deps.log.error('QQ session %s could not be created (cwd=%s): %o', sessionId, cwd, error);
673
+ throw error;
674
+ }
675
+ })();
676
+ this.agentCreation.set(sessionId, creation);
677
+ void creation.then(() => { this.agentCreation.delete(sessionId); }, () => { this.agentCreation.delete(sessionId); });
678
+ }
679
+ return creation;
680
+ }
681
+ /** 该会话是否属于「本 bot 服务的角色」的 c2c 导演会话(与 ensureAgent 判定一致)。 */
682
+ async isDirectorSession(sessionId) {
683
+ if (!this.deps.roleId || this.deps.persona?.loadRole === undefined)
684
+ return false;
685
+ const role = await this.deps.persona.loadRole(this.deps.roleId);
686
+ if (!role)
687
+ return false;
688
+ const openid = this.deps.persona.openidFromSessionId?.(sessionId);
689
+ return openid !== undefined && openid === role.binding.openid && Boolean(role.persona);
690
+ }
691
+ /**
692
+ * 确保导演会话的持久化记录 agentPreset='pygmalion-director':补记
693
+ * agent-preset/selected 事件。dsh 冷恢复(含核心 api-proxy 路径)经
694
+ * resolveSessionPreset 决定挂哪个 preset,header 无 agentPreset、日志无
695
+ * selected 事件时回退 standard 默认 composition → director_send 等工具缺失。
696
+ * 每进程每会话只补记一次。
697
+ */
698
+ async recordDirectorPreset(sessionId, agent) {
699
+ if (agent === undefined || this.directorPresetRecorded.has(sessionId))
700
+ return;
701
+ if (!(await this.isDirectorSession(sessionId)))
702
+ return;
703
+ this.directorPresetRecorded.add(sessionId);
704
+ try {
705
+ agent.session.append('agent-preset/selected', { agentPreset: 'pygmalion-director' });
706
+ this.deps.log.info('QQ ensureAgent: 补记导演 preset 到 %s (agent-preset/selected)', sessionId);
707
+ }
708
+ catch (error) {
709
+ this.deps.log.warn('QQ ensureAgent: 补记导演 preset 失败 %s: %o', sessionId, error);
710
+ }
711
+ }
712
+ /** Record when this conversation last saw a real user message. */
713
+ markUserActivity(sessionId, at = Date.now()) {
714
+ this.lastActivity.set(sessionId, at);
715
+ }
716
+ /** Last user-activity timestamp for a session, or undefined. */
717
+ userActivityAt(sessionId) {
718
+ return this.lastActivity.get(sessionId);
719
+ }
720
+ /** Forget in-flight creation state after an agent is disposed. */
721
+ onAgentDisposed(sessionId) {
722
+ this.agentCreation.delete(sessionId);
723
+ this.stopTyping(sessionId);
724
+ }
725
+ /** Clear every typing timer; used during plugin teardown. */
726
+ dispose() {
727
+ for (const timer of this.typingTimers.values())
728
+ clearInterval(timer);
729
+ this.typingTimers.clear();
730
+ }
731
+ }
732
+ /** Extract the target encoded in a session id (inverse of baseSessionId). */
733
+ export function targetOfSession(sessionId) {
734
+ // The optional #n<thread> suffix carries no target info — strip it before parsing.
735
+ const stripped = sessionId.split('#')[0];
736
+ const parts = stripped.split(':');
737
+ // 新格式:qq:v2:<botId>:<scope>:<id>(parts[3]===scope)
738
+ if (parts[1] === 'v2' && parts[3] === 'c2c' && parts[4] !== undefined)
739
+ return { kind: 'c2c', userId: parts[4] };
740
+ if (parts[1] === 'v2' && parts[3] === 'group' && parts[4] !== undefined)
741
+ return { kind: 'group', groupId: parts[4] };
742
+ if (parts[1] === 'v2' && parts[3] === 'channel' && parts[4] !== undefined)
743
+ return { kind: 'channel', channelId: parts[4] };
744
+ // 旧格式:qq:v2:<scope>:<id>
745
+ if (parts[1] === 'v2' && parts[2] === 'c2c' && parts[3] !== undefined)
746
+ return { kind: 'c2c', userId: parts[3] };
747
+ if (parts[1] === 'v2' && parts[2] === 'group' && parts[3] !== undefined)
748
+ return { kind: 'group', groupId: parts[3] };
749
+ if (parts[1] === 'v2' && parts[2] === 'channel' && parts[3] !== undefined)
750
+ return { kind: 'channel', channelId: parts[3] };
751
+ return { kind: 'c2c', userId: 'unknown' };
752
+ }
753
+
754
+ /** 从 session id 提取 botId(新格式 `qq:v2:<botId>:<scope>:<id>` 的 parts[2])。 */
755
+ export function botIdOfSession(sessionId) {
756
+ const parts = String(sessionId ?? '').split('#')[0].split(':');
757
+ return parts[1] === 'v2' && parts.length >= 3 ? parts[2] : undefined;
758
+ }
759
+ //# sourceMappingURL=inbound.js.map